|
~ Introduction to Programming: C ~ Session 7 - While Loops |
In This Session...
In this session we will be covering the following topics:-
Last session we covered:-
One of the best things about computers is their ability to perform dull tasks (dull if we did them, anyway) over and over again. For example, take the case of typing out the same letter to a hundred subscribers. A computer gives us the ability to take the list of subscribers and the standard letter, and put the names and addresses into the letter in the appropriate places over and over again. Lots of saved time! If you're wondering, this process is known as mail-merging, and is a standard facility of most Word-Processors (for example, Microsoft Word).
There are lots of other mundane uses for a loop. We will be taking a look at the while loop in C as an example of how to repeat a task a number of times.
The while loop will perform a series of instructions (written in C) over and over again while a condition holds true - it's a bit like the if statement, except the instructions associated with a while statement will happen over and over again instead of just once.
The structure of the while statement is as follows:-
while (condition)
{
block of one or more C statements (instructions);
}
Don't type this out - it is just for illustration, and doesn't actually do anything by itself!
Try the following program as an example of a while loop:-
#include <stdio.h>
#include <conio.h>
main()
{
int i;
printf("Counting\n--------\n\n");
i=1;
while (i<=10)
{
printf("i is %d\n",i);
getch();
i++;
}
printf("All done. Press a key."); getch();
}
When you execute it, press a key after each number. Notice that the number increases by 1 each time, and stops at 10. So how does this work?
If we break down the program into its parts, we can see that:-
i is a variable that holds whole numbers (it is an integer). It is initially set to a value of 1 (one).
The while loop has a condition of (i<=10). This means that the instructions that follow between the { and the } will be repeated while this condition is true. In the condition, the <= symbol means "less than or equal to" so we can read this as "while the contents of variable i are less than or equal to ten". The first time we meet this condition, the value of i is 1, so as 1 is less than 10, the instructions inside the curly brackets (often said as "inside the loop") are executed.
The instructions in the loop display the
contents of the i variable (e.g. i is 1\n) and waits for a key
to be pressed (getch). We then meet a curious looking instruction i++;
This is new to us, and simply means "add 1 to the contents of variable i".
This can also be written as i=i+1 (meaning we take the contents of i,
add 1 to it, and store the results back into i again) - but the i++
form is preferred in C programming.
At this point, the value of i is 2.
When the closing curly brace is reached, the program goes back to the top of the while statement, and tests i again. The contents of i are still less than 10, so the instructions between the curly braces are executed again....
This carries on until i reaches 11. At this point, the test at the top of the while loop checks whether i is less than or equal to 10, and as this is not true, the instructions between the curly braces are not executed. Instead, execution continues after the closing curly brace - i.e. to display the printf("All done. Press a key."); instruction.
Exercise 23 - Counting backwards
Change the program you typed in above to count from 10 down to 1. Do this as follows:-
Set the contents of variable i to be initially 10.
Change the condition to be while (i>=1) or alternatively while (i>0) - the first means "while the contents of variable i are greater than or equal to 1 (one)" whereas the second means "while the contents of variable i are greater than (and not including) zero"
Instead of i++ use i--
This is a shorthand way of subtracting 1 (one) from the contents of
variable i - e.g. if it was 10, then i-- will change i
to contain 9.
Validation is the process of making sure that data is in a form that the computer can use correctly - i.e. making sure the data is valid or acceptable to use.
Validation is an important part of writing computer programs. Every time you accept data into your program from an external source - for example, a user typing data at the keyboard - you should check that the data is in a form that can be used.
A common way of doing this is to use a do while loop which executes the code first, and then checks to see whether a condition is true (for example, that the data entered by the user is okay), and loops around if the condition is not met, for the user to try again.
Exercise 24 - Validating a number range
Try the following program, which asks for a number between 1 and 9, and loops around until a valid number has been entered:-
#include <stdio.h>
#include <conio.h>
main()
{
int num;
do
{
printf("Enter number 1-9: "); scanf("%d",&num);
}
while ((num<1) || (num>9));
printf("You chose %d. Press a key.",num);
getch();
}
Typical output for this might be:-
Enter number 1-9: 10
Enter number 1-9: 0
Enter number 1-9: 15
Enter number 1-9: -5
Enter number 1-9: 3
You chose 3. Press a key._
When you write your validation, it is important to test that it works correctly by trying values that should not work. You can see in this case that the loop continues cycling around until a number between 1 and 9 is pressed (3 in the example). 10 and 0 did not exit the loop, which is good.
We have introduced a new symbol in the while condition - the || symbol. This is two vertical bars next to each other. Read it to mean "or" - in other words, the loop will continue while the number entered is less than 1 or greater than 9. If it is within this range (great than or equal to 1 and less than or equal to 9) then the loop will quit, and the program continues.
Joining conditions using && and ||
As in the example above, you can join two conditions together so that if one condition is true or another condition is true (and you can have any number of these or conditions put together) then the result is true (e.g. in the example above, the loop will go around again). The symbol for joining two conditions together is the || symbol. Be careful to put extra brackets around each of the conditions
You can also say that the condition is true only if more than one condition are all true using the and condition (uses the && symbol).
Exercise 25 - Choosing options - Calculator example.
It is often useful to ask the user (person using your program) to select an option to choose one of a number of different options. In the example below, the user is asked to type a number to decide whether they wish to add, subtract, multiply, or divide a number...
Try the example below, which is a simple calculator program. It asks you for an initial number (which goes into the num1 variable). The user is then asked to choose whether they wish to add, subtract, multiply or divide by typing 1, 2, 3 or 4 respectively. If the user types 9, no more calculating is performed. Notice that if the user tries anything but 1, 2, 3, 4 or 9, then they have to choose another number - there is a validation loop checking that the contents of the choice variable is from 1 to 4 or 9 before the loop finishes.
If you chose anything except 9, then you will be asked to type in another number, whose contents are stored in the next_num variable.
If you chose 1, then the contents of next_num
are added to the contents of num1 and stored back into num1 again.
If you chose 2, then the contents of next_num are subtracted from the
contents of num1 and stored back into num1 again.
If you chose 3, then the contents of next_num are multiplied by the
contents of num1 and stored back into num1 again.
If you chose 4, then the contents of next_num are divided by the contents
of num1 and stored back into num1 again.
The contents of num1 are then displayed on the console to see the result of the sum.
Finally, a further loop is wrapped around everything except typing the first number. The loop will only exit if 9 was chosen for the choice variable, and therefore you can do more maths on the value of num1.
#include <stdio.h>
#include <conio.h>
main()
{
int num1, next_num, choice;
printf("Enter first number: "); scanf("%d",&num1);
do
{
do
{
printf("1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: ");
scanf("%d",&choice);
}
while ( ((choice<1) || (choice>4)) && (choice!=9));
if (choice!=9)
{
printf("Enter next number: ");
scanf("%d",&next_num);
}
if (choice==1) num1=num1+next_num;
else if (choice==2) num1=num1-next_num;
else if (choice==3) num1=num1*next_num;
else if (choice==4) num1=num1/next_num;
printf("Result is now %d\n",num1);
}
while (choice!=9);
printf("Press a key."); getch();
}
Notice in this example that we have a loop inside another loop. This is fine. It is known as nesting loops. To tell which ending curly bracket matches which starting curly bracket, and which instructions are inside which loops, we indent (move further to the right) and lines between new curly brackets. It is good style to do this, and a good habit to get into. It's worth the effort of typing a few extra spaces!
Typical results after running this program might be:-
Enter first number: 10 1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: 0 1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: 5 1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: 1 Enter next number: 5 Result is now 15 1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: 4 Enter next number: 3 Result is now 5 1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: 2 Enter next number: 2 Result is now 3 1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: 3 Enter next number: 4 Result is now 12 1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: 9 Result is now 12 Press a key.
We will see a slightly better way of doing this when we look at the switch...case statement together with a character variable - in a session coming soon...
Exercise 26 - Tidying up the Calculator example
Have you noticed that when you choose option 9, we see the result again. Can you think of a way of stopping this from happening? Have a look to see how we stop the user entering the next number when they choose option 9, and follow this as an example.
There is another way of achieving this. We can make use of another C instruction called break; which skips past any remaining instructions inside the loop, ignores the condition, and continues execution after the end (our outside) of the loop. It breaks out of the loop. The program now looks like this:-
#include <stdio.h> #include <conio.h> #define TRUE 1 main() { int num1, next_num, choice; printf("Enter first number: "); scanf("%d",&num1); do { do { printf("1 for add, 2 for subtract, 3 for times, 4 for divide, 9 to exit: "); scanf("%d",&choice); } while ( ((choice<1) || (choice>4)) && (choice!=9)); if (choice==9) break;
printf("Enter next number: ");
scanf("%d",&next_num);
if (choice==1) num1=num1+next_num;
else if (choice==2) num1=num1-next_num;
else if (choice==3) num1=num1*next_num;
else if (choice==4) num1=num1/next_num;
printf("Result is now %d\n",num1);
}
while (TRUE);
printf("Press a key."); getch();
}
We have effectively moved the condition that ends the loop from the end up to just after the end of the first loop. This means that in order to loop back round to the top once we get to the bottom of the loop, we need a condition that says "loop around every time". We do this by placing a value of 1 in brackets - 1 means "true" in C (0 means "false"). Rather than use the number 1, which looks a bit meaningless, we have defined a value called TRUE which, when it is is located in the program, gets replaced by the number 1. This is a constant, and cannot change in the program. We will look at using the #define directive in more detail a little later in the course. The use of CAPITALS for a constant is a generally used style when writing C programs.
In the next session we will be covering the following topics:-
Character variables
Using getch() and getche() to get a character from the keyboard
Using the %c modifier in printf
Characters as number codes
Using a loop to give your program a Yes/No choice Quit option
Exam entry forms given out and exam procedure explained.
![]()
(c) Copyright
2002-4 Simon Huggins. All Rights Reserved.
If you have any issues or questions regarding the content of this web
site, please contact the
author by clicking here.
Alternatively, you can leave a voice message on 00 44 (0)7050-618-297 or fax
on 00 44 (0)7050-618-298
This Page was last updated: 29 January 2004 13:06