What is loop?
In computer programming, a loop is a sequence of
instructions that is continuously repeat until a certain condition is
reached.
There are two types of loops in C Programming:
Entry Controlled loops: In Entry controlled loops the
test condition is checked before entering the main body of the loop. For Loop
and While Loop is Entry-controlled loops.
Exit Controlled loops: In Exit controlled loops
the test condition is evaluated at the end of the loop body. The loop body will
execute at least once, irrespective of whether the condition is true or false.
do-while Loop is Exit Controlled loop.
For Loop
for loop in C programming is a repetition control
structure that allows programmers to write a loop that will be executed a
specific number of times. for loop enables programmers to perform n number of
steps together in a single line.
Syntax:
for (initialize expression; test expression; update
expression)
{
//
// body of for
loop
//
}
Example:
#include <stdio.h>
int main()
{
int i = 0;
for (i = 1; i
<= 10; i++)
{
printf(
"Hello ICSK\n");
}
return 0;
}
Algorithm:
step-1: start the program.
Step-2: set i = 0
step-3: check i <= 10, if true go to step-4, if false go to step-6
step-4: print ICSK
step-5: i++, go to step-3
step-6: stop the program
While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations was previously known to us but in the While loop, the execution is terminated on the basis of the test condition. If the test condition will become false then it will break from the while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
update_expression;
}
Example:
#include <stdio.h>
int main()
{
// Initialization expression
int i = 2;
// Test expression
while(i < 10)
{
// loop body
printf( "Hello ICSK\n");
// update expression
i++;
}
return 0;
}
do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition which is tested at the end of the body. In the do-while loop, the loop body will execute at least once irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;
} while (test_expression);
Example:
#include <stdio.h>
// Driver code
int main()
{
// Initialization expression
int i = 2;
do
{
// loop body
printf( "Hello ICSK\n");
// Update expression
i++;
// Test expression
} while (i < 1);
return 0;
}
Source: https://www.geeksforgeeks.org/c-loops/
No comments:
Post a Comment