for loop:
- One of the control statements that enables repetitive
operations is the for loop. This is a control statement that repeats a given
number of times. The structure is as follows.
for ('initial expression'; 'conditional expression'; 'incremental
expression')
{
'Repeat sentences'
}
'Repeat sentences'
}
-
First, the conditional expression is determined with the
initial expression. At this time, if the condition of the conditional
expression is not satisfied, the for loop is terminated.
-
If the condition is satisfied, it executes the iteration
statement and increases or decreases the loop counter variables according to
the increment / decrement expression.
- Then, it judges whether the condition of the conditional expression is
satisfied again.
- If the condition is satisfied, repeat execution statement and repeat the
above process.
- If the condition of the conditional expression is not satisfied, the for loop
is terminated.
Example Code
#include
<iostream>
using
namespace std;
int
main() {
for(int i = 0; i < 4; i++){
cout<<" i = "<< i
<< endl;
}
return 0;
}
results:
i
= 0
i
= 1
i
= 2
i
= 3
(1)
The initial expression defines an integer variable 'i' (loop
counter variable) and assigns 0 to 'i'. 0 is assigned to 'i', and this value is
used as the initial value.
(2)
The condition of conditional expression 'i < 4' is
judged. 'i' is assigned 0 and thus 'i < 4' is satisfied. Thus the iteration
statement is executed. (print "i = 0")
(3)
Next, perform increment expression (i++) and increment
the value of 'i' (loop counter variable) to 1. As a result, 'i' is assigned 1.
(4)
Go back to the conditional expression to judge the
condition. 1 is assigned to 'i' and satisfies the condition of 'i < 4', so a
statement of "i = 1" is printed by executing the iteration statement.
(5)
This process is repeated until the condition is false. When 'i' is 4 or more,
'i < 4' is not satisfied, so the sentence is repeated until i = 3 finally.
Example Code
#include
<iostream>
using
namespace std;
int
main() {
int num;
cout << "Enter a natural number
! : ";
cin >> num;
cout << endl;
for(int i = 1; i < 10; i++){
cout<< num << " *
"<< i << " = " << num*i << endl;
}
return 0;
}
-
The integer variable 'num' was defined. Then,
the value input through 'cin' is assigned to the variable 'num'.
- The
for loop was written so that 'i' (loop counter variable) is repeated from 1 to
9.
-
When you run it, you will see a prompt to enter a natural number. For example,
if you type 5 and press Enter, you get the following results.
results:
Enter
a natural number ! : 5
5
* 1 = 5
5
* 2 = 10
5
* 3 = 15
5
* 4 = 20
5
* 5 = 25
5
* 6 = 30
5
* 7 = 35
5
* 8 = 40
5
* 9 = 45
No comments:
Post a Comment