C while and do.while Loop Loops are used in programming to repeat a specific block of code. In this article, you will learn to create while and do.while loops in C programming. Statements and flow control A simple C statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon (;), and are executed in the same order in which they appear in a program. But programs are not limited to a linear sequence of statements.
A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration.
In C++ we have three types of basic loops: for, while and do-while. In this tutorial we will learn how to use “for loop” in C++.
Syntax of for loopFlow of Execution of the for Loop
As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the control flow, or the flow of execution of the program.
For Loop Dev C++![]()
First step: In for loop, initialization happens first and only once, which means that the initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each loop iteration, if the condition is true then the statements inside for for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
![]() Loop Dev C++
The steps from second to fourth repeats until the loop condition returns false.
Example of a Simple For loop in C++
Here in the loop initialization part I have set the value of variable i to 1, condition is i<=6 and on each loop iteration the value of i increments by 1.
Output:
Infinite for loop in C++
A loop is said to be infinite when it executes repeatedly and never stops. This usually happens by mistake. When you set the condition in for loop in such a way that it never return false, it becomes infinite loop.
For example:
This is an infinite loop as we are incrementing the value of i so it would always satisfy the condition i>=1, the condition would never return false. Antares autotune torrent for mac. Dev c c compiler free download mac.
Here is another example of infinite for loop:
Example: display elements of array using for loop
Output:
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
December 2020
Categories |