|
~ Introduction to Programming: C ~ Session 3 - Introduction to arithmetic and variables |
In This Session...
In this session we will be covering the following topics:-
Last week we covered:-
Here is a recap of the program, who project you may have called numbers.mak as suggested. Open the project in the method discussed in Session 1.
#include <stdio.h>
#include <conio.h>
void main()
{
int a,b,c;
a=1; b=1; c=a+b;
printf("a+b=%d\n",c);
printf("Press a key to finish.");
getch();
}
In this session we will go through the parts of the programming highlighted below in bold :-
Including Library files - identify libraries where data is held
Main function - identify what instructions will be executed first
Variable declarations - identify boxes to put information into
Variable assignment - put values into these boxes
Printf function - Displaying variable contents and text together
getch function - Waiting for a character to be pressed
A variable is like a file-box in which you wish to keep some useful piece of information. If you are a manic filer (like myself) then you will know that it is helpful to label your file-boxes so you know what sort of information
each file-box contains.
In programming terms, we give our 'file-boxes' any name we like, so long as they contain a mixture of letters and optionally numbers (but cannot start with numbers) and certain symbols (an underline or underscore character (_) is popular to represent different words). For example, the following are valid (OK) names for variables:-
hello, Hello, hello123,hello_there_everybody, helloThereEverybody, HeLlO
The following are invalid (not OK) names for variables:-
123, 123Hello, Hello There Everybody
Can you see why? A variable MUST contain at least one letter, and must start with a non-number, and cannot contains spaces (looks like three separate commands).
Note that C is what is known as a case-sensitive language, which means that it distinguishes between upper and lower case. This means all of the following variable names would be treated as separate variables:-
helloThere, HelloThere, hellothere, HELLOTHERE, HeLlOtHeRe.
To tell C we want to use a variable (box) to put our information in, we declare it. For example:-
int myNumber;
The first word int refers to the type of information that will be held in the box. This tells us that the information in the box called
myNumber will be an integer, or whole number. To finish off our request to create a new box called
myNumber that will create a whole number, we put a semi-colon on the end. The computer is then ready for the next instruction.
If you wanted to create two boxes that contain different whole numbers, we could create two boxes together like this:-


int myFirstNumber, mySecondNumber;
That is, we list all of the names of whole-number boxes by separating them with commas.
In our program, we have created three boxes called a, b and c. Each will hold an integer (whole number). These are created as follows:-
int a,b,c;

So we have three empty boxes to hold numbers. How do we put information into these boxes? In computer terms, we assign data into the variable. This means we put information into the boxes.
For example:-
a=1;
can be read as "put 1 into the box labelled a" or "assign the number 1 to variable a". In mathematical terms, this means "a equals 1" which means that "whenever you read a in the program from this point onwards, read 1 instead".
Variables are so called because you can replace the contents of the boxes (i.e. vary the contents - hence variable) at any time. So we could have these three commands our program, and after each one has been executed, they will contain different things:-
a=1;
a=4;
a=5;
You can never have more than one piece of information in a variable at any one time. Which means, when you put 4 into variable 'a' the original information '1' is thrown away and lost. Similarly, when you put 5 into variable 'a' the information '4' is thrown away and lost, leaving the value of 5 in the variable.
You can do simple arithmetic on variables. For example, the following shows three separate instructions on one line. This is perfectly OK - you could put them on separate lines, and they would work the same. The semi-colon is what identifies each instruction as having ended.
a=1; b=1; c=a+b;
What is happening?
The value 1 is put into a box called 'a' where it stays
The value 1 is put into a box called 'b' where it stays
The values inside boxes a and b are retrieved (both contain 1) and added together using the + symbol (ie. a contains 1, b contains 1, so a+b is the same as saying 1+1). The result of this calculation (i.e. 2) is placed in box c. So the value of 2 is placed into box c.
So, after these three instructions have been executed:-
Box A contains 1
Box B contains 1
Box C contains 2
You can also subtract (take away) numbers using the '-' symbol, multiply (times) two numbers together using the '*' symbol, and divide two numbers using the '/' symbol. Note that the * and / symbols are different to how you would normally write them, which does take a bit of getting used to.
In the program, change values of a and b, and change the arithmetic symbol for c as follows.
Write down what you think the answer would be first, and then execute the program to see if the result is what you expected it to be. If this does not seem to make sense, ask!
a=5; b=3; c=a-b;
What does C contain after these three instructions have been executed?
a=2; b=3; c=a*b;
What does C contain after these three instructions have been executed?
a=8; b=2; c=a/b;
What does C contain after these three instructions have been executed?
Change the expression back to the original formula as follows:-
a=1; b=1; c=a+b;
printf is a function that is held in the stdio library (hence the need to use #include <stdio.h> at the beginning of the program). Its purpose is to place data on standard output devices - e.g. the console (screen), a printer, a disk file etc.
In our case, we wish to see the results of our calculations on the console to see if our program worked correctly.
We need to give printf some information in order for it to know what to display on the console, and how to display it.
printf("a+b=%d\n",c);
The function is called printf, and the information between the opening and closing parentheses (brackets) is
the information to be passed into the printf function - i.e. what is to be placed on the
console (shown on the screen).
Two items (in computer jargon, these are known as parameters) are listed to be given to the printf function. The first is a rather cryptic-looking set of characters. This is surrounded by speech marks (make sure you don't use apostrophes by mistake!).
Speech marks show where text to be sent to a function begins and ends. It distinguishes it from the rest of your program - e.g. commands, arithmetic etc.
The second item of data to be sent is the contents of variable c (in this case, it contains the results of the sum a+b, which [as a=1 and b=1] is 1+1 = 2).
The printf function takes the text in the quotes and first looks for any special symbols.
When it comes across a percentage symbol (%) it looks at the next character - 'd' in this case. This particular combination of symbols (%d) means "take the next item, which must be an integer, to be fed into the printf function, and replace the %d with that data".
So, the next item after the text is the variable c which contains the number 2. Therefore, the text that will be displayed on the console becomes "a+b=2\n". This is what is known as "substitution".
Change the line:-
printf("a+b=%d\n",c);
to
printf(a+b=%d\n,c);
and compile it. Do you get an error? Do you know why?
The computer is trying to treat your text as though it was a piece of arithmetic - it is trying to add variables and b together, and trying to assign something else to them - %d\n. This isn't proper maths - in fact, in this context, it is nonsense, so the Compiler complains. And rightly so! Change it back, and make your compiler happy again!
Change the line:-
printf("a+b=%d\n",c);
to
printf("a+b=%d\n",a+b);
and compile and execute it. What answer do you get back? Do you know why.
Have you spotted that this now makes the use of the 'c' variable redundant.
What happens is that the second item to get passed to the printf function is first calculated before it gets sent to the function. Thus the result of a+b is 2 (which was how c was calculated originally) and the value of 2 is then passed to printf to be placed in the text.
Change the following lines:-
int a,b,c;
to
int a,b;
and also:-
a=1; b=1; c=a+b;
to
a=1; b=1;
thus removing any reference to the variable 'c'. Execute and run your program again. Does it still work?
The "\n" is way of telling the console to perform a particular action by using a special character. In this case, it means "new-line" - remember "\n for \new-line".
This means that the cursor is moved to the next line down on the console window, and to the left-hand margin - rather like pressing the Enter key when typing out a document.
Remove the \n from the line:-
printf("a+b=%d\n",c);
to give:-
printf("a+b=%d",c);
Compile and execute the program again. What has happened? Can you see why removing the \n has stopped the cursor going down on to the next line, so that the next bit of text to be displayed will come straight afterwards instead of on the next line down?
Put the \n back again.
The next line of our program is:
printf("Press a key to finish.");
which simply places text on the console. Notice that there are no %d symbols, so no further items of data need to be given to the printf function. Furthermore, the text does not end with a \n, which means that the cursor stays at the end of the text (just after the period (full-stop) symbol.
The final line is:-
getch();
This is a function held in the conio.h library (remember what happened when we took the include command out for this library?). It's function is to wait for the user to press any key on the keyboard. When it does, it passes back the key that was pressed. However, in our case we do not need to use this information - we are simply using this as a way of keeping the results displayed on the console while we look at it, and then indicating that we have finished looking by pressing a key.
Take the getch(); line out of your program. Compile and Execute the program. What happens? Do you get to see your results?
What is happening is that the instructions are being executed, and when the program gets to the end of the main() function (i.e. the closing curly bracket), it sees that the program has finished, and so closes the console window and returns you back to the C++ Builder IDE.
Put the getch(); line back again. Now you can see why we need it there to stop the window from closing before we have finished with it. The computer waits at the getch(); function until a key is pressed, and only then does the program continue with the next instruction. There is no next instruction, so the program ends.
Looking-up help on library functions in C++ Builder
If you ever get stuck understanding what a particular function does in C++, click somewhere within the command your are interested in, and press the F1 key.
Click on the getch function. Press the F1 key.
A window should pop up showing you information on this function. Sometimes it can be rather technical, but it should give you an indicator. You are allowed to use the on-line help during examinations (but not text books or notes).
The useful bit is really at the top, under the Syntax heading:-
#include <conio.h>
int getch(void);
The top line tells you the library that the function is held within. This is useful if you have forgotten which library you need to include at the top of your program.
The second line tells you the inputs and outputs (i.e. what goes in, what comes out) of the function. In this case, the data going in (between the brackets) is 'void' - which means nothing. So no information needs to go in. The information coming out is an integer - which represents the character you press on the keyboard. This may seem surprising, but we will see why this is in a later session when we talk about character codes and the ASCII character set...
If you have time, why not try to create a program that performs the following steps:-
Has three variables called 'first', 'second', and 'result'. Don't include the single-quotes!
Displays a title "Calculator" followed by two new lines.
Sets 'first' to the value of 1, 'second' to 2, and adds 'first' and 'second' together to put the results in 'result'.
Displays the text "Result is 3" on the screen followed by a new line, by substituting the value of 'result' using %d in the text to be given to printf.
Waits for the user to press a key.
Sets 'first' to the value of 3, 'second' to 4, and multiplies 'first' by 'second'
Displays the text "Result is 12" on the screen followed by a new line, by substituting the value of 'result' using %d in the text to be given to printf.
Waits for the user to press a key.
Displays the text "The end - press a key."
Waits for the user to press a key
Program ends.
Another Exericise...
You do not need to do this exercise, but if you have some time on your hands, it is a useful 'look ahead' to the next session. Create a new project and program and type in the following C source code (program), trying to maintain the starting position (alignment) of each line of text:-
#include <stdio.h>
#include <conio.h>
void main()
{
float net,vat,gross;
printf("VAT Calculator (17.5\%)\n\n");
printf("Enter Gross amount (incl. VAT): ");
scanf("%f",&gross);
net = gross / ((100+17.5)/100);
vat = gross - net;
printf("VAT is GBP%9.2f\nNet value (before VAT) is GBP%9.2f\n\n",vat,net);
printf("Press a key to finish.");
getch();
}
Execute (run) the program by clicking on the green arrow (check for errors if necessary). Type out a decimal value in pounds (e.g. 117.50 for one-hundred-and-seventeen pounds and fifty pence) but don't include the £ symbol. This program will take this amount, work out the net amount (before VAT at 17.5%) and find out how much of the original amount was VAT - i.e. Sales Tax. A lot isn't it!? Below is a sample console output given the user typing in a value of 117.50
VAT Calculator (17.5%) Enter Gross amount (incl. VAT): 117.50 VAT is GBP 17.50 Net value (before VAT) is GBP 100.00 Press a key to finish.
In the next session we will be covering the following topics:-
More on mathematics and statistics: Precedence, Parentheses, Totals, Percentages and Averages.
Introduction to using scanf for keyboard input
A look at executable programs.
![]()
(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