Thursday, September 19, 2019

For, While and Do ....While

. 1) What is looping? Describe “for”, “while” and “do-while” loops with appropriate examples.
Answer:
Looping statements or Iterative Statements
'A loop' is a part of code of a program which is executed repeatedly. A loop is used using condition. The repetition is done until condition becomes condition true. A loop declaration and execution can be done in following ways.
• Check condition to start a loop
• Initialize loop with declaring a variable.
• Executing statements inside loop.
• Increment or decrement of value of a variable.
For loop:
This is an entry controlled looping statement. In this loop structure, more than one variable can be initialized. One of the most important feature of this loop is that the three actions can be taken at a time like variable initialization, condition checking and increment/decrement. The “for” loop can be more concise and flexible than that of while and do-while loops.
Syntax:
for(initialisation; test-condition; incre/decre)
{
statements;
} Example:
#include
#include
main()
{
int a;
clrscr();
for(i=1; i<=5; i++)
{
printf("%d\n",i);
}

getch();
}
while loop:
This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true.
Syntax:
while(condition)
{
statements;
increment/decrement;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the loop and executes the block of statements associated with it. At the end of loop increment or decrement is done to change in variable value. This process continues until test condition satisfies.
Example:
#include
#include
main()
{
int a;
clrscr();
a=1;
while(a<=5)
{
printf("\n %d \n",a);
a++;
}
getch();
}

Do-While loop :
This is an exit controlled looping statement. Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
}while(condition);
In above syntax, the first the block of statements are executed. At the end of loop, while statement is executed. If the resultant condition is true then program control goes to evaluate the body of a loop once again. This process continues till condition becomes true. When it becomes false, then the loop terminates.
Example:
#include
#include
 main()
{
int a;
a=5;
do
{
printf("%d\n ",a);
a++;
}while("%d\n",a);

getch();
}

0 comments:

Post a Comment