Loop in C programming
some time we need a statement to repeat again and again. In general, statements are executed sequentially. The first statement in a function is executed first and second statement is executes after 1st and and so on.
Programming languages provide various structures that allow for more complicated execution paths.
C programming provides the following types of loops.
There are following types of loops in c
- For Loop
- while loop
- do…while loop
1. For Loop
What is a for loop?
A for loop enables a particular set of conditions to be executed repeatedly until a condition is true. In the situation where you would have to print numbers from 1 to 100. What would we do? Will we type in the printf command a hundred times ? This simple task would take an eternity. By Using a ‘for loop’ we can perform this action only in 3 statements. This is the most basic example of the for loop.
Flowchart of for loop
How for loop works?
The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for loop is executed and the update expression is updated.This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
To learn more on test expression (when test expression is evaluated to nonzero (true) and 0 (false)), check out relational and logical operators.
2.while loop
While loop is similar as for loop, but have less functionality. A while loop continues executing the statements as the condition in the while remains true.the example is as follows.
syntax of while loop
The syntax of while loop is as follows.
while(condition) { statement(s); }
Flowchart of while loop.
How while loop works.
in the following above flowchart when the condition is tested and the result is false. The loop body will be skipped and the first statement after the while loop will be executed.if the condition is true then the loop is executed again and again
3.do while loop
The do while loop is similar to the while loop but the body of do while loop is executed once. before testing expression. the do while loop is executed at least once first.
syntax of do while loop
The syntax of do while loop is as follows.
Do { //statement } while(condition true);
Flowchart of do while loop
How do while loop works
In do while loop the first statement is tested if the condition is true then the program is executed otherwise the program is skip and if the condition is true the program is executed again and again until the condition is false.
Leave a Reply