Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE Application Programming

Similar presentations


Presentation on theme: "ECE Application Programming"— Presentation transcript:

1 16.216 ECE Application Programming
Instructor: Dr. Michael Geiger Summer 2012 Lecture 5 Loops

2 ECE Application Programming: Lecture 5
Lecture outline Announcements/reminders Program 4 due today Program 5 posted; due Tuesday, 7/31 Exams to be returned during tomorrow’s lecture Will catch up on program grading ASAP Exam 2 next Thursday, 8/2 Today’s lecture: loops While loops Do-while loops For loops Break/continue 1/28/2018 ECE Application Programming: Lecture 5

3 ECE Application Programming: Lecture 5
Repetition Say we have a program to print squares of numbers between 0 and 10: void main() { int i; // Number to square int iSquared; // Square of the number printf(" i i^2\n"); // Column headings // Compute and display the squares of numbers 0 through 10 i = 0; iSquared = i * i; printf("%2d%10d\n", i, iSquared); ... // Code for i = 1, 2, ... 8, 9 i = 10; } 1/28/2018 ECE Application Programming: Lecture 5

4 ECE Application Programming: Lecture 5
while loops Previous program does same thing 11 times Repetitive code can be captured in a loop Much less code to do same amount of work Simplest form: while loop while (<expression>) <statement>  loop body Loop body will repeat as long as <expression> is true Loop body must therefore change expression <statement> may be one or more lines If multiple lines, need { } to denote block 1/28/2018 ECE Application Programming: Lecture 5

5 ECE Application Programming: Lecture 5
while loops - example x = 7; while ( x < 10 ) { printf("%d ",x); x = x + 1; } OUTPUT: 7 8 9 1/28/2018 ECE Application Programming: Lecture 5

6 ECE Application Programming: Lecture 5
while loops - example x = 7; while ( x < 3 ) { printf("%d ",x); x = x + 1; } OUTPUT: (no output) Possible to have while loop body that never executes! 1/28/2018 ECE Application Programming: Lecture 5

7 Repetition with while loop
Rewriting previous program with loop int main() { int i; // Number to square int iSquared; // Square of the number printf(" i i^2\n"); // Column headings // Compute and display the squares of numbers 0 to 10 i = 0; // Initialize i while (i <= 10) { // Loop until i > 10 iSquared = i * i; printf("%2d%10d\n", i, iSquared); i = i + 1; // Increment i } return 0; 1/28/2018 ECE Application Programming: Lecture 5

8 Application: loop with flexible limit
Could determine loop limit based on variable Result of calculation Input value See while2.c for an example Program to calculate average grade First reads # of grades to enter, then list of grades Keeps running sum of all grades entered Calculates average at end Loop: while (gradeCount < numGrades) { scanf("%lf", &grade); // Read grade gradeSum = gradeSum + grade; // Add to sum gradeCount = gradeCount + 1; // Inc. count } 1/28/2018 ECE Application Programming: Lecture 5

9 Application: sentinel value
Common to read input until a certain value(sentinel) is entered May be predetermined (i.e., run program until user enters ‘q’ for “quit”) Run until invalid value entered In file input, will often run until end of file See while3.c for an example Refined version of average grade program Core of program: // Prompt for and read first grade printf("Enter grade: "); scanf("%lf", &grade); /* Continue reading/accumulating grades until invalid value entered */ while ((grade >= 0.0) && (grade <= 100.0)) { gradeSum = gradeSum + grade; // Accumulate grade gradeCount = gradeCount + 1; // Increment grade count printf("Enter grade: "); // Prompt for and scanf("%lf", &grade); // read next grade } 1/28/2018 ECE Application Programming: Lecture 5

10 ECE Application Programming: Lecture 5
do-while loops while loop is pre-tested Check condition at start; if false, don’t enter loop To guarantee at least one iteration, use post-tested loop: do-while Checks condition at end of loop do { <statements> } while ( <expression> ); Don’t forget semicolon! 1/28/2018 ECE Application Programming: Lecture 5

11 While vs. do-while: flowcharts
while: pre-tested loop Check condition, then execute loop body do-while: post-tested loop Execute loop body, then check condition A = 0? Loop body FALSE TRUE A = 0? TRUE Loop body FALSE All loops characterized by conditional test, backwards arrows indicating repetition of code 1/28/2018 ECE Application Programming: Lecture 5

12 comparison while vs do-while
x = 7; do { printf("%d ",x); x = x + 1; } while ( x < 10 ); OUTPUT: 7 8 9 x = 7; while ( x < 10 ) { printf("%d",x); x = x + 1; } OUTPUT: 7 8 9 1/28/2018 ECE Application Programming: Lecture 5

13 comparison while vs do-while
x = 7; do { printf("%d",x); x = x + 1; } while ( x < 3 ); OUTPUT: 7 x = 7; while ( x < 3 ) { printf("%d",x); x = x + 1; } OUTPUT: (no output) 1/28/2018 ECE Application Programming: Lecture 5

14 Application: sentinel value
Core of program demonstrating while loop // Prompt for and read first grade printf("Enter grade: "); scanf("%lf", &grade); /* Continue reading/accumulating grades until invalid value entered */ while ((grade >= 0.0) && (grade <= 100.0)) { gradeSum = gradeSum + grade; // Accumulate grade gradeCount = gradeCount + 1; // Increment grade count printf("Enter grade: "); // Prompt for and scanf("%lf", &grade); // read next grade } 1/28/2018 ECE Application Programming: Lecture 5

15 Application: sentinel value
Rewrite grade average program to ensure at least one grade is read Change core of program (shown previously): /* Prompt for and read grades until invalid value entered */ do { printf("Enter grade: "); // Prompt for and scanf("%lf", &grade); // read grade if ((grade >= 0.0) && (grade <= 100.0)) { gradeSum = gradeSum + grade; // Accumulate grade gradeCount = gradeCount + 1; // Inc. grade count } } while ((grade >= 0.0) && (grade <= 100.0)); 1/28/2018 ECE Application Programming: Lecture 5

16 Example: while/do-while loops
What do each of the following print? int i = 0; while (i < 30) { if ((i % 3) == 0) printf("%d\n", i); i = i + 2; } Assume input is: do { scanf("%d",&x); printf("x = %d, x/2 = %d\n", x, x/2); } while ((x > 2) || (x < 0)); Assume input is: b c d e f g h char c = 'a'; while (c != 'h') { printf("%c", c); scanf("%c", &c); 1/28/2018 ECE Application Programming: Lecture 5

17 ECE Application Programming: Lecture 5
Example solution int i = 0; while (i < 30) { if ((i % 3) == 0) printf(“%d\n”, i); i = i + 2; } Output: 6 12 18 24 1/28/2018 ECE Application Programming: Lecture 5

18 Example solution (cont.)
Assume input is: do { scanf(“%d”,&x); printf(“x = %d, x/2 = %d\n”, x, x/2); } while ((x > 2) || (x < 0)); Output: x = 3, x/2 = 1 x = 8, x/2 = 4 x = -4, x/2 = -2 x = -7, x/2 = -3 x = 0, x/2 = 0 1/28/2018 ECE Application Programming: Lecture 5

19 Example solution (cont.)
Assume input is: b c d e f g h char c = ‘a’; while (c != ‘h’) { printf(“%c”, c); scanf(“%c”, &c); } Output: ab c d e f g 1/28/2018 ECE Application Programming: Lecture 5

20 ECE Application Programming: Lecture 5
Justifying for loops Common loop structure Initialize variable Loop until that variable reaches certain limit At end of each iteration, change variable by fixed amount Example: squares program i = 0; while (i <= 10) { iSquared = i * i; printf("%2d%10d\n", i, iSquared); i = i + 1; } 1/28/2018 ECE Application Programming: Lecture 5

21 ECE Application Programming: Lecture 5
for loops for loops include all three aspects in one construct Form: for (<init var>; <test>; <change var>) <statements> <init var> is basic assignment <test> same type of condition as if, while <change var> change variable by fixed amount Example: for (i = 0; i < 20; i++) … You may be wondering what i++ means 1/28/2018 ECE Application Programming: Lecture 5

22 ECE Application Programming: Lecture 5
Changing variables Can do operation + assignment w/one operator Simply adding/subtracting 1: x++  x = x + 1 (post-increment) x--  x = x – 1 (post-decrement) ++x  x = x + 1 (pre-increment) --x  x = x – 1 (pre-decrement) Augmented assignment: change variable by amount other than 1 x += y  x = x + y x -= y  x = x – y x *= y  x = x * y x /= y  x = x / y 1/28/2018 ECE Application Programming: Lecture 5

23 Pre- vs. post-increment/decrement
Pre-increment/decrement: perform increment/ decrement, then evaluate expression Post-increment/decrement: evaluate expression, then perform increment/decrement Example: what does the following print? int n = 5; printf(“n = %d\n”, ++n); printf(“Now, n = %d\n”, n++); printf(“Finally, n = %d\n”, n); 1/28/2018 ECE Application Programming: Lecture 5

24 ECE Application Programming: Lecture 5
Example soln. int n = 5; printf(“n = %d\n”, ++n); printf(“Now, n = %d\n”, n++); printf(“Finally, n = %d\n”, n); Output: n = 6 (n pre-incremented) Now, n = 6 (n post-incremented) Finally, n = 7 (Shows effect of n++) 1/28/2018 ECE Application Programming: Lecture 5

25 Simple usage of for loop
ECE Intro to Computer Engineering I 03/07/2005 Simple usage of for loop Common sequence of code: x=0; while (x<12) { printf("%d ",x); x++; } Output: 1/28/2018 ECE Application Programming: Lecture 5 (c) 2005, P. H. Viall

26 ECE Application Programming: Lecture 5
Intro to for loops Common sequence of code: x=0; while (x<12) { printf("%d ",x); x++; } Equivalent for construct for (x=0 ; x<12 ; x++ ) { printf("%d ",x); } Initial value Test condition Body of loop (may be 0, 1, or several statements) End of loop change 1/28/2018 ECE Application Programming: Lecture 5

27 Repetition with for loop
Rewriting squares program with loop int main() { int i; // Number to square int iSquared; // Square of the number printf(" i i^2\n"); // Column headings // Compute and display the squares of numbers 0 to 10 for (i = 0; i <= 10; i++) { // Loop until i > 10 iSquared = i * i; printf("%2d%10d\n", i, iSquared); } return 0; 1/28/2018 ECE Application Programming: Lecture 5

28 Repetition with for loop (cont.)
Generalizing program: int main() { int i; // Number to square int iSquared; // Square of the number int iStart; // Initial value int iStop; // Last value int iStep; // Increment printf(“Enter start, stop, and increment: “); scanf(“%d %d %d”, &iStart, &iStop, &iStep); printf(" i i^2\n"); // Column headings // Compute and display the squares of numbers iStart to iStop // with increment iStep for (i = iStart; i <= iStop; i += iStep) { iSquared = i * i; printf("%2d%10d\n", i, iSquared); } return 0; 1/28/2018 ECE Application Programming: Lecture 5

29 ECE Application Programming: Lecture 5
Example: for loops What does each of the following print? for (i=5; i<40; i+=8) { printf("%d ", i); } for (i=10; i<=100; i=i+10) { if (i%20) printf("%d ", i); } for (i=5; i<10; i+=i%2) { printf("%d ", i++); } for (i=-5; i<-10; i--) { printf("%d ", i); } 1/28/2018 ECE Application Programming: Lecture 5

30 ECE Application Programming: Lecture 5
Example solution What does each of the following print? for (i=5; i<40; i+=8) { printf("%d ", i); } OUTPUT: for (i=10; i<=100; i=i+10) { if (i%20) printf("%d ", i); } OUTPUT: for (i=5; i<10; i+=i%2) { printf("%d ", i++); } OUTPUT: 5 6 8 for (i=-5; i<-10; i--) { printf("%d ", i); } OUTPUT: No output 1/28/2018 ECE Application Programming: Lecture 5

31 ECE Application Programming: Lecture 5
Justifying for loops Common loop structure Initialize variable Loop until that variable reaches certain limit At end of each iteration, change variable by fixed amount Example: squares program i = 0; while (i <= 10) { iSquared = i * i; printf("%2d%10d\n", i, iSquared); i = i + 1; } 1/28/2018 ECE Application Programming: Lecture 5

32 ECE Application Programming: Lecture 5
for loops for loops include all three aspects in one construct Form: for (<init var>; <test>; <change var>) <statements> <init var> is basic assignment <test> same type of condition as if, while <change var> change variable by fixed amount Example: for (i = 0; i < 20; i++) … You may be wondering what i++ means 1/28/2018 ECE Application Programming: Lecture 5

33 ECE Application Programming: Lecture 5
Changing variables Can do operation + assignment w/one operator Simply adding/subtracting 1: x++  x = x + 1 (post-increment) x--  x = x – 1 (post-decrement) ++x  x = x + 1 (pre-increment) --x  x = x – 1 (pre-decrement) Augmented assignment: change variable by amount other than 1 x += y  x = x + y x -= y  x = x – y x *= y  x = x * y x /= y  x = x / y 1/28/2018 ECE Application Programming: Lecture 5

34 Pre- vs. post-increment/decrement
Pre-increment/decrement: perform increment/ decrement, then evaluate expression Post-increment/decrement: evaluate expression, then perform increment/decrement Example: what does the following print? int n = 5; printf("n = %d\n", ++n); printf("Now, n = %d\n", n++); printf("Finally, n = %d\n", n); 1/28/2018 ECE Application Programming: Lecture 5

35 ECE Application Programming: Lecture 5
Example soln. int n = 5; printf("n = %d\n", ++n); printf("Now, n = %d\n", n++); printf("Finally, n = %d\n", n); Output: n = 6 (n pre-incremented) Now, n = 6 (n post-incremented) Finally, n = 7 (Shows effect of n++) 1/28/2018 ECE Application Programming: Lecture 5

36 Simple usage of for loop
ECE Intro to Computer Engineering I 03/07/2005 Simple usage of for loop Common sequence of code: x=0; while (x<12) { printf("%d ",x); x++; } Output: 1/28/2018 ECE Application Programming: Lecture 5 (c) 2005, P. H. Viall

37 ECE Application Programming: Lecture 5
Intro to for loops Common sequence of code: x=0; while (x<12) { printf("%d ",x); x++; } Equivalent for construct for (x=0 ; x<12 ; x++ ) { printf("%d ",x); } Initial value Test condition Body of loop (may be 0, 1, or several statements) End of loop change 1/28/2018 ECE Application Programming: Lecture 5

38 Repetition with for loop
Rewriting squares program with loop int main() { int i; // Number to square int iSquared; // Square of the number printf(" i i^2\n"); // Column headings // Compute and display the squares of numbers 0 to 10 for (i = 0; i <= 10; i++) { // Loop until i > 10 iSquared = i * i; printf("%2d%10d\n", i, iSquared); } return 0; 1/28/2018 ECE Application Programming: Lecture 5

39 Repetition with for loop (cont.)
Generalizing program: int main() { int i; // Number to square int iSquared; // Square of the number int iStart; // Initial value int iStop; // Last value int iStep; // Increment printf(“Enter start, stop, and increment: “); scanf(“%d %d %d”, &iStart, &iStop, &iStep); printf(" i i^2\n"); // Column headings // Compute and display the squares of numbers iStart to iStop // with increment iStep for (i = iStart; i <= iStop; i += iStep) { iSquared = i * i; printf("%2d%10d\n", i, iSquared); } return 0; 1/28/2018 ECE Application Programming: Lecture 5

40 ECE Application Programming: Lecture 5
Example: for loops What does each of the following print? for (i=5; i<40; i+=8) { printf("%d ", i); } for (i=10; i<=100; i=i+10) { if (i%20) printf("%d ", i); } for (i=5; i<10; i+=i%2) { printf("%d ", i++); } for (i=-5; i<-10; i--) { printf("%d ", i); } 1/28/2018 ECE Application Programming: Lecture 5

41 ECE Application Programming: Lecture 5
Example solution What does each of the following print? for (i=5; i<40; i+=8) { printf("%d ", i); } OUTPUT: for (i=10; i<=100; i=i+10) { if (i%20) printf("%d ", i); } OUTPUT: for (i=5; i<10; i+=i%2) { printf("%d ", i++); } OUTPUT: 5 6 8 for (i=-5; i<-10; i--) { printf("%d ", i); } OUTPUT: No output 1/28/2018 ECE Application Programming: Lecture 5

42 ECE Application Programming: Lecture 5
Early loop exits May want to Exit loop early Skip rest of loop body but run more iterations Early loop termination: break Stops loop immediately and goes to statement after loop end Skipping loop body: continue Stops current iteration, but will execute following iteration if loop is not done In for loop, statement at end of loop still executed E.g. i++ always executed in: for (i = 0; i < 10; i++) 1/28/2018 ECE Application Programming: Lecture 5

43 ECE Application Programming: Lecture 5
Using break with loops The keyword break will exit a loop immediately Similar to its use with switch/case Modifying grade averaging program: // Prompt for and read grades until invalid value entered do { printf("Enter grade: "); // Prompt for and scanf("%lf", &grade); // read grade if ((grade < 0.0) || (grade > 100.0)) break; // Grade must be valid if you reach this point gradeSum = gradeSum + grade; // Accumulate grade gradeCount = gradeCount + 1; // Inc. grade count } while (1); // Condition is unnecessary // Use “infinite” loop 1/28/2018 ECE Application Programming: Lecture 5

44 Using continue with loops
Want to leave loop body but execute more iterations Use continue—will end loop and then evaluate condition Example: Read and sum 10 non-zero numbers n = 0; sum = 0; while (n < 10) { scanf(“%d”, &i); if (i == 0) continue; sum = sum + i; n++; /* continue jumps to this point */ } 1/28/2018 ECE Application Programming: Lecture 5

45 ECE Application Programming: Lecture 5
Next time PE3 (Loops) Functions Exam 1 Review Reminders Program 4 due today Program 5 due Tuesday, 7/31 Exam 2 Thursday, 8/2 1/28/2018 ECE Application Programming: Lecture 5


Download ppt "ECE Application Programming"

Similar presentations


Ads by Google