12 lec 12 loop

Preview:

DESCRIPTION

Loop while,do while loop, for loop

Citation preview

Introducing to LoopsIntroducing to Loops

GoalsGoals

By the end of this unit, you should By the end of this unit, you should understand …understand …

• … … basic loop concepts, including basic loop concepts, including pretest & posttest loops, loop pretest & posttest loops, loop initialization ,condition and initialization ,condition and increment. increment.

• … … how to program a while loop.how to program a while loop.• … … how to program a do-while loop.how to program a do-while loop.• … … how to program a for loops.how to program a for loops.

What is a loop?What is a loop?

• A A loop loop is a programming structure that is a programming structure that allows an action to repeat until the allows an action to repeat until the program meets a given condition.program meets a given condition.

• After each After each iterationiteration of a loop, the loop of a loop, the loop checks against a checks against a loop control expressionloop control expression to see if the program met the given to see if the program met the given condition. If it did, the loop stops. If not, condition. If it did, the loop stops. If not, the loop moves on to the next iteration.the loop moves on to the next iteration.

Types of LoopsTypes of Loops

• C supports two categories of C supports two categories of loops, based on where the loops, based on where the program tests the condition:program tests the condition:– Pretest LoopsPretest Loops– Post-test LoopsPost-test Loops

Pretest LoopsPretest Loops

• With each iteration, the program tests the With each iteration, the program tests the condition first before executing the loop’s condition first before executing the loop’s block.block.

• If the condition results to If the condition results to truetrue, the loop , the loop continues and executes the block; if the continues and executes the block; if the condition results to condition results to falsefalse, the loop , the loop terminates.terminates.

• With a pretest loop, there is a chance the With a pretest loop, there is a chance the loop may never execute once in the program.loop may never execute once in the program.

Post-Test LoopsPost-Test Loops

• With each iteration, the program With each iteration, the program executes the loop’s block first and tests executes the loop’s block first and tests against a condition.against a condition.

• If the condition tests to If the condition tests to truetrue, the loop , the loop continues and executes another continues and executes another iteration; if the condition tests to iteration; if the condition tests to falsefalse, , the loop terminates.the loop terminates.

• With a post-test loop, the loop will With a post-test loop, the loop will always execute at least once!always execute at least once!

Pretest vs. Post-Test LoopsPretest vs. Post-Test Loops

from Figure 6-2 in Forouzan & Gilberg, p. 305

Variable InitializationVariable Initialization

• int i=5;int i=5;• I have initialized the variable i with a value i=5;I have initialized the variable i with a value i=5;

Updating a LoopUpdating a Loop

• A loop update is what happens inside a A loop update is what happens inside a loop’s block that eventually causes the loop’s block that eventually causes the loop to satisfy the condition, thus ending loop to satisfy the condition, thus ending the loop.the loop.

• Updating happens during each loop Updating happens during each loop iteration.iteration.

• Without a loop update, the loop would be Without a loop update, the loop would be an infinite loop.an infinite loop.

Initialization & UpdatingInitialization & Updating

Loop Comparison Loop Comparison

from Table 6-1 in Forouzan & Gilberg, p. 308

C Implementation of LoopsC Implementation of Loops

• Pretest LoopsPretest Loops– whilewhile Loop Loop– forfor Loop Loop

• Post-test LoopPost-test Loop– do … whiledo … while loop loop

• All loops in C execute so long as a All loops in C execute so long as a condition evaluates to condition evaluates to truetrue and terminate and terminate when the condition evaluates to when the condition evaluates to falsefalse..

The The while while LoopLoop

from Figure 6-11 in Forouzan & Gilberg, p. 311

Example of while loopExample of while loop#include<stdio.h>#include<stdio.h>

#include<conio.h> #include<conio.h>

int main() int main()

{ {

int start, end; int start, end;

scanf("%d",&end); scanf("%d",&end);

start = 0;start = 0;

while ( start < end) while ( start < end)

{ {

start++; start++;

printf("%d\n", start);printf("%d\n", start);

} }

return 0;return 0;

}}

If we input value of end as 10 then output will be 1 to 10

ExampleExample#include<stdio.h> #include<stdio.h>

int main()int main()

{ int i; { int i;

i = 0; i = 0;

while(i++ < 5) while(i++ < 5)

{ printf("%d\n", i); { printf("%d\n", i);

} }

printf("\n");printf("\n");

i = 0; i = 0;

while(++i < 5)while(++i < 5)

{ printf("%d\n", i); } { printf("%d\n", i); }

return 0; } return 0; }

The output of the postfix and prefix increment example will look like this: 1 2 3 4 5

1 2 3 4

The The for for LoopLoop

• A A forfor loop is a pretest loop that includes three loop is a pretest loop that includes three expressions in its header:expressions in its header:– Loop initialization statementLoop initialization statement– Limit test expression(condition)Limit test expression(condition)– Loop update statementLoop update statement

• The for loop is often used as a start-controlled The for loop is often used as a start-controlled loop since we can accurately predict the loop since we can accurately predict the maximum number of iterations.maximum number of iterations.

The The forfor Loop Loop

Comparing Comparing whilewhile with with forfor

Comparing Comparing whilewhile with with forfor

i = 1;i = 1;

sum =0;sum =0;

while (i <= 20)while (i <= 20)

{{

scanf(“%d”, &a);scanf(“%d”, &a);

sum = sum+a;sum = sum+a;

i++i++

}//end while}//end while

sum = 0;sum = 0;

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

{{

scanf(“%d”, &a);scanf(“%d”, &a);

sum = sum+a;sum = sum+a;

}//end for}//end for

The while Loop The for Loop

Example of for loopExample of for loopmain ( )main ( )

{{

int p, n, count ;int p, n, count ;

float r, si ;float r, si ;

for ( count = 1 ; count <= 3 ; count = count + 1 )for ( count = 1 ; count <= 3 ; count = count + 1 )

{{

printf ( "Enter values of p, n, and r " ) ;printf ( "Enter values of p, n, and r " ) ;

scanf ( "%d %d %f", &p, &n, &r ) ;scanf ( "%d %d %f", &p, &n, &r ) ;

si = (p * n * r) / 100 ;si = (p * n * r) / 100 ;

printf ( "Simple Interest = Rs.%f\n", si ) ;printf ( "Simple Interest = Rs.%f\n", si ) ;

}}

}}

ExampleExample#include <stdio.h>#include <stdio.h>

  #include<conio.h>#include<conio.h>

void main()void main()

{{

        int i = 0, j = 8;int i = 0, j = 8;

        printf("Times 8 Table\n");printf("Times 8 Table\n");

        for(i = 0; i <= 12; i = i + 1)for(i = 0; i <= 12; i = i + 1)

        {{

      printf("%d x %d = %d\n", i, j, j*i);printf("%d x %d = %d\n", i, j, j*i);        }}

        printf("\n");printf("\n");

}}

Nested Nested for for LoopsLoops

• We can nest any statement, even We can nest any statement, even another another forfor loop, inside the body of loop, inside the body of a parent a parent forfor loop. loop.

• When we nest a child When we nest a child forfor loop, it loop, it iterates all of it’s cycles for each iterates all of it’s cycles for each iteration of the parent.iteration of the parent.

Example of nested for loopExample of nested for loop• /* Demonstration of nested loops *//* Demonstration of nested loops */

main( )main( )

{{

int r, c, sum ;int r, c, sum ;

for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */

{{

for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */

{{

sum = r + c ;sum = r + c ;

printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;

}}

}}

}}

When you run this program you will get the following output:r = 1 c = 1 sum = 2r = 1 c = 2 sum = 3r = 2 c = 1 sum = 3r = 2 c = 2 sum = 4r = 3 c = 1 sum = 4r = 3 c = 2 sum = 5

The The do … whiledo … while Loop Loop

• C implements a post-test loop using a C implements a post-test loop using a structure called a structure called a do … whiledo … while loop. loop.

• In the In the do … whiledo … while, the loop begins with , the loop begins with the keyword the keyword dodo, followed by the body, , followed by the body, followed by the keyword followed by the keyword whilewhile and the and the loop expression. loop expression.

• A semi-colon (A semi-colon (;;) follows the loop ) follows the loop expression.expression.

The The do … whiledo … while Loop Loop

Example of do-whileExample of do-while/* Execution of a loop an unknown number of time*//* Execution of a loop an unknown number of time*/

main( )main( )

{{

char another ;char another ;

int num ;int num ;

dodo

{{

printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;

printf ( "square of %d is %d", num, num * num ) ;printf ( "square of %d is %d", num, num * num ) ;

printf ( "\nWant to enter another number y/n " ) ;printf ( "\nWant to enter another number y/n " ) ;

scanf ( " %c", &another ) ;scanf ( " %c", &another ) ;

} while ( another == 'y' ) ;}} while ( another == 'y' ) ;}

Output:Enter a number 5square of 5 is 25Want to enter another number y/n yEnter a number 7square of 7 is 49Want to enter another number y/n n

Same using for loopSame using for loop/* odd loop using a for loop *//* odd loop using a for loop */

main( )main( )

{{

char another = 'y' ;char another = 'y' ;

int num ;int num ;

for ( ; another == 'y' ; )for ( ; another == 'y' ; )

{{

printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;

printf ( "square of %d is %d", num, num * num ) ;printf ( "square of %d is %d", num, num * num ) ;

printf ( "\nWant to enter another number y/n " ) ;printf ( "\nWant to enter another number y/n " ) ;

scanf ( " %c", &another ) ;scanf ( " %c", &another ) ;

}}}}

Same using while loopSame using while loop/* odd loop using a while loop *//* odd loop using a while loop */

main( )main( )

{{

char another = 'y' ;char another = 'y' ;

int num ;int num ;

while ( another == 'y' )while ( another == 'y' )

{{

printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;

printf ( "square of %d is %d", num, num * num ) ;printf ( "square of %d is %d", num, num * num ) ;

printf ( "\nWant to enter another number y/n " ) ;printf ( "\nWant to enter another number y/n " ) ;

scanf ( " %c", &another ) ;scanf ( " %c", &another ) ;

}}}}

Comparing Comparing do … whiledo … while with with whilewhile

The The breakbreak Statement in Loops Statement in Loops

• We often come across situations where we want We often come across situations where we want to jump out of a loop instantly, without waiting to to jump out of a loop instantly, without waiting to get back to the conditional test.get back to the conditional test.

• The keyword The keyword break allows us to do this. break allows us to do this. • When break is When break is encountered inside any loop, encountered inside any loop,

control automatically passes to the first control automatically passes to the first statement after the loop.statement after the loop.

Example of breakExample of break• Write a program to determine whether a number is Write a program to determine whether a number is

prime or not. A prime number is one, which is prime or not. A prime number is one, which is divisible only by 1 or itself.divisible only by 1 or itself.

• All we have to do to test whether a number is prime or All we have to do to test whether a number is prime or not, is to divide it successively by all numbers from 2 to not, is to divide it successively by all numbers from 2 to one less than itself.one less than itself.

• If remainder of any of these divisions is zero, the number If remainder of any of these divisions is zero, the number is not a prime. If no division yields a zero then the is not a prime. If no division yields a zero then the number is a prime number.number is a prime number.

ExampleExamplemain( )main( )

{int num, i ;{int num, i ;

printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;

i = 2 ;i = 2 ;

while ( i <= num - 1 )while ( i <= num - 1 )

{if ( num % i == 0 ){if ( num % i == 0 )

{{

printf ( "Not a prime number" ) ;printf ( "Not a prime number" ) ;

break ;break ;

}}

i++ ;i++ ;

} if ( i == num )} if ( i == num )

printf ( "Prime number" ) ;printf ( "Prime number" ) ;

}}

ExampleExample

The keyword The keyword breakbreak breaks the breaks the control only control only from the while in from the while in which it is placed.which it is placed.

main( ){int i = 1 , j = 1 ;while ( i++ <= 100 ){while ( j++ <= 200 ){if ( j == 150 )break ;elseprintf ( "%d %d\n", i, j ) ;}}}

The The continuecontinue Statement Statement

• In some programming situations we want to take In some programming situations we want to take the control to the beginning of the loop, the control to the beginning of the loop, bypassing the statements inside the loop,bypassing the statements inside the loop,

which have not yet been executed. The keyword which have not yet been executed. The keyword continue allows continue allows us to do this.us to do this.

• When When continue is encountered inside any continue is encountered inside any loop, loop, control automatically passes to the control automatically passes to the beginning of the loop.beginning of the loop.

Example of continue statementExample of continue statementmain( )main( )

{{

int i, j ;int i, j ;

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

{{

for ( j = 1 ; j <= 2 ; j++ )for ( j = 1 ; j <= 2 ; j++ )

{{

if ( i == j )if ( i == j )

continue ;continue ;

printf ( "\n%d %d\n", i, j ) ;printf ( "\n%d %d\n", i, j ) ;

}}

}}

}}

The output of the above program would be...1 22 1