Upload
ravg10
View
211
Download
3
Embed Size (px)
Citation preview
06-18187.1 Foundations of Computer Science Paul Blain Levy8 October, 2007 School of Computer Science, University of Birmingham
Handout 2
Structured Programming
1 Pseudocode
Over the next few weeks we shall look at the basic building blocks of algorithms, and how to usethem. These building blocks can be expressed in many different programming languages such as Java,C, Pascal, Pop-11, Basic, etc. But the algorithms look roughly the same. People often describe analgorithm using pseudocode, an informal language that incorporates bits of English when convenient.In these notes, we shall use pseudocode based on Java, because you are learning Java in the SoftwareWorkshop module.
Programs are built up out of commands. We shall learn some basic commands, and also someways of building more complex commands out of other commands. This way of organizing programsis called structured programming and was popularized in the 1970s. The basic commands we shallsee are printing and assignment. The more complex features are selection, for loops, while loops,procedures and functions (the last two we do not study yet).
2 The Print Command
Here is a program. (We follow Java by ending each individual command with a semicolon.)
print (“I ”);print (“love ”);print (“you.”);
It prints
I love you.
In this program we see examples of strings. A string is a piece of data that consists of characters(e.g. letters, spaces, digits, symbols)
3 The println Instruction
The println command prints a string, and then prints a newline character, so that the output movesonto the next line. Here is a program:
println (“Good morning, students.”);println (“Here are your marks.”);
Its output is
Good morning, students.
Here are your marks.
Exercise 1 What does the following print? (There’s a trick!)
1
print (“Hello, ”);print (“Mary. I would li”);println (“ke to buy”);print (“half a kilo of ”);println (“carrots.”);print (“But only if”);println (“they’re cheap today.”);
�
Note In Java, you would write System.out.print instead of print, and you would writeSystem.out.println instead of println.
4 Turning An Integer Into A String
I told you that the print and println commands print strings. . . but what if we want to print aninteger? We can use inttostring to turn an integer into a string, then print it. Example:
println inttostring(8+7);
This prints
15
By contrast, if you write
println (“8+7”);
it would print
8+7
8+7 is the integer 15, whereas inttostring(8+7) is the string “15”, which is two characters long.It’s important to understand the difference. Many programming languages allow you to omit theinttostring, allowing you to write
println (8+7);
but you should be aware that it’s there implicitly.
Exercise 2 This exercise tests whether you know the standard conventions for writing arithmetic.What does this program print?
println ((3 + 4) × 2);println (3+(4 × 2));println (3+4× 2);println (“3+4× 2”);println ((7-5)-4);println (7-(5-4));println (7-5-4);
�
2
5 Comments
If you want to write a comment on your program, you put it after a // symbol. Anything you writebetween that symbol and the end of the line does absolutely nothing.
println (“Goodbye, Bill.”);println (“It’s been a pleasure seeing you.”);// Actually, I can’t stand him.println (“You must come again.”); // hopefully not
This prints
Goodbye, Bill.
It’s been a pleasure seeing you.
You must come again.
6 Booleans
A boolean is either true or false. Booleans often arise from comparisons, using the operators ==(equal to), ! = (not equal to), >, <, >=, <=. For example
3 + 4 > 7 is false
3 + 4 >= 7 is true
3 + 4 == 7 is true
3 + 4 ! = 7 is falseJust as we can do arithmetic on integers, so we can do it on booleans. && means “and”, || means
“or” and ! means “not”. The following table shows how.true && true is true
true && false is false
false && true is false
false && false is false
true || true is true
true || false is true
false || true is true
false || false is false
! true is false
! false is trueFor example:
(! (true || false)) && ! false
is false. Another example:
! ( (Paris is the capital of France) || (3 + 4 > 7))
is false.
1. (3 + 17 > 2 + 5) || ! (vinegar is acidic)
2. ! ! ! ! ! ! (22 >= 8)
3. (3 × 5 < 3) && ! (this lecture is fun)
3
We can use booleans in programs with if commands.
println (“Hello.”);if (3>7) {
println (“The world is very strange,”);println (“but we learn to live with it.”);
} else {println (“Computer science teaches us”);println (“ways of exploiting mathematical truths.”);
}println (“Goodbye.”;
This prints
Hello.
Computer science teaches us
ways of exploiting mathematical truths.
Goodbye.
If the boolean that follows the if is true, the block of code immediately after is executed. If itis false, the block of code marked else is executed.
if (15>2) {println (“red”);if (12>8) {
println (“green”);println (“blue”);
} else {println (“yellow”);println (“black”);
}} else {
println (“purple”);}
In many languages (such as Java), you can omit the else clause. So you can just write
if (15>2) {println (“green”);println (“blue”);
}
7 Variables
A variable is a cell (or box) containing something—an integer, let’s say. The contents changes overtime. Let’s say that x is a variable storing the integer 5, and y is a variable storing the integer 7,and now we run the following program:
println (x+3);x = x+y;println (x+3);
This will print
4
8
15
In the first line, x + 3 actually means “the contents of x, plus 3”.The second line is called an assignment. It is executed in two steps:
1. Work out the right-hand side.
2. Place the answer in the variable indicated on the left-hand side.
In this example, when we work out the right-hand side (which means “the contents of x, plus thecontents of y”), we get the answer 12. So the variable x is assigned 12. The previous contents (5) isdiscarded.
The instruction
int x = 5;
is slightly different from x = 5;. It means create an integer variable x initialized to 5.
Exercise 3 Execute
int x = 11;int y = 5;int z = x+1;y = y+1;x = x × z;if (y>3) {
print (“happy”);} else {
print (“sad”);}
�
8 For Loop
Consider the following program
println (“good”);println (“bad”);
Let’s say you want to repeat this 5 times. One possibility is this:
println (“good”);println (“bad”);println (“good”);println (“bad”);println (“good”);println (“bad”);println (“good”);println (“bad”);println (“good”);println (“bad”);
5
But if you wanted to repeat it 100 times, this would be rather tedious. And what if you want torepeat it x+7 times?
Here is an alternative:
for (int i = 0; i<5; i++) {println (“good”);println (“bad”);
}
This is called a for loop. The two lines between the braces are called the body of the loop. What thisprogram does is to
• first execute the body with i being 0
• then execute the body with i being 1
• then execute the body with i being 2
• then execute the body with i being 3
• then execute the body with i being 4.
If we try the following
for (int i = 0; i < 5; i++) {println (“good”);println (i+3);
}
it prints
good
3
good
4
good
5
good
6
good
7
If the bounds are equal, e.g.
for (int i = 4; i<4; i++) {println (“good”);println (i+3);
}
the body will be executed 0 times, i.e. the code will do nothing.
Exercise 4 Suppose x stores 3 and y stores 17 and z stores 2. What does the following print?
for (int i = x+3; i<y-5; i++) {print (i+7);z = z+4;
}print (z);
6
�
Exercise 5 What does this print?
for (int i = 0; i<10; i++) {if (i>4) {
println (“red”);} else {
println (“green”);}
}
�
Now that we understand what loops are, we can put loops inside other loops. This is callednesting.
Exercise 6 What does the following program print?
for (int i = 0; i<4; i++) {for (int j = 0; j<i; j++) {
println (i+j);}
}
�
9 While Loops
A for loop is very useful when you know in advance how many times you want to repeat a block ofcode. But sometimes that’s not the case. A while loop is a way of performing a block of code againand again, checking each time that a certain condition is true. Let’s say we have an integer variablex storing 5, and an integer variable y storing 11, and we execute the following:
while (x < y) {x = x+3;y = y+1;println (“red”);
}println (“green”);
The lines between the braces are called the body of the loop, and the condition at the top is calledthe loop condition.
• First, we check the loop condition.
• It’s true, so we execute the loop body, increasing x to 8 and y to 12, and printing “red”.
• Then we check the loop condition again.
• It’s true, so we execute the loop body, increasing x to 11 and y to 13, and printing “red”.
• Then we check the loop condition again.
• It’s true, so we execute the loop body, increasing x to 14 and y to 14, and printing “red”.
7
• Then we check the loop condition again.
• It’s false, so we’ve completed the while loop.
• We then print “green”.
Here are some more examples of while loops, that illustrate different aspects of this concept.Suppose x is an integer variable storing 5, and we run
while (x < 8) {x = x+10;println (“red”);x = x-9;
}println (“green”);
This prints
red
red
red
green
It emphasizes the fact that the loop condition is checked before the loop body, not during the loopbody. The fact that the loop condition becomes false in the middle of the loop body does not matter.
Suppose x is an integer storing 5, and we run
while (x < 5) do {println (“red”);x = x+1;
}println (“green”);
The loop condition is tested and immediately found to be false. So the loop body is not executed.All that gets printed is
green
Suppose x is an integer storing 5, and we run
while (x>4) {println (“red”);x = x+1;
}println (“green”);
This prints
red
red
red
red
red
red
8
and so on forever. Because the loop condition is true every time, the loop never terminates1.Suppose x is an integer storing 5, and we run
while (x>4) {if (x < 8) {
println (“red”);x = x+1;
} else {x = x+2;
}}println (“green”);
This program prints
red
red
red
and then it just hangs. Nothing more is ever printed, and it never terminates.
Exercise 7 Suppose x stores 0 and y stores 2. Run
while (x<3 and y<3) {x = x+1;y = y-1;println (x);println (y);
}
�
10 Drawing For Loops And While Loops As Flowcharts
Let’s go back to the program
while (x < y) {x = x+3;y = y+1;println (“red”);
}
A way of showing what this program does is to draw it as a flowchart. This is a diagram where everycommand is written as a rectangle, and arrows indicate where to go next. Each condition is shownas a diamond, with YES and NO arrows coming out of it.
1That’s not what happens in Java, though. We’ll learn about this in a few weeks’ time.
9
x < y
x := x+3
y := y+1
START
ENDNO
YES
println "red"
This clearly shows that the condition is tested before each body.Now recall the for loop we saw above
for (int i=0; i<5; i++) {println (“good”);println (i+3);
}
We can express this with a while loop by first assigning i to be 0, and then incrementing it (i.e.increasing it by one) after each execution of the body.
int i = 0;while (i < 5) {
println (“good”);println (i+3);i = i+1;
}
and we can draw this as a flowchart:
10
i < 5
START
ENDNO
YES
pritnln ("good");
println (i+3);
i = i+1;
int i = 0;
11 A Program For A Task
So far, all of our programs have served merely to illustrate the language, not to accomplish anyprogramming task. Let’s now suppose we want to divide 14 by 3 and find the remainder.
amountleft = 14;numremoved = 0;while (amountleft >= 3) {
amountleft = amountleft - 3;numremoved = numremoved + 1;
}print (“Quotient is ”);println (numremoved);print (“Remainder is ”);println (amountleft);
11