Loops: Pretest Loops Post Test Loops

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 33

Loops

Pretest loops
post test loops
Pretest loop- first test condition should be
evaluated if it true executes the body of the
loop.-while and for loops
post test loop- first body of the loop is executed
after that condition would be tested.
do-while.
Looping process include 4 steps
1.Loop counter initialization
2. test the condition.
3. execute the body of the loop.
4.increment or decrement the loop counter.
While Statements
 The "while" loop is a generalized looping structure that employs a
variable or expression for testing the ending condition.
 Is a repetition statement that allows an action to be repeated while some
conditions remains true.
 Variables used in the loop control testing must be initialized
 Testing for the termination condition is done at the top of the while() loop

 The body of WHILE statement can be a single statement or compound


statements
Syntax:
Form 1: Simple Statement
while (condition)
statement;
Form 2: Compound Statements
while (condition)
{ s1; s2; s3; …..}
While statement

while is a
reserved word If the condition is true, the
statement is executed.
while ( condition ) Then the condition is
statement; evaluated again.

The statement (or a block of statements) is executed


repetitively until the condition becomes false.
Tips on while loop
1. Statements within the while loop would keep on executed until the condition
becomes false. Then the control passes to the first statement after the while loop.
2. Condition may be any valid expression
while(i<=0)
while(i>=10&&j<=15)
3. The statement within the loop may be single or block of statements. Parantheses are
optional.
while(x<=10)
x=x+1;
while(x<=10)
{
x=x+1;
}
both are same.
4. Condition must eventually become false.otherwise the loop would be executed
forever indefinitely.
main()
{
int i=1;
while(i<=10)
printf(“%d”, i);
}
correct answer
main()
{
int i=1;
while(i<=10)
printf(“%d”, i);
i=i+1;
}
5. Loop counter can also decremented to execute the body of the
loop repeatedly.
main()
{
int x=10;
while(x>=1)
{
printf(“%d\n”,x);
x=x-1;
}//while
}//main
6. Loop counter can also be float need not be in int.
main()
{
float x=2.0;
while(x<=2.5)
{
printf(“%f\n”,x);
x=x+0.1;
}//while
}//main
What is the output of the following program.
main()
{
int x=1;
while(x<=32767)
{
printf(“%d\n”,x);
x=x+1;
}//while
}//main
No, it doesn’t print numbers from 1 to 32767
goes to indefinite loop.

main()
{
int x=1;
while(x<=10);
{
printf(“%d”, i);
i=i+1;
}//while
}//main
Program to compute y=xpow n
main()
{
int i=1,n,x,y=1;
printf(“enter the value of x:”);
scanf(“%d”,&x);
printf(“enter the n value”);
scanf(“%d”,&n);
while(i<=n)
{
y=x*y;
i++;
}//while
printf(“the result=%d”,y);
}//main
Nesting of while loops
 While loops within the other while loop.
Write a program to generate the given format
using while loops
1
2 3
4 5 6
7 8 9 10
main()
{
int n,i=1,j=1,k=1;
printf(“\n enter the n value”);
scanf(“%d”, &n);
while(i<=n)
{
while(j<=i)
{
printf(“%d \t”,k);
j++;
k++;
}//while j
j=1;
i++;
printf(“\n”);
}//while I
getch();
}//main
The “do while” statement

Statements in the loop are executed


first (at least once, and condition is
tested last

Loop is controlled by a condition or


counter

Syntax
do {
statement;
statement;
} while (condition);
statement;
While example
#include <stdio.h>
Do-while example
int main() #include <stdio.h>
{ Void main()
int i = 1, sum = 0; {
int result = 1;
int x = 5;
while ( i<= 10) { do {
sum = sum + i; result *= x;
x = x-1;
i = i + 1; } while (x > 1);
} printf(“Factorial of 5=%d”,result);
printf(“Sum = %d\n”, sum); }
return 0;
}
Program to reverse a number
main()
{
int n,x,y=0;
printf(“enter the number”);
scanf(“%d”, &n);
do
{
x=n%10;
y=(y*10)+x;
n=n/10;
}while (n>0);
printf(“\n the reverse number is %d”,y);
getch();
}//main
The “for” Loop
When the number of passes
through a loop is known in
advance, a for statement is often
used
for (expr1; expr2; expr3)
statement;
expr1 controls the looping action,
expr2 represents a condition that
ensures loop continuation, expr3
modifies the value of the control
variable initially assigned by expr1
When a for statement is executed, expr2 is evaluated and
tested at the beginning of each pass through the loop. expr3 is
evaluated at the end of each pass
If the loop continuation condition is initially false, the body part
of the loop is not performed
Any of the three parts can be omitted, but the semicolons must
be kept
keyword
final value of control variable
control variable i for which the condition is true

for (i=1; i <= n; i = i + 1)

initial value increment of control variable


of control loop continuation
variable condition

Examples
Vary the control variable from 1 to 100 in increments of 1
for (i = 1; i <= 100; i++)
Vary the control variable from 100 to 1 in increments of -1
for (i = 100; i >= 1; i--)
Vary the control variable from 5 to 55 in increments of 5
for (i = 5; i <= 55; i+=5)
Few points on for loop
1. Counter variable is initialized only once when the
for statement is executed for the first time.
2. The condition is tested. If it is true the body of the
loop is executed.
3. When it reaches to the closed braces, the control is
send back to the for statement, where the value of
the variable gets incremented or decremented
4. Again the test is performed, if true it enters into the
next iteration.
5. The body of the loop executed repeatedly until the
condition becomes false.
Few points on for loop
6. initialization, testing and increment part of a loop can be replaced by any
valid expression.
ex:
for(x=10;x;x--)
for(i<4;j=5;j=0)
for(scanf(“%d”,&x);x<=10;x++)
program to print numbers from 1 to 10
main()
{
int x;
for(x=1;x<=10;x++)
printf(“%d\n”, x);
}//main
Few tips on for loop
7. We can omit any part of the for statement but we need to keep semicolons
int I;
for(i=1;i<=10)
{
printf(“%d\n”,i);
i=i+1;
}//for

int i=1;
for(;i<=10;i++)
printf(“%d\n”,i);

int i=1;
for(;i<=10;)
{
printf(“%d\n”,i);
i++;
}
int i;
for(i=0;i++<10;)
printf(“%d\n”,i);
Nested for loops
Nested means there is a loop within a loop
Executed from the inside out
 Each loop is like a layer and has its own counter variable, its own loop

expression and its own loop body


 In a nested loop, for each value of the outermost counter variable, the

complete inner loop will be executed until it satisfies its condition.

General form
Most compilers
for (loop1_exprs) {
allow 15 nesting
loop_body_1a
levels – DON’T
DO IT!!
for (loop2_exprs) {
loop_body_2
}
loop_body_1b
}
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i=1,j=1;
clrscr();
printf(“enter n value\n);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
printf(“ “);
for(j=1;j<=I;j++)
printf(“%d”,i);
printf(“\n”);
}//for I
return 0;
Getch();
}//main
Output
enter the n value
1
2 2
3 3 3
4 4 4 4
Multiple initialization of for loop
* The initialization part of the for loop can have more than one
variable initialization separated by a comma.
ex:
for(i=0,j=0;j<=10;j++)

• In incrementation part also we can use use multiple variables


to be incremented.
ex:
for(i=0,j=0;j<=10;i++,j++)
* Only one expression is allowed in the test expression.
Program to find whether the number
is prime or not
#include<stdio.h>
#include<conio.h>
int main()
{
int n,i,counter=1;
clrscr();
printf(“enter the number\n”);
scanf(“%d”,&n);
for(i=1;i<n;i++)
{
if(n%i==0)
{
counter=counter+1;
}
}//for
if(counter==2)
printf(“%d is a prime munber\n”);
else
printf(“%d is not a prime number\n);
return 0;
getch();
}//main
Break statement
-When you want to jump out of the loop
instantly use keyword break
- When a break is used inside the loop, control

automatically passes to the statement which


immediately follows the loop.e
Write a program to whether a given
main()
number is prime or not
{
int n,i=2;
printf(“enter the number\n”);
scanf(“%d”, &n);
while(i<=n-1)
{
if(n%i==0)
{
printf(“the number is not a prime number”);
break;
}
i++;
}//while
if(i==n)
printf(“the number is prime number\n”);
}//main
GOTO statement
Used to alter the sequence of program execution by transferring control
(jump) to some other parts of the program.
Main()
• The goto statement in C allows
the transfer of control from one {
position to another position in the ...
same program. If (. . . ) goto End;
The goto statement
• The destination must be marked
allows one to jump
with a label.
... from any place to
anywhere else within a
• The general syntax:
function.
End:
label: statement;

•The syntax for goto: ...

goto label; }
- Using goto we can move from forward to backward and vice-
versa
example
int i=0,total=0;
sum:
total=toatal+i;
i++;
if(i<=10)
goto sum;
printf(“sum of the first 10 numbers is %d”, sum);
Continue statement
- To take the control to the beginning of the loop, by skipping
some statements inside the loop.
- use keyword continue
ex:-
int i=1,j=0;
While(i<=5)
{
i++;
if(i==3)
continue;
j++;
}//while
BREAK and CONTINUE
- break; causes an exit from the innermost loop or switch.
terminate : for, while, do while, and switch

- continue; causes the current iteration of a loop to stop


and the next iteration to begin immediately.
effective only in : for, while and do while
Continue Example
Break Example
. . . . . .
.....
for (i = 0; i < TOTAL; ++i) {
while (1) {
c = getchar();
scanf("%f", &x);
if ( '0'<=c && c <='9')
if (x < 0.0)
continue;
break;
....... /* process other
/* exit loop if the value is
character */
negative */
printf("\n%f", sqrt(x));
/* continue transfers control to
....
here
}
to begin next iteration */
/* break jumps to here */
}

You might also like