Download presentation
Presentation is loading. Please wait.
Published byKelley Rhoda Waters Modified over 9 years ago
1
CGS 3460 Program looping n Why we need loop lMake code concise for repetitive processes n When to use loop lRun a block of code repetitively lProcess multiple data using same procedure n How to use loop lfor lwhile ldo
2
CGS 3460 for loop n Format: for( init_expression; loop_condition; loop_expression ) { program statement; } n Flow: Condition satisfied? No Initial Expression Yes Program statement loop expression
3
CGS 3460 while loop n Format while (loop_condition) { program statement; } n Flow Condition satisfied? Program statement Yes No
4
CGS 3460 for loop vs while loop Condition satisfied? No Initial Expression Yes Program statement loop expression Condition satisfied? Program statement Yes No for loopwhile loop
5
CGS 3460 Convert for loop to while loop while (loop_condition) { program statement; } for( init_expression; loop_condition; loop_expression ) { program statement; } program statement; loop_expression; init_expression; while(loop_condition) { }
6
CGS 3460 Convert for to while – Example F = 1; N = 10; for(M=1; M<=N; M=M +1) { F = F * M; } init_expression; while(loop_condition) { program statement; loop_expression; } F = 1; N = 10; M = 1; while(M<=N) { } F = F * M; M = M +1;
7
CGS 3460 do-while loop n Format do { program statement } while (loop_condition); Condition satisfied? Program statement Yes No
8
CGS 3460 while and do-while loop n In while loop, program statement may never be evaluated. While in do-while loop, it is evaluated at least once Condition satisfied? Program statement Yes No while (loop_condition) { program statement; } do { program statement } while (loop_condition); Condition satisfied? Program statement Yes No
9
CGS 3460 Example p = 7; c = 1; p = 1; do { p = p + c; c++; } while( c<= 3 ); Code 2 c = 1; p = 1; while( c <= 3 ) { p = p + c; c++; } Code 1
10
CGS 3460 Example p = 1;p = 6; c = 5; p = 1; do { p = p + c; c++; } while( c<= 3 ); Code 2 c = 5; p = 1; while( c<= 3 ) { p = p + c; c++; } Code 1
11
CGS 3460 break n Used to break out of a loop immediately lPossibly due to detection of an error int i; for(i=0; i < 3; i++) { printf(“here\n”); break; printf(“there\n”); } here
12
CGS 3460 continue n Used to continue at the next point lPossibly due to detection of an error int i = 0; for(i=0; i < 3; i++) { printf(“here\n”); continue; printf(“there\n”); } here
13
CGS 3460 Example – summation of valid scores count = 0; n = 10; sum = 0; while (count < n) { scanf("%d", &score); if (score 100) continue; count++; sum = sum + score; }
14
CGS 3460 Example – summation of valid scores count = 0; n = 10; sum = 0; while (count < n) { scanf("%d", &score); if (score 100) { printf(“Wrong data. Exiting program\n”); break; } count++; sum = sum + score; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.