while loop in C

Previous
Next

While loop:

  • “while” is a keyword.
  • “while loop” execute a block of instructions repeatedly as long as the specified condition is valid.
  • We need to specify the condition as argument
#include<stdio.h>
int main()
{
	while(1)
	{
		printf("Loop \n");
	}
	return 0;
}

Output: “Loop” statement executes infinite times as we specified true(1) as condition directly.

#include<stdio.h>
int main()
{
	short int x=1;  
	while(x)
	{
		printf("x value : %d\n", x);
		++x;
	}
	return 0;
}

Output: 1, 2, 3, …, 32767, -32768, -32767, …., -3, -2, -1

Program to print 1 to 10 numbers:

#include<stdio.h>
int main()
{
	int x=1;  
	while(x<=10)
	{
		printf("x value : %d\n", x);
		++x;
	}
	return 0;
}

Print values in given range:

#include<stdio.h>
int main()
{
	int n, i;
	printf("Enter n value : ");
	scanf("%d", &n);
	
	i=1;
	while(i<=n)
	{
		printf("%d \n", i);
		++i;
	}
	return 0;
}

Print even numbers in the given range:

#include<stdio.h>
int main()
{
	int n, i;
	printf("Enter n value : ");
	scanf("%d", &n);
	
	i=1;
	while(i<=n)
	{
		if(i%2==0)
		{
			printf("%d \n", i);
		}
		++i;
	}
	return 0;
}
Previous
Next

Add Comment

Courses Enquiry Form