What is looping?types of loops.

What is looping?

Looping is a control structure used for repeating the execution of statements for multiple times when the specified condition is true. It is also called as iteration or repetitive statement. It contains initialization, condition, execution statement and update (increment or decrement). There are three types of loops in C programming:

 

C programming has three types of loops.

  1. for loop
  2. while loop
  3. 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.

Example:

#include <stdio.h>

 

int main () {

 

int a;

 

/* for loop execution */

for( a = 10; a < 20; a = a + 1 ){

printf(“value of a: %d\n”, a);

}

 

return 0;

}

Output

  • value of a: 10
  • value of a: 11
  • value of a: 12
  • value of a: 13
  • value of a: 14
  • value of a: 15
  • value of a: 16
  • value of a: 17
  • value of a: 18
  • value of a: 19

 

 

 

While loop

  • The while loop evaluates the test expression inside the parenthesis ().
  • If the test expression is true, statements inside the body of while loop are executed. Then, the test expression is evaluated again.
  • The process goes on until the test expression is evaluated to false.
  • If the test expression is false, the loop terminates (ends).

 

While loop Example:

 

// Print numbers from 1 to 5

 

#include <stdio.h>

int main()

{

int i = 1;

 

while (i <= 5)

{

printf(“%d\n”, i);

++i;

}

 

 

 

return 0;

}

Output: 1 2 3 4 5

 

Do…while loop

  • The body of do…while loop is executed once. Only then, the test expression is evaluated.
  • If the test expression is true, the body of the loop is executed again and the test expression is evaluated.
  • This process goes on until the test expression becomes false.
  • If the test expression is false, the loop ends.

 

do…while loop

// Program to add numbers until the user enters zero

 

#include <stdio.h>

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;

}

 OUTPUT

Enter a number: 1.5

Enter a number: 2.4

Enter a number: -3.4

Enter a number: 4.2

Enter a number: 0

Sum = 4.70

 

 

C programming language provides the following types of loops.

Sr.No. Loop Type & Description
1 while loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3 do…while loop

It is more like a while statement, except that it tests the condition at the end of the loop body.

Please follow and like us:

Leave a Reply

Your email address will not be published.