lecture07-feb3

# lecture07-feb3 - Announcements Lecture 7 Assignment 2 due...

This preview shows pages 1–3. Sign up to view the full content.

2/3/10 1 Announcements Lecture 7 • Assignment 2, due next Thurs. – questions?? • Tip: #include <stdlib.h> . . . system (“cls”); /* clear the screen */ • Read Chapters 7 (7.3*) now, 8 for next week Exam 1 – Friday, Feb. 19 th (in class) • finish looping (Ch.6) – while, for, do • more details on basic data types (ch.7) – More on numerics char data type – Type conversions – Type casting (explicit) For loop The for statement has the form for ( expression1 ; expression2 ; expression3 ) statement The following code has the equivalent semantics of the above for statement: expression1; while ( expression2 ) { statements expression3 ; } For example, the for statement for ( i = 10; i > 0; i-- ) { printf("T minus %d and counting\n", i); } Any or all of the three expressions in a for statement may be omitted – Omitting the middle expression creates an infinite loop. Useful for counter controlled loops for Loop Semantics Initialize counter variable check the condition T F Perform the statement(s) in the loop body Adjust the counter variable loop exit expression1 expression2 expression3 for Loop examples /* print out the even numbers from 2 to 100 */ int i; for (i = 2; i<=100; i = i + 2) { printf (“i is = %d\n”, i); } /* print out the squares from 1 to 100 and sum them (squares) all up and print out the sum */ int i, sum = 0; for (i = 1; i <= 100; i++) { printf (“i squared is = %d\n”, i * i); sum = sum + i * i; } printf (“sum of squares is = %d\n”,sum); How many iterations are performed ? for Loop Semantics for (i = 1; i<=100; i++) { /* loop body in here */ } Initialize counter variable check the condition T F Perform the statement(s) in the loop body Adjust the counter variable i = 1; i++; i <= 100; loop exit What if we need the body of this loop to contain another loop inside of it ? Nested Loop Semantics Initialize counter variable check the condition T F Perform the Adjust the counter variable

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2/3/10 2 Nested Loops • What is the output of the following code? • Can you trace its execution? int i, num; for (i = 1; i <= 5; i++) { for (num = 0; num < i; num++) { printf ( “%d ”, num * 2 + 1); } printf ( “\n”); } Outer loop Inner loop Tracing the Code i 1 2 3 4 5 0,1 0,1, 2 0,1, 2, 3 0,1, 2, 3, 4 0,1, 2, 3, 4, 5 Outer loop Inner loop num * 2 + 1 1 1 3 1 3 5 1 3 5 7 1 3 5 7 9 Values output num What it does Terminal Window Options x - 1 1 3 1 3 5 1 3 5 7 1 3 5 7 9 The break;
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 4

lecture07-feb3 - Announcements Lecture 7 Assignment 2 due...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online