Let us look at various examples of the while loop in c.
#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;
}
10
12345678910
Here, we printed n natural numbers by running a while loop till the temp reaches the nth value.
#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;
}
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.
#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;
}
input:1234
output:4321
this program is similar to the above-given code, the only difference here is that we printed those digits.
#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;
}
input:
7
output:
7
14
21
28
35
42
49
56
63
70
Note: also read about Loops in C & Loops and its examples
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…