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
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.
+ 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.