|
~ Introduction to Programming: C ~ Session 5 - Interaction with scanf keyboard entry and conditional expressions |
In This Session...
In this session we will be covering the following topics:-
Introducing scanf to read data from the keyboard into a variable
Conditional Instructions - The if command (incl. about code blocks).
Exercise 16 - (Extra) - Changing our stats program and using it as a separate executable
Last session we covered:-
Introducing scanf to read data into variables from the keyboard
The program be looked at in the previous session was fine to use when working within the C++ IDE (Integrated Development Environment). But what if we wanted to give the program to somebody else without the C compiler, so that they could change the years values in the program without having to change the original source code?
You need some way of letting the person (or user) get data into the program - the obvious choice being the keyboard.
The scanf function will wait for the user to type in data at the keyboard, and when they press the Enter key, will take the data they have typed, and place it into a variable.
For example, if we wanted to read somebody's age, and write out the approximate number of days and weeks they have lived, these three lines of code would do the trick (note that this isn't a complete program, so will not work on its own if you type it in): -
float age,days,weeks;
printf("Enter age in years: "); scanf("%f",&age);
days = age*365.25; weeks = age*52.0;
printf( "You have lived for %5f days and %4f weeks", days, weeks );
This assumes the average number of days in the year is 365.25 and there are 52 weeks
in the year.
The scanf function is a bit like the opposite of the printf function - printf writes
data out to the console, scanf reads data in from the console.
Notice that scanf also uses the %f code to show that we want to read data into a floating-point variable. If we wanted to read into an integer variable, we would use %d instead.
The &age shows that the %f that is read in from the keyboard will be put into the age
variable. Why do we need the & in front of the variable? We will cover this in a
later session, when we deal with passing variables to functions by reference. Don't
worry about this for the moment.
But be VERY CAREFUL not to forget the & symbol, otherwise the results could be rather unpredictable!!
Here's an example where a variable has been created which holds an integer, and the user types in a number to place the value into the integer:-

Exercise 12 - Turn source code snippet into a program
We are going to turn the four lines of C (a 'snippet' of source code) above into a full C program that will run.
Create a new project and type in the program above. Complete it by making sure you include the rest of what is needed to make it into a complete C program as follows:-
Create a new project - remember to go through File / New / Other / Console Wizard / OK / Delete text / File / Save All / Save two filenames (the same name each time) - once for the project file, once for the C source program itself that you are going to type.
Remember to put the #include statements at the top of the program - the two libraries stdio.h and conio.h are enough to cover the printf / scanf function (held in stdio.h) and the getch function (held in conio.h)
Start the program with a main() on one line and an opening curly brace { on the following line. Add a few blank lines, and finish it with a closing curly brace } on a line on its own. Remember, this tells the computer where to start the program - i.e. the main part of the program.
Move the cursor to a blank line between the two curly braces and type the program instructions. By doing it in this order, you won't forget to put the closing curly brace at the end after you have typed in the main part of the program.
Remember to add a final instruction of getch(); before the closing curly bracket - so that the computer waits for a key to be pressed before closing the black console (results) window.
Exercise 13 - Add together two integers
Write a program that declares (creates) three integer variables - call them int1, int2, results - and then reads in two numbers using two scanf functions to the int1 and int2 variables. Remember that to read into an integer variable, scanf uses the %d code rather than the %f used by floating-point variables.
Add the contents of the two variables together (int1+int2) and place the result in the integer variable called result. Show this result using a printf statement (e.g. a message saying The result is 5 if you had typed in 2 and 3 for the values of int1 and int2).
Hint: Remember to put double-quotes ("this is my text") around the text to be displayed, and to use the %d code in the text to represent the number to be shown, and to put a comma (,) and the name of the variable (result) to be displayed inside the brackets and after the text to show what is to replace the %d code.
Conditional instructions - The if command
We now know how to read in data from the keyboard and store it into a variable using the scanf function. This gives us our first taste of interacting with a user without having to change the source code (C Program).
Once we have data from the user, it would be useful to perform some sort of action based on the input that has been given. For example, the program below asks you for your age. If you type in less than 17 (for 17 years), it will tell you that you are too young to drive. Otherwise, it will tell you that you are old enough to drive, and ask you how many lessons you would like to book. It will give you a cost based on this and the cost of the lesson being £18.
It achieves this using the if keyword or statement. This is an inbuilt command in the C programming language, and does not require you to #include any library to use it. The if statement will execute (run) a command, or set of commands, based on the results of a check - known as a condition (or sometimes as a conditional expression or boolean expression). Used with the else keyword you can choose to do another command, or set of commands, if the condition is not correct.
Exercise 14 - An example of an IF command
Type out the program below to try this out:-
#include <stdio.h>
#include <conio.h>
void main()
{
int years,lessons;
printf("What is you age in years? "); scanf("%d", &years);
if (years < 17)
printf("Sorry. You are too young to drive.\n");
else
{
printf("You are old enough to drive.\n");
printf("How many lessons would you like to take? ");
scanf("%d", &lessons);
printf("It will cost you %d pounds to take %d lessons.\n", lessons*18, lessons);
}
printf("\nPress a key... "); getch();
}
The if statement takes the form:-
if (condition) statements(s) else statement(s)
or if you do not want to do anything different if the check you carry out is not correct:-
if (condition) statements(s)
IF statement and blocks of code
Notice that if you wish to do one statement, you just put in that statement followed by as semi-colon - e.g.
if (years < 17)
printf("Sorry. You are too young to drive.\n");
else
However, if you wish to do more than one statement, you need to put curly-braces around the statements, to show that they are grouped together, like so:-
else
{
printf("You are old enough to drive.\n");
printf("How many lessons would you like to take? ");
scanf("%d", &lessons);
printf("It will cost you %d pounds to take %d lessons.\n", lessons*18, lessons);
}
This is true for most statements in C - we will look at examples as we go along. The instructions between the curly-braces are known as a block of code.
A condition or conditional expression describes something that must be correct in order for something to be executed. In the case of an if statement, the following command (or code block within curly braces) will be executed if the condition is correct.
The example given above is as follows:-
if (years < 17)
printf("Sorry. You are too young to drive.\n");
else
{
printf("You are old enough to drive.\n");
printf("How many lessons would you like to take? ");
scanf("%d", &lessons);
printf("It will cost you %d pounds to take %d lessons.\n",
lessons*18, lessons);
}
This fits into our 'template' of an if statement as follows:-
if (condition) statements(s) else statement(s)
The condition then is years
< 17 - read this as "the contents of the years
variable is less than seventeen". So if the contents of the years
variable is less than seventeen, the statement in pink printf("Sorry.
You are too young to drive.\n"); will be executed. Thus, the
message Sorry. You are too young to drive will only be displayed if
the user typed in a value of 17 or less.
However, if (and only if) the contents of the years variable are not less than seventeen - i.e. are 17 or above, then the block in green (after the else keyword) will be executed. Thus, the message You are old enough to drive, followed by a request to type in the number of lessons you wish to take, followed by a message showing the cost (18 times by the number of lessons) and the number of lessons typed out.
Once the end of the if statement completes, the program carries on as normal. The if statement is what is known as a branching statement.
The flow of the program normally moves from top-to-bottom. However, the if command makes the flow change to take one of two possible routes based on the outcome of a condition (i.e. the flow branches out into one of two possible outcomes). Once the if command has been completed, flow resumes normally in a top-to-bottom way (until another branching statement is encountered). See the diagram to the right for a graphical representation of this flow.
Types of conditions
We saw in the example above that the < symbol represents "less than" - so years < 17 represents a check to see whether the contents of the years variable is less than the number 17 (i.e. is 16 or less).
There are other symbols available to use, which are listed here:-
| years = 17 | equals: The contents of the years variable is [equal to] 17. |
| years < 17 | less than: The contents of the years variable is less than 17 (i.e. is 16 or less) |
| years > 17 | greater than: The contents of the years variable is greater (i.e. larger) than 17 (i.e. is 18 or more) |
| years != 17 | is not equal to: The contents of the years variable is not [equal to] 17. I.e. it could be 16 or less, or 18 or more |
| years <= 17 | is less than or equal to: The contents of the years variable is less than or is [equal to] 17. I.e. it could be 17 or less |
| years >= 17 | is greater than or equal to: The contents of the years variable is greater than or is [equal to] 17. I.e. it could be 17 or more. |
You can reverse the meaning of a condition by putting parentheses (brackets) around the condition and placing an apostrophe (!) before it - e.g. years < 17 becomes !(years < 17 ) which changes the meaning to check to see whether the contents of the years variable is 17 or above - i.e. it isn't less than 17, which means it must be 17 or above. This is the same as saying years >= 17.
The following table lists the effect of putting a ! (known as the not symbol) in front of different conditions:-
| !(years = 17) | years != 17 |
| !(years < 17) | years >= 17 |
| !(years > 17) | years <= 17 |
| !(years != 17) | years = 17 |
| !(years >= 17) | years < 17 |
| !(years <= 17) | years > 17 |
Exercise 15 - Floating Ornamental Elephants
We wish to write a program that will calculate the discount on a product based on the quantity purchased. We will be selling floating ornamental elephants, which cost a different amount based on the quantity bought:-
1 elephant - £30
Up to 10 elephants - £25 each
Up to 50 elephants - £20 each
Over 50 elephants - £10 each
To do this, we need to create three variables - they can be integers in this case. One variable holds the number of elephants bought (e.g. called quantity). Another variable (e.g. called cost) will be set using one of several if statements according to the number of elephants bought - i.e. the contents of the quantity variable. You do not need to use the else statement in this example. Use three if statements. Be careful what order you put them in - you will see why when you test the program.
The third variable (called total) will times these two values together.
The end amount should be displayed on the screen - remember to wait for a key to be pressed at the end. N.b. Don't use the £ symbol in your program. Just work with numbers - e.g. 10 means £10.
Finally, test the program with these values: 0, 1, 2, 9,10,11,49,50,51 and 100. The results should be (respectively):-
| 0 elephants | £0 |
| 1 elephant | £30 |
| 2 elephants | £50 |
| 9 elephants | £225 |
| 10 elephants | £250 |
| 11 elephants | £220 |
| 49 elephants | £980 |
| 50 elephants | £1000 |
| 51 elephants | £510 |
| 100 elephants | £1000 |
Notice how when the discount amount is reached, the price suddenly drops. That's the benefit of buying in bulk!
Exercise 16 - A bit about executable programs
Try changing your statistics program to read the five values in from the keyboard - e.g. for each of the 5 variables (remember to change the number 1 twice in each line): -
printf("Enter years value 1: "); scanf("%f",&years1);
Type in the original numbers, and an alternative set of numbers. Do you get the results you expect?
Close C++ Builder now.
Open Windows explorer, and navigate to the Z: drive. You should see an executable file with the same name as your project - e.g. if you called it exercise11 then there will be a file called exercise11.exe in the Z: drive. This is the version of the program that has been translated by the C Compiler from C into the machine language that your computer's microprocessor (the hardware 'brains' of your computer) understands.
You could copy this program, put it on a disk, and put it into another PC type computer that DOES NOT have C++ Builder on it, and the program would work from there - once it is translated to machine code, the program no longer needs the compiler - the translation has been done and is finished with.
Try Double-clicking on the program from Windows Explorer. This should start the program automatically. See - you don't need C++ Builder open to use a program you have written. This is the form that programs come in when you buy them from the shop or download them from a web site.
Exercise 17 - The ? : Operator
This topic is advanced, and you do not need to know, but if you're keen, it's quite clever!
It is possible to use the equivalent of the if statement from within an equation. For example:-
printf("What is you age in years? "); scanf("%d", &years);
printf("You are "); printf(years<17?"too young":"old enough"); printf(" to drive");
If you put a condition followed by a question mark, then the item after the question mark (?) will be used if the condition is correct (or true) otherwise if the condition is incorrect (or false) the item after the colon (:) is used.
Try the above snippet as a proper program as we did with exercise 12. Remember the getch() at the end to make the program wait for a key to be pressed. Does it work ok? Test it with the ages 16,17 and 18.
You can also use this when making calculations. Try re-writing exercise 15 to use the ? : form instead of if statements. Test it with the same values suggested in exercise 15.
In the next session we will be covering the following topics:-
Looping - while, do-while.
Break and continue.
Interactive example.
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