Powered by Blogger.

Text Widget

Featured

Recent Post

Follow

Popular Posts

Featured

Pages

Subscribe

Kamu Pasti Tertarik

Most Popular
Videos

MoreBaru diupdate

Gallery

story

Thursday, 7 January 2016

while and do-while

How are you doing? Today i am going to discuss some questions regarding while and do-while loops.

First think about this question... What is a loop? When i need to printf "hello world", i will use the statement,
printf("hello world");

When I need to printf "hello world" for 2 times, i will write the above code twice. But when i need to print it for 100 times? So, we make use of loops. Loops are used for executing block of statements for multiple times. The main usage of loop is that they reduce the code size.
As we have seen already about the for loops, we will just move on now to while and do while loops. This is a very common question which was asked in many interviews... "What is the difference between while and do-while?". We have seen in the if-statement that when the given condition is true, then the particular block gets executed. Otherwise the else block gets executed. 

while

The while block is similar to that of the if-statement, i.e., the condition is evaluated first and if it is true then the loop body gets executed. After the execution of the loop  body, the condition in while is evaluated again. This repeats until the condition becomes false.

Example:

#include <stdio.h>

void main()

{

int x=0;

while(x<20)
{
printf("\n The value of x is %d",x);
x++;
}
}

Output:

The value of x is 0The value of x is 1The value of x is 2The value of x is 3The value of x is 4The value of x is 5The value of x is 6The value of x is 7The value of x is 8The value of x is 9The value of x is 10The value of x is 11The value of x is 12The value of x is 13The value of x is 14The value of x is 15The value of x is 16The value of x is 17The value of x is 18The value of x is 19

do while

This loop is similar to the while loop but it differs in the way that this loop executes the block of statements at least once irrespective of the condition.

Example:

#include <stdio.h>

void main()

{

int x=0;

do
{
printf("\n The value of x is %d",x);
x++;
}while(x>2);
}

Output:

The value of x is 0

Tags: Difference between while and do-while, example for while loop, do-while loop examples,

Copy Article URL:

No comments:

Post a Comment

Template By Way2Themes | Some Rights Reserved.