Loops in C programming (6th day)
The statements which appear in the source code only once but execute many times, such kind of statements are called loops. Repeated executions of certain statements are popularly known as loops. Almost all the programming languages support looping instructions. In C program while, do wile, for are the looping instructions.For example, consider you want to calculate the sum of 1 to 10 numbers; the program will be like this
In the above program the statement sum=sum+n will execute 10 times. A loop will execute continuously till it satisfy the loop exit condition.
The following processes are included in a loop.
- Declaration of a counter variable or loop control variable.
- Execution of statements inside loop body.
- Evaluating the test conditions.
- Incrementing or decrementing the counter (loop control) variable.
while loop
It is an entry controlled loop, the loop body will execute till the test condition is false. The syntax of while() loop is given below,Example: sum of 1 to 10 numbers
If the test condition is always true, indefinite loop will arise. That is the body will execute without break. This method is used in any embedded C programming. while(1) is commonly used to create indefinite loops. So while(1) is an essential part of any embedded C programming.
do--while loop
This is an exit controlled loop, because the loop body will execute at least once even if the test condition is false.Syntax:
When the program control reaches the do, the body will execute once, it will verify the test condition only after the first execution of loop body.
for loop
It is somewhat efficient entry controlled loop in C program.Syntax:
Execution of for loop:
- We are initializing a counter variable (loop control variable) i=0 or 1, something like that.
- Evaluation of test condition. If the condition is true, to body will execute.
- After the execution, the value of loop control variable is either incremented or decremented, again validates the test condition.
- If the condition is true, to body will execute, and this process will repeat.
- When the test condition fails, the loop terminates.
Ads
0 comments:
Post a Comment