Using for

I'm a beginner. I don't quite understand about loop especially about statement for. And how do we using for to get the output e.g : 1+2+3+4+5=15
I wish your help.
When you know the number of iterations to solve the problem, you should use for loops, using a loop for you can get 1,2,3,4,5 values for a variable, and then use it to perform some operation like a sum -in your exercise-;

for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//LoopFor.cpp

#include <iostream>
using std::cout;
using std::endl;


int main(){


// for statement header includes initialization         
// loop-continuation condition and increment     
for(int i=1;i<=5;i++){ //initial value is 1; final value: 5; increment is: 1
        cout<<i <<' '; //output 1,2,3,4,5 -value of i variable- and 1 blank space
                             //between each number.
}//end loop for

cout<<endl; //start a new line of output

return 0; //indicates success
}//end main 


Output:

1 2 3 4 5
Last edited on
Topic archived. No new replies allowed.