This presentation includes custom animations. To view the animations, you must view the presentation in Slide Show mode and activeX controls must be allowed. If you have opened this lesson in PowerPoint, use the PowerPoint menus to view it in slide show mode. If you have opened this lesson in a browser and see a bar similar to that below, click on the Slide Show icon A notice similar to the one below may appear warning that ActiveX or other scripts are disabled. Enable the controls for this website in order to see the animations.
do while Loops This slide show illustrates the order of execution of a do while loop. Christine S. Wolfe Ohio University Lancaster 2008-Aug-01 Vocabulary: do while *affect the condition (of the loop) initialization (of the loop) loop body loop repetition condition
In a do while loop: a set of instructions is executed at least once and is repeated as long as a condition is true.
body of the loop the test affect the test initialize the test } while (ThisVote != ‘Q’); { do ©Christine S. Wolfe printf(“Vote for your favorite of the following TV shows”); printf(“\n\nA – Lost”); printf(“\nB – The Office”); printf(“\nC – Dancing with the Stars”); printf("\nEnter your vote as A, B, or C: ”); fflush(stdin); scanf(“\n%c”, &ThisVote); printf(“Vote for your favorite of the following TV shows”); printf(“\n\nA – Lost”); printf(“\nB – The Office”); printf(“\nC – Dancing with the Stars”); printf("\nEnter your vote as A, B, or C: ”); fflush(stdin); scanf(“\n%c”, &ThisVote); switch(ThisVote) { case ‘A’: ++TotalVotesA; break; case ‘B’: ++TotalVotesB; break; case ‘C’: ++TotalVotesC; break; default: printf(“\n Invalid response: “); getchar(); } notice that the body is executed once BEFORE even reaching the test!
X = 1; { Y = X * 2; } x < 3 ++X; X = 1; { Y = X * 2; } ++X; do while ( ) x < 3 while ( ) ; while X = 1; { Y = X * 2; } ++X; x < 3 Like ALL loops, a do while loop can be written as a while loop. The opposite is NOT true. It is NOT true that all while loops can be rewritten as do while loops – at least not elegantly.
X = 1; { Y = X * 2; } X = 1; { Y = X * 2; } ++X; do while ( ) x < 3 while ( ) ; ++X; X < 3 XY Ending Values X 3 Y 4 XY Ending Values X 3 Y 4
INIT BLOCK includes while loop WHILE TEST AFFECT INIT BLOCK includes do while loop WHILE TEST AFFECT T F F T do