Looping control structures are used to execute a block of code multiple times until a condition is met. It is extremely important that the condition is met at some point in the loop, or you get what is known as an endless loop - one that never stops without killing the program.
Three basic loop structures are:
All loops have three basic parts:
A pre-test loop is one in which the condition is tested before the code block is executed. This means that the code block may never be executed.
A post-test loop is one in which the condition is tested after the code block is executed. This means that the code block will always execute at least once.
The steps that take place in a pre-test loop are:
The steps that take place in a post-test loop are:
The for Loop
Identify the three basic parts in the loops below initialize, test, increment/decrement
for ( int i=0; i<10; i++ ); for ( int i=0; <n; i++ ) x += i; // this loop will calculate the triangle value of n for ( int i=1; i=<n; i++ ) { // why start the loop at 1? x += i; // triangle value of n y *= i; // factorial value of n }The while Loop
Identify the three basic parts in the loops below initialize, test, increment/decrement
int i = 0; while ( i<10 ) i++; int i = 0; while ( i<n ) i++; int i = 1; // why start the loop at 1? while ( i=<n ) { x += i; // triangle value of n y *= i; // factorial value of n i++; }The do while Loop
Identify the three basic parts in the loops below initialize, test, increment/decrement
int i = 0; do { x += i; // this loop will calculate the triangle value of n i++; } while ( i<n );