DEV Community

221910303043
221910303043

Posted on

Loops in C

WHAT ARE LOOPS?
The computer has an ability to perform a set of instructions repeatedly . This involves repeating some portion of the program a specific number of times or infinite times until the basic condition is satisfied. These kind of repetitive structures or statements are called loops.

METHODS IN LOOPS
1.For statement
2.While statement
3.Do-While statement

  1. WHILE LOOPS: A while loop in C programming repeatedly executes a target statement as long as a given condition is true Until the given condition is true, while loop in repeatedly executes a target statement. When the condition becomes false, the program control passes to the line immediately following the loop

SYNTAX OF WHILE LOOP:

// while(condition) {
statement(s);
}
1.Statement(s): may a block of statements.
2.Condition: can be any expression.
EXAMPLE:

// Print numbers from 1 to 5

include

int main()
{
int i = 1;

while (i <= 5)
{
    printf("%d\n", i);
    ++i;
}

return 0;
Enter fullscreen mode Exit fullscreen mode

}

FOR LOOP:
Used in repetition control structure.
Used when a loop that needs to execute a specific number of times.

SYNTAX OF FOR LOOP:

// for ( initialization; condition; increment ) {
statement(s);
}
FLOW OF CONTROL IN FORLOOP:

1.INITIALIZATION:
It is the first step to be executed and it can be executed only
once.
Initialization allows you to declare and initialize any loop
control variables.
2.CONDITION:
Condition is the second step in ‘for’ loop where it can be
evaluated.
3.INCREMENT:
Increment is the third step after condition . Flow of control
jumps back to the increment statement after the body of ‘for’
loop executes.
Loop control variables can be updated using this statement.
This statement can also be left blank.
EXAMPLE:
// Print numbers from 1 to 10

include

int main() {
int i;

for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}

DO-WHILE LOOP:
The Do-While loop is similar to the while loop with one important difference. The body of do-while loop is executed at least once. Only then, the test expression is evaluated.

SYNTAX OF DO-WHILE :
do
{
// statements inside the body of the loop
}
while (testExpression);
EXAMPLE:
// Program to add numbers until the user enters zero

include

int main()
{
double number, sum = 0;

// the body of the loop is executed at least once
do
{
    printf("Enter a number: ");
    scanf("%lf", &number);
    sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
Enter fullscreen mode Exit fullscreen mode

}

The major difference between While and do-while :

WHILE
1.It tests the condition before executing any of the statements
within the while loop.

2.It doesn’t execute its statements if the condition fails for the
first time.

DO - WHILE
1.It tests the condition after having the executed the statements
with in the loops.

2.It executes the statements at least once, even if the condition
fails.

Top comments (0)