Principles of Comp Programming - 3 Reduced Ex
Principles of Comp Programming - 3 Reduced Ex
Computer
1
Programming
LECTURE NOTES
Dr George O. Ofori-Dwumfuo
BSc, PhD, FBCS, JP
Wisconsin Int Univ College
Reserved Words. These are words such as if, int and else, which
have a predefined meaning that cannot be changed. These words
cannot be used as identifiers, since they play key roles in the
language.
Library Identifiers. These words are supplied default meanings by
the programming environment, and should only have their
meanings changed if the programmer has strong reasons for doing
so. Examples are cin, cout and sqrt (square root).
Programmer-supplied Identifiers. These words are "created" by the
programmer, and are typically variable names, such as firstname,
Mar 27, 202
year_now, capital_o2 and another_age. 4
19 Identifiers…
Identifiers have two aspects: name and value.
The name of an identifier remains the same all
through the program, but
its value may change from time to time
depending upon the processing going on.
Purpose of a variable:
simply put, is to save some value off, until
you are ready to:
use it,
refer it,
compare it with something else,
or evaluate it against something else.
(Stage 1)
Write comments suitable for the WU Student
Results Program (WUSRP)
(Stage 2)
List possible identifiers suitable for the WU
Student Results Program (WUSRP)
b) number = number + 1;
In each example above, the expression on the right is computed, and the resulting
value assigned to the variable named on the left
In the second example above, the current value of the variable number is used in
evaluating the expression on the right hand side.
The result is then assigned to the same memory location, that of number.
Thus number on the right refers to the old number, while the same name on Mar
the27,left
202
4
refers to the new.
Assignment Statements: Logical
39
Expression1Expression2...ExpressionN
The series of statements:
cout << "Enter the year for which you wish to know your age.\n";
cout << "Your age in " << another_year << ": ";
(Stage 4)
(Stage 5)
Input data into your appropriate WUSRP
identifiers or variables (assume initially that
there is only one student per course)
(Stage 6)
Write the appropriate assignment statements
(Stage 8)
Still assuming that there is only one student per
course, concatenate all your program segments so far
into one complete program
return 0;
Mar 27, 202
4
}
54 SEQUENTIAL FLOW…
All (C++) programs have this basic "top-level" structure.
Notice that each statement in the body of the program ends with a
semicolon.
In a well-designed large program, many of these statements will
include references or calls to sub-programs, listed after the main
program or in a separate file.
These sub-programs have roughly the same outline structure as the
program here, but there is always exactly one such structure called
main.
(You will learn more about sub-programs later.)
Input F
Subtract 32
Multiply by 5 Input F
Divide by 9
Output C Subtract 32
Multiply by 5
Divide by 9
Input R,H,D
Input R,H,D
G=R*H
G = R*H
P = G-D
P=G-D
Update records
Print cheque
Update Record
Print Cheque
cout << "Enter the year for which you wish to know your age.\
n";
cin >> another_year;
another_age = another_year - (year_now - age_now);
cout << "Your age in " << another_year << ": "; Mar 27, 202
4
Condition
False True
Steps Steps
B A
Steps
B
Exit
Notice that the paths come together again; there is just one entry to the component,
and one exit from it. Note also that either of steps A or B may be empty. (In flowcharts,
Mar 27, 202
rectangular boxes are used for the sequential steps and diamond-shaped boxes 4 for
the decision step.)
62 Example
Code= D
False True
Subtract Add
Amount Amount
Steps
B
Exit
Condition 1
False True
Exit
66 Example:
Suppose that in the bank example above, the
bank wants a safeguard against incorrect code
values (may be, due to typing errors), how
should the algorithm be modified?
Here, another condition needs to be added; if the
code is neither D nor W, an error message is
printed and no change is made to the account.
Algorithm
If code = D
Then add amount
Otherwise test for error
If code=W
Then subtract amount
Otherwise print error message
Code=D
True False
Exit
69 IF-THEN-ELSE Statement
IF logical expression
(THEN) carry out steps A
ELSE carry out steps B
If the steps to be carried out in A involve more than one
statement, then the necessary statements are framed
together using the marks BEGIN and END, DO and
END, {} or ( ), depending on the programming
language.
Mar 27, 202
4
73 C++ if statement
In C++, it is simply called an if statement, and the general
syntax is:
if (condition)
{Statement1;
...
...
StatementN;
} else
{StatementN+1;
...
...
StatementN+M;
}
Mar 27, 202
4
74 Examples:
a) if (nummaps < maxmaps)
nummaps += 1;
else
{
cout << “capacity exceeded”;
quit = true;
};
// true may have to be defined as logical before use
b) if (rate < alarm)
cout << “ time is” << time<< “ rate is” << rate;
else
cout << “alarm” << alarm <<” rate is” << rate;
Mar 27, 202
4
75 C++ if statement…
The "else" part of an "if statement" may be
omitted, and furthermore, if there is just one
Statement after the "if (condition)", it may be
simply written as:
if (condition)
Statement;
b) if (n >=) 500
{ cout << “d”;
n - = 500;
};
c) if (number > max)
{max = number;
location = count;
}; Mar 27, 202
4
Nested IF Statement
77
It is quite common to find "if statements" strung together in programs, as follows. This is called
nesting:
...
if (total_test_score < 50)
cout << "You are a failure. You must study much harder.\n";
else if (total_test_score < 65)
cout << "You have just scraped through the test.\n";
else if (total_test_score < 80)
cout << "You have done quite well.\n";
else if (total_test_score < 95)
cout << "Your score is excellent. Well done.\n";
else {
cout << "You cheated!\n";
total_test_score = 0;
}
Mar 27, 202
4
...
Course Project…
78 WU Student Results Program (Stage 9)
Condition
False True
Steps
A
Exit
Notice that this component, like the others, has just one entry
and one exit.
Mar 27, 202
4
83 The Indexed Loop
When the exact number of repetitions can be
specified conveniently, the indexed form of
loop control can be used; the indexed loop.
The procedure is repeated for each
designated value of an integer variable
known as the index, (or control variable or
running variable.)
True False
Count > 100
Do Convert
Increase Count
Exit
Mar 27, 202
4
85 Example:…
In the above example, notice that Count is
initialized at one.
This makes the governing condition false, so the
conversion steps are carried out (Convert) for the
first time.
Count is then increased to 2, a second transit of the
loop is made, and so on.
After the 100th execution of the procedure for the
conversion, Count goes to 101, the condition
becomes true, and exit from the loop occurs.
Where
ind = index or loop counter
lwb = starting value of loop counter
upb = maximum value of loop counter
inc = incremental value of loop counter
Eg:
FOR I=1 TO 100 BY 1
}
return 0; Mar 27, 202
4
}
91 Example code:
The above code produces the output:
Actually, any "for" loop can be re-written as a "while" loop. Similarly, any
"while" loop can also be written as a "for" loop.
For example, the last program code can be written equivalently as follows:
int main()
{ int number;
char character;
number = 32;
while (number <= 126)
{
character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";
cout << number << " in the computer.\n";
number++;
}
return 0; Mar 27, 202
4
}
96 Do ... while
There is a third kind of "loop" statement (in C++,
etc) called a "do ... while" loop (or
REPEATUNTIL statement in some other
languages).
These differ from the "for" and "while" loops in
that the statement(s) inside the {} braces are
always executed once, before the repetition
condition is even checked, ie,
the system performs the steps before testing the
condition.
FOR (….)
{ FOR (….)
{
…….
}
};
Program A
int main(){ int year_now, age_now, another_year, another_age; cout <<
"Enter the current year then press RETURN.\n"; cin >> year_now; cout
<< "Enter your current age in years.\n"; cin >> age_now; cout <<
"Enter the year for which you wish to know your age.\n"; cin >>
another_year; another_age = another_year - (year_now - age_now); if
(another_age >= 0) { cout << "Your age in " << another_year << ": ";
cout << another_age << "\n"; } else { cout << "You weren't even born
in "; cout << another_year << "!\n"; } return 0; } Mar 27, 202
4
Program B)
102 int main()
{ // This is the better of the two programs
int year_now, age_now, another_year, another_age;
cout << "Enter the current year then press RETURN.\n";
cin >> year_now;
cout << "Enter your current age in years.\n";
cin >> age_now;
cout << "Enter the year for which you wish to know your age.\n";
cin >> another_year;
another_age = another_year - (year_now - age_now);
if (another_age >= 0) {
cout << "Your age in " << another_year << ": ";
cout << another_age << "\n";
} else {
cout << "You weren't even born in ";
cout << another_year << "!\n";
}
Mar 27, 202
return 0; 4
}
103 Remarks about Program Style…
#include <iostream>
using namespace std;
int main()
{
int year_now, age_now, another_year, another_age;
cout << "Enter the current year then press RETURN.\n";
cin >> year_now;
cout << "Enter your current age in years.\n"; Mar 27, 202
4
cin >> age_now;
106 Complete C++ Program…
cout << "Enter the year for which you wish to know your
age.\n";
cin >> another_year;
another_age = another_year - (year_now - age_now);
if (another_age >= 0) {
cout << "Your age in " << another_year << ": ";
cout << another_age << "\n";
} else {
cout << "You weren't even born in ";
cout << another_year << "!\n";
}
return 0; Mar 27, 202
4
}
Course Project…
107 WU Student Results Program (Stage 12)
Array Philosophy
Array Declaration
Array Use
The identifier ITEM, for example, can stand for a list of items
in a warehouse while ITEM(1), ITEM(2), ITEM(3)…
represent the first, second, third, and other individual items in
that list.
The integers (I=1,2,3…) within the parentheses are called
subscripts.
Variables of this sort; ITEM(1), ITEM(2), ITEM(3)…, are
called subscripted variables.
Since one subscript is enough to designate a particular value,
they are also known as one-dimensional arrays.
variable.
114 Array Declaration
As stated above, arrays have to be declared before use in a program.
This causes the compiler to reserve adequate storage space for them.
The statement
char phrase[14] = "Enter age: ";
is equivalent.
(Stage 16)
Give an array declaration for the Course Codes
Input data into the declared Course Code array
Mar 27, 202
4
Course Project…
126
WU Student Results Program (Stage 17)
Now, assume again there are sixty (60) students per course, write
a complete program to do these using arrays and IF statements:
Input each student’s middle initial as name
Input course code as one character
Input three continuous assessment marks (over 50, 30, 20)
Compute total continuous assessment mark (over 30)
Check if this total is less than 10, give student warning
Input final examination mark (over 100)
Compute final examination mark (over 70)
Check if this total is less than 25, give student warning
Find final semester mark as sum of continuous assessment and final
examination mark (over 100)
Output all data (student’s full name, full course code, all marks,Mar
4 etc)
27, 202
SUBPROGRAMS
127
The Need for Sub-programs
Main program;
……
Call subprogram 1;
Call subprogram 2;
……
Subprogram 1;
…..
End;
Subprogram 2;
…...
End; Mar 27, 202
4
Thank you.