Computer Programming
Computer Programming
Input
process
output
For a computer to do any job, it has to be programmed i. e. it must be given a set of instructions
in any of the programming languages, instructing it on WHAT and HOW to do it e .g adding two
numbers:
I). Tell computer to read the first number (Num1)
II). Tell computer to read the second number (Num2)
III). Tell computer to process i.e. sum=Num1+Num2
IV). Tell computer to display sum
There exist several programming languages each one having specific rules which can be
understood by the hardware/computer system.
LEVELS (CATEGORIES) OF PROGRAMMING LANGUAGES
A).COMPUTER PROGRAMMING LANGUAGE (MACHINE LANGUAGE)
For a program to run on a computer the instruction must be represented in binary numbers ,such
a program is called machine language program and it is described as machine code or object
code.
DISADVANTAGES
1. Programs written in machine code are difficult to read and understand.
2. They are lengthy and time consuming.
3. They are machine dependent i.e. they are not portable hence difficult to be executed by a
machine of
1
The processing steps of a particular program must have a beginning and an end. Therefore the
beginning and the end of a flow chart are presented by terminators.
b).Parallelogram
c) A rectangular block
4
Assignment
Develop a program project to read the name of an employee, hours worked and the rate of pay.
The flow chart should display the name, gross and net pay of each employee, given the
following;
1. Gross=hours x rate
2. Netpay=gross-tax
3. if employee earns more than 3000/=, tax him/her 200/= otherwise no tax
{if gross>3000 then net=Gross
Else
Gross=Net pay}
Solution
Input: 1.Name 2.Hours worked 3.Rate of pay
Processes 1.Gross=hours x rate 2.netpay=Gross-Tax=Gross
Output = Name, Gross pay, Netpay
DIAGRAM
EXAMPLE
Draw a program flow chart for adding the first 100 counting numbers i.e. 1+2+3+4+
.99+100
DIAGRAM
EXAMPLE
Draw a flow chart for multiplying the first 100 counting numbers:
DIAGRAM
EXAMPLE
Draw a program flow chart to read employees name, hours worked and the rate of pay. The
program should calculate the total salary for 10 employees, given salary=hours x rate
DIAGRAM
PSEUDO CODES
A pseudo code description uses human vocabularies, mathematical notations and a set of
commands.
It outlines general instruction
Example 1
Developing a pseudo code algorithm to read 3 integers and then display average.
Procedure
1. Begin
2. Input: Num1, Num2, Num3
3. Process 3.1 sum=Num 1+Num2+Num3
3.2 Average=sum/3
4. Output: Average.
5. End.
Example 2.
Develop a pseudo code for the following case:
A program that can read the name of an employee, hours worked and the rate of pay. The pseudo
code should display the name, gross and net pay of each employee, given the following:
1. Gross=hours x rate
2. Netpay=Gross-tax
3. if employee earns more than 3000, tax him/her 200
Otherwise no tax {if gross> 3000 then
Net=gross-tax
Else net=gross}
3.2 repeat
Total salary =total salary+ salary
Counter =counter +1
UNTIL counter <=10
4. Output: total salary
5. End
OR
1. Begin
2. Input name, hours, rate
3. Processes: 3.1 salary =hours x rate
3.2 total salary=0
Counter =0
3.3 WHILE counter <=10 DO
Total salary=total salary +salary
Counter=counter +1
4 .output total salary
5. End
The pseudo code has the following:
1 .They must have a beginning (start)
2. They must read data (input)
3 .They must write data (output)
4 .They can perform calculations
5 .They can select out of alternatives
E.g. IfThen..Else
6. They can perform repetitions
E.g. repeat .Until
While ..Do
7. They must have an end.
MEMORY VARIABLES
These are names of location in the RAM memory of the computer.
They are used to store temporary data during processing
A memory variable must:
1. Start with a letter
2. Have no blank space
3. Have a maximum of 30 characters
11
#include <iostream.h>
main() {
// A simple C++ program
int x, y, sum;
cout << "A program which adds two integers\n";
cout << "Enter 1st integer: ";
cin >> x;
cout << "Enter 2nd integer: ";
cin >> y;
sum = x + y;
cout << "Sum is " << sum << endl;
return 0;
#include <iostream.h>
main()
{
int length, width;
int perimeter, area;
cout << "Length = ";
12
program body
We will use this program to see the basic structure of a C++ program and I/O statements in C++.
Preprocessor directives
Before compilation of a C++ program, it is processed by a preprocessor. The preprocessor
directives tell the preprocessor to perform some manipulations which must be done before
compilation. Almost all C++ programs has at least one preprocessor directive. A preprocessor
directive begins with a #.
preprocessor directives tell the preprocessor to include the functions provided by the
specified file. They are similar to the uses statements in Turbo Pascal.
#include
For C++ programs that output data to the screen and/or input data from the keyboard, the
following preprocessor directive must be present:
#include <iostream.h>
Program body
Declarative statements and executable statements
The program body consists of declarative and executable statements. In Program 1,
int x, y, sum;
13
is a declarative statement, while the other statements within the braces, {}, are executable
statements.
Unlike Pascal, declarative statements need not come before executable statements in a C++
program. Sometimes a declarative statement may be found in the middle of the program body.
is a part of every C++ program. It indicates the beginning of the main program. In addition,
braces are required to enclose all the statements of the main program. The left brace ({) and the
right brace (}) are equivalent to begin and end in Pascal.
In C++, each statement must be ended with a semicolon (;), even the last statement.
The last statement in the main program is
return 0;
A return statement is used in a function to exit the function and return a value. Since the main
program is considered as a function in C++, return statement is also used. The main program
returning 0 indicates successful termination.
Comment
In a C++ program, a line that begins with // indicates that the remainder of the line is a
comment.
In addition, comments in C++ can also be enclosed by /* and */.
Output statements
cout
To print something on the screen, we can use a cout statement. It starts with cout, then the <<
operator, and finally the items to be displayed. For example, the statement
cout << "Enter the 1st integer: ";
instructs the computer to display the string "Enter the 1st integer:
cout behaves like write in Pascal.
In C++, a string of characters are enclosed by a pair of double quotation marks (").
14
can display multiple items (including strings, numbers and values stored in variables). For
example, the C++ statement
cout
cout << "First value is " << a + b << " and second value is " << c + d;
Special characters
Unlike Pascal, there is no reserved word or standard identifier which behaves like writeln in
Pascal. To output a newline character, we use \n within the quotation marks. For example, the
statement
cout << "A program which adds two integers\n";
2nd
b
3rd
c
4th
d
endl
is used with cout. It outputs a newline and then forces any outputs accumulated in the
buffer to be printed. For the
purpose of tracing simple programs, you may consider endl to be similar to the newline character
"\n".
endl
15
Input statements
To obtain a value from the keyboard and store it into a variable, we can use a cin statement. It
starts with cin, then >> operator, and finally a variable.
In Program 1, the statement "cin >> x;" accepts an integer (x is an integer variable) from the
keyboard and stores it in x.
If required, the cin statement can accepts multiple values and store them in the corresponding
variables. For example, the statement "cin >> x >> y;" accepts two values from the keyboard
and store them in x and y respectively (here x and y can be of different types).
Declaring variables
Declarative statements can appear anywhere in the program, provided that the declaration of a
variable must appear before the variable is used in the program.
A declarative statement starts with the type of the variable(s), followed by the variable name(s),
and ends with a semicolon (;). If more than one variable is declared in a declarative statement,
we use commas (,) to separate them.
Examples
int x;
float a1, a2;
// x is an integer variable.
// a1 and a2 are floating-point variables.
Length
int
signed
signed int
unsigned int
unsigned
signed char
8 bits
-128 to 127
shortint
unsigned char
8 bits
0 to 255
byte
short
short int
signed short int
16 bits
-32768 to 32767
integer
unsigned short
16 bits
0 to 65535
word
long
long int
signed long int
32 bits
-2147483648 to
2147483647
longint
unsigned long
unsigned long
32 bits
0 to 4294967295
float
32 bits
3.4E-38 to 3.4E+38
single
double
64 bits
1.7E-308 to 1.7E+308
double
long double
80 bits
3.4E-4932 to 1.1E+4932
extended
Range
Notes
1. char is usually used as a character data type (equivalent to char in Pascal),
and normally char variables will be displayed as a character. However, it can
also be treated as integral data type. See an example here.
2. A character is enclosed by a pair of single quotation marks ( '). For
example,'b'.
3. int and unsigned int (or unsigned) types have the length of the system word.
In MS-DOS and 16-bit versions of Windows, their lengths are 16 bits (same as
short and unsigned short respectively). In 32-bit operating systems, their
lengths are 32 bits (same as long and unsigned long respectively).
4. There is no Boolean data type in C++. "True" and "false" are implemented as
a non-zero value and zero respectively.
5. For simplicity, int and float in C++ will be considered as equivalent to
integer and real in Pascal.
17
Equivalent Pascal
statements
typedef
Variable assignment
The assignment operator used in C++ is "=". It is equivalent to ":=" in Pascal.
Note that in C++, "=" does not mean "equal to". Use "==" (two equal signs) as "equal to" in C++.
Also, initialisation of a variable can be done in the declarative statement. For example, the
following two C++ program segments are the same.
C++
Equivalent Pascal
statements statements
int x;
x = 4;
int x = 4;
var x: integer;
...
x := 4;
We can also declare and initialise more than one variable in one statement. Moreover, it is
possible that we do not initialise all the variables in a declarative statement:
Equivalent Pascal
statements
C++ statements
18
ch2 := 'A';
var i, j, k: integer;
...
i := 4;
k := 3;
int i = 4, j, k = 3;
// j is not initialised
Mixed-mode assignments
In an assignment statement where the operands on the two sides of the assignment operator (=)
are different (mixed-mode assignment), the value of the right hand side will be coerced to the
data type of the variable on the left hand side before it is stored. In particular:
// i is an integer variable.
// x is a floating-point variable.
// c is a character variable.
// 4.7 is assigned to x.
endl;
endl;
endl;
//
//
//
//
//
endl;
return 0;
}
19
#include <iostream.h>
...
int a[100];
...
for (i = 0; i < 100; i++)
...
if (n >= 100 * 2)
...
As you can see, #define preprocessor directives can be used to define constants. But the main
differences between using const and using #define is that the const statement tells the
program to allocate some memory space to store the constant, while the aliases defined by the
#define preprocessor directives are not stored in memory; they are translated to their original
name during compilation.
In fact, most C++ programmers prefer using #define preprocessor directives to define constants.
Operators (Part 1)
Unary and binary operators
A unary operator is an operator which requires one operand only. For example, the negative
sign (-) in the number "-10" is a unary operator.
A binary operator is an operator which requires two operands, one on the left and the other on
the right.
20
Parentheses
When writing expressions, parentheses () (singular: parenthesis) are used to group expressions
which are to be performed first, or just for increasing readability of the program.
Arithmetic operators
The following table shows five arithmetic operators (addition, subtraction, multiplication,
division and modulus). They are all binary operators.
Operator in
Sample C++
Operation
C++
expression
Addition
p + q
p + q
Subtraction m - n
m - n
Multiplicati
a * b
on
a * b
x div y (if both x and y are of integer
/ (See
Program 3)
Division
x / y
Modulus
r % s
types)
x / y (if at least one operand is of
floating point type)
r mod s
Notes
1. The data type of the result of addition, subtraction, multiplication and division
operations depends on its operands:
a. If both operands are of integer types, the result will be of integer type.
b. If at least one of the operands is of floating-point type, the result will
be a floating-point number.
2. The following program demonstrates how the data types of the operands affect the results
of division:
Program 3: Division in C++
#include <iostream.h>
main()
21
{
int i = 17, j = 5;
float x = 17, y, z;
cout << i / j << endl;
// Note
y = i /
cout <<
z = x /
cout <<
//
//
//
//
2 will be
2.25 will
2.25 will
2.25 will
displayed.
be displayed.
be displayed.
be displayed.
return 0;
}
Equivalent Pascal
expression
(x + y - a) % b (x + y - a) mod b
22
x = -0.25;
i = c2 * x;
is ...
cout << i << endl;
return 0;
}
Operators (Part 2)
Cast operators
A cast operator temporarily changes the data type of the operand (following the cast operator).
It is formed by placing parentheses around a data type name. It is a unary operator, and the
operands is on the right of the operator.
For example, suppose x is an integer variable. The expression "(float) x" temporarily treats x
as a floating-point variable in the expression.
The following program shows some examples how cast operators are used:
Program 5:Using cast operators
#include <iostream.h>
main()
{
int a = 17, b = 5;
float x, y;
char ch = 'A';
// Compare the following:
cout << (float) a / b << endl;
cout << a / b << endl;
x = a / (float) b;
// 3.4 will be stored in x.
y = a / b;
// 3 will be stored in y.
cout << "x=" << x << " y=" << y << endl;
cout << ch << endl;
cout << (int) ch << endl;
displayed.
return 0;
}
In addition to "=", there are ten more assignment operators. Five of them are shown below:
Assignment operator Sample expression Explanation
+=
-=
*=
/=
%=
a
b
c
d
e
+=
-=
*=
/=
%=
7
3
2
5
4
a
b
c
d
e
=
=
=
=
=
a
b
c
d
e
+
*
/
%
7
3
2
5
4
a = 14;
a -= 3;
cout << a << endl;
// 11 will be assigned to a.
b = 7;
b += a * 3;
cout << b << endl;
// 7 + 11 * 3 = 40 will be assigned to b.
c = 'A';
c += 3;
cout << c << endl;
return 0;
Multiple assignments
In most programming languages (including Pascal), one statement has to be used to perform one
assignment operation, and the assignment operation does not return anything. However, in C++,
an assignment operation can be an expression, and can return value. Therefore a statement can
perform multiple assignments. See the following program:
24
Assignments are performed from right to left in a multiple assignment statement. Therefore in
this statement, "b = 3" is performed first, and this expression returns the value 3. Then the
assignment "a = 3" is performed.
c = b *= 7;
In this statement, "b *= 7" is performed first. The value stored in b becomes 3*7=21, and this is
the returned value. Then the assignment "c = 21" is performed.
c += d = 8;
In this statement, "d = 8" is performed first, and the returned value is 8. Then the assignment "c
+= 8" is performed, i.e. 21+8=29 is stored in c.
e = 7 * (a += 1);
The precedence of assignment operation is lower than multiplication. Therefore parentheses are
necessary in this statement. After the assignment operation "a += 1", the value 3+1=4 is stored
in a, and the returned value is 4. Finally, "e = 7 * 4" is performed, and 28 is stored in e.
Operator
Name of
operator
Sample
expression
++<operand>
Preincrement
++a
Predecrement --c
Explanation
Increment a by 1, then use the new value of a
in the expression in which a resides.
Use the current value of b in the expression in
which b resides, then increment b by 1.
Decrement c by 1, then use the new value of c
in the expression in which c resides.
Use the current value of d in the expression in
which d resides, then decrement d by 1.
All increment and decrement operators are unary operators. As seen from the above table,
preincrement and predecrement operators have their operand on their right, while postincrement
and postdecrement operators have their operand on their left.
The following program shows the differences between preincrement and postincrement
operators. Note the properties shown applies to predecrement and postdecrement operators.
Program 8: Using increment operators
#include <iostream.h>
main()
{
int i = 1,
j;
// i is initialised to 1.
Operators (Part 3)
26
==
!=
<
>
<=
>=
Sample C++
expression
Equivalent Pascal
expression
a == b
a = b
a != b
a <> b
a < b
a < b
a > b
a > b
a <= b
a <= b
a >= b
a >= b
&&
||
!
Sample C++
expression
Equivalent Pascal
expression
a && b
a and b
a || b
a or b
!a
not a
As seen from the above table, "&&" and "||" are binary operators, while "!" is a unary operator
with its operand on its right.
See the following tables for their operations.
Logical OR (||)
a && b
a || b
!a
27
0
non-zero
non-zero
0
non-zero non-zero
0
0
1
0
non-zero
non-zero
0
non-zero non-zero
1
1
1
non-zero
There is no Boolean type in C++. The values returned by the equality, relational and logical
operations are 1 (true) and 0 (false). In general, non-zero numerical value is considered as "true"
while zero is considered as "false" in C++.
Conditional operator
The conditional operator is a ternary operator (an operator which operates on three operands). It
is in the following form:
<expression_1> ? <expression_2> : <expression_3>
This means that a statement using the conditional operator can be replaced by an if-else
control structure.
See the following program as an example:
Program 9: Using the conditional operator
#include <iostream.h>
main()
{
int x, y, min;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
min = (x < y ? x : y);
cout << x << (x > y ? " > " : " <= ") << y << endl;
cout << min << " is the smaller number." << endl;
}
return 0;
28
Precedence of operators
In the following table, the operators are shown top-to-bottom in decreasing order of precedence.
Category
Parenthesis
Unary
Multiplicative
Additive
Relational and equality
Logical AND
Logical OR
Conditional
Assignment
Operators
()
! ++ -- +
* / %
+
(addition) - (subtraction)
In the above table, the operators within the same category have equal precedence.
29
Single-way selection
C++ control
Equivalent Pascal control
structure
structure
if
if <condition> then
<statement_1>
(<condition>)
<statement_1>;
return 0;
Two-way selection
C++
control
structure
if
(<conditi
on>)
Equivalent
Pascal control
structure
if <condition>
then
<statemen
t_1>;
else
else
<statement_1>
<statement_2>
<statemen
t_2>;
31
Nesting selectors
Like Pascal, C++ also supports nested control structures.
We can use nested if-else statements for multiple cases. For example, the following program
outputs a grade according to the input score. The indentation shows how the if-else statements
are nested.
Program 13: Using nested if-else statements
C++ version
#include <iostream.h>
main()
{
int score;
char grade;
cout << "Score? ";
cin >> score;
if (score >= 80)
grade = 'A';
else
// score < 80
if (score >= 70)
grade = 'B';
else
// score < 70
if (score >= 60)
grade = 'C';
else
// score < 60
if (score >= 50)
grade = 'D';
else
// score < 50
grade = 'F';
cout << "Grade: " << grade << endl;
32
return 0;
}
But to enhance readability, the nested if-else statements are usually written as follows:
if (score >=80)
grade = 'A';
else if (score >= 70)
grade = 'B';
else if (score >= 60)
grade = 'C';
else if (score >= 50)
grade = 'D';
else
grade = 'F';
33
In this control structure, case <value>: (in C++) and <value>: (in Pascal) are case labels. The
<ordinal_expression> is evaluated. The statements for the particular returned value are
executed while the other are ignored. If the returned value is not in the cases listed, the
statements for the default case (default in C++ or else in Turbo Pascal) will be executed. See
the following program:
Program 14: Using the switch statement
C++ version
#include <iostream.h>
main()
{
char grade;
cout << "Grade: ";
cin >> grade;
switch (grade) {
case 'A': case 'B':
cout << "Good!" << endl;
break;
case 'C':
cout << "Average." << endl;
break;
case 'D':
cout << "Fair." << endl;
break;
case 'F':
cout << "Poor." << endl;
break;
default:
cout << "Invalid grade!" << endl;
}
return 0;
}
In C++, if the value returned by the <ordinal_expression> matches the <value> in any of the
case labels, the statements starting from the case label to the break statement are executed.
Therefore you may notice that there is a break statement just before the next case label.
Unexpected result may be obtained if any of the break statements is missing. See the following
program for an example. The following program is similar to the above program except that one
break statement is missing.
Program 15: Missing a break statement while using the switch control structure
34
#include <iostream.h>
main()
{
char grade;
cout << "Grade: ";
cin >> grade;
switch (grade) {
case 'A': case 'B':
cout << "Good!" << endl;
break;
case 'C':
cout << "Average." << endl;
// One break statement is missing here.
case 'D':
cout << "Fair." << endl;
break;
case 'F':
cout << "Poor." << endl;
break;
default:
cout << "Invalid grade!" << endl;
}
return 0;
}
As you can see from the above sample output, both "Average." and "Fair." appear on the
screen when grade is 'C'. Since there is no break statement after "Average." is displayed, the
next statement (i.e. displaying "Fair.") is also executed.
while
while <condition> do
(<condition>)
<loop_body>
<loop_body>;
35
<condition> is checked upon entry of this control structure. <loop_body> will be executed
whenever <condition> is non-zero (i.e. true). This control structure is exited only when
<condition> is zero (i.e. false). Note that in C++, do is not required, but the parentheses around
the condition is necessary (similar to if statements).
If the loop body contains more than one statement, it should be enclosed by a pair of braces.
A while loop is logically controlled. Whether the loop body should be executed depends on the
condition to be tested. For example, the following program lists all the integers which are powers
of n (the input value) and are less than or equal to 1000 (the loop body is executed when
product is less than or equal to 1000):
Program 16: Using the while loop
C++ version
#include <iostream.h>
main()
{
int n, product;
cout << "n? ";
cin >> n;
product = n;
while (product <= 1000) {
cout << product << endl;
product *= n;
}
return 0;
}
In particular, there are two types of loops which can be implemented by a while statement:
counter-controlled loop and sentinel-controlled loop.
Counter-controlled loop
The general structure of a counter-controlled loop (using while statement) is as follows:
36
return 0;
No.
No.
No.
No.
No.
254
1:
2:
3:
4:
5:
78
39
45
63
29
Usually, a counter-controlled loop is implemented by a for statement. Also, the number of times
the loop body should be executed is known in a counter-controlled loop.
Sentinel-controlled loop
The following program accepts a number of scores and calculate their sum. In contrast to the
previous program, the number of scores to be entered is unknown in this program. To indicate
37
the end of data entry, we use a sentinel value, which marks the end of data input. The sentinel
must not lie within the acceptable range of input values.
Program 18: A sentinel-controlled loop
C++ version
#include <iostream.h>
main()
{
int score, sum;
sum = 0;
cout << "Enter score (-1 to quit): ";
cin >> score;
while (score != -1) {
sum += score;
cout << "Enter score (-1 to quit):
";
return 0;
score
score
score
score
score
score
score
331
(-1
(-1
(-1
(-1
(-1
(-1
(-1
to
to
to
to
to
to
to
quit):
quit):
quit):
quit):
quit):
quit):
quit):
74
35
63
52
80
27
-1
In the above program, since there is no score equal to -1, the program can use it as a sentinel
value. When such a sentinel value is entered, the program stops executing the loop body.
Usually, the structure of a sentinel-controlled loop is as follows:
C++ control structure
Get the first value as <entered_value>;
while (<entered_value> != <sentinel>) {
<statements_to_be_executed>;
Get the next value as <entered_value>;
}
do-while statement
Structure
do
<loop_body>;
while (<condition>);
If the loop body contains more than one statement, it should be enclosed
by a pair of braces.
In a do-while loop, the condition is tested after execution of the loop
body. If the condition is non-zero (i.e. true), the control goes back and
the loop body is executed again. If the condition is zero (i.e. false), the
loop is exited.
The C++ do-while structure is equivalent to the following:
Equivalent structure using while statement in C++
Equivalent structure using repeat-until statement in Pascal
<loop_body>;
while (<condition>)
<loop_body>;
repeat
<loop_body>
until not <condition>
while loop
It is possible that the loop body is never
executed (when the condition is zero as the loop
is entered).
The condition is tested before the loop body is
executed.
Sample program
The result of this program is identical to Program 18 except that there is only one cin statement
in the loop in this program. This is because a do-while loop is used.
39
main()
{
int score, sum = 0;
do {
cout << "Enter score (-1 to quit):
";
repeat
write('Enter score (-1 to quit):
');
readln(score);
if score <> -1 then
sum := sum + score
until score = -1;
writeln('Sum = ', sum);
end.
for statement
for (<expression_1>; <expression_2>; <expression_3>)
<loop_body>;
If the loop body contains more than one statement, it should be enclosed by a pair of braces.
The above C++ for structure is equivalent to the following:
<expression_1>;
while (<expression_2>) {
<loop_body>;
<expression_3>;
}
40
return 0;
<counter> = <initial>;
while (<counter> <= <final>) {
<loop_body>;
<counter>++;
}
The following shows how Program 17 (containing a counter-controlled loop) can be re-written
using for statement:
Program 21: Using a for statement as a counter-controlled loop
C++ version
P
#include <iostream.h>
main()
{
int score, sum, i;
sum = 0;
for (i = 1; i <=5; i++) {
cout << "Score No. " << i << ": ";
cin >> score;
sum += score;
}
cout << "Sum = " << sum << endl;
}
return 0;
Unconditional branch
We can use goto statements (unconditional branch statements) to jump to a label in a program.
In C++ and Pascal, a label is specified by an identifier (the name of the label) followed by a
colon (:). However, labels in a Pascal program should be declared with the reserved word label,
while labels in C++ programs need not be declared.
41
The following program makes use of an unconditional branch to draw an inverted triangle with
asterisks (*). However, the number of rows is limited to 10 or less.
Program 22: Using unconditional jumps
C++ version
#include <iostream.h>
main()
{
int i, j, n;
cout << "n? ";
cin >> n;
for (i = 1; i <= n; i++) {
if (i > 10)
goto finished;
for (j = n; j >= i; j--)
cout << "* ";
cout << endl;
}
finished:
cout << "Finished!" << endl;
return 0;
}
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* * * *
* * *
* *
*
One-dimensional arrays
Declaration
The following are some examples of array declarations:
C++ version
The integer constant in the square brackets ([]) specifies the number of elements in the array. In
C++, the subscript of an array must start with 0.
43
The elements of an array must be initialised separately if the initialisation is not done in the array
declaration.
If the number of elements in the array is more than the number of the initialisers, the remaining
elements are automatically initialised to zero. For example:
C++ version
If an array is not initialised in array declaration, the values stored in the array are unknown until
initialisation of the elements are done separately.
There will be a compile-time error if the number of initialisers is more than the number of the
elements in the array.
If the array size is not specified in the array declaration, there should be an initialiser list. The
number of elements in the array will be the numbers of elements in the initialiser list. For
example, the statement
int x[] = {4, 7, 10, 8, 5};
specifies that there are 5 elements in the array (range of subscripts is 0 to 4).
The following sample program uses a one-dimensional array to store odd numbers:
Program 24: Using a one-dimensional array
44
C++ version
#include <iostream.h>
#define MAX 10
main()
{
int a[MAX], i;
for (i = 0; i < MAX; i++)
a[i] = 2 * i + 1;
cout << "Subscript? (-ve value to
quit) ";
cin >> i;
while (i >= 0) {
if (i >= MAX)
cout << "Subscript out of
range!"
<< endl;
else
cout << "a[" << i << "]: "
<< a[i] << endl;
cout << "Subscript? (-ve value to
quit) ";
cin >> i;
}
return 0;
}
quit) 5
quit) 9
quit) 10
quit) 0
quit) -2
Character arrays
In C++, there are two ways to implement strings: character arrays and character pointers.
Here we only discuss character arrays.
In this page, all character arrays are assumed to be treated as strings.
Declaration
The following is an example of character array declaration:
45
In C++, there is a null character (with ASCII 0, indicated by '\0' in C++) at the end of a string.
Therefore, if you want to have a character array which holds at most n characters, it would be
better if the array size is n + 1 (the last one is used for holding the null character).
We can also initialise a character array in the middle of the program. However, we have to use a
string function called strcpy. To use this function, the preprocessor directive "#include
<string.h>" must appear near the top of the program.
strncmp(s, t, n)
Meaning
copy string t to string s.
copy at most n characters of string t to string s.
('\0' may not be automatically appended if the length of t >= n.)
concatenate string t to the end of string s.
concatenate at most n characters of string t to string s;
terminate s with '\0'.
return the length of string s.
compare string s to string t;
return a negative value if s < t, zero if s = t, or a positive value if s >
t.
compare at most n characters of string s to string t;
return a negative value if s < t, zero if s = t, or a positive value if s >
t.
46
Sample program:
Program 25: Using string functions
#include <string.h>
#include <iostream.h>
main()
{
char a[] = "C++ programming", b[50], c[50], d[50];
int i;
cout << "a contains " << strlen(a) << " characters\n"; // 15 characters
strcpy(b, "Welcome to this program!");
strncpy(c, b, 11);
stored in c
// b is initialised
// "Welcome to " is
Sample output:
a contains 15 characters
b: Welcome to this program!
c: Welcome to C++
d: Welcome to C++ programming
b > d
b and d differ at character 12.
47
Multi-dimensional arrays
Declaration and referring an array element
The following is an example of multi-dimensional array declarations:
C++ version
Note that the above declaration cannot be written as "int a[5, 8], b[2, 3, 4]".
For the declaration "int a[5][3]", the two-dimensional arrays a can be visualised as follows:
column
row
[0]
[1]
[2]
[3]
[4]
[0]
a[0][0]
a[1][0]
a[2][0]
a[3][0]
a[4][0]
[1]
a[0][1]
a[1][1]
a[2][1]
a[3][1]
a[4][1]
[2]
a[0][2]
a[1][2]
a[2][2]
a[3][2]
a[4][2]
A two-dimensional array can be considered as an array of arrays. Each row can be considered as
a one-dimensional array. When the above two-dimensional array is stored in the memory, the
first element is a[0][0], then a[0][1], next a[0][2], a[1][0], ..., so on.
Note that each subscript must be enclosed by one pair of square brackets.
Although three-dimensional arrays, four-dimensional arrays, etc., cannot be visualised here, the
way of referring to elements is similar to referring elements in a two-dimensional array.
48
[0] 14 23
[1] 10 5
7
8
The elements of an array must be initialised separately if the initialisation is not done in the array
declaration.
If the number of elements in the array is more than the number of the initialisers, the remaining
elements are automatically initialised to zero. For example:
If an array is not initialised in array declaration, the values stored in the array are unknown until
initialisation of the elements are done explicitly.
There will be a compile-time error if the number of initialisers is more than the number of the
elements in the array.
The size of a multi-dimensional array should not be omitted in the declaration (except for the
first level index). If the size of the first level index is missing, the array should be initialised
(using an initialiser list) during declaration. The size of the first level index will be determined by
the initialiser list. For example:
C++ statement
Remark
int a[][4];
Same as above.
49
table[i][j] = i * j;
Sample output:
| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|
--+--+--+--+--+--+--+--+--+--+--+
0| 0 0 0 0 0 0 0 0 0 0
1| 0 1 2 3 4 5 6 7 8 9
2| 0 2 4 6 8 10 12 14 16 18
3| 0 3 6 9 12 15 18 21 24 27
4| 0 4 8 12 16 20 24 28 32 36
5| 0 5 10 15 20 25 30 35 40 45
6| 0 6 12 18 24 30 36 42 48 54
7| 0 7 14 21 28 35 42 49 56 63
8| 0 8 16 24 32 40 48 56 64 72
9| 0 9 18 27 36 45 54 63 72 81
Records
Defining a record data type and declaring a record
In C++, records are called structures. We can use the reserved word struct to define a record
data type and declare a record type variable:
struct StudentRecord {
student's info
char student_no[8];
char name[20];
char class_name[3];
int class_no;
};
1st
2nd
3rd
4th
50
field:
field:
field:
field:
Student Number
Name
Class
Class Number
struct StaffRecord {
staff's info
char employee_no[6];
float salary;
};
The syntax for referring a field of a record in C++ is the same as that in Pascal: using a dot (.).
For example, according to the above record definitions, an_employee.salary refers to the field
salary of the record an_employee.
Array of records
Declaring an array of record is similar to declaring an array of simple data types. For example,
according to the above record definitions, the following statement declares two arrays of records:
StudRec students[1500];
StaffRec staff[100];
The following sample program outputs all students with surname "Chan":
Program 27: Using an array of records
C++ version
#include <iostream.h>
51
#include <string.h>
#define MAX 5
main()
{
typedef struct StudentRecord {
char student_no[8];
char name[20];
} StudRec;
StudRec students[MAX];
int i;
char s[20];
for (i = 0; i < MAX; i++) {
cout << "Student " << i << ":\n";
cout << "Student Number: ";
cin.getline(students[i].student_no,
8);
// The above statement reads a
string
// of maximum length 8 into the
variable
// students[i].student_no.
cout << "Name: ";
cin.getline(students[i].name, 20);
}
for (i = 0; i < MAX; i++) {
strncpy(s, students[i].name, 4);
s[4] = '\0';
if (strcmp(s, "Chan") == 0)
cout << students[i].name <<
endl;
}
return 0;
}
52
Functions
Function declaration
C++ version
<return_type> <function_name>(<parameter_list>)
{
<statements>;
return <return_value>;
}
For example:
C++ version
float power(float x, int y)
{
int i;
float p = 1;
for (i = 1; i <= y; i++)
p *= x;
return p;
}
If the function does not require any parameters, we can use the keyword void for the
<parameter_list>, or just omit it. For example, "int
function_without_parameters(void)" or "int function_without_parameters()". Note
that the parentheses must be present in the function call and in the function declaration even the
function does not require parameters.
Function prototype
In C++, the function can be put either before or after the main program:
Program 28: Using functions
C++ version
(function
declaration
before main
program)
#include <iostream.h>
float power(float x, int y)
{
int i;
float p = 1;
for (i = 1; i <= y; i++)
p *= x;
return p;
}
53
main()
{
int i;
for (i = 0; i < 10; i++)
cout << i << "\t" << power(1.5, i) << "\t" << power(-0.5,
i) << endl;
return 0;
}
#include <iostream.h>
float power(float base, int n);
// function prototype
main()
{
int i;
for (i = 0; i < 10; i++)
cout << i << "\t" << power(1.5, i) << "\t" << power(-0.5,
C++ version
i) << endl;
(function
declaration after
return 0;
main program)
}
float power(float x, int y)
{
int i;
float p = 1;
for (i = 1; i <= y; i++)
p *= x;
return p;
}
program prog_28(input, output);
var
i: integer;
Pascal version
54
If functions are declared after the main program, there should be a statement called function
prototype before the main program. The function prototype tells the C++ compiler the types of
the parameters, the number of parameters and the return type of the function. These must agree
with the definition and uses of the function. The names of the parameters in the function
prototype are not necessary and need not be the same as in the function definition. For example,
in the above program, the function prototype
float power(float base, int n);
can be written as
Procedures
In C++, a procedure is considered as a function which does not return anything. We can use the
reserved word void as the return type of the function. For example:
Program 29: Procedures
C++ version
#include <iostream.h>
void a_message(int
{
if (a > b)
cout << a << "
else if (a < b)
cout << a << "
else
cout << a << "
}
a, int b)
> " << b << endl;
< " << b << endl;
= " << b << endl;
main()
{
int x, y;
cin >> x >> y;
a_message(x, y);
return 0;
}
Scope rules
Scope rules of C++ are similar to those of Pascal.
For normal variables which are declared at the beginning of a function, the scope is the function
in which the name is used. If a variable is declared in the middle of a function, its scope starts
from where it is declared. Global variables should be declared at the very beginning of the
55
program (just after the preprocessor directives). Note that variables declared in main() are not
global variables; they are local to the main program only.
#include <iostream.h>
int x, y;
/* x and y are global variables. */
void foo1()
{
int a; /* Scope of a starts here. */
/* Here is the scope of a but not the scope of b. */
/* c (declared in main) cannot be used in foo1. */
/* foo2 cannot be called here. */
...
char b; /* Scope of b starts here. */
/* Here is the scope of a and b. */
...
} /* Scope of a and b stops here. */
void foo2()
{
/* foo1 can be called here. */
int x;
/* All "x" appeared here have no relations to the global "x". */
...
}
main()
{
int c; /* Scope of c starts here */
/* a and b (declared in foo1) cannot be used here. */
...
}
Parameter-passing methods
56
57