Unit 2 Loop Control Statements LECTURE – 16

Download Report

Transcript Unit 2 Loop Control Statements LECTURE – 16

Loop: A Loop is defined as a block of statements which are
repeatedly executed for certain number of times.
Steps in Loops:
Loop Variable: It is a variable used in the Loop.
Initialization: It is the 1st step in which starting & final value is
assigned to the loop variable. Each time the updated value is
checked by the loop itself.
Increment/Decrement: It is the numerical value added or
subtracted to the variable in each round of the loop.
Basic of Computer & 'c' Programming
1
Syntax of loop:
for (expression-1; expression-2; expression-3)
statement;
While
expression-1;
while (expression-2)
{
statement;
expression-3;
}
do-while
expression-1;
do
{
statement;
expression-3;
}
while (expression-2);
Basic of Computer & 'c' Programming
2
for(initialize
counter;
test
counter;
increment/decrement counter)
The for statements is equivalent to while and dowhile statements. The only difference between for
and while is that the letter cheeks the logical
condition and then executes the body of the loop,
where as in for statements test is always performed
at the beginning of the loop. The body of the loop
may not be executed at all times if the condition
fails at the beginning.
Basic of Computer & 'c' Programming
3
Q. WAP To Print 5 Natural No using while Loop.
#include<stdio.h>
void main()
{
int n;
n=1;
while (n<=5)
{
printf(“ \n Number is %d”,n);
n++;
}}
Basic of Computer & 'c' Programming
4
Q. WAP To Print 5 Natural No using do-while Loop.
#include<stdio.h>
void main()
{
int n;
n=1;
do
{
printf(“ \n Number is %d”,n);
n++;
}
while (n<5);
}
Basic of Computer & 'c' Programming
5
Q. WAP To Print 5 Natural No using for Loop.
#include<stdio.h>
void main()
{
int n;
for(n=1;n<=5;n++)
printf(“ \n Number is %d”,n);
}
Basic of Computer & 'c' Programming
6
Q. WAP To Print Odd & Even No using for Loop.
#include<stdio.h>
void main()
{
int n;
for(n=1;n<=5;n++)
{
if (n%2= = 0)
printf(“ \n Number is Even %d”,n);
else
printf(“ \n Number is Odd %d”,n);
}
}
Basic of Computer & 'c' Programming
7
Thanks
Basic of Computer & 'c' Programming
8