while loop examples in c

  • March 1, 2022
  • C
Matrix multiplication

Let us look at various examples of the while loop in c.

Printing n numbers:
#include <stdio.h>

int main() {
   int n,sum=0;
   scanf("\n%d",&n);
    int temp=1;
    while(temp<=n)
    {
          printf("%d",temp);
        temp++;
    }
   
    return 0;
}
output:
10
12345678910

Here, we printed n natural numbers by running a while loop till the temp reaches the nth value.

counting digits in a number:
#include <stdio.h>

int main() {
   int n,count=0;
   scanf("\n%d",&n);
    int temp=n;
    while(temp!=0)
    {
        temp=temp/10; 
         count++; 
        
    }
   printf("%d",count);
    return 0;
}
output:
120
3

Here, the number gets divided by 10 repeatedly until the condition becomes false; the count variable gets incremented till the loop runs, which results in the count of digits in a number.

printing reverse of a number:
#include <stdio.h>

int main() {
   int n,count=0;
   scanf("\n%d",&n);
    int temp=n;
    while(temp!=0)
    {
        int r=temp%10; 
        printf("%d",r);
        temp=temp/10;
        
    }
   
    return 0;
}
output:
input:1234
output:4321

this program is similar to the above-given code, the only difference here is that we printed those digits.

printing table of a number:
#include <stdio.h>

int main() {
   int n,count=0;
   scanf("\n%d",&n);
    int temp=1;
    while(temp<=10)
    {
        printf("\n%d",(temp*n));
        temp++;
        
    }
   
    return 0;
}
output:
input:
7
output:
7
14
21
28
35
42
49
56
63
70

Note: also read about  Loops in C & Loops and its examples

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *