do-while loop

http://install4install.com

The functionality of do-while is slightly different from while and for loop.The condition of do-while is at the bottom of loop and it executes at least once even if the condition is false.The initialization of a variable loop is done before the loop block.

Syntax

do

{

set_of_statements;

}

while(condition);

 

Example 1

Say we need to print  numbers from 0 to 100.

Program 1

#include <stdio.h>

int main()
{
int i = 0;
do
{
	printf("%d\t",i);
	i++;
}
while(i<=100);
	return 0;
}

 

Run

 

Example 2

Say we want to print a table of a user entered number.

Program 2

#include <stdio.h>

int main() 
{
	int num,i=1;
	int tab;
	//printf("Enter the number");
	scanf("%d",&num);
	do
	{
		
		tab = num * i;
		printf("%d * %d = %d\n",num,i,tab);
		i++;
		
		
	}
	while(i<=10);

	return 0;
}

Run

 

Example 3

Say we want to print even numbers and odd numbers from 0-100  separately .

Program 3

#include <stdio.h>

int main()
{
int i=0;
int j=1;
printf("The even mumbers are :\n");
do
{
	printf("%d\t",i);
	i=i+2;
}
while(i<=100);
printf("\nThe odd numbers are :\n");
do
{
	printf("%d\t",j);
	j=j+2;
}
while(j<100);
return 0;
}

 

Run

 

Example 4

Say we want to print series like 30,27,24,21,18,15,12,9,3.

Program 4

#include <stdio.h>

int main() 
{
int i=30;
do
{
	printf("%d\t",i);
	i=i-3;
	
}
while(i>=3);
	return 0;
}

 

Run

 



Short URL: http://tinyit.cc/ec0f9d
Author: Cusp2207 on July 8, 2014
Category: Computer Science
Tags:

Leave a Reply

Last articles