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

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago