In the previous blog we saw how to print from  N to 1 using a for loop . In this blog we will see how to print from 1 to N integers using a while loop .

What is a Loop?:-

A loop is a programming construct that repeats a block of code until the specified condition is satisfied.

There are three types of loops in C programming:

  1. for loop
  2. while loop
  3. do...while loop
While loop:-
The syntax of the while loop is:

while (testExpression) {
  // the body of the loop 
}

How it works ?

The testExpression inside the parenthesis is evaluated by the while loop ().

If testExpression is true, statements within the while loop's body will be executed. After then, testExpression is evaluated once more.

The procedure continues until testExpression is found to be false.

The loop finishes if testExpression is false (ends).

Code:-

#include<stdio.h>
int main()
{
    int i=1, n;
    printf("Enter a number ");
    scanf("%d",&n);
    while(i!=n+1)
    {
        printf("%d ",i);
        i++;
    }
}

Algorithm:-

1.Start 

2.Declare the two integer variables of type int namely i and n .Initialize the variable i to 1 .

3.Use the scanf statement to get the input of the variable n by using the format specifier "%d" .

4.Run a while loop 
Explanation:-

Run a loop while loop until the condition i is not equal to n+1 .We use this condition because the loop have to print only from 1to n.

5.Print the variable i and increment the value of i by 1 .

6.Stop .

Screenshot:-
1.Code Screenshot:-



2.Output Screenshot:-




In the next blog we will see how to print from N to 1 using a while loop .