13_pdfsam_lecture2 - Loops Any loop can be written with a...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Loops Any loop can be written with a while, do-while, or for loop Usually one type of loop is more natural E.g. the following three are equivalent i=0; while(i<N) { ssprintf(%d\n, i); ssi++; } for(i=0; i<N; i++) { ssprintf(%d\n, i); } i=0; do { ssif(i < N) { ssprintf(%d\n, i); ssi++; ss} } while(i < N); Loops Any loop can be written with a while, do-while, or for loop Usually one type of loop is more natural E.g. the following three are equivalent int n; do { ssprintf(enter a number:); ssn = read_int(); } while(n <= 0); int n; printf(enter a number:); n = read_int(); while(n <= 0) { ssprintf(enter a number:); ssn = read_int(); } int n; printf(enter a number:); for(n = read_int(); n <= 0 ; n = read_int()){ ssprintf(enter a number:); } break and continue A break inside a loop causes the loop to terminate immediately int n = 10; while( 1 ) { ssif(n == 0) break; ssn--; } A continue statement causes the loop to immediately begin executing the next iteration int n; for(n=0; n < 10; n++) { ssif(n == 0) continue; ssprintf(%d\n, n); } Common pitfalls What do these code fragments do? int i; for(i=0; i<10; i++); ssprintf(%d\n, i); int i=1; while( i = 1 ) { ssprintf(%d\n, i); 11111 (innite loop) ssi = 3; } Reserved words in C We've already covered half of the language! break case char default else continue double extern goto long short struct union while oat if register unsigned sizeof switch static typedef void for int return enum do More on printf Syntax: printf(format_string, val1, val2, . . . ); format_string can include placeholders that specify how the arguments val1, val2, etc. should be formatted %c : format as a character %d : format as an integer %f : format as a oating-point number %% : print a % character int i = 90; float f = 3.0; printf(%d roads\n, 42); printf(i = %d%%, f = %f\n, i, f); 42 roads i = 90%, f = 3.000000 ...
View Full Document

Page1 / 6

13_pdfsam_lecture2 - Loops Any loop can be written with a...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online