Whats in this post?
- Background and Explanation of the code
- Download Code
To copy code: Click “View Source” on the right of this code snippet.
Background and Explanation of the code
1. The above program calculates the average of ‘n’ numbers using an array. The value of ‘n’ is entered by the user (maximum= 50, the size of array).
2. To input the elements of an array we use a looping statement (for loop in this case) that starts from ‘0’ to ‘n-1′.
Note: The first element of an array has an index ‘0’ and not ‘1’ and the last element has an index ‘N-1′ and not ‘N’, if ‘N’ is the array size.
3. The statement cin>>x[i]; inputs the ‘i’th element where ‘i’ ranges from 0 to n-1.
3. If n=1 (2nd element’s index) then the above statement inputs 2nd element of the array. The sum of the elements of array is calculated which is then used to calculate average. Finally the calculated average is displayed.
How many elements =3 (press Enter)
Enter the elements : 5 10 15(Press Enter)
Average of elements = 10