If you program using the Visual C++ Express edition

  1. Choose file:new project win32 console application
  2. go through the wizard: you must enter a name for the progra, check 'console application' and 'precompiled headers'.
  3. Add the line: #include
    note no .h for some reason.
  4. add the line using namespace std;
  5. When ready build using "build" "build solution"
  6. Run by selection "debug", "start without debugging"

Last week

we learned:
  1. about the main function, how it encloses the program in braces.
  2. that statements are separated with semicolons; like that.
  3. about declaring variables as ints or doubles.
  4. about assigning values to variables using assignment statements
  5. about ouputing text or data using cout.
  6. that comments make programs easier to understand.
  7. about compiling and running a program
You should understand the following program:

// File: eg1 week2.cpp

#include <iostream.h>

void main()
{
// Comments explaining what variables are for where they are declared is a good idea.
// This is called a variable dictionary
// i is my number (integer) of interest,
// isq is for i squared (also an integer).

int i;
int isq;

i=184;

isq = i*i;

cout << i<<" squared is "<<isq<< endl;

}// end of program


You can cut and paste it into your compiler if you want.

New Stuff!

cin

Just as cout takes values from variables and puts it on the screen, cin takes values from the keyboard and puts in in variables. The arrows go the other way. // File: eg2 week2.cpp

#include <iostream.h>

void main()
{
// Comments explaining what variables are for where they are declared is a good idea.
// This is called a variable dictionary
// i is my number (integer) of interest,
// isq is for i squared (also an integer).

int i;
int isq;

cout<<"Enter an integer ";
cin>>i;

isq = i*i;

cout << i<<" squared is "<<isq<< endl;

}// end of program




Note you have to click on the window to be able to enter from the keyboard.

You will notice if you try this out that it works out fine for negative numbersand quite big numbers -but not for a million. Ints cannot hold numbers as big as a trillion a million million and things go wrong. We may come back to this at a later date.

Project for You!

Below is a list of programs based on the program above (Ask the user for input, do calculations, output the result). Here I want you to use doubles, and there may be more than one step to the calculation and more than one input variable.
Choose one of:
  1. The area of a triangle is half the width times the height. Ask the user for the width and height and output the area.
  2. The coordinates of the midpoint of a line is the average of the x values of the end valeus and the average of the y values (x1+x2)/2, (y1+y2)/2.
  3. The average speed of a runner in a race is the length of the race in metres divided by the time in seconds. However, this is the speed in metres per second. To convert it to kilometres per hour you must multiply it this by 3.6. Output the speed in both units.
  4. Suppose you are concerned to get enough vitamen c or other nutrient in your diet. When you buy food you typically get the following information: Price of can or packet, size of paccket (may be grams or millilitres), percentage of daily requirements in a 'serving' and the serving size in the same units as package size. I want you to calculate percentage of daily need per gram or milliitre (divide percentage per serving by serving size). Calculate the cost per gram or millilitre (divide package size by cost). Then calculate the cost of getting 100% of your daily allowance from that food. 100 x cost/gram /(%age per gram).

Plan your program

Write your program

Write a few statements at a time and then compile. That way you don`t have far to look when you make errors (and you will make errors). I will want you to cut and paste the program to me in an e-mail with the other programs that you write today.

Test Your Program

Make sure that it gives the results that you expect. Are there limits to the program? Input it cant deal with?

If

Look at the following program. It contains two 'if' statements. These consist of I am going to let Wei deal with the rules for logical expressions. Most of the time we simply ask whether (the contents of) a variable is greater than or less than a number. So we will stick with that today. I have put the statement that is effected by the if on a new line. I needn't have done. Note the logical expression is not followed by a semicolon. // File: eg2 week2.cpp

#include <iostream.h>

void main()
{
int age;
cout<<"Enter your age in years ";
cin>>age;

if(age<17)
cout<<"Why not enrole in one of RDC's Summer camps for kids"<<endl;
if(age>16)
cout<<"Thinking about college? Consider RDC"<<endl;
}// end of program


Compound Statements {}

Suppose we want a long sequence of statements to be executed if age>17. This is easily done by means of the 'compound statement'. This is a group of statements enclosed in braces {}. When you create a compound statement it is a good idea to:
  1. Create both braces at the same time, before typing the contents.
  2. Put a little comment on the end of the closing brace to say what it is closing.
  3. Increase the amount to which the enclosed text is indented.
So you probably understand the following:

if(age<25)
{
cout<<"Shady Valley Auto Insurance is happy to Serve the younger customer " <<endl;
premium=premium*2.5;
}// end of rip-off youngsters section

The point is that compound statements can contain other compound statements. The rule is that a closing brace closes the most recent opening brace. There should always be an equal number of opening and closing braces. The following is part of a program suggesting what you might have for suppper based on what ingredients you have.

if(eggs>3)
{
cout<<"Fried eggs again??" <<endl;
if(mlMilk>250)
{
if(gmsCheese>100}
cout<<"Cheese Omelette?" <<endl;

if(gmsFlour>100}
cout<<"Pancakes?" <<endl;
}//if milk

}//if eggs


Match up the opening and closing braces.

Practice

  1. Write a program that inputs two integers i and j. If i is greater than j the contents are swapped. Hint to swap the contents of 2 variables you need a third as a temporary place to keep them.
  2. Write a program that inputs two doubles and types out "close" if they are within 5% of each other.
  3. Write a program that inputs two integers. If they are both negative make them both positive (multiply by -1).

While Loops

A while loop in theory consists of the word 'while', a logical (or boolean) expression and a (compound) stements that will continue to be executed while the logical expression is true. In practice we usually have the following steps.
  1. Before the loop we usually set the values of the variables used in the logical expression.
  2. Then the 'while' with the logical expression and the opening brace.
  3. Next usually comes the meat of the loop. The calculations (assignemnt statements) or whatever that must be done many times. Often it will use the variables which are used in the logical expression.
  4. At some stage one or more variable used to control the loop is changed in such a way that the conditinal expression will at a desired time become nflase and we can escape from the loop.
The simplest loop looks something like this: // File: eg4 week2.cpp

#include <iostream.h>

void main()
{
int counter;
counter = 1; //set up loop
while (counter<101)
{
cout <<counter<< endl;// the repeated task

counter=counter+1;//update the counter so that eventually the conditional statement will be false
}//end of counter loop
}// end of program




Paste this program in and run it. You can now write a program to repeat a takes 100 times or a 1000,000 times or as many times as is necessary. For instance:
I want you to modify this program. I want you to add another variable called 'tri' for triangular number. Triangular numbers are the series 1,3,6,10.. We came across then in our study of algorithm times. Before the loop I want you to set tri to 0. Theneach time through the loop I want you to add 'counter' to the value already in tri. Change the cout so it prints out counter and tri with a space in the middle. Add this to the e-mail.

Interation

There are many things that are calculated by adding up lots of smaller and smaller things. The correct answer requires an infinite number of sums but we can get quite close with just a few.When you use your calculator to determine the sine of an angle that is what happens. The Series 1/2 + 1/4 + 1/8 .. should sum to 1. We can see how quickly it get there with a loop.

Find All

Suppose we want to find all the factors of an integer, how can we do that? A factor is a number that divides exactly into it. Well we have an operator % which gives the remainder for integer division. x=20%7; will put 6 into x because 7 goes into 20 twice remainder 6. If a is a factor of b then a%b gives 0 because there is no remainder. so we can use the test if((b%a)<1))coutb0;<a<<" is a factor of"<<b<<endl; And we can put this inot a loop where a starts at 1 and goes up to b.

The 'Model'

An important use of the loop, and the shortest cut to somewthing less geeky is a type of computer modelling where each pass through the loop represents a short period of time. The situation in out model, which may contain many variables gets updated for each pass based on their current values. This is very important in economics and climate science. I would like to describe an area which interests me which involves modelling epidemics. The population is divided into three: S="Susceptible", I="infected" and R="Removed". It is sometimes called a SIR model. Initially there is a small number of infected, most people are susceptible and nobody is removed. In each time slice a number of susceptible people become infected. This number is calculated as S*I*k1 where k1 is just some number we pull out of the air to represent the speed at which the disease spreads. Also Some people get 'removed' from the infected state (they recover, die or get physically taken out of the general population).

Whats Left?

I'm sorry this is too much too fast. Most of the rest of the course will be understanding what is above. However we will try to understand three exiting ideas that give your programs real power:
  1. Nesting loops: What happens when you put a loop inside a loop? Answ: I usually get confused. But lets live dangerously.
  2. Arrays: Instead of allocating variables one at a time we can ask for a block of 10 or 1000 or 10000000. They come in numberd blocks so we might have integers called i[0], i[1], i[2]......i[999999].
  3. Functions. If we organise our program so that it is divided up into may small program chunks called functions, not only will it be more readable but new techniques will be possible. Also a functin that we develope for one program might be useable by another.
Text file handout
Home Page of RDScience