for Loop in c++:
In C++, for circle is a passage controlled circle that is utilized to execute a block of code over and over for the predefined scope of values. Fundamentally, for circle permits you to rehash a bunch of directions for a particular number of cycles.
For circle is by and large liked over while and do-while circles on the off chance that the quantity of emphasess is known in advance.
Syntax of for Loop
The syntax of for loop in C++ is shown below:
for ( initialization; test condition; updation)
{
// body of for loop
}
C++ for Loop Syntax Breakdown
The various parts of the for loop are:
1. Instatement Articulation in for Circle:
We need to instate the circle variable to some esteem in this articulation.
2. Test Condition in for Circle:
In this articulation, we need to test the condition. On the off chance that the condition assesses to valid, we will execute the body of the circle and go to the update articulation. If not, we will exit from the for circle.
3. Update Articulation in for Circle:
Subsequent to executing the circle body, this articulation increases/decrements the circle variable by some worth.
Flowchart of for Loop in C++:
- Control falls into the for circle. Introduction is finished.
- The stream leaps to Condition.
- Condition is tried.
- Assuming the Condition yields valid, the stream goes into the Body.
- Assuming the Condition yields bogus, the stream goes outside the circle.
- The assertions inside the body of the circle get executed.
- The stream goes to the update.
- Updation happens and the stream goes to Stage 3 once more.
- The for circle has finished and the stream has headed outside.
Examples of for Loop in C++:
Example 1:
The below example demonstrates the use of a for loop in a C++ program.
- C++
1 2 3 4 5
Explanation:
The above program uses a for loop to print numbers from 1 to n (here n=5). The loop variable i iterates from 1 to n and in each iteration condition is checked (is i<=n i.e i<=5 ), if true then it prints the value of i followed by a space and increment i. When the condition is false loop terminates.
Example 2:
Example to demonstrate the use of a for loop in a C++ program for printing numbers from n to 1 (i.e. reverse).
- C++
Explanation:
The above program uses a for loop to print numbers from n to 1 (here n=5) the loop variable i iterates from n to 1 and in each iteration condition is checked (is i>=1) if true then it prints the value of i followed by a space and decrement i. When the condition is false loop terminates.
So we can conclude that no matter what the updation is, as long as the condition is satisfied, for loop will keep executing.
Note: Scope of the loop variables that are declared in the initialization section is limited to the for loop block.you also study more loops by clicking on the following links: 1.while-loop 2.do-whlie loop
No comments:
Post a Comment