C while loop

What is while loop?

In this tutorial, you will learn about while loop and its working. Firstly, As we all know that the loop will help to execute the program for the specified number of times or until it satisfies the particular condition. The common steps in looping always include setting and initialization of counter. After that, we will perform the testing step where we will test the specified condition. When the given condition satisfies we will go to the body of the loop. Finally, we will either increment or decrement the pointer in order to update the pointer. Using the while loop, we will enter into the body of code when the given condition is true.

How does the while loop work?

Following is the syntax which will make you understand the working of the while loop.

Syntax:
initialization,
while(condition)
{
the body of the loop
Increment or Decrement
}

Following the flowchart for the while loop.
Flowchart:

Example of while loop:

//To print whether the given number is an armstrong or not.
#include<stdio.h>
int main(){
	int n,r,sum=0, temp;
	printf("Enter the number: ");
	scanf("%d",&n);
	temp=n;
	while(n>0){
		r=n%10;
		sum=sum+r*r*r;
		n=n/10;
	}
	if(temp==sum)
	printf("%d is an Armstrong number.",temp);
	else
	printf("%d is not an Armstrong", temp);
}

The above code will find whether the given number is an Armstrong number or not.  An Armstrong number is the numbers where the sum of cubes of its digits is equal to the number itself. The output of the above code will be displayed as:

Output:

Enter the number: 153
153 is an Armstrong number.
Things to remember:
  • While loop checks the condition at first
  • This loop is used to carry out the looping operation at first until the condition satisfies.
  • It is also known as entry controlled loop.
SHARE C while loop

You may also like...

Leave a Reply

Your email address will not be published.

Share