Categories: C

while loop examples in c

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

Share
Published by
Rabecca Fatima

Recent Posts

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 days ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago