is this correct

Started by
15 comments, last by corrington_j 19 years, 7 months ago
i need to create an integer array that holds 10 random values. Create a loop to find the average of those 10 values and print the result. i was wondering if my code was correct

#include <iostream>

main()
{
	int intarray[10]={0};
	int x = 0;
	int average = 0;
	for (x; x < 10; x++)
	{
		intarray[x] = rand();
		
		average += intarray[x];
		
	}
	std::cout << average/10  << std::endl;;
	return 0;
}


Advertisement
Looks alright to me, why don't you try running it and see if it works? (Unless you know of some specific problem with it already...)
well acctualy when i run your program i always get the same number
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
int intarray[10]={0};

I don't think that's valid. Try:

int intarray[10];


Also, you have one too many semicolons on the second last line.
it works i was just checking to see if i was doing it the right way and to make sure i understood the assignment thats all
thanks for the reply

int intarray[10]={0};
that line initializes the whole array to zero
You might also want to store the average as a float to prevent integer division.
______________________________________________________________________________________The Phoenix shall arise from the ashes... ThunderHawk -- ¦þ"So. Any n00bs need some pointers? I have a std::vector<n00b*> right here..." - ZahlmanMySite | Forum FAQ | File Formats______________________________________________________________________________________
You allways get the same number becouse you dont seed the random number generator. You should call srand() with a different value every time at the start of the program.
ok yeah it works if you seed the num gen.
____________________________"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
Seed it with the system time, since that changes everytime you run the program:

#include <time.h>srand( (unsigned)time( NULL ) )
Quote:Original post by ostamo1
it works i was just checking to see if i was doing it the right way and to make sure i understood the assignment thats all
thanks for the reply

int intarray[10]={0};
that line initializes the whole array to zero


Actually it only sets intarray[0] to 0. YOur compiler in debug mode is likely zeroing the array, so it looks zeroed out to you. Try changing it to int intarray[10]={1}; and you will see what I mean. The correct way to zero it is with meset, a for loop or int array[0]={0,0,0,0,0,0,0,0,0,0}; .
// Only the first element will be one#include <iostream>int main(){	int a[10]={1};	for (int i=0; i<10; ++i)		std::cout << "a["<<i<<"]="<< a<< std::endl;;	std::cin.ignore();	return 0;}

This topic is closed to new replies.

Advertisement