lec1300_part5

lec1300_part5 - while HES1300 C Programming Lecture Notes...

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

View Full Document Right Arrow Icon
Swinburne University of Technology 1 HES1300 C Programming Lecture Notes – Part 5 Swinburne University of Technology while s The first of the looping keywords is while(). While will repeat a statement (or a compound statement) repetitively, until its conditional part is FALSE. s Commonly, a counter is used to tell the computer when to stop. For example, to repeat the block 5 times, the following while form is used: int i=0; /* It is OK to initialise a variable when it is declared */ while(i < 5) { /* Do something */ i = i + 1; } Swinburne University of Technology for s The for() statement is a more advanced looping function. It provides a convenient way to describe all of the control elements of the loop in a concise format. s The format is as follows: for( ( initialise counter) ; (condition); (increment)) { } Swinburne University of Technology for Example: int i; for(i=0;i<5;i++) { /* Do something */ } Swinburne University of Technology do s The do statement is like while(), but is up side down. Instead of testing for the condition at the top, it does so at the bottom. This is handy when you always want the loop to execute at least once. Example: do { printf(“Hello!\n”); } while (++i > 0); Note that if there is only one line in the statement, the braces are not needed. Swinburne University of Technology Nesting Loops s Loops can be nested to any depth the programmer requires. It is important to note, however, that loops that are too complex will be both difficult to follow, and very hard to read.
Background image of page 1

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

View Full DocumentRight Arrow Icon
Swinburne University of Technology 2 Swinburne University of Technology Nesting Loops Example: int cLevel1=0,cLevel2=0,cLevel3=0; while(cLevel1++ <3) { printf(“c”); while(cLevel2++ <3) { printf(“b”); while(cLevel3++ <3) printf(“a”); } } The code above wil produce the fol owing output: cbaaabbcc Swinburne University of Technology goto s The goto statement enables the program to jump to any predefined position in the program, and continue
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

lec1300_part5 - while HES1300 C Programming Lecture Notes...

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

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