Program Looping EE 2372 Software Design I Dr










- Slides: 10
Program Looping EE 2372 Software Design I Dr. Gerardo Rosiles
Program Looping • Looping programming elements are one of the most powerful feature in programming languages. • Consider writing program to sum 10 numbers… easy • Consider writing a program to sum 1, 000 numbers => one million sums … • Looping constructs make this easy • In C-language we have three types of loops: – for loops – while loops – do loops
for loops • Similar to the MATLAB for loops • Syntax for (init_expression, loop_condition, loop_expression) program statement • Syntax with block of statements for (init_expression, loop_condition, loop_expression) { program statements }
for loops • init expression – set any initial values before the loop begins. Typically initializes a variable to control the loop condition. • loop condition(s) – a condition that continues the loop as long as it evaluated to TRUE. • loop expression(s) – evaluated each time after the body of the loop is executed. Typically involved a variable controlling the loop.
for loops - example #include <stdio. h> int main(void) { int n, number, triangular. Number; printf( “What triangular number do you want? “); scanf (“ %i “, &number); printf( “TABLE OF TRIANGULAR NUMBERS nn”); printf(“ n Sum from 1 to n n”); printf(“---------n”); triangular. Number = 0; for( n = 1; n<=number; ++n) { triangular. Number += n; printf(“ %i %i n”, n, triangular. Number); } return(0); }
Some variants • Nested for loops for( n = 1; n<=number; ++n) { sum = 0; for ( m = number; m >= n; m--) { sum = sum + m; printf(“ sum %d to %d = %d n”, n, number, sum); } } • Multiple expressions, for( i=0, j=100; i < 10; ++i, j=j-10)
Some variants • Omitting fields for( ; ; ){. . } // infinite loop for( ; j!= 0 ; j++ ){. . . } • Declaring variables for( int i; i <= 10 ; i++ ){. . . } i is a local variable and can’t be accessed outside of the loop. Disappears after the loop finished.
while loops • Syntax while( expression ) { program statements } • Equivalency with for loops init_expression; while (loop_condition) { program statements loop_expression; } • while statements are useful when there is not a predetermined number of times the loop needs to be executed.
do-while loops • Syntax: do{ program statements } while( expression ); • do-while loops are a transpositions of while loops. • However, do-while loops ensure the program statement is executed at least once.
Loop interruption statements • In some situations it may be desirable to stop the loop or to finish early the current iteration of the loop. • break – can finish the execution of a loop before the loop condition is not satisfied. • continue – finishes early the current iteration of the loop if some specific condition arises. Otherwise the loop continues executing.