I have trouble with the (for)loop please if anyone can help write some examples and explain how it works (int's value)after(for) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I have trouble with the (for)loop please if anyone can help write some examples and explain how it works (int's value)after(for)

how does the integer's value change after the( for) loop

10th Feb 2017, 7:01 PM
Sultan
Sultan - avatar
2 Answers
+ 13
int i, n, factorial = 1; for (i = 1; i <= n; ++i) { factorial = factorial * i; } 1) Initially, i is equal to 1, test expression is true, factorial becomes 1. 2) i is updated to 2, test expression is true, factorial becomes 2. 3) i is updated to 3, test expression is true, factorial becomes 6. 4) i is updated to 4, test expression is true, factorial becomes 24. 5) i is updated to 5, test expression is true, factorial becomes 120. 6) i is updated to 6, test expression is false, for loop is terminated.
10th Feb 2017, 7:18 PM
Elena Puzic
Elena Puzic - avatar
+ 2
The “for loop” loops from one number to another number and increases by a specified value each time. The “for loop” uses the following structure: for (Start value; end condition; increase value) statement(s); Look at the example below: #include<iostream> using namespace std; int main() { int i; for (i = 0; i < 10; i++) { cout << "Hello" << "\n"; cout << "There" << "\n"; } return 0; } Note: A single instruction can be placed behind the “for loop” without the curly brackets. Lets look at the “for loop” from the example: We first start by setting the variable i to 0. This is where we start to count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must be increased by one (i++). In the example we used i++ which is the same as using i = i + 1. This is called incrementing. The instruction i++ adds 1 to i. If you want to subtract 1 from i you can use i–. It is also possible to use ++i or -i. The difference is is that with ++i the one is added before the “for loop” tests if i < 10. With i++ the one is added after the test i < 10.
10th Feb 2017, 7:18 PM
sai kumar
sai kumar - avatar