~ Introduction to Programming: C ~

Session 6 - A recap of what we have covered so far

<<  Back to Contents Page

Session 6 - A recap of what we have covered so far 

In This Session...

In this session we will be covering the following topics:-

Review of Last Session

Last session we covered:-

Creating a new project

Remember the steps to create a new project in C++ Builder. These should be followed every time you start a new program.

Also remember that in C++ Builder, each program you write is stored in two files - the Project file which holds details such as version information and any special settings you want to apply to your program (we do not look at this on the beginner's course, but you still need it). The Program or Source file is where you type in the C program to try it out. You need to save both to make your program work properly. If you want to copy a program to a floppy disk, make sure you copy both programs. It is best to call both files the same name (e.g. called it exercise17 for both to create two files - the project file, called either exercise17.mak or exercise17.bpr depending on the version of C++ Builder that you are using, and the source file called exercise17.cpp

In C++ Builder 6, the steps for creating a file are as follows:-

Exercise 18 - Create a new project

Create a new project called exercise18 which contains no program in it. Just save it, and save the blank program also as exercise18.  Start-up Windows Explorer, and look on the Z: drive. You should see two new files called exercise18.bpr and exercise18.cpp

Bare-bones C program

All of your C programs should have the same basic structure, as shown below. Type out the following program:-

#include <stdio.h>
#include <conio.h>

void main() {

  /* program goes here */ 

  getch();

}

Save the program by clicking on the or Save All button on the toolbar or choosing the File menu and the Save All option.

Compile and Execute (start) the program by clicking on the button.  This is the process that this simple click initiates:-

Nothing much happens, other than a cursor flashing in the top-left hand corner of the screen. Press a key to return from the program to view the source code again. Here is what is happening:-

printf and character constants

Remember that the printf function is a function that is held in the stdio.h library? It's easiest form is as follows:-

printf("Hello world\n");

Remember that anything between brackets is data to be passed to a function - in this case the printf (means print formatted) function. Also note, that to specify some text that we want to be treated as it looks, rather than as calculations within the program, we surround the text with double-quotes. So in this case we are passing the text Hello world\n to the printf function so that it can be displayed on the black console window.

Character Constants

Note that there are some special command characters that start with a backslash (\) to show certain common actions that should be interpreted. For example:-

Exercise 18 continued

Type in the following to add to the program above (the new portion is highlighted - remove the comment):-

#include <stdio.h>
#include <conio.h>

void main() {

  printf("Hello there\nWelcome!\a"); 

  getch();

}

Notice the semi-colon (;) symbol is used to show where the end of each instruction ends. In this case, the words Hello there will be shown on the black console window, and the cursor moved to the next line down / to the left (\n character constant) followed by the word Welcome! followed by a beep sound from the computer.

Save the program under the same project as before, and click on the button to compiler/link/run the program.

FOR YOU: Add another line that displays the message Press A Key followed by a tab character followed by a beep. The cursor will wait to the right of the message for the user to press a key before terminating the program.

Variables and printf

A variable is just a box or memory-jogger that stores some data, and is given a name so that you can remember what the data is for.  It is essential for performing calculations in a program, or storing the results of user input - e.g. which key they have pressed. The contents are often used by conditional statements such as if and while to decide what to do with the data.

You need to tell the computer what type of information is to be stored in the box so that the computer knows what to do with it. This is called declaring the variable. The most common types are as follows:-

Once you have declared your variable, you need to put some data into it. E.g. to declare three integer variables called myNum1, myNum2 and myNum3 and place the values in them:-

#include <stdio.h>
#include <conio.h>

void main() {

  printf("Three variables\n");
  int myNum1,myNum2,myNum3;
  myNum1 = 3; myNum2 = 4; myNum3 = 5;
  printf("myNum1 is %d, myNum2 is %d, myNum3 is %d\n", myNum1, myNum2, myNum3);

  getch();

}

Type out this program, and add a fourth number myNum4 with a value of 6 and display its contents in the same way as the other three numbers..

Remember that for a printf function, if the text inside the double-quotes has %d inside it, then where this appears, the first value after the end of the text, and after a comma, will be substituted in. Therefore, in the above example, the first %d has the contents of the myNum1 variable substituted in (therefore the first  %d becomes 3) and the same respectively for any other %ds 0 i.e. the second will have 4 substituted and the third will have 5 substituted. Note you must use %d when substituting in integer values, otherwise you can get unexpected results.

Displaying floating-point numbers

If we wanted to create the same program for floating-point numbers, it might looks like this (try typing it in):-

#include <stdio.h>
#include <conio.h>

void main() {

  printf("Three variables\n");
  float myNum1,myNum2,myNum3;
  myNum1 = 3.5; myNum2 = 2.23; myNum3 = 5.0;
  printf("myNum1 is %3.1f, myNum2 is %3.1f, myNum3 is %3.1f\n", myNum1, myNum2, myNum3);

  getch();

}

Notice the use of %f to substitute in floating-point variables. Notice that between the % and the f are two numbers, separated by a period (.) character. The first number (3 in this case) shows the maximum width of the number - in this case, three characters long (including period). The second number shows the number of digits after the decimal point - .e.g. one digit.

If a number does not fit into the size specified, then it will be rounded to the nearest number to make it fit. E.g. 2.23 is four characters long, so to make it fit into three characters, it will needed to be rounded - in this case downwards, as it is nearer to 2.2 than it is to 2.3 

FOR YOU: Change the printf statement so that the formatted floating-point numbers appear as four-characters wide with two digits after the period (i.e. two decimal-places in mathematical speak).

Exercise 19 - Arithmetic

You can perform arithmetic on variables and store the results into other variables. For example:- 

#include <stdio.h>
#include <conio.h>

void main() {

  int x, y, result;
  x = 3; y = 4; result = 2*(x+y);
  printf("The result of the sum is %d\n", result);

  getch();

}

Create a new project called exercise13 and type this out and run it. Can you see what has happened?

Remember when we perform calculations that there are precedence rules. These determine what order things are calculated. In general, times and divides (* and /) are calculated before additions and subtractions (+ and -). You can't always just read a formula from left-to-right. If you want to force a + or - to be done before a times or divide, put brackets around the plus or minus sum. Calculations inside brackets get done before anything else.

In the above example, x+y is calculated first, because it is in brackets. This works out as 3+4=7, so the sum becomes 2*(7) which gives 14. Therefore, the value placed into the result variable is 14

FOR YOU: What happens if we remove the brackets from around the (x+y)? Can you guess what the answer would be. Try changing the program and running it again to see if you were correct.

Statistics - finding the total and average

Let's add another two variables called total and average - also integers. After the printf function, we will add up the values of x, y and result to give us a total (3+4+14 = 21). We will place the result in the total variable. We will then divide the value of total by the number of items totalled (3) and place the result in the average variable. We will then display the result. Try the program below:-

#include <stdio.h>
#include <conio.h>

void main() {

  int x, y, result, total, average;
  x = 3; y = 4; result = 2*(x+y);
  printf("The result of the sum is %d\n", result);
  total = x+y+result; average = total/3;
  printf("Total is %d, average is %d\n", total, average);

  getch();

}

FOR YOU: Change the value of y to 5. Can you guess what the contents of the result and total and average variables will be? Run the program to find out. What has happened to the value of average? You might have expected that as total is now 23  that the result would be 23/3 = 21/3 remainder 2, or 7 remainder 2 (i.e. 7 + 2/3 = 7.6666666). However, total can only hold an integer, so it rounds to the nearest whole number, which is 8 in this case.

Exercise 20 - Using scanf to read data from the keyboard

The opposite of printf (which writes data to the console or screen) is scanf (which reads data in from the keyboard). You can replace typing numbers directly into your program by having the user type them in outside the program using scanf each time the program is run.  In this way, the user does not need to change your program to put data into your program. It does however mean that we do not know when we write the program what values will be put in later.

Type out the following program, which works out the total of three numbers, and the percentage of the total for each number. Remember to include the & before the variable to receive the keyboard input in each scanf statement. Note we use %d to read in an integer and place it into an integer variable: - 

#include <stdio.h>
#include <conio.h>

void main() {

  int x, y, z, total, percX, percY, percZ;
 
  printf("Enter X: "); scanf("%d", &x);
  printf("Enter Y: "); scanf("%d", &y);
  printf("Enter Z: "); scanf("%d", &z);
  total = x + y + z;
  percX = (x / total) * 100;
  percY = (y / total) * 100;
  percZ = (z / total) * 100;
  printf("x is %d%%, y is %d%%, z is %d%%\n", percX, percY, percZ);
  getch();

}

Run it and try it with various values. Why are we coming back with zero values? This is because x divided by total is nearly always going to come back less than zero. This is converted to an integer (i.e. put to the nearest whole number - zero) and then multiplied by 100 giving 0 again.

Do you notice that to get a percentage symbol, we need to repeat it twice. This is to prevent it being interpreted as a special code.

FOR YOU: Redo the exercise, but using float instead of int and %f instead of %d.  For the printf statement, use %6.2f instead of %d. Try the values 2, 4 and 6. The total is 12, so 2 out of 12 gives a sixth. Times by a hundred gives 16.6666 percent of the whole. y gives 33.33% (4 out of 12 gives a third). Finally, z is 6, which is half of the total of 12, giving 50%.

Exercise 21 - The if command and conditions

An important part of writing a program is making decisions based on data that has been calculated or input before.

For example, you may have an age restriction on whether you can sell a specific item (or, for example, rent a video in a video rental library). To check this, you would need to look at the piece of information (held in a variable) relating to the age of a person, and perform a test.

Create a new project called video (or if you prefer to keep consistent, call it exercise15).

In the following example, we will create a program to ask an age, check if the age is less than 18, and then if the person is old enough, confirm the rental of the video.

#include <stdio.h>
#include <conio.h>

main()
{
  int age,rating;
  rating=18;
 
  printf("what is the renters age? "); scanf("%d",&age);
  if (age<18)
    printf("Renter is too young\n";
  else
  {
    printf("Confirm the booking by pressing y: ");
      if(getche()=='y')
        printf("\nconfirmed");
      else
        printf("\nrejected");
  }
  getch();
}

Remember that when using an if statement, to enclose the condition - that is, the decision to be made, in brackets ().  Note in this case, we execute a single statement (followed by a semi-colon ;) if the condition is true or if it is false, we execute the instructions between the starting { and ending } after the else instruction.  In this way, we perform a test to see if the renter is less than 18, and if he isn't (i.e. if he is old enough), do a further check to confirm the booking.

Note that the getche() command is being used - this is like getch, except the key pressed is echoed or shown on the console.  Thus if the 'y' key is pressed, the command becomes:-

      if('y'='y')

which of course is true.

FOR YOU: If the video is rented, still display the 'confirmed' message, but then ask if the video is to be rented for a week (press y to confirm). If it is, display the message Cost is 3.50 for a week otherwise display the message Cost is 1.95 for a day. Be careful to turn the single printf('confirmed'); command into a compound statement - i.e. a number of instructions started with a { and ended with a }.

N.b. Remember: The standard conditions you can use in an if statement are as follows:-

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.

City & Guilds Modules

We are now working towards the City & Guild Unit 201: Create software components using 'C'.  The examination for this module is 1 hour long and is multiple choice.

In addition, we will be covering enough information to take the four-hour written/practical examination - unit 206: Test software components.  You will need to follow instructions, create a design, implement the design as a well-constructed C program, and then test the correct working of the program using a test plan.

If you wish to obtain the full level 2 diploma for IT Practitioners (Software Development), you will need to take two additional units from the standard list (covered by other courses):-

There is a cost associated with the taking of each examination. Details to follow shortly, with entry  forms.

In the Next Session...

In the next session we will be covering the following topics:-

(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