Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit


Computing for Engineers

Lecture 3

Loops in the C programming language


1. Introduction

So far all of our programs have been extremely simple. They have just been a series of C program lines involving I/O and variable definition/declaration        executed one after the other, in sequence.

In this lecture, we will write more sophisticated C programs in which program control (the order in which program lines are executed) is not just a simple      sequence.

There are two main ways of achieving and they are through:

Iteration

Selection

Iteration repeatedly executes a number of C program lines until some          condition is met – these are referred to as “loops”, and we will study these further in this lecture.

Selection chooses which set of program lines to execute depending on the          result of some conditional statement. This enables programs to make decisions about program flow. We will look at selection in lecture 4.

2.for loops

The basic format for the for statement is:

for (start condition; continue condition; re-evaluation)

program statements;

As an example, the following program simply loops 10 times and prints out the integers 1..10 :

This gives:

1 2 3 4 5 6 7 8 9 10

Thefor statement therefore has three parts:

The start initialisation   (count=1)

o This is the initialisation made at the start of the loop.

The continue condition   (count<=10)

o If this condition is true at the end of the loop section, then the loop will continue.

o If the condition is false (i.e. 11), then the loop will terminate.

The re-evaluation – usually a counter (count++)

o This is any C statement which is executed before the continue condition is checked. Normally the commonest operation is to increment the loop variable by one.

Looking at the program step-by-step:

The program declares an integer variable count which is initialized to 1 in the loop statement.

Thefor loop continues whilst the condition count <= 10 evaluates as TRUE.

Since the variable count has been initialized to 1, this condition is TRUE and so the printf() statement is executed.

Next, the remaining statement, count++, of the for loop is executed and the variable count is incremented, now becoming 2.

Control now passes back to the conditional test count <= 10 which still evaluates as TRUE since count now equals 2. Hence the printf() statement is once again executed.

This sequence is repeated 10 times. When count has reached the value   10 (and the 10th printf() has been executed), count is again incremented in the for loop so that its value becomes 11. Now the statement count<=10 evaluates as FALSE and the for loop terminates.

Program control passes to the statement immediately following the for loop and the newline character is printed. The program terminates.

The following program simply loops 10 times and prints out the integers from   10 down to 1. Note carefully how the continue condition has to change so that the loop stops at 1. Also the i++ statement now needs to become i--.

program output:

10 9 8 7 6 5 4 3 2 1

In the next example A…E are printed instead of numbers. Note that this

program shows that, even though the variable letter is declared as a char, it can still be incremented as it is stored internally in ASCII which is a number  between 1 and 127.

Example to print out letters instead of numbers:

#include

int main(void)

{

char letter;

for (letter=’A’; letter <= ‘E’; letter++)

printf("%c ", letter);

printf("\n");

return 0;

}

program output:

A B C D E

with two loop variables:

#include

int main(void)

{

int total, loop;

for (total = 0, loop = 1; loop<=10;

total=total+loop;

loop++)

printf("Total = %d\n",total); return 0;

}

program output :

Total = 55

The next example of a for loop demonstrates that more than a single              statement may be repeatedly executed in which case they must be enclosed inside  { … } brackets:

#include

int main(void)

{

int x, total=0;

for (x=1; x<=6; x++)

{

printf("The current value is %d\n", x); total += x;

}

printf("The total of all the values is %d", total);

return 0;

}

Example: we now want to count upwards in steps of 10 instead of 1, starting at 5. We can use the “+=” operator (lecture 2):

#include

int main(void)

{

int count;

for (count=5; count<=105; count+=10)

printf("%d ",count);

printf("\n");

return 0;

}

This gives:

5 15 25 35 45 55 65 75 85 95 105

Finally in this section let’s look at what happens if we use the less than             operator (<) instead of <= in our condition. This is very commonly done when using arrays (lecture 5). The effect is that the loop stops one before the final

value:

This gives

0 1 2 3 4 5 6 7 8 9

i.e. the loop stops one before 10.

If count is actually equal to 10, the continue condition (count <10) is false, the loop terminates and the value of 10 cannot be printed.

3. The while loop

The while statement provides a mechanism for repeating C statements whilst a condition is true. The format of the while loop is:

while (condition)

program statement;

The while condition behaves exactly like the conditon in a for loop. If the          condition is true, the loop continues. If the condition is false, the loop               terminates, and the program moves onto the next statement after the end of the loop.

Somewhere in the body of the while loop, a statement must alter the value of the condition to allow the loop to finish. The example below shows how a while loop can iterate a fixed number of times. Obviously, this code could         equally well be implemented using a for loop.

#include

int main(void)

{

int loop=1;

while(loop <= 10)

{

printf("%d ", loop);

loop++;

}

printf("\n");

return 0;

}

Sample program output:

1 2 3 4 5 6 7 8 9 10

Thus the program repeats the statements:

printf("%d", loop)

loop++;

whilst the variable loop is less than or equal to 10.

The following points should be noted about using the while loop:

The variable on which the while is dependent (the variable loop in this case) must be initialized prior to the while statement.

The value of the variable loop must be altered within the loop so that eventually the conditional test will succeed (hopefully!) and the while loop will terminate.

It is possible for a while loop not to be entered at all if the test fails          immediately. (Contrast this with the do…while loop described later.)       Thus in the following program, the loop is not entered and therefore no values are printed:

4. The dowhile loop

The do…while loop allows a loop to continue whilst a condition evaluates as TRUE.

The do…while loop must execute at least once - recall that the while loop does not need to execute at all.

The format of the do…while loop is:

do

program statement;

while (condition);

Example: Suppose we want to add up the first n numbers (e.g. 1+2+3;          1+2+3+4;  1+2+3+…n etc.) and we want to find out how many numbers we need to add up in order to get a sum of 1000 or more.

#include

int main(void)

{

int n=0, total=0;

do

{

n++;

total += n;

} while (total<1000);

printf("1+2+…%d adds up to %d", n, total); return 0;

}

Sample program output:

1+2+...45 adds up to 1035

Note this loop has to execute at least once – unlike the for and while loops.


4.1.     Input validation

Frequently in a C program we need to carry out input validation. This means    that a value entered into a program is checked to see whether whether it         meets certain criteria. For example a number may need to be within a specific range.

A scanf statement should be placed within a do…while loop.

If the user enters an invalid value, then the program will display an error           message, and carry on looping until the user enters a valid value. The program then carries on with the next statement.

In the following program, input validation is performed on an integer called v. If the user enters a value of v less than 100 an error message is displayed, and the loop continues. If the user enters a value of v greater or equal to 100 then the program continues with the next statement.