Looping
Looping is used for repetition execution of
same statement again & again
C are used to execute a block of code several times until the given
condition is true. Whenever we need to execute some statements multiple times,
we need to use a loop statement.
Types of looping
·
for loop
·
while loop
·
do while loop
For loop
A for
loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is −
for ( init; condition; increment/
decrement )
{
statement(s); // body of for loop
}
Here is the flow of control in a 'for'
loop −
·
Where init= This is allows to initialize values for variable to
start loop .
·
Wherecondition = is used to check the
condition If it is condition is true, the body of the loop is executed until
the given condition became false. If condition is false, the body of the for
loop terminate and the flow of control jumps to the next statement just
after the 'for' loop.
·
After the body of the 'for'
loop executes, the flow of control jumps back up to the increment
/ decrement statement.
This statement allows you to increase or decrease the value for variable
initialized at the begins .
Note:
for is also called entry loop
Flowchart
Example c program that print the sum of natural number from 1 to 10
#include<stdio.h>
void main()
{
inti, sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
printf(“ sum of N natural num,ber from 1 to 10 is %d”, sum);
}
output
sum of N natural num,ber from 1 to 10 is 55
Example 2
#include <stdio.h>
int main () {
int a;
/* for loop execution */
for( a = 1; a < 5; a++){
printf("value of a: %d\n", a);
}
return 0;
}
Out put
value of a: 1value of a: 2
value of a: 3
value of a: 4
value of a: 5
1 comment:
awesome post presented by you..your writing style is fabulous and keep update with your blogs Data Science online Course
Post a Comment