Sunteți pe pagina 1din 57

Fundamental of Computer programming

Def: 1 .A computer is an electronic data processing tool.


2. A computer is a device that will accept data and instructions, then
manipulate the captured data to produce information.
DIAGRAM

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

a different family (IBM, Intel, Apple, Macintosh).


4. They are difficult to debug (identifying and removal of programming errors)
ADVANTAGES
Any program developed by machine language executes faster because the language used is in
binary numbers while other languages the program must first be converted to machine code
before execution.
Other languages------Translator-------object code/machine code
B) .LOW LEVEL PROGRAMMING LANGUAGES
Instructions are symbols representation of machine code instructions. The symbols are referred to
as MNEMONICS i.e. easy to remember codes.
An example of low level programming language is Assembly programming language.
DISADVANTAGE
They are machine dependent.
C) .HIGH LEVEL PROGRAMMING LANGUAGE
The grammar of high level language is near to human being vocabularies, hence easy for humans
to understand and use.
ADVANTAGES
1. Programs are machine independent
2. They are self documenting i.e. the program statement can display the purpose of the program.
3. They are shorter in length.
DISADVANTAGES
Execution time is slower compared to equivalent machine language. This is due to a language
translator being required to convert the source code to machine language
A translator is a program that converts source code to object code.
There exist two types of translators;
1. Compiler-this translates the whole program at once into equivalent object code.
2. Interpreter-this converts statement by statement to equivalence object code
2

EXAMPLES OF HIGH LEVEL PROGRAMMING LANGUAGES ARE:


a.) BASIC (Beginners All Purpose Symbolic Instruction code)
-it is a general purpose programming i.e it can be used to develop
Mathematical, scientific and business oriented software systems.
b.) COBOL-(Common Business Oriented Language)
-it was developed for business and commercial data processing where
Volumes of data are involved.
c.) FORTRAN-(Formula translation)
-it was developed for scientific calculations, therefore it was used by
Engineers.
d.) PASCAL-It is a general purpose programming language.
e) C -A general purpose programming language.
D.FOURTH GENERATION PROGRAMMING LANGUAGE (4GL)
These languages are user oriented (user-friendly).The language grammar/syntax is equivalent to
human being.
The use of menus and icons to guide any computer user with no programming knowledge .They
can be used to manipulate database management system
They produce systems which can execute faster.They are easy to debug.
Examples of 4GLS are:
a. Dbase-Dbase II
Dbase III
Dbase IV
DbaseV
b. FoxPro
c. clipper
d. Oracle

E).FIFTH GENERATION PROGRAMMING LANGUAGES (5GLS)


They are used to program artificial intelligence systems/expert systems i.e. systems that can
work to the level of human beings e.g. robots, weather forecasting system, diagnosis system.
3

Example of a 5GL is PROLOG (Programming in logic)


OBJECT ORIENTED PROGRAMMING LANGUAGES
There is very little code to be written, therefore, they use objects.
Examples:
DELPH
VISUAL BASIC
SMALL TALK
C++
COMPUTER AND PROBLEM SOLVING
For a computer to perform a Job /Task, An instruction (Program) must be written instructing the
hardware on what to do.
An algorithm can be expressed in two ways:
a. Inform of flowcharts
b. Pseudo codes.
FLOW CHARTS
A flow chart will graphically represent a program.
FLOW CHART SYMBOLS
a). Terminators BEGIN and END

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

It is also called input/output symbol


It is used to indicate that values have been introduced into the program or values have been
passed out of the program.

c) A rectangular block
4

It is used to represent a process.


A process can be a mathematical calculation (e.g. SUM=A+B) or assignment statement
(e.g. x: =7)
d. Decision box

The symbol is used to represent a decision.


e) .An arrow
Represent the flow of control
Q: Draw a program flow chart to be used to read two numbers and then display average.
Solution
Input: Num1, Num2
Process 1: sum=Num1+Num2
2. Average=Sum/2
Output=Display average
DIAGRAM

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

THE OBJECTIVES OF PROGRAM FLOW CHARTS


1. To clarify the program logic
2. To identify an alternative method available
3. To act as a guide for program coding
4. To serve as a documentation
*NOTE: it is simple and easy to understand
8

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}

Input=name, hours, rate


Process=gross=hours x rate
Net=gross-200
Output= name, grosspay, netpay
Solution
1. Begin
2. Input: name, hours, rate
3. Process: 3.1 gross =hours x rate
3.2 If gross>3000 then
Netpay=gross-200
Else
Netpay=gross
4. Output = name, gross, net pay
5. End
Example 3
Develop a pseudo code to read employees, hours worked and the rate of pay. The program
should calculate the total salary of 10 employees, given salary = hours x rate
Solution
1. Begin
2. Input name, rate, hours
3. Process 3.1 salary =hours x rate
3.2 repeat
Total salary = total salary+ salary
Counter =counter +1
UNTIL counter <=10
4. Output =Name, Gross, Netpay
5. End
EXAMPLE 3
Develop a pseudo code 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.
Solution
1. Begin
2. Input Name, rate, hours
3. Process 3.1 salary=hours x rate
10

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

Start C++ program


The following shows a simple C++ program which adds two integers. Click here to see an
equivalent Pascal program.
Note that C++ is case-sensitive. For example, SUM, sum and Sum are considered different in C++.
If you are interested, you may also click here to see how C handles input and output (also
supported by C++).
Program 1: A C++ program which adds two integers
preprocessor directive(s)

#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;

Sample output (text in red is entered by user):


A program which adds two integers
Enter 1st integer: 3
Enter 2nd integer: 4
Sum is 7
Example 2

#include <iostream.h>
main()
{
int length, width;
int perimeter, area;
cout << "Length = ";
12

program body

cin >> length;


cout << "Width = ";
cin >> width;
perimeter = 2*(length+width);
area = length*width;
cout << endl
<< "Perimeter is " << perimeter;
cout << endl
<< "Area is " << area<< endl; Return 0;
}

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>

This preprocessor directive can be seen almost in every C++ program.

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.

The structure of the main program


The line
main()

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.

" onto the screen. Here

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;

is equivalent to the Pascal statement

write('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";

instructs the computer to display the following on the screen:


A program which adds two integers

The next character to be displayed will be on the next line.


Also, the statement "cout << "Welcome\nto C++!\n";" will causes the computer to display
the following on the screen:
Welcome
to C++!

Note that \n inserts a newline character between "Welcome" and "to".


In C++, \ is an escape character. This means that a special character is to be output. The
following table introduces some common escape sequences:
Escape sequence Description
\n
Newline character
\t
Horizontal tab
\\
The backslash \
\"
The double quotation mark "
For example, "cout << "1st\t2nd\t3rd\t4th\na\tb\tc\td\n";" instructs the computer to
display the following on the screen:
1st
a

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

For example (as seen in Program 1):


cout << "Sum is " << sum << endl;

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).

Data types, variables and variable


assignment
Variables
In C++, variables must be declared before they are used. Like Pascal, a variable name consists of
letters, digits and underscores, and it cannot begin with a digit. However, C++ is case sensitive.
Therefore the variables abc, ABC, Abc, AbC, etc. are different.

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.

Simple data types


16

The following table shows some data types in C++:


Equivalent
Turbo Pascal
data type

C++ type names

Other C++ type


names

Length

int

signed
signed int

System dependent (see Notes)

unsigned int

unsigned

System dependent (see Notes)

char (see Notes)

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

unsigned short int

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

User-defined data types


We can use typedef to define new data types. For example:
C++ statements

Equivalent Pascal
statements

typedef int Length; type Length = integer;


Length x;
var x: Length;

typedef

is useful for defining structured data types (especially records).

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

char ch1 = 'a', ch2 = 'A'; var ch1, ch2: char;


...
ch1 := 'a';

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:

If a floating-point value is to be assigned to an integer variable, the fractional


part will be truncated.
If a character value is to be assigned to an integer variable, the ASCII code of
the character will be stored.
If a numerical value is to be assigned to a char variable, the character with
ASCII code equal to the integer part of the number will be stored.

The following program demonstrates mixed-mode assignments.


Program 2: Mixed-mode assignment
#include <iostream.h>
main()
{
int i;
float x;
char c;
x = 4.7;
cout << x <<
i = x + 2.1;
cout << i <<
c = 81;
cout << c <<
i = 'b';
cout << i <<

// 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;

//
//
//
//
//

6 (after truncating the fractional part of ...


... 6.8) is assigned to i.
The character with ASCII code 81 ('Q') is ...
... assigned to c. The character is 'Q'.
The ASCII code of 'b' (98) is assigned to i.

endl;

return 0;
}

19

Constants and aliases


Aliases
An alias is a name (usually more meaningful, easier to remember or type) used in a program.
Before compilation, the alias will be translated into another name or string (usually less
meaningful, less easy to remember or type).
Const float pie =3.14;
We can use #define preprocessor directives to define an alias. For example, the statement
#define MAX 100
defines an alias called MAX

which is identical to 100. During compile time, any occurrence of MAX


in the program will be replaced by 100:
#include <iostream.h>
#define MAX 100
...
int a[MAX];
...
for (i = 0; i < MAX; i++)
...
if (n >= MAX * 2)
...

#include <iostream.h>

... is translated to ...

...
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

Equivalent Pascal 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 <<

// 3 (NOT 3.4) will be displayed.

that i & j are of type int while x is of type float.


j;
// 3 will be stored in y.
y << endl;
j;
// 3.4 will be stored in z.
z << endl;

// Compare the following:


cout << 18 / 8 << endl;
cout << 18.0 / 8 << endl;
cout << 18 / 8.0 << endl;
cout << 18.0 / 8.0 << endl;

//
//
//
//

2 will be
2.25 will
2.25 will
2.25 will

displayed.
be displayed.
be displayed.
be displayed.

return 0;
}

3. The addition, subtraction, multiplication and modulus operations are similar


to those in Pascal. For example:
C++
expression

Equivalent Pascal
expression

(x + y - a) % b (x + y - a) mod b

4. The operands in a modulus operation must be of integer types.


5. Character values can also be used in arithmetic expressions. In this case, the
ASCII code of the character will be used for calculation. See the following
program:
Program 4: Using characters in arithmetic expressions
#include <iostream.h>
main()
{
char c1 = 'A',
c2;
int i;
float x;
c2 = c1 + 5;
cout << c2 << endl;

// The ASCII code of 'A' is 65.

// 'F' (ASCII code = 65+5 = 70) is stored in c2.

22

x = -0.25;
i = c2 * x;
is ...
cout << i << endl;

// -17 [integer part of 70*(-0.25) = -17.5]


// ... stored in i.

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;

// 3.4 will be displayed.


// 3 will be displayed.

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.

// 'A' will be displayed.


// 65 (ASCII of 'A') will be

return 0;
}

More assignment operators


23

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

All assignment operators are binary operators.


In general, any statement of the form
<variable> <operator>= <expression>;
where <operator> is one of "+", "-", "*", "/" or "%", can be written in the form
<variable> = (<variable>) <operator> (<expression>);
The following program makes use of these assignment operators:
Program 6:Using special assignment operators
#include <iostream.h>
main()
{
int a, b;
char c;

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;

// 'D' will be assigned to c.

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

Program 7: Multiple assignments


include <iostream.h>
main()
{
int a, b, c, d, e;
// 3 is assigned to b, and then 3 is assigned to a.
a = b = 3;
// 3*7 = 21 is assigned to b, and then 21 is assigned to c.
c = b *= 7;
// 8 is assigned to d and then 21+8 = 29 is assigned to c.
c += d = 8;
// 3+1 = 4 is assigned to a, and then 7*4 = 28 is assigned to e.
e = 7 * (a += 1);
cout << "a\tb\tc\td\te\n";
cout << a << "\t" << b << "\t" << c << "\t" << d << "\t" << e << endl;
return 0;
}
a = b = 3;

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.

Increment and decrement operators


C++ provides two types of increment operators and two types of decrement operators:
25

Operator

Name of
operator

Sample
expression

++<operand>

Preincrement

++a

<operand>++ Postincrement b++


--<operand>

Predecrement --c

<operand>-- Postdecrement d--

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.

cout << i << endl;


// "i++" and "++i" have no observable differences when they are used as
// statements by themselves (not part of an expression).
i++;
// i is incremented to 2.
cout << i << endl;
++i;
// i is incremented to 3.
cout << i << endl;
j = i++;
// j is assigned to 3 and then i is incremented to 4.
cout << "i=" << i << ", j=" << j << endl;
j = ++i;
// i is incremented to 5 and then j is assigned to 5.
cout << "i=" << i << ", j=" << j << endl;
return 0;
}

These operators also apply to character variables and floating-point variables.

Operators (Part 3)
26

Relational and equality operators


In C++, "==" and "!=" are equality operators while "<", ">", "<=" and ">=" are relational
operators:
Operator in C++ Operation
equal to
not equal to
less than
greater than
less than or equal to
greater than or equal
to

==
!=
<
>
<=
>=

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

All equality and relational operators are binary operators.


Note that "==" (equality) should not be confused with "=" (assignment).

Logical (Boolean) operators


(In the following, assume that a and b are of numerical type in C++ and of Boolean type in
Pascal.)
Operator in C++ Operation
logical AND
logical OR
logical negation
(NOT)

&&
||
!

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 AND (&&)

Logical OR (||)

Logical negation (!)

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>

is always evaluated first. If it is non-zero ("true"), the result of this operation is


the returned value of <expression_2>; otherwise, the result is the returned value of
<expression_3>. Usually, it may be interpreted as:
"If <expression_1> then <expression_2> else <expression_3>."
<expression_1>

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;

Sample output 1 (text in red is entered by user):


Enter x: 10
Enter y: 5
10 > 5
5 is the smaller number.

28

Sample output 2 (text in red is entered by user):


Enter x: 4
Enter y: 7
4 <= 7
4 is the smaller number.
min = (x < y ? x : y);
If x is less than y, the expression "x < y" will be true (i.e. non-zero) and the value of x will be
assigned to min.
If x is greater than or equal to y, the expression "x < y" will be false (i.e. zero) and the value of
y will be assigned to min.
x > y ? " > " : " <= "
If x is greater than y, the expression "x > y" will be true, and the above expression will return "
> ".
If x is less than or equal to y, the expression "x > y" will be false, and the above expression will
return " <= ".

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
()
! ++ -- +

(unary plus) - (unary minus) (type) (cast operator)

* / %
+

(addition) - (subtraction)

< > <= >= == !=


&&
||
?:
= += -= *= /= %=

In the above table, the operators within the same category have equal precedence.

Selection structures: if and if-else


statements
The selection structures provided in C++ are similar to those in Pascal.

29

Single-way selection
C++ control
Equivalent Pascal control
structure
structure
if
if <condition> then
<statement_1>
(<condition>)
<statement_1>;

will be executed if <condition> is non-zero


(i.e. true). Note that in C++, then is not required but the parentheses around the condition is
necessary.
<statement_1>

can be a compound statement if more than one statement are to be executed


when the condition is true. This applies to all kinds of control structures.
<statement_1>

A compound statement is a group of statements enclosed by a pair of braces. There is no


semicolon after the right brace.
Sample program:
Program 11: Using the if selection structure
C++ version
#include <iostream.h>
main()
{
int OT_hours, wages = 8000;
cout << "Number of overtime hours? ";
cin >> OT_hours;
if (OT_hours > 30) {
cout << "Maximum OT hours is 30" <<
endl;
OT_hours = 30;
}
wages += OT_hours * 50;
cout << "Wages: $" << wages << endl;
}

return 0;

Sample output 1 (text in red is entered by user):


Number of overtime hours? 50
Maximum OT hours is 30
Wages: $9500

Sample output 2 (text in red is entered by user):


30

Number of overtime hours? 12


Wages: $8600

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>;

If <condition> is non-zero (i.e. true), <statement_1> is executed. Otherwise, <statement_2>


is executed.
A statement using the conditional operator can be replaced by this selection structure. For
example, Program 9 can be rewritten as follows:
Program 12: Using the if-else selection structure
C++ version
#include <iostream.h>
main()
{
int x, y, min;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
if (x < y)
min = x;
else
min = y;
cout << x;
if (x > y)
cout << " > ";
else
cout << " <= ";
cout << y << endl;

31

cout << min << " is the smaller number."


<< endl;
return 0;
}

Sample output 1 (text in red is entered by user):


Enter x: 10
Enter y: 5
10 > 5
5 is the smaller number.

Sample output 2 (text in red is entered by user):


Enter x: 4
Enter y: 7
4 <= 7
4 is the smaller number.

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;
}

Sample output 1 (text in red is entered by user):


Score? 74
Grade: B

Sample output 2 (text in red is entered by user):


Score? 32
Grade: F

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';

Selection structures: switch statement


Multiple selectors
In addition to nested if-else statements, we can also use switch statement for multiple
selection according to the value of an ordinal type expression.
C++ control structure
switch (<ordinal_expression>) {
case <value_1>:
<statement_1_for_case_1>;
<statement_2_for_case_1>;
...
<statement_n_for_case_1>;
break;
case <value_2>:
<statement_1_for_case_2>;
<statement_2_for_case_2>;
...
<statement_n_for_case_2>;
break;
...
default:
<statement_1_for_default_case>;
<statement_2_for_default_case>;
...
<statement_n_for_default_case>;
}

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;
}

Sample output 1 (text in red is entered by user):


Grade: C
Average.

Sample output 2 (text in red is entered by user):


Grade: X
Invalid grade!

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;
}

Sample output (text in red is entered by user):


Grade: C
Average.
Fair.

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.

Repetition structures: while statement


Structure of a while statement
C++ control
structure

Equivalent Pascal control


structure

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;
}

Sample output (text in red is entered by user):


n? 3
3
9
27
81
243
729

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

C++ control structure


<counter> = <initial_value>;
while (<counter> <= <final_value>) {
<statements_to_be_executed>;
<counter> += <step>;
}

In particular, when <initial_value> is 1, <step> is 1 and <final_value> is n, the loop body


will be executed n times.
The following program accepts 5 scores and display their sum. The while loop is countercontrolled, and the counter is i.
Program 17: A counter-controlled loop
C++ version
#include <iostream.h>
main()
{
int score, sum, i;
sum = 0;
i = 1;
while (i <= 5) {
cout << "Score No. " << i << ": ";
cin >> score;
sum += score;
i++;
}
cout << "Sum = " << sum << endl;
}

return 0;

Sample output (text in red is entered by user):


Score
Score
Score
Score
Score
Sum =

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):
";

cin >> score;


}
cout << "Sum = " << sum << endl;

return 0;

Sample output (text in red is entered by user):


Enter
Enter
Enter
Enter
Enter
Enter
Enter
Sum =

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>;
}

Repetition structures: do-while and for statements


38

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>

Comparison between do-while loop and while loop in C++


do-while loop
The loop body is executed at least once.
The condition is tested after the loop body is
executed.

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.

Comparison between do-while loop in C++ repeat-until loop in Pascal


do-while loop in C++
The loop is exited when the condition is false
(i.e. zero).

repeat-until loop in Pascal


The loop is exited when the condition (after
until) is true.

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

Program 19: Using a do-while loop


C++ version (using do-while loop)
Pascal version (using repeat-until loop)
#include <iostream.h>

program prog_19(input, output);


var
score, sum: integer;
begin
sum := 0;

main()
{
int score, sum = 0;
do {
cout << "Enter score (-1 to quit):

";

cin >> score;


if (score != -1)
sum += score;
} while (score != -1);
cout << "Sum = " << sum << endl;
return 0;

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>;
}

Therefore Program 16 can be re-written as follows:


Program 20: Using for statement
#include <iostream.h>
main()
{
int n, product;
cout << "n? ";
cin >> n;
for (product = n; product <= 1000; product *= n)
cout << product << endl;

40

return 0;

Usually, for statement is used as a counter-controlled loop. In such case, <expression_1> is an


intialisation statement, <expression_2> is an expression testing whether the final value is
reached, and <expression_3> indicates how the counter variable is incremented (or
decremented) in the loop.
(<counter> = <initial>; <counter> <= <final>;
Counter-controlled loop in for
<counter>++)
C++ (using for)
<loop_body>;

Equivalent countercontrolled loop in C++


(using while)

<counter> = <initial>;
while (<counter> <= <final>) {
<loop_body>;
<counter>++;
}

Equivalent Pascal control


structure

for <counter> := <initial> to <final> do


<loop_body>

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;
}

Sample output 1 (text in red is entered by user):


n? 8
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Finished!

Sample output 2 (text in red is entered by user):


n? 15
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Finished!

*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*

*
*
*
*
*
*
*

*
*
*
*
*
*

*
*
*
*
*

* * * *
* * *
* *
*

Although using unconditional branches is quite convenient, it is not preferable. In practice, it is


almost always easy to write code without unconditional branches. For example, the shaded part
of the above program can be written as follows:
42

Program 23: Re-writing Program 22 without using unconditional branches


C++ version
#include <iostream.h>
main() {
int i, j, n;
cout << "n? ";
cin >> n;
i = 1;
while ((i <= n) && (i <= 10)) {
for (j = n; j >= i; j--)
cout << "* ";
cout << endl;
i++;
}
cout << "Finished!" << endl;
return 0;
}

One-dimensional arrays
Declaration
The following are some examples of array declarations:
C++ version

Equivalent Pascal version

int a[5], b[10]; var


a: array[0..4] of integer;
b: array[0..9] of integer;

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.

Referring an array element


Referring an array element in C++ is the same as in Pascal: the array name, followed by a
subscript (which is an integer expression) enclosed by square brackets. For example, "a[4]",
"b[x + 1]" (assume that x is an integer variable).

43

Initialising the elements of an array in the array declaration


In addition to initialising the elements of an array one by one, they can also be initialised in the
array declaration by following the declaration with "=", followed by a comma-separated list of
initialisers (the initialisation values) which is enclosed in braces. For example:
C++ version

Equivalent Pascal version

int n[5] = {14, 23, 7, 10, 5}; var n: array[0..4] of integer;


...
n[0] := 14;
n[1] := 23;
n[2] := 7;
n[3] := 10;
n[4] := 5;

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

Equivalent Pascal version

int n[5] = {14, 23}; var n: array[0..4] of integer;


...
n[0] := 14;
n[1] := 23;
n[2] := 0;
n[3] := 0;
n[4] := 0;

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;
}

Sample output (text in red is entered by user):


Subscript? (-ve value to
a[5]: 11
Subscript? (-ve value to
a[9]: 19
Subscript? (-ve value to
Subscript out of range!
Subscript? (-ve value to
a[0]: 1
Subscript? (-ve value to

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

C++ version Equivalent Turbo Pascal version


char s[10]; var s: string[10];

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).

Initialisation and assignment


We can initialise a character array during declaration. For example:
char s[] = "Hello";

is equivalent to char s[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

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.

Common string functions


In order to use the following functions, the preprocessor directive "#include <string.h>" must
appear near the top of the program.
Common string
functions
strcpy(s, t)
strncpy(s, t, n)
strcat(s, t)
strncat(s, t, n)
strlen(s)
strcmp(s, t)

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

// The following statement is necessary because


// strncpy does not automatically append '\0' at the end of the string
c[11] = '\0';
strcpy(d, c);
strncat(c, a, 3);
strcat(d, a);
stored in d

// "Welcome to " is stored in d


// "Welcome to C++" is stored in c
// "Welcome to C++ programming" is

// b: "Welcome to this program!"


// c: "Welcome to C++"
// d: "Welcome to C++ programming"
cout << "b: " << b << "\nc: " << c << "\nd: " << d << endl;
// Here we can see that b > d
if (strcmp(b, d) > 0)
cout << "b > d\n";
else if (strcmp(b, d) == 0)
cout << "b = d\n";
else
cout << "b < d\n";
for (i = 0; !strncmp(b, d, i); i++) ;
// the loop body is
empty
// The above for loop is exited when strncmp(b, d, i) == 0
cout << "b and d differ at character " << i << "." << endl;
return 0;
}

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

Equivalent Turbo Pascal version

int a[5][3], b [2][3][4]; var


a: array[0..4, 0..2] of integer;
b: array[0..1, 0..2, 0..3] of integer;

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.

Initialising the elements of an array in the array declaration


The following example shows how multi-dimensional arrays can be initialised.
int n[2][3] = {{14, 23, 7}, {10, 5, 8}};

48

n [0] [1] [2]

[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:

int n[2][3] = {{14, 23}, {10}};

n [0] [1] [2]


[0] 14 23 0
[1] 10 0
0

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[][2] = {{3, 4}, {7}, {2,


3}};

This is a valid declaration. The size of the first level


index 3.

int a[][4];

This is invalid because there is not initialised before.

int a[3][] = {{4, 74}, {3, 2},


{1, 3}}

This is invalid because the size of the second level


indexing missing.

int a[][] = {{4, 7}, {3, 2},


{1,3}}

Same as above.

The following program makes use of a two-dimensional array:


Program 26: Using a two-dimensional array
C++ version
#include <iostream.h>
main()
{
int table[10][10], i, j;
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)

49

table[i][j] = i * j;

cout << " |";


for (i = 0; i < 10; i++)
cout << " " << i << "|";
cout << endl;
for (i = 1; i <= 11; i++)
cout << "--+";
cout << endl;
for (i = 0; i < 10; i++) {
cout << " " << i << "|";
for (j = 0; j < 10; j++) {
if (table[i][j] < 10)
cout << " ";
cout << table[i][j] << " ";
}
cout << endl;
}
return 0;

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;
};

// Defining a record data type to store


//
//
//
//

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;
};

// Defining a record data type to store


// 1st field: Employee Number
// 2nd field: Salary

struct StudentRecord a_student;


struct StaffRecord an_employee;

// a_student is a student record variable


// an_employee is a staff record variable

Usually, we use typedef to define a record data type for convenience:


C++ version
typedef struct StudentRecord {
char student_no[8];
char name[20];
char class_name[3];
int class_no;
} StudRec;
typedef struct StaffRecord {
char employee_no[6];
float salary;
} StaffRec;
StudRec a_student;
StaffRec an_employee;

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];

// an array of 1500 student records


// an array of 100 staff records

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;
}

Sample output (text in red is entered by user):


Student 0:
Student Number: 123456
Name: Chan Chi Ming
Student 1:
Student Number: 475721
Name: Lam Wai Ming
Student 2:
Student Number: 134578
Name: Chan Kin Wing
Student 3:
Student Number: 721535
Name: Chan Lai Sheung
Student 4:
Student Number: 127310
Name: Man Chi Wah
Chan Chi Ming
Chan Kin Wing

52

Chan Lai Sheung

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

function power(x: real; y: integer): real;


var
i: integer;
p: real;
begin
p := 1;
for i := 1 to y do
p := p * x;
power := p
end;
begin
for i := 0 to 9 do
writeln(i, ' ', power(1.5, i), ' ', power(-0.5, i))
end.

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

float power(float, int);

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

In C++, parameters in functions are passed by value. If pass-by-reference is to be implemented,


we have to pass the address of the variable to the function. This can be done by using an asterisk
(*) in the function argument and using an ampersand (&) in the actual parameter of the function
call. For example, in the function find_average in the following program, the first and the
second parameters are passed by value while the third parameter is passed by reference. The
average of the first two parameters are transferred back to the function call through the third
parameter:
Program 30: Pass by value and pass by reference
C++ version
#include <iostream.h>
void find_average
(float x, float y, float *z)
{
*z = (x + y) / 2;
}
main()
{
float a = 4, b = 3, c;
find_average(a, b, &c);
cout << "Average: " << c << endl;
return 0;
}

57

S-ar putea să vă placă și