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 numbersOutput the above program
#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;
}
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
When I'm trying to Run this program there is an Error occurs
ReplyDeleteundefined symbol 'end1'
My qstn is from where u got end1 and why u use it ???
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.
DeleteThanks for your comment
using namespace std; this line is missing that's why problem
Delete