Oct 8, 2013

C++ program to find the sum and average of given numbers using for loop

Unknown | 10:19 AM |
The for loop is the most commonly used statement in C++. This loop consists of three expressions. The first expression is used to initialize the index value, the second to check whether or not the loop is to be continued again and the third to change the index value for further iteration.
                         
Sometimes, the operations carried out by the while loop can also be done by using the for loop.
However, it is the programmer who has to decide which loop to be used in a given situation.

The syntax of the for loop is:
for (expression_1; expression_2; expression_3)
statement;
Now I am going to tell you a C++ program using the for loop. This program to find the sum and average of given numbers. The C++ program code is following bellow




// A program to find the sum and average of given numbers
#include <iostream.h>
void main (void)
{
int n;
cout <<"How many numbers ?\n";
cin >>n;
float sum = 0;
float a;
for (int i = 0; i <= n-1; ++i) {
cout <<"Enter a number \n";
cin >>a;
sum = sum+a;
}
float av;
av = sum/n;
cout <<"sum = " << sum << endl;
cout <<" Average = " << av << endl;
}
Output the above program

How many numbers ?
4
Enter a number
3
Enter a number
2
Enter a number
1
Enter a number
4
sum = 10
Average = 2.5

3 comments:

  1. When I'm trying to Run this program there is an Error occurs
    undefined symbol 'end1'
    My qstn is from where u got end1 and why u use it ???

    ReplyDelete
    Replies
    1. endl use for closing this line. endl= end line. If you have any error please avoid to use it. you can run this program without endl.

      Thanks for your comment

      Delete
    2. using namespace std; this line is missing that's why problem

      Delete

Twitter Delicious Facebook Digg Stumbleupon Favorites More

Search