What do you mean by looping? Explain while loop with suitable example. Compare while loop with do-while loop. Write a program to find sum and average of first n natural numbers.

This answer is restricted. Please login to view the answer of this question.

Login Now

Loop may be defined as a block of the statement which is repeatedly executed for a certain number of times or until a particular condition is satisfied. When an identical task is to be performed for a number of times, then the loop is used.

The syntax of while loop is:

while(test condition)
{
    //body of loop
}

User Loaded Image | CSIT GuideThe test condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body once, the test-condition is again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test-condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop.

Example:

#include <stdio.h>

int main(){
   int i=1;
   while(i<=10){
      printf("The value of a = %d", i);
      i++;
   }
}

The output of the above program is:

The value of a = 1
The value of a = 2
The value of a = 3
The value of a = 4
The value of a = 5
The value of a = 6
The value of a = 7
The value of a = 8
The value of a = 9
The value of a = 10

The comparison between while loop and do-while loop are

While Loop Do While Loop
The statement is executed after the condition is checked. The statement is executed at least once, then after the condition is checked.
The statement is executed zero times if the condition is fast at first. At least once, the Statement is executed.
There is no semi-column at the end of the while loop. The is a semi-column at the end of the while loop.
If there is a simple statement, Brackets are not required. Brackets are required for all conditions.
While loop is entry controlled loop. Do while loop is exit controlled loop.

 

The program to find sum and average of first n natural numbers is

#include <stdio.h>

int main(){

    int a, i = 0, sum = 0;
    float average;
    
    printf("How many numbers?\n");
    scanf("%d", &a);

    for(int i = 1; i <= a; i++){
        sum += i;
    }

    average = sum / a;

    printf("\nSum = %d", sum);
    printf("\nAverage = %0.2f", average);

}

The output of above program is

How many numbers? 
10 

Sum = 55 
Average = 5.00

Content Source: https://codehelppro.com/detail/c-programming/while-loop/

If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .