CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Flow of control in a C program - bounded loops

One of the most powerful features of computers, in general, is to perform thousands, millions, of repetitive tasks quickly

(in fact, one of the motivating first uses of computers in the 1940s was to calculate trigonometric tables for the firing of artillery shells).

C provides its for control statement to loop through a sequence of statements, a block of statements, a known number of times:

The most common form appears below, in which we introduce a loop control variable, i, to count how many times we go through the loop: The loop control variable does not always have to be an integer:

// here, variable i holds the values 1,2,...10

for(int i = 1 ; i <= 10 ; i = i+1) {
// the above introduced a loop-control variable, i
  .....
  printf("loop number %i\n", i);
  .....
// variable i is available down to here
}

// but variable i is not available from here


// here, variable ch holds each lowercase value

for(char ch = 'a' ; ch <= 'z' ; ch = ch+1) {
  .....
  printf("loop using character '%c'\n", ch);
  .....
}




Notice that in both cases, above, we have introduced new variables, here i and ch, to specifically control the loop.

The variables may be used inside each loop, in the statement block, but then "disappear" once the block is finished (after its bottom curly bracket).

It's also possible to use any other variable as the loop control variable, even if defined outside of the for loop. In general, we'll try to avoid this practice - unless the value of the variable is required outside of the loop.

 


CITS2002 Systems Programming, Lecture 2, p12, 24th July 2024.