Sie sind auf Seite 1von 35

Introduction to Loops

Goals
By the end of this unit, you should understand basic loop concepts, including pretest & posttest loops, loop initialization & updates, event & start-controlled loops. how to program a while loop. how to program a do-while loop. how to program a for loops.

What is a loop?
A loop is a programming structure that allows an action to repeat until the program meets a given condition. After each iteration of a loop, the loop checks against a loop control expression to see if the program met the given condition. If it did, the loop stops. If not, the loop moves on to the next iteration.

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

Pretest Loops
With each iteration, the program tests the condition first before executing the loops block. If the condition results to true, the loop continues and executes the block; if the condition results to false, the loop terminates. With a pretest loop, there is a chance the loop may never execute once in the program.

Post-Test Loops
With each iteration, the program executes the loops block first and tests against a condition. If the condition tests to true, the loop continues and executes another iteration; if the condition tests to false, the loop terminates. With a post-test loop, the loop will always execute at least once!

Pretest vs. Post-Test Loops

Loop Initialization
Programs typically require some type of preparation before executing loops. Loop initialization, which happens before a loops first iteration, is a way to prepare the loop..

Updating a Loop
A loop update is what happens inside a loops block that eventually causes the loop to satisfy the condition, thus ending the loop. Updating happens during each loop iteration. Without a loop update, the loop would be an infinite loop.

Initialization & Updating

Concept of a start-Controlled Loop

Loop Comparison in a start-Controlled Loop

The while Loop

Example of while loop


#include<stdio.h> #include<conio.h> int main() { int start, end; scanf("%d",&end); start = 0; while ( start < end) { start++; printf("%d\n", start); } return 0; If we input value of end as 10 then output will be 1 to 10

Example
#include<stdio.h> int main() { int i; i = 0; while(i++ < 5) { printf("%d\n", i); } printf("\n"); i = 0; while(++i < 5) { printf("%d\n", i); } 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 for Loop


A for loop is a pretest loop that includes three expressions in its header:
Loop initialization statement Limit test expression Loop update statement

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

The for Loop

Comparing while with for

Comparing while with for


i = 1; sum =0; while (i <= 20) { scanf(%d, &a); sum += a; i++ }//end while sum = 0; for (i = 1; i <= 20; i++) { scanf(%d, &a); sum += a; }//end for

The while Loop

The for Loop

Example of for loop


main ( ) { int p, n, count ; float r, si ; for ( count = 1 ; count <= 3 ; count = count + 1 ) { printf ( "Enter values of p, n, and r " ) ; scanf ( "%d %d %f", &p, &n, &r ) ; si = (p * n * r) / 100 ; printf ( "Simple Interest = Rs.%f\n", si ) ; } }

Example
#include <stdio.h> #include<conio.h> void main() { int i = 0, j = 8; printf("Times 8 Table\n"); for(i = 0; i <= 12; i = i + 1) {

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


} printf("\n"); }

Nested for Loops


We can nest any statement, even another for loop, inside the body of a parent for loop. When we nest a child for loop, it iterates all of its cycles for each iteration of the parent.

Example of nested for loop


/* Demonstration of nested loops */ When you run this main( ) program you will get the following output: { r = 1 c = 1 sum = 2 int r, c, sum ; r = 1 c = 2 sum = 3 r = 2 c = 1 sum = 3 for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */ r = 2 c = 2 sum = 4 r = 3 c = 1 sum = 4 { r = 3 c = 2 sum = 5 for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */ { sum = r + c ; printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ; } } }

The do while Loop


C implements a post-test loop using a structure called a do while loop. In the do while, the loop begins with the keyword do, followed by the body, followed by the keyword while and the loop expression. A semi-colon (;) follows the loop expression.

The do while Loop

Example of do-while
/* Execution of a loop an unknown number of time*/ main( ) { Output: char another ; Enter a number 5 square of 5 is 25 int num ; Want to enter another number y/n y do Enter a number 7 square of 7 is 49 { Want to enter another number y/n n printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; } while ( another == 'y' ) ;}

Same using for loop


/* odd loop using a for loop */ main( ) { char another = 'y' ; int num ; for ( ; another == 'y' ; ) { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ;

Same using while loop


/* odd loop using a while loop */ main( ) { char another = 'y' ; int num ; while ( another == 'y' ) { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; }}

Comparing do while with while

The break Statement in Loops


We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. The keyword break allows us to do this. When break is encountered inside any loop, control automatically passes to the first statement after the loop.

Example of break
Write a program to determine whether a number is prime or not. A prime number is one, which is divisible only by 1 or itself. 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 one less than itself. If remainder of any of these divisions is zero, the number is not a prime. If no division yields a zero then the number is a prime number.

Example
main( ) {int num, i ; printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; i=2; while ( i <= num - 1 ) { If ( num % i == 0 ) { printf ( "Not a prime number" ) ; break ; } i++ ; } if ( i == num ) printf ( "Prime number" ) ;

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

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

The continue Statement


In some programming situations we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The keyword continue allows us to do this. When continue is encountered inside any loop, control automatically passes to the beginning of the loop.

Example of continue statement


main( ) { int i, j ; for ( i = 1 ; i <= 2 ; i++ ) { for ( j = 1 ; j <= 2 ; j++ ) { if ( i == j ) continue ; printf ( "\n%d %d\n", i, j ) ; } } The output of the above program would be... 12 21