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

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

4 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

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

10 months ago

Efficient Order Log Storage

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

11 months ago