David Vernon Principles of Computer Programming PDF
David Vernon Principles of Computer Programming PDF
Basic Principles of
Computer Programming in C
A C Program
/* Example 1 */
/* This is a C program to ask you to type a letter */
/* and then to tell you what you typed */
#include <stdio.h>
main() {
char letter;
A C Program
main() {
A C Program
#include <stdio.h>
A C Program
printf(Please type a letter & then press Return >>);
A C Program
scanf(%c,&letter);
A C Program
printf(You typed the letter %c, letter);
Did you spot the semi-colons, i.e. the ; characters, in all of the
above?
q In the C programming language, the semi-colons are used to temininate or finish-
off each distinct statement
Summary
/* This is a comment */
; terminates a statement
Summary
The program does something like this:
A Second Example
Lets say we want the program to compare two numbers and tell
us if they are the same.
q a simple task but all decisions basically come down to comparing two
values.
This time, rather than start with the finished program, well take
one step back and figure out for ourselves what it should look
like.
Well do this using the pseudo-code we met above.
A Second Example
A Second Example
Lets say the first number is 10 and the second number is 12.
How do we compare them?
q see if they are the same number.
q How can we say that?
q We could ask are they equal.
q In C the way we check to see if things are equal is to say something like:
if one_thing == another_thing
A Second Example
In the number system, 10 comes before 12
How might we formulate that? We simply say:
A Second Example
Thats progress but we need more.
What are we going to do if one thing is equal to another (or if
one thing is less than another)
Again, its fairly straightforward. You just say
then do something
A Second Example
And what if the answer to our question wasnt correct (or true)?
q We have two options:
do nothing
or
do something else
A Second Example
We normally write this as follows:
if one_thing < another_thing
then
do one thing
else
do a different thing
Note that if we didnt want to do anything at all if the test was not
TRUE (that is, if it was FALSE) wed just leave out the else part
(often called the else-clause)
A Second Example
#include <stdio.h>
main() {
/* Example 2 */
/* This is a C program to ask you to enter two */
/* numbers; it then compares them and prints a */
/* message to say whether they are equal or not */
#include <stdio.h>
void main() {
TEXT DELETED
if (first_number == second_number)
printf(The two numbers %d are identical,
first_number);
else
printf(The two numbers %d and %d are different,
first_number, second_number);
}
A Second Example
We declared them in the same way as before but we separated them with a
comma.
A Second Example
Note that we put a pair of brackets around the test in the if statement;
these brackets MUST be there
if (first_number == second_number)
A Second Example
In the second printf statement, we now have two variables:
first_number and second_number.
Finally, did you notice that we left out the word then in the C
program?
In C, the then is omitted
Since it is normally required in many other programming
languages and since it sounds more natural anyway, well keep
on using it in our pseudo-code and then simply drop it when
we write the corresponding C program
Now, lets enter and run the program
Example No. 3
Learn a little more C
Begin to learn how to solve problems
q software development is more about solving problems that it is about writing
code
q As we become more proficient at software development, we begin to take the
underlying skills (or writing code) for granted
Example No. 3 S1
C3 O1 M3 P3 U1 T1 E1
Example No. 3
First: how would you solve the problem if you had seven letters in
front of you?
q Probably, youd pick up the first letter and find out its value.
q Then youd pick up the second letter,
find out its value,
and add that to the first.
q Then youd pick up the third,
find its value,
and add it to what? To the running total.
q And again with the fourth, the fifth, the sixth, and the seventh.
Example No. 3
Thats the beginning of a solution
Example No. 3
What if we had not just 7 letters but 70
q The approach above is not going to work simply because wed need to write out
the above program segment 10 times
q Instead of writing out each and every step, we can say
do the following again and again and again until you have done it enough.
q This means we loop around the same code again and again until we are finished.
Example No. 3
In pseudo-code:
Example No. 3
Note the way we indented the three statements with respect to
the Do the following seven times
q this indentation is a way of visually saying that these are the statements which
are governed by the loop i.e. which are done seven times.
q Well see in a moment that the C language needs a little extra help in addition to
the indentation but well retain the indentation nonetheless.
Example No. 3
How do we know when we have looped seven times?
q We count! And when we have counted up to the total of seven, were finished.
q Of course, that means we start counting at 1
q Note that there are other way of counting.
11 to 17
0 to 6
Example No. 3
The C programming language has shorthand way of saying all
this.
q It uses a counter
q gives it an initial value
q tells it to add a number each time round the loop
q and also says when to stop counting
q Actually, it doesnt say when to stop, it says when it is allowed to keep on
counting the exact opposite of when to stop.
q That simply means: keep counting if we havent reached the required number
yet. Heres the C code:
Example No. 3
for (i=1; i<= 7; i = i+1)
Example No. 3
What about the next pseudo-code statement: pick up a
letter?
Weve done that already in our first program. We simply ask the
user of the program for a letter and then we read it:
Example No. 3
if letter == A
then
value is 10;
else
if letter == B
then
value is 2;
else
....
if letter == Z
then
value is 10;
Example No. 3
Note something very important:
q we wrote the actual letter, not on its own, but in between two inverted commas
(e.g. Z).
q Why didnt we just write the letter on its own (e.g. Z)?
q When we wrote the word letter we were referring to a variable called
letter, an object into which we could place a value when we needed to (and
change the value later, if we needed to).
q Similarly, if we write A then this is just a variable with a very short name
q We want the value of the letter A, i.e. the C representation of the letter A.
Example No. 3
To make this a little clearer, lets consider another example.
q A short while ago, we used a variable called i as a counter
q i took on the numerical values 1, 2, 3, 4, 5, 6, and 7 in turn
q In this case, i is a number variable and we give it number values
Example No. 3
q Actually, there are two types of numbers we could choose:
real numbers (i.e. numbers with a decimal place)
whole numbers (i.e. numbers with no decimal place).
In computer terminology, we refer to real numbers as floating point numbers (there is
a technical reason for this to do with their computer representation but we dont have
to bother with it at this point).
In C, we call floating point numbers float for short.
We refer to the whole numbers as integers or int for short.
Example No. 3
q So what about our letters?
q Letters are just a subset of things called characters which also include
exclamation mark (!), commas (,), full stops (.), and so on.
q In fact anything you can type on a keyboard is a character.
q In C, we call them char for short.
Example No. 3
Whenever we declare a variable in a program, we must say what
type of variable it is.
q Is it an int (integer or whole number)
q a float (floating point number or real number)
q or a char (character)?
Well see how to do this in a moment when we write out this C
program.
Example No. 3
Note that float, int, and char are not the only types in C.
There are many other types and well even define our own types.
However, the float, int, and char types form the basic
building blocks for all these more advanced types.
Almost everything we can think of can be described (i.e.
represented) by a sequence of characters or a collection of
numbers.
Example No. 3
In Scrabble, not all the letters have different values: some letters
have the same value.
We can use this fact to help reduce the number of if-then-else
statements by grouping the letters which have the same value
together:
Example No. 3
Letter Value
AEILNORSTU 1
DG 2
BCMP 3
FHVWY 4
K 5
JX 8
ZQ 10
Example No. 3
Our series of checks now becomes:
if letter == or letter ==
then
value is ;
else
if letter ==
then
value is ;
else
...
if letter ==
then
value is 10;
Example No. 3
We are almost ready to write our program.
We have decided on the actions we need to take the logic of
the program now all we need to do is to decide what variables
we need to represent our information.
In this example, we have only three pieces of information:
q The letter entered by the user
q its Scrabble value,
q the total Scrabble value
q (the enter character)
Example No. 3
Have we forgotten anything?
Yes, we have! We forgot our loop counter i.
Lets give these four variables names and types.
/* Example 3 */
/* Compute the total value of 7 Scrabble letters */
/* Input: the user is prompted to enter each letter */
/* in turn */
/* Output: the program prints the sum of the seven */
/* individual letter values */
#include <stdio.h>
void main() {
/* initialize variables */
total_scrabble_value = 0;
if ((letter == ) (letter == ))
scrabble_value = 0;
else
if ((letter == ) (letter == ))
scrabble_value = 0;
MORE.
Example No. 3
Again, several things are worth noting about this program:
Did you notice the { which follows immediately after the for statement?
In C, only one statement is part of the loop (i.e. only one statement is repeated
again and again.)
This is the statement which follows immediately after the for statement.
If we want more than one statement to be repeated (and we certainly do in this
case) then we simply enclose them in a pair of braces or curly brackets
Example No. 3
Example No. 3
Note how we translated our pseudo-code statement:
into
Example No. 3
We see three things:
q Second, we put brackets around each test.
This isnt strictly necessary but its good practice.
C has its own rules about how it goes about figuring out whether or not the if
statement is true or false and, on occasion, the rules can be tricky to follow.
However, if we put brackets around the test like we have, its clear how things work.
We call one of these tests (e.g. letter == A) a relational expression because it finds
out the relationship between the object on the left (in this case the variable letter) and
the object on the right (the character value A)
Example No. 3
We see three things:
q Thirdly, we put a pair of braces around the entire if test just as we did in the
second example.
Example No. 3
As a general rule, when we use variables we should never
assume anything about their initial values.
Variables are like boxes for holding things.
When you declare a variable, you get a box but you have no idea whats in it.
So, we always repeat, always initialize the variables with some value before
we ever use that variable.
Think about it: it makes a lot of sense to put something into the box before taking
anything out!
Example No. 3
When we declared the four variables, we put one on each line
but we didnt have to.
We do it just to make the presentation visually appealing and to improve
readability.
We assigned a value to total_scrabble_value with the =
operator.
A very common mistake made by people who are new to C is to
get the two operators = and == mixed up.
Example No. 3
The difference is crucial:
== is a relational operator and it is used to test the equality of the two objects on
either side of it. Actually, these two objects are called operands: the things that
the operators operate on!)
Example No. 3
At this point, weve learned quite a lot of C programming. We
know how to:
Key Skills
q Manual walkthroughs
q Creative thinking about the problem
q Spotting patterns
q Using pseudo-code
Example 4:
Comparing Numbers
Design and write a program to prompt the user
three times and reads three numbers.
It should then compare these three numbers
and tell the user whether
q all three numbers are the same
q all three numbers are different
q just two numbers are the same
tell the user which two numbers they are
Example 4:
Comparing Numbers
The program should continue to ask the user
for input until he enters three zeros.
In pseudo-code:
n1 = 1; n2 = 1; n3 = 1;
While the three numbers are not all zero
(i.e. NOT(all three numbers are zero))
do the following
Read a number n1
Read a number n2
Read a number n3
if n1 == n2 and n2 == n3 and n1 == n3
then
print the numbers are all the same
else
if n1 != n2 and n2 != n3 and n1 != n3
then
print the numbers are all different
else
/* two are the same which are they? */
if n1 == n2
then
print two are the same:
the first and the second: n1, n2
else
if n1 == n3
print two are the same:
the first and the third: n1, n3
else
print two are the same:
the second and the third: n2, n3
/* A program to prompt the user three times and reads three numbers. */
/* It compare these three numbers and tell the user whether */
/* */
/* - all three numbers are the same */
/* - all three numbers are different */
/* - just two numbers are the same */
/* in this case, it also tells the user which two numbers they are */
/* */
/* The program continues to ask the user for input until he enters */
/* three zeros. */
#include <stdio.h>
#define TRUE 1
#define FALSE 0
void main() {
n1 = 1;
n2 = 1;
n3 = 1;
n1 = 1;
n2 = 1;
n3 = 1;
if (n1 == n2) {
printf("The first and second numbers are the same: %d\n,
n1, n2);
}
else {
if (n2 == n3) {
printf("The second and third numbers are the same: %d\n",
n2, n3);
}
else { /* no need to check if the first and third */
/* are the same ... it's the only possibility */
printf("The first and third numbers are the same:%d\n",
n1, n2);
}
}
}
}
}
}
Example No. 4
Note how we translated our pseudo-code statement:
if n1 == n2 and n2 == n3 and n1 == n3
into
if ((n1 == n2) && (n2 == n3) && (n1 == n3))
Example No. 4
We used a while loop rather than a for loop
It has the format:
Example No. 4
while (! ((n1 == 0) && (n2 == 0) && (n3 == 0))) {
}
Example No. 4
Example No. 4
We could also have used a third type of loop:
the do while loop
It has the format:
do
statement
while <condition is true>
Programs:
Statements + Data Constructs
Each program contains one or more functions,
one of which is called main
int main()
{ /* beginning of body */
} /* end of body */
Declarations
q Define variables:
name
o a sequence of characters by which we refer to that variable: this is
called an identifier
type
o a definition of all the possible values that the variable can have.
For example:
int counter;
o declares a variable called counter which can take on any of the
integer values
o We say the counter variable is instantiated
Data Constructs
Declarations
q Optionally, declarations initialize variables
q For example:
int counter = 0;
declares a counter of type integer and gives it an initial value zero
Data Constructs
Data Constructs
There are three basic types in C:
int
float
char
q int variables can have integer values
q float variable can have real number (floating point) values
q char variables can have character values
Data Constructs
Floating Point Values
q Type float
82.247
.63l
q Type double (8 byte representation)
82.247
.63
83.
47e-4
1.25E7
61.e+4
Data Constructs
Character Values
q A enclosed in single quotes
q Special characters (escape sequences)
\n newline, go to the beginning of the next line
\r carriage return, back to the beginning the
current line
\t horizontal tab
\v vertical tab
\b backspace
\f form feed
\a audible alert
Data Constructs
Character Values
\\ backslash
\ single quote
\ double quote
\? question mark
\000 octal number
\xhh hex number
Data Constructs
Floating Values
Implementation dependent
Data Constructs
String Values
q String literal
q String
How many numbers?
a
q a is not the same as a
q A string is an array of characters terminated by the escape
sequence \0
q Other escape sequences can be used in string literals, e.g. How
many\nnumbers?
Statements: Comments
/* text of comment */
Statements: Assignment
Assignment Statement
q Syntax:
variable = expression ;
q For example
x = p + q * r;
q Operators:
+, *, =
q Operands:
p, q, r, x
Statements: Unary Operators
Unary operator: -, +
neg = - epsilon;
pos = + epsilon;
a = b + c;
sizeof (double)
Statements: output
For output, use (C library function) printf
char ch = A; int i = 0;
float f = 1.1; double ff = 3.14159;
Statements: output
To use printf you must include stdio.h
#include <stdio.h>
syntax:
printf(<format string>,
<list of variables>);
<format string>
String containing text to be printed and
conversion specifications
Statements: output
Conversion specifications
%c characters
%d decimals
%f floats or doubles
%s strings
Statements: input
For input, use (C library function) scanf
char ch = A; int i = 0;
float f = 1.1; double ff = 3.14159;
Comparison and
Logical Operators
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
&& logical AND
|| logical OR
! logical NOT
Comparison and
Logical Operators
<, >, <=, >= are relational operators
== and != are equality operators
Conditional Statements
Syntax
if (expression)
statement1
else
statement2
q The else clause is optional
Semantics
q statement1 is executed if the value of expression is non-zero
q statement2 is executed if the value of expression is zero
Conditional Statements
Where appropriate statement1 and
statement2 can be compound statements
if (a >= b)
{ x = 0;
if (a >= b+1)
{ xx = 0;
yy = -1;
}
else
{ xx = 100;
yy = 200;
}
}
Iteration Statements
while-statement syntax
while (expression)
statement
semantics
q statement is executed (repeatedly) as long as expression is non-zero
(true)
q expression is evaluated before entry to the loop
Iteration Statements
/* compute s = 1 + 2 + ... + n */
s = 0;
i = 1;
while (i <= n)
{ s += i;
i++;
}
Iteration Statements
do-statement syntax
do
statement
while (expression);
semantics
q statement is executed (repeatedly) as long as expression is non-zero
(true)
q expression is evaluated after entry to the loop
Iteration Statements
/* compute s = 1 + 2 + ... + n */
s = 0;
i = 1;
do /* incorrect if n == 0 */
{ s += i;
i++;
} while (i <= n)
Iteration Statements
for-statement
for (statement1 expression2; expression3)
statement2
semantics
q statement1 is executed
q statement2 is executed (repeatedly) as long as expression2 is true
(non-zero)
q expression3 is executed after each iteration (i.e. after each execution
of statement2)
q expression2 is evaluated before entry to the loop
Iteration Statements
/* compute s = 1 + 2 + ... + n */
s = 0;
for (i = 1; i <= n; i++)
s += i;
Switch
switch (expression) statement
q the switch statement causes an immediate jump to the
statement whose label matches the value of expression
q statement is normally a compound statement with several
statements and several labels
q expression must be of type int, char
Switch
switch (letter)
{ case N: printf( New York\n );
break;
case L: printf( London\n );
break;
case A: printf( Amsterdam\n );
break;
default: printf( Somewhere else\n);
break;
}
Switch
switch (letter)
{ case N: case n: printf( New York\n);
break;
case L: case l: printf( London\n);
break;
case A: case a: printf( Amsterdam\n);
break;
default: printf( Somewhere else\n);
break;
}
Bit Manipulation
File Input/Output
So far, we have read all input from the keyboard
and written all output to the screen.
Often, we want to be able to read and write
information to and from files on disk
We can use everything we learned about printf
and scanf to do this, with just a few changes
File Input
File Input
fp=fopen(input.txt, "r");
if (fp == 0) {
printf("unable to open input.txt\n");
exit();
}
File Input
int end_of_file;
end_of_file = fscanf(fp,%d,&number);
if (end_of_file == EOF) {
printf(end of input.txt reached\n");
exit();
}
File Input
int end_of_file;
fp=fopen(input.txt, "r");
if (fp == 0) {
printf("unable to open input.txt\n");
exit();
}
/* read a number */
fclose(fp);
File Output
fp_out=fopen(output.txt, w");
if (fp_out == 0) {
printf("unable to open output.txt\n");
exit();
}
fprintf(fp_out, %f%, pi);
fclose(fp_out);
File Input/Output
Exercise
q Write a program to read a file containing five integers and
find the maximum value
q Input: in.txt
q Output: maximum is written to the screen
File Input/Output
Exercise
q Write a program to copy a file of integers to another file
q Input: in.txt
q Output: out.txt
q Note: we dont know how many numbers are in the input file
Functions
C allows us to create our own functions
We normally use functions if we have a well-
defined segment of code which we wish to use
many times in a program
We can then use that segment of code simply
by referring to the function name
Functions
Function A Question:
How do we provide
the functions with information
Function B or data to use?
Main(){ Answer:
A(); We use parameters
B(); and arguments
}
Functions
void B(float y)
The value of z is passed
Main(){ to the function B
float z;
A(10); This is called
B(z); parameter passing
}
Argument
Functions
Function Definition:
q Function name
q Function type
q Function parameters
q Constituent statements
q Local variables
Function Call
q Passing parameters (arguments)
q Execution of a function
void main()
{
int x=2;
Functions
Points to notice:
Functions
2 Pass parameter
2 by value:
x
message_number make a copy
of the argument
message message
Functions
What happens if we DO want to change the
argument?
Functions
/* Example function call */
void main()
{
int x=2, check;
message2(1, &check);
message2(x, &check);
message2(0, &check);
}
/* Pass a parameter by reference */
Functions
/* Example function call */
void main()
{
int x=2, check;
}
Functions
Points to notice:
q we now have two parameters and two arguments;
both agree in type
Functions
2 2
x message_number
0
Pass parameter
0 *valid by reference
message
check
Functions
Altering Variables via Parameters
C++ allows reference parameters
Functions
Altering Variables via Parameters
C does not allow reference parameters
* (unary operator)
object that has the address given by the operand
Functions
Altering Variables via Parameters
Functions
Altering Variables via Parameters
Pointers
q p is a pointer
void main()
{
int x=2, check;
Functions
Points to notice:
q the type of the variable (or value) used in the return statement
must be the same as the type of the function
Functions
Example 2:
q Write a function to sort two floating point numbers, each
passed as a parameter.
q On returning from the function, the first argument should be
the smaller of the two numbers.
q The function should return 0 if the numbers are different, 1 if
they are the same.
Data Constructs - Arrays
We know that there are three basic types in C:
int
float
Char
We declare an array by
q giving its base type (i.e. the type we are collecting together)
q giving the number of elements in the collection
q int a[30]; /* declare an array of */
/* 30 integers */
Data Constructs - Arrays
z a
0 1 2 3 4 5 6 7 8
#include <stdio.h>
void main()
{
int x[40];
initialize(x, 40, 0); /* init array values to zero */
}
Data Constructs - Arrays
2-D arrays
2-D Arrays
float a[4][5];
a[3][0] = 6.1;
6.1
Data Constructs - Arrays
#include <stdio.h>
init_2D(x, 5, 6, 0);
init_2D(x, 1, 6, 7);
}
q all strings have an extra character at the end to mark the end
of the sequence of characters: \0
Data Constructs - Arrays
h e l l o \0
0 1 2 3 4 5 6 7 8
H I \0
0 1 2 3 4 5 6 7
#include <string.h>
struct colour {
int r;
int g;
int b;
}
white.r = 255;
white.g = 255;
white.b = 255;
black.r = 0; black.g = 0; black.b = 0;
Data Constructs - Structures
For example:
struct point {
int x;
int y;
struct colour clr;
}
Data Constructs - Structures
Example input:
1 2 23 45 67
2 3 44 55 0
33000
4 4 255 255 255
Example output:
23 45 67
44 55 0
000
255 255 255
Data Constructs - Structures
Example input:
1 2 23 45 67
3 3 44 55 0
33000
4 4 255 255 255
Example output:
1 2 23 45 67
3 3 44 55 0
4 4 255 255 255
Arrays, Pointers, and Strings
Address Arithmetic
Address of operator &
The value of an expression &x is an address
#include <iostream.h>
int main()
{ int table[10], minimum(int *a, int n);
cout << Enter 10 integers: \n;
for (int i=0; i<10; i++) cin >> table[i];
cout << \nThe minimum of these values is
<< minimum(table, 10) << endl;
return 0;
}
Functions
Function Arguments and Arrays
// definition of minimum, version A
P = &n
Arrays, Pointers, and Strings
Pointers
It is essential to assign value to pointers
int main()
{ char *p, ch;
*p = A; // Serious error! Why?
return 0;
}
int main()
{ char *p, ch;
p = &ch;
*p = A;
return 0;
}
Arrays, Pointers, and Strings
Pointers
Pointer conversion and void-pointers
int i;
char *p_char;
*ABC is equal to A
*(ABC + 1) is equal to B
*(ABC + 2) is equal to C
*(ABC + 3) is equal to \0
ABC[0] is equal to A
ABC[1] is equal to B
ABC[2] is equal to C
ABC[3] is equal to \0
Arrays, Pointers, and Strings
Strings
Assigning the address of a
string literal to a pointer
variable can be useful:
// POINTER
#include <stdio.h> // POINTER
int main() #include <iostream.h>
{ char *name = main; int main()
printf(name); { char *name = main;
return 0; cout << name;
} return 0;
}
char s[4];
int main()
{ char s[100]=Program something., t[100];
strcpy(t, s);
strcpy(t+8, in C++.;
cout << s << endl << t << endl;
return 0;
} // what is the output?
int main()
{ char *p;
set_new_handler(0); // required with Borland C++
for (int i=1;;i++) // horrible style
{ p = new char[10000];
if (p == 0) break;
cout << Allocated: << 10 * i << kB\n;
}
return 0;
} // rewrite this in a better style!
#include <stdlib.h>
int n;
char *s;
...
cin > n;
s = (char *) malloc (n);
#include <stdlib.h>
int n;
float *f;
...
cin > n;
s = (float *) malloc (n * sizeof(float));
q free(s);
int main()
{ char *p[3] = {Charles, Tim, Peter};
int age[3] = {21, 5, 12}, i;
for (i=0; i<3; i++)
printf(%-12s%3d\n, p[i], age[i]); // left align
return 0;
}
f(table);
return 0;
}
int f(float t[][5]) // may omit the first dimension
{ // but all other dimensions must
} // be declared since it must be
// possible to compute the
// address of each element. How?
Table[2][3]
dtable
dtable[2][3]
argv
Program name
argc = 4 A B C \0
P Q \0
X Y Z \0
#include <stdio.h>
...
char s[50]=123 456 \n98.756;
int i, j;
double x;
sscanf(s, %d %d %lf, &i, &j, &x);
#include <stdio.h>
...
char s[50]=123 456 \n98.756;
sprintf(s,Sum: %6.3f Difference:%6.3f,
45 + 2.89, 45 - 2.89);
// function definition
float example (int i, int j)
{ return 3.14159 * i + j;
}
p(12, 34); // !!