Monday, July 27, 2009

C++ Help, no idea how to write arrays?

I have to write a program that reads 10 numbers from the user and computes the average in an array, but I have no idea how to do that. any tips? I'm trying to teach myself, but having little success.

C++ Help, no idea how to write arrays?
int arr[10];


int sum = 0;





for (int inc=0;inc %26lt; 10;inc++)


{


printf("Enter #%d: ",inc);


scanf("%d",%26amp;arr[inc]);


}





for (int inc=0;inc %26lt;10;inc++)


{


sum += arr[inc];


}


printf("The average is: %d",sum/10);





It is more efficient to have the "sum" calculation inside the 1st for statement and rid the 2nd for statement all together but your question mentioned that you had to "compute the avg in an array"...if you look closely though you dont need an array to calc the avg at all.
Reply:int num[10];


int sum = 0;


float average;





for (int i = 0 ; i %26lt; 10 ; i++)


{


cout %26lt;%26lt; "Enter num: ";


cin %26gt;%26gt; num[i];


sum = sum + num[i];


}





average = float(sum) / 10





cout%26lt;%26lt;"The average is: "%26lt;%26lt;average%26lt;%26lt;endl;





Hope this helps!!


No comments:

Post a Comment