You are on page 1of 77

Woldia University

Institute of Technology
School of Electrical and Computer engineering
For 1st year
Computer Programming (ECEg-1052)

Module name: Computer Programming

Prepared by: Tesfamariam G.

Preparation date: 04/05/15


Learning module for C++ 2015 E.C

Contents page
Chapter one ..................................................................................................................................... 1
Basics of computer system .......................................................................................................... 1
1.1 What is computer? ........................................................................................................... 1
1.2 Benefits of Computers ..................................................................................................... 1
1.3 Hard ware component ...................................................................................................... 2
1.4 Software component ........................................................................................................ 2
1.3.1 Data representation in a computer ............................................................................ 3
1.3.2 Integer representation................................................................................................ 4
1.3.3 Decimal (base 10) number system ............................................................................ 7
1.3.4 Binary (base 2) number system................................................................................. 7
1.3.5 Hexadecimal (base 16) number system .................................................................... 7
Chapter two ................................................................................................................................... 12
Fundamentals of C++ programming ......................................................................................... 12
2.1 Introduction to computer program ................................................................................. 12
2.2 Algorithm....................................................................................................................... 14
2.3 Flowchart ....................................................................................................................... 14
2.3.1 Flowchart Symbols ................................................................................................. 14
2.2.2 Type of Algorithms and flowchart .......................................................................... 15
2.4 Variables ........................................................................................................................ 17
2.5 Simple input/output ....................................................................................................... 18
2.6 Names ............................................................................................................................ 20
Chapter three ................................................................................................................................. 24
Control structure........................................................................................................................ 24
3.1 Sequential structure ....................................................................................................... 24
3.2 Selective structure.......................................................................................................... 24
3.3 Looping structures (iteration) ........................................................................................ 35
3.4 Unconditional control structure ..................................................................................... 41
Chapter four .................................................................................................................................. 46
Functions ................................................................................................................................... 46

Prepared by: Tesfamariam G. Page i


Learning module for C++ 2015 E.C

4.1 Definition of function .................................................................................................... 46


4.2 Function prototype ......................................................................................................... 46
4.3 Function definition ........................................................................................................ 47
4.4 Calling a Function ......................................................................................................... 48
4.4.1 Call by Value .......................................................................................................... 49
4.4.2 Call by Reference .................................................................................................... 50
4.5 Overloaded functions ..................................................................................................... 52
Chapter five ................................................................................................................................... 53
Array and structure .................................................................................................................... 53
5.1 Introduction to array ...................................................................................................... 53
5.2 Declaring Arrays............................................................................................................ 53
2.3 Array initialization ......................................................................................................... 53
5.4 Accessing array element ................................................................................................ 53
5.5 Two-Dimensional Arrays .............................................................................................. 55
5.6 Pointer to an array.......................................................................................................... 56
5.7 Passing Arrays to Functions .......................................................................................... 57
5.8 Structure ............................................................................................................................ 58
5.9 Defining a Structure....................................................................................................... 58
5.10 Accessing Structure Members ..................................................................................... 59
Chapter six .................................................................................................................................... 61
Strings and pointers ................................................................................................................... 61
6.1 Strings ............................................................................................................................ 61
6.2 The C-Style Character String .................................................................................... 61
6.3 The String Class in C++............................................................................................. 63
6.4 Pointers .............................................................................................................................. 64
6.5 Pointer arithmetic .......................................................................................................... 64
Chapter Seven ............................................................................................................................... 66
Input/output with files ............................................................................................................... 66
7.1 Classes ........................................................................................................................... 66
7.2 Open file ........................................................................................................................ 66
7.3 Closing files .................................................................................................................. 67
Prepared by: Tesfamariam G. Page ii
Learning module for C++ 2015 E.C

Chapter Eight ................................................................................................................................ 69


Object oriented programming ................................................................................................... 69
8.1 Classes ........................................................................................................................... 69
8.2 Constructors and destructors ......................................................................................... 71
8.3 Overloading Constructors .............................................................................................. 73

Prepared by: Tesfamariam G. Page iii


Learning module for C++ 2015 E.C

Chapter One

Basics of computer System

1.1 What is computer?


Computer is an advanced electronic device that takes raw data as input from the user and processes
it under the control of set of instructions (called program), gives the result (output), and
saves it for the future use.

1.2 Benefits of Computers


The three main benefits of using computers are :

1. Speed
2. Accuracy
3. Capacity to take large amount of work.

Computer work at a very high speed and are much faster than humans. The human equivalent of
an average computer would be more than one million mathematicians working 24 hours a day.
In addition to being fast, computers are very accurate. If the input and the instructions are accurate
the output will also be accurate.

Unlike humans, computers do not get bored or tired. The monotony of repetitive work for long
hours do not affect the computers.

Applications of Computers

Computers are used in various fields ranging from making cartoon films to space research. Some
applications of computers are:

1. Railway reservations
2. Banking and Accounts
3. Weather Forecasts

Prepared by: Tesfamariam G. Page 1


Learning module for C++ 2015 E.C

4. Space Research
5. Medical Diagnoses
6. Chemical Analyses

Generally, computer was developed from two parts, i.e. from hardware and software.

1.3 Hardware component


Computer hardware includes all the electrical, mechanical, and the electronic parts of a computer.
Any part that we can see or touch is the hard ware. Computer hardware includes:

1. System Unit
2. Peripheral devices
3. Input devices i.e. keyboard, mouse etc.
4. Output devices i.e. Display Unit, printer etc.
5. Storage devices like hard disk, floppy disks etc.

1.4 Software component


The functioning of the computer is not dependent on hardware alone. So, what else is required? It
requires a set of instructions that tells the computer what is to be done with the input data.
In computer terminology, this set of instructions is called a program and one or more programs is
termed as software. This software can be categorized as system software and application software.

Applications Software

Software especially suited for specific applications for example, railway and airline reservation,
billing, accounting or software which enables creation and storage of documents are termed as
application software.

System software

System software In the above airline reservation example, the clerk types your name and
other details through the keyboard. But how does this go to the system unit? This activity is done
by a set of instructions called the Operating Systems.

Prepared by: Tesfamariam G. Page 2


Learning module for C++ 2015 E.C

System software is a set of instructions that serves primarily as an intermediary between computer
hardware and application programs, and may also be directly manipulated by knowledgeable users.

1.3.1 Data representation in a computer


Computer uses a fixed number of bits to represent a piece of data, which could be a number, a
character, or others. A n-bit storage location can represent up to 2^n distinct entities. For example,
a 3-bit memory location can hold one of these eight binary
patterns: 000, 001, 010, 011, 100, 101, 110, or 111. Hence, it can represent at most 8 distinct
entities. You could use them to represent numbers 0 to 7, numbers 8881 to 8888, characters 'A' to
'H', or up to 8 kinds of fruits like apple, orange, banana; or up to 8 kinds of animals like lion, tiger,
etc.
Integers, for example, can be represented in 8-bit, 16-bit, 32-bit or 64-bit. An 8-bit unsigned integer
has a range of 0 to 255, while an 8-bit signed integer has a range of -128 to 127 - both representing
256 distinct numbers.
It is important to note that a computer memory location merely stores a binary pattern. It is entirely
up to you, as the programmer, to decide on how these patterns are to be interpreted. For example,
the 8-bit binary pattern "0100 0001B" can be interpreted as an unsigned integer 65, or an ASCII
character 'A', or some secret information known only to you. The interpretation of binary pattern
is called data representation or encoding.

Prepared by: Tesfamariam G. Page 3


Learning module for C++ 2015 E.C

1.3.2 Integer representation


Computers use a fixed number of bits to represent an integer. The commonly-used bit-lengths for
integers are 8-bit, 16-bit, 32-bit or 64-bit. Besides bit-lengths, there are two representation schemes
for integers:
1. Unsigned Integers: can represent zero and positive integers.
2. Signed Integers: can represent zero, positive and negative integers. Three representation
schemes had been proposed for signed integers:

1. Sign-Magnitude representation

2. 1's Complement representation

3. 2's Complement representation

n_bit unsigned integer

Unsigned integers can represent zero and positive integers, but not negative integers. The value of
an unsigned integer is interpreted as "the magnitude of its underlying binary pattern".
Example 1: Suppose that n=8 and the binary pattern is 0100 0001B, the value of this unsigned
integer is 1×2^0 + 1×2^6 = 65D.
Example 2: Suppose that n=16 and the binary pattern is 0001 0000 0000 1000B, the value of
this unsigned integer is 1×2^3 + 1×2^12 = 4104D.
Example 3: Suppose that n=16 and the binary pattern is 0000 0000 0000 0000B, the value of
this unsigned integer is 0.
An n-bit pattern can represent 2^n distinct integers. An n-bit unsigned integer can represent
integers from 0 to (2^n)-1, as tabulated below:

Prepared by: Tesfamariam G. Page 4


Learning module for C++ 2015 E.C

Signed integer

signed integers can represent zero, positive integers, as well as negative integers. Three
representation schemes are available for signed integers:

1. Sign-Magnitude representation

2. 1's Complement representation

3. 2's Complement representation

n-bit sign integers in 1’s compliment representation

In 1's complement representation:

• Again, the most significant bit (msb) is the sign bit, with value of 0 representing positive
integers and 1 representing negative integers.
• The remaining n-1 bits represents the magnitude of the integer, as follows:
o For positive integers, the absolute value of the integer is equal to "the magnitude of the
(n-1)-bit binary pattern".
o For negative integers, the absolute value of the integer is equal to "the magnitude of
the complement (inverse) of the (n-1)-bit binary pattern" (hence called 1's complement).
Example 1: Suppose that n=8 and the binary representation 0 100 0001B.
Sign bit is 0 ⇒ positive
Absolute value is 100 0001B = 65D
Hence, the integer is +65D
Example 2: Suppose that n=8 and the binary representation 1 000 0001B.
Sign bit is 1 ⇒ negative
Absolute value is the complement of 000 0001B, i.e., 111 1110B = 126D
Hence, the integer is -126D

Prepared by: Tesfamariam G. Page 5


Learning module for C++ 2015 E.C

n- bit sign integers in 2’s complement representation

In 2's complement representation:

• Again, the most significant bit (msb) is the sign bit, with value of 0 representing positive
integers and 1 representing negative integers.
• The remaining n-1 bits represents the magnitude of the integer, as follows:
o for positive integers, the absolute value of the integer is equal to "the magnitude of the
(n-1)-bit binary pattern".
o for negative integers, the absolute value of the integer is equal to "the magnitude of
the complement of the (n-1)-bit binary pattern plus one" (hence called 2's complement).
Example 1: Suppose that n=8 and the binary representation 0 100 0001B.
Sign bit is 0 ⇒ positive
Absolute value is 100 0001B = 65D
Hence, the integer is +65D
Example 2: Suppose that n=8 and the binary representation 1 000 0001B.
Sign bit is 1 ⇒ negative
Absolute value is the complement of 000 0001B plus 1, i.e., 111 1110B + 1B = 127D
Hence, the integer is -127D

Prepared by: Tesfamariam G. Page 6


Learning module for C++ 2015 E.C

1.3.3 Decimal (base 10) number system


Decimal number system has ten symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, called digits. It
uses positional notation. That is, the least-significant digit (right-most digit) is of the order
of 10^0 (units or ones), the second right-most digit is of the order of 10^1 (tens), the third right-
most digit is of the order of 10^2 (hundreds), and so on. For example,

735 = 7×10^2 + 3×10^1 + 5×10^0

1.3.4 Binary (base 2) number system


Binary number system has two symbols: 0 and 1, called bits. It is also a positional notation, for
example,

10110B = 1×2^4 + 0×2^3 + 1×2^2 + 1×2^1 + 0×2^0

1.3.5 Hexadecimal (base 16) number system


Hexadecimal number system uses 16 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F,
called hex digits. It is a positional notation, for example,

A3EH = 10×16^2 + 3×16^1 + 14×16^0

Hexadecimal system is used as a compact form or shorthand for binary bits. Each hex digit is
equivalent to 4 binary bits, i.e., shorthand for 4 bits, as follows:

Prepared by: Tesfamariam G. Page 7


Learning module for C++ 2015 E.C

Conversion from hexadecimal to binary

Replace each hex digit by the 4 equivalent bits, for examples,

A3C5H = 1010 0011 1100 0101B

102AH = 0001 0000 0010 1010B

Conversion from binary to hexadecimal

Starting from the right-most bit (least-significant bit), replace each group of 4 bits by the equivalent
hex digit (pad the left-most bits with zero if necessary), for examples,

1001001010B = 0010 0100 1010B = 24AH

10001011001011B = 0010 0010 1100 1011B = 22CBH

Conversion from base r to decimal (base 10)

Given a n-digit base r number: dn-1 dn-2 dn-3 ... d3 d2 d1 d0 (base r), the decimal equivalent is
given by:

dn-1 × r^(n-1) + dn-2 × r^(n-2) + ... + d1 × r^1 + d0 × r^0

For examples,

A1C2H = 10×16^3 + 1×16^2 + 12×16^1 + 2 = 41410 (base 10)

10110B = 1×2^4 + 1×2^2 + 1×2^1 = 22 (base 10)

Conversion from decimal (base r) to base r

Use repeated division/remainder. For example,

To convert 261D to hexadecimal:

Prepared by: Tesfamariam G. Page 8


Learning module for C++ 2015 E.C

261/16 => quotient=16 remainder=5


16/16 => quotient=1 remainder=0
1/16 => quotient=0 remainder=1 (quotient=0 stop)
Hence, 261D = 105H

The above procedure is actually applicable to conversion between any 2 base systems. For
example,

To convert 1023(base 4) to base 3:


1023(base 4)/3 => quotient=25D remainder=0
25D/3 => quotient=8D remainder=1
8D/3 => quotient=2D remainder=2
2D/3 => quotient=0 remainder=2 (quotient=0 stop)
Hence, 1023(base 4) = 2210(base 3)

General conversion between two base system with factorial part

1. Separate the integral and the fractional parts.

2. For the integral part, divide by the target radix repeatably, and collect the ramainder in
reverse order.

3. For the fractional part, multiply the fractional part by the target radix repeatably, and collect
the integral part in the same order.

Example 1:

Convert 18.6875D to binary


Integral Part = 18D
18/2 => quotient=9 remainder=0
9/2 => quotient=4 remainder=1
4/2 => quotient=2 remainder=0
2/2 => quotient=1 remainder=0
1/2 => quotient=0 remainder=1 (quotient=0 stop)

Prepared by: Tesfamariam G. Page 9


Learning module for C++ 2015 E.C

Hence, 18D = 10010B


Fractional Part = .6875D
.6875*2=1.375 => whole number is 1
.375*2=0.75 => whole number is 0
.75*2=1.5 => whole number is 1
.5*2=1.0 => whole number is 1
Hence .6875D = .1011B
Therefore, 18.6875D = 10010.1011B

Example 2:

Convert 18.6875D to hexadecimal


Integral Part = 18D
18/16 => quotient=1 remainder=2
1/16 => quotient=0 remainder=1 (quotient=0 stop)
Hence, 18D = 12H
Fractional Part = .6875D
.6875*16=11.0 => whole number is 11D (BH)
Hence .6875D = .BH
Therefore, 18.6875D = 12.BH

Binary addition

Example1: Add 010011112 to 001000112 using signed-magnitude arithmetic.

We find 010011112 + 001000112= 011100102 in signed-magnitude representation.

Example2: Add 010011112 to 011000112 using signed-magnitude arithmetic.

Prepared by: Tesfamariam G. Page 10


Learning module for C++ 2015 E.C

We obtain the erroneous result of 79 + 99 = 50.

Binary subtractions

Example1: Subtract 010011112 from 011000112 using signed-magnitude arithmetic.

We find 011000112-010011112=000101002 in signed-magnitude representation.

Example2: Add 100100112 (-19) to 000011012 (+13) using signed-magnitude arithmetic.

The first number (the augend) is negative because its sign bit is set to 1. The second number (the
addend) is positive. What we are asked to do is in fact a subtraction. First, we determine which of
the two numbers is larger in magnitude and use that number for the augend. Its sign will be the
sign of the result.

Prepared by: Tesfamariam G. Page 11


Learning module for C++ 2015 E.C

Chapter Two

Fundamentals of C++ Programming

2.1 Introduction to computer program


A computer program is a sequence of instructions written using a Computer Programming
Language to perform a specified task by the computer.

• A computer program is also called a computer software, which can range from two
lines to millions of lines of instructions.
• Computer program instructions are also called program source code and computer
programming is also called program coding.
• A computer without a computer program is just a dump box; it is programs that
make computers active.

There are hundreds of programming languages, which can be used to write computer programs
and following are a few of them:

• C • PHP
• C++ • Perl
• Java • Ruby
• Python
Compiler
Actually, the computer cannot understand your program directly given in the text format, so we
need to convert this program in a binary format, which can be understood by the computer.
The conversion from text program to binary file is done by another software called Compiler
and this process of conversion from text formatted program to binary format file is called
program compilation. Finally, you can execute binary file to perform the programmed task.

Prepared by: Tesfamariam G. Page 12


Learning module for C++ 2015 E.C

Interpreter
Compilers are required in case you are going to write your program in a programming
language that needs to be compiled into binary format before its execution. There are other
programming languages such as Python, PHP, and Perl, which do not need any compilation
into binary format, rather an interpreter can be used to read such programs line by line
and execute them directly without any further conversion. So, if you are going to write your
programs in PHP, Python, Perl, Ruby, etc., then you will need to install their interpreters before
you start programming.

Prepared by: Tesfamariam G. Page 13


Learning module for C++ 2015 E.C

2.2 Algorithm
An algorithm is an effective method of step by step procedure which expressed as a finite set
of well-defined instructions.

2.3 Flowchart
The flowchart is a diagram which visually presents the flow of data through processing systems.
This means by seeing a flow chart one can know the operations performed and the sequence
of these operations in a system. Algorithms are nothing but sequence of steps for solving
problems. So a flow chart can be used for representing an algorithm.

2.3.1 Flowchart Symbols


There are 6 basic symbols commonly used in flowcharting of assembly language Programs:
Terminal, Process, input/output, Decision, Connector and Predefined Process.

Symbol Name Function


Process Indicates any type of internal
operation inside the Processor
or Memory

input/output Used for any Input / Output (I/O)


operation.

Decision Used to ask a question that can be


answered in a binary format
(Yes/No, True/False)
Connector Allows the flowchart to be drawn
without intersecting lines.

Terminal Indicates the starting or ending


of the program, process, or
interrupt program

Prepared by: Tesfamariam G. Page 14


Learning module for C++ 2015 E.C

Flow Lines Shows direction of flow.

2.2.2 Type of Algorithms and flowchart


The algorithm and flowchart can be classified into three types of control structures. They are:

1. Sequence

The sequence is exemplified by sequence of statements place one after the other – the one above
or before another gets executed first. In flowcharts, sequence of statements is usually contained in
the rectangular process box.

Example 1: Write an algorithm and draw flowchart to read two numbers and find their sum.

Inputs to the algorithm: Step5: Print Sum

First num1 Step6: End

Second num2

Expected output:

Sum of the two numbers

Algorithm:

Step1: Start

Step2: Read\input the first num1.

Step3: Read\input the second num2.

Step4: Sum num1+num2 // calculation of


sum

2. Branching (Selection)

It refers to a binary decision based on some condition. If the condition is true, one of the two
branches is explored; if the condition is false, the other alternative is taken. This is usually

Prepared by: Tesfamariam G. Page 15


Learning module for C++ 2015 E.C

represented by the ‘if-then’ construct in pseudo-codes and programs. In flowcharts, this is


represented by the diamond-shaped decision box.

example1: write algorithm and draw flowchart to find the greater number between two numbers

Step1: Start

Step2: Read/input A and B

Step3: If A greater than B then C=A

Step4: if B greater than A then C=B

Step5: Print C

Step6: End

3. Loop (Repetition)

It allows a statement or a sequence of statements to be repeatedly executed based on some


loop condition. It is represented by the ‘while’ and ‘for’ constructs in most programming
languages, for unbounded loops and bounded loops respectively. In the flowcharts, a back
arrow hints the presence of a loop.

Example1: An algorithm and draw flowchart to calculate even numbers between 9 and 99

1. Start 6. End

2. I ← 10

3. Write I in standard output

4. I ← I+2

5. If (I <=98) then go to line 3

Prepared by: Tesfamariam G. Page 16


Learning module for C++ 2015 E.C

2.4 Variables
A variable is a symbolic name for a memory location in which data can be stored and subsequently
recalled. Variables are used for holding data values so that they can be utilized in various
computations in a program. All variables have two important attributes:

• A type which is established when the variable is defined (e.g., integer, real, character).
Once defined, the type of a C++ variable cannot be changed.
• A value which can be changed by assigning a new value to the variable. The kind of values
a variable can assume depends on its type. For example, an integer variable can only take
integer values (e.g., 2, 100, - 12).

Example

#include <iostream> float workHours, payRate, weeklyPay; //


float is data type the other is variable
using namespace std;
workDays = 5; // 5 is value of workDayays in
int main ()
the memory allocation

{
workHours = 7.5;

int workDays; //workdays is a variable, int


payRate = 38.55;
is data type

Prepared by: Tesfamariam G. Page 17


Learning module for C++ 2015 E.C

weeklyPay = workDays * workHours * cout << weeklyPay;


payRate;
cout << ' \n';
cout << "Weekly Pay = ";
}

2.5 Simple input/output


The most common way in which a program communicates with the outside world is through
simple, character - oriented Input/output (IO) operations. C++ provides two useful operators for
this purpose: >> for input and << for output. #include <iostream.h>

Example

#include <iostream> cout << "What is the hourly pay rate? ";

cin >> payRate;


using namespace std;
weeklyPay = workDays * workHours *
int main () payRate;

{ cout << "Weekly Pay = ";

int workDays = 5; cout << weeklyPay;

float workHours = 7.5; cout << ' \n';

float payRate, weeklyPay; }

Integer numbers
An integer variable may be defined to be of type short , int , or long . For example, on the author’s
PC, a short uses 2 bytes, an int also 2 bytes, and a long 4 bytes.

short age = 20;

int salary = 65000;

long price = 4500000;

A literal integer (e.g., 1984 ) is always assumed to be of type int , unless it has an L or l and U
or u suffix, in which case it is treated as a long . For example:

1984L, 1984l, 1984U, 1984u, 1984LU, 1984ul

Prepared by: Tesfamariam G. Page 18


Learning module for C++ 2015 E.C

An integer is taken to be octal if it is preceded by a zero ( 0 ), and hexadecimal if it is preceded by


a 0x or 0X . For example:

92 // decimal

0134 // equivalent octal

0x5C // equivalent hexadecimal

Real number

A real variable may be defined to be of type float or double . The latter uses more bytes and
therefore offers a greater range and accuracy for representing real numbers. For example, on the
author’s PC, a float uses 4 and a double uses 8 bytes.

float interestRate = 0.06;

double pi = 3.141592654;

A literal real (e.g., 0.06 ) is always assumed to be of type double , unless it has an F or f suffix,
in which case it is treated as a float , or an L or l suffix, in which case it is treated as a long double
.

0.06F 0.06f 3.141592654L 3.141592654l

Characters

A character variable is defined to be of type char. A character variable occupies a single byte
which contains the code for the character. For example, the character A has the ASCII code 65,
and the character a has the ASCII code 97.

char ch = 'A';

A litera l character is written by enclosing the character between a pair of single quotes (e.g., 'A'
). Nonprintable characters are represented using escape sequences. For example:

'\n' // new line '\v' // vertical tab

'\r' // carriage return '\b' // backspace

'\t' // horizontal tab '\f' // formfeed

Prepared by: Tesfamariam G. Page 19


Learning module for C++ 2015 E.C

Single and double quotes and the backslash '\'' // single quote (')
character can also use the escape
'\"' // double quote (")
notation:
'\\' // backslash ( \)

Strings

A string is a consecutive sequence (i.e., array) of characters which are terminated by a null
character. A string variable is defined to be of type char* (i.e., a pointer to character). For example,
consider the definition:

char *str = "HELLO";

2.6 Names
Programming languages use names to refer to the various entities that make up a program. We
have already seen examples of an important category of such names (i.e., variable names). Other
categories include: function names, type names, and macro names.

C++ imposes the following rules for creating valid names (also called identifiers). A name should
consist of one or mor e characters, each of which may be a letter (i.e., 'A'- 'Z' and 'a'- 'z'), a digit
(i.e., '0' - '9'), or an underscore character ('_'), except that the first character may not be a digit.
Upper and lower case letters are distinct. For example:

salary // valid identifier

salary2 // valid identifier

2salary // invalid identifier (begins with a digit)

_salary // valid identifier

Salary // valid but distinct from salary

Reserved words

In C++ there are called reserved words or keywords and are summarized in Table.

Prepared by: Tesfamariam G. Page 20


Learning module for C++ 2015 E.C

Expressions in C++

C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional
expressions. It also provides operators which produce useful side effects, such as assignment,
increment, and decrement. C++ provides five basic arithmetic operators. These are summarized
in Table.

C++ provides six relational operators for comparing numeric quantities. These are summarized
in Table.

Prepared by: Tesfamariam G. Page 21


Learning module for C++ 2015 E.C

C++ provides three logical operators for combining logical expression. These are summarized in
Table.

C++ provides six bitwise operators for manipulating the individual bits in an integer quantity.
These are summarized in Table.

The next table illustrates bit sequences for the sample operands and results in the above Table. To
avoid worrying about the sign bit (which is machine dependent), it is common to declare a bit
sequence as an unsigned quantity:

unsigned char x = ' \011';

unsigned char y = ' \027';

Prepared by: Tesfamariam G. Page 22


Learning module for C++ 2015 E.C

The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, a dding and subtracting 1 from a numeric variable. These are summarized in Tabl e
suppose K=5.

The assignment operator is used for storing a value at some memory location (typically denoted
by a variable). Its left operand should be left value, and its right operand may be an arbitrary
expression. The latter is evaluated and the outcome is stored in the location denoted by the left
value.

Any number of assignments can be concatenated in this fashion to form one expression. For
example:

int m, n, p;

m = n = p = 100; // means: n = (m = (p = 100));

m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2; i.e m=100

m + = n = p = 10; // means: m = m + (n = p = 10)

Prepared by: Tesfamariam G. Page 23


Learning module for C++ 2015 E.C

Chapter Three

Control Structure
C++ provides control structures that serve to specify what has to be done by our program, when
and under which circumstances. With the introduction of control structures we are going to have
to introduce a new concept: the compound statement or block. A block is a group of statements
which are separated by semicolons (;) like all C++ statements, but grouped together in a block
enclosed in braces: { } :

{statement1;

statement2;

statement3 ;}

There are four types of control structure, those are:

1. Selective
2. Sequential
3. Looping
4. Unconditional

3.1 Sequential structure


It is the built in control structure in c++.

3.2 Selective structure


It is a decision making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false. It can be described in the figure as follows.

Prepared by: Tesfamariam G. Page 24


Learning module for C++ 2015 E.C

C++ programming language provides following types of decision making statements.

if statement An ‘if’ statement consists of a Boolean expression followed by one or more


statements.

Syntax

The syntax of an if statement in C++ is:

if(boolean_expression)

// statement(s) will execute if the Boolean expression is true

If the Boolean expression evaluates to true, then the block of code inside the if statement will be
executed. If Boolean expression evaluates to false, then the first set of code after the end of the if
statement (after the closing curly brace) will be executed.

Prepared by: Tesfamariam G. Page 25


Learning module for C++ 2015 E.C

Example 1

#include <iostream> {

using namespace std; // if condition is true then print the following

int main () cout << "a is less than 20;" << endl;

{ }

// local variable declaration: cout << "value of a is : " << a << endl;

int a = 10; return 0;

// check the boolean condition }

if( a < 20 )

The output as follows:

a is less than 20;

Value of a is: 10

if...else statement An ‘if’ statement can be followed by an optional ‘else’ statement, which
executes when the Boolean expression is false.

Syntax

The syntax of an if...else statement in C++ is:

Prepared by: Tesfamariam G. Page 26


Learning module for C++ 2015 E.C

if(boolean_expression)

// statement(s) will execute if the boolean expression is true

else

// statement(s) will execute if the boolean expression is fal se

If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.

Example 1

#include <iostream> // local variable declaration:

using namespace std; int a = 100;

int main () // check the boolean condition

{ if( a < 20 )

Prepared by: Tesfamariam G. Page 27


Learning module for C++ 2015 E.C

{ // if condition is false then print the following

// if condition is true then print the following cout << "a is not less than 20;" << endl;

cout << "a is less than 20;" << endl; }

} cout << "value of a is : " << a << endl;

else return 0;

{ }
The output as follows:

a is not less than 20;

value of a is : 100

if...else if...else Statement

An if statement can be followed by an optional else if...else statement, which is very usefull to
test various conditions using single if...else if statement.When using if , else if , else statements
there are few points to keep in mind.

• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax

The syntax of an if...else if...else statement in C++ is:

if(boolean_expression 1)

// Executes when the boolean expression 1 is true

else if( boolean_expression 2)

Prepared by: Tesfamariam G. Page 28


Learning module for C++ 2015 E.C

// Executes when the boolean expression 2 is true

else if( boolean_expression 3)

// Executes when the boolean expression 3 is true

else

// executes when the none of the above condition is true.

Example 1

#include <iostream> {

using namespace std; // if else if condition is true

int main () cout << "Value of a is 20" << endl;

{ }

// local variable declaration: else if( a == 30 )

int a = 100; {

// check the boolean condition // if else if condition is true

if( a == 10 ) cout << "Value of a is 30" << endl;

}
{
else
// if condition is true then print the following
{
cout << "Value of a is 10" << endl;
// if none of the conditions is true
}
cout << "Value of a is not matching" << endl;
else if( a == 20 )
}

Prepared by: Tesfamariam G. Page 29


Learning module for C++ 2015 E.C

cout << "Exact value of a is : " << a << endl; }

return 0;

The output as follows:

Value of a is not matching

Exact value of a is : 100

Nested if statements You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else
if’ statement(s).

Syntax

The syntax for a nested if statement is as follows:

if( boolean_expression 1)

// Executes when the boolean expression 1 is true

if(boolean_expression 2)

// Executes when the boolean expression 2 is true

You can nest else if...else in the similar way as you have nested if statement.

Example 1

#include <iostream> // local variable declaration:

using namespace std; int a = 100;

int main () int b = 200;

{ // check the boolean condition

Prepared by: Tesfamariam G. Page 30


Learning module for C++ 2015 E.C

if( a == 100 ) }

{ }

// if condition is true then check the following cout << "Exact value of a is : " << a << endl;

if( b == 200 ) cout << "Exact value of b is : " << b << endl;

{ return 0;

// if condition is true then print the following }

cout << "Value of a is 100 and b is 200" <<


endl;

The output as follows:

Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

Switch statement a ‘switch’ statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked for each
case.

Syntax

The syntax for a switch statement in C++ is as follows:

switch(expression){

case constant-expression :

statement(s);

break; //optional

case constant-expression :

statement(s);

break; //optional

Prepared by: Tesfamariam G. Page 31


Learning module for C++ 2015 E.C

// you can have any number of case statements.

default : //Optional

statement(s);

Example 1

#include <iostream> switch(grade)

using namespace std; {

int main () case 'A' :

{ cout << "Excellent!" << endl;

// local variable declaration: break;

char grade = 'D'; case 'B' :

Prepared by: Tesfamariam G. Page 32


Learning module for C++ 2015 E.C

case 'C' : break;

cout << "Well done" << endl; default :

break; cout << "Invalid grade" << endl;

case 'D' : }

cout << "You passed" << endl; cout << "Your grade is " << grade << endl;

break; return 0;

case 'F' : }

cout << "Better try again" << endl;

The output as follows:

You passed

Your grade is D

Nested switch statements you can use one ‘switch’ statement inside another ‘switch’ statement(s).

Syntax

The syntax for a nested switch statement is as follows:

switch(ch1) {

case 'A':

cout << "This A is part of outer switch";

switch(ch2) {

case 'A':

cout << "This A is part of inner switch";

break;

case 'B': // ...

Prepared by: Tesfamariam G. Page 33


Learning module for C++ 2015 E.C

break;

case 'B': // ...

Example

#include <iostream> cout << "This is part of outer switch" << endl;

using namespace std; switch(b) {

int main () case 200:

{ cout << "This is part of inner switch" << endl;

// local variable declaration: }}

int a = 100; cout << "Exact value of a is : " << a << endl;

int b = 200; cout << "Exact value of b is : " << b << endl;

switch(a) { return 0;

case 100: }

This would produce the following result:

This is part of outer switch

This is part of inner switch

Exact value of a is : 100

Exact value of b is : 200

The? : Operator

We have covered conditional operator “? :” in previous chapter which can be used to replace
if...else statements. It has the following general form:

Prepared by: Tesfamariam G. Page 34


Learning module for C++ 2015 E.C

Exp1 ? Exp2 : Exp3;

Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a ‘?’ Expression is determined like this: Exp1 is evaluated. If it is true, then Exp2
is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is
evaluated and its value becomes the value of the expression.

3.3 Looping structures (iteration)


Loops have as purpose to repeat a statement a certain number of times or while a condition is
fulfilled. There are number of iteration (looping) control structure those are as follows:

1. while loop
2. do…while loop
3. fore loop
4. nested loop

while loop Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.

Syntax

The syntax of a while loop in C++ is:

while(condition)

statement(s);

Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.

Prepared by: Tesfamariam G. Page 35


Learning module for C++ 2015 E.C

Example 1

// custom countdown using while

#include <iostream>

using namespacestd;

intmain ()

intn;

cout << "Enter the starting number > ";

cin >> n;

while(n>0) {

cout << n << ", ";

--n;

cout << "FIRE!\n";

return0;}

When the above code is produces the following result:

Prepared by: Tesfamariam G. Page 36


Learning module for C++ 2015 E.C

Enter the starting number > 8

8, 7, 6, 5, 4, 3, 2, 1, FIRE!

for loop Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

Syntax

The syntax of a for loop in C++ is:

for ( init; condition; increment )

statement(s);

Prepared by: Tesfamariam G. Page 37


Learning module for C++ 2015 E.C

Example 1

// countdown using a for loop cout << n << ", ";

#include <iostream> }

using namespacestd; cout << "FIRE!\n";

int main () return0;

{ }

for(intn=10; n>0; n--) {

When the above code is compiled and executed, it produces the following result:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

do...while loop Like a ‘while’ statement, except that it tests the condition at the end of the
loop body.

Syntax

The syntax of a do...while loop in C++ is:

do

statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s)
in the loop execute once before the condition is tested.

Prepared by: Tesfamariam G. Page 38


Learning module for C++ 2015 E.C

Example 1

#include <iostream> cout << "Enter number (0 to end): ";

using namespacestd; cin >> n;

intmain () cout << "You entered: "<< n << "\n";

{ } while(n != 0);

unsigned longn; return0;

do{ }

The expected output can be:

Enter number (0 to end): 12345

You entered: 12345

Enter number (0 to end): 160277

You entered: 160277

Enter number (0 to end): 0

You entered: 0

nested loops You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop up to 256 times.

Prepared by: Tesfamariam G. Page 39


Learning module for C++ 2015 E.C

Syntax

The syntax for a nested for loop statement in C++ is as follows:

for ( init; condition; increment )

for ( init; condition; increment )

statement(s);

statement(s); // you can put more statements.

Example 1

The following program uses a nested for loop to find the prime numbers from 2 to 100:

#include <iostream> for(j=2; j <= (i/j); j++)

using namespace std; if(!(i%j)) break; // if factor found, not prime

int main () if(j > (i/j)) cout << i << " is prime\n";

{ }

int i, j; return 0;

for(i=2; i<100; i++) { }

This would produce the following result:

2 is prime 11 is prime

3 is prime 13 is prime

5 is prime 17 is prime

7 is prime 19 is prime

Prepared by: Tesfamariam G. Page 40


Learning module for C++ 2015 E.C

23 is prime 53 is prime

29 is prime 59 is prime

31 is prime 61 is prime

37 is prime 67 is prime

41 is prime 71 is prime

43 is prime 73 is prime

47 is prime 79 is prime

83 is prime

89 is prime

97 is prime

3.4 Unconditional control structure


break statement Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.

Syntax

The syntax of a break statement in C++ is:

break;

Prepared by: Tesfamariam G. Page 41


Learning module for C++ 2015 E.C

Example 1

#include <iostream> a = a + 1;

using namespace std; if( a > 15)

int main () {

{ // terminate the loop

// Local variable declaration: break;

int a = 10; }

// do loop execution }while( a < 20 );

do return 0;

{ }

cout << "value of a: " << a << endl;

When the above code is compiled and executed, it produces the following result:

value of a: prettyprint notranslate10

value of a: 11 value of a: 14

value of a: 12 value of a: 15

value of a: 13

Prepared by: Tesfamariam G. Page 42


Learning module for C++ 2015 E.C

continue statement causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.

Syntax

The syntax of a continue statement in C++ is:

continue;

Example 1

#include <iostream> {

using namespace std; // skip the iteration.

int main () a = a + 1;

{ continue;

// Local variable declaration: }

int a = 10; cout << "value of a: " << a << endl;

// do loop execution a = a + 1;

do }while( a < 20 );

{ return 0;

if( a == 15) }

Prepared by: Tesfamariam G. Page 43


Learning module for C++ 2015 E.C

When the above code is compiled and executed, it produces the following result:

value of a: 10 value of a: 16

value of a: 11 value of a: 17

value of a: 12 value of a: 18

value of a: 13 value of a: 19

value of a: 14

goto statement Transfers control to the labeled statement. Though it is not advised to use goto
statement in your program.

Syntax

The syntax of a goto statement in C++ is:

goto label;

..

label: statement;

Where label is an identifier that identifies a labeled statement. A labeled statement is any statement
that is preceded by an identifier followed by a colon (:).

Prepared by: Tesfamariam G. Page 44


Learning module for C++ 2015 E.C

Example 1

#include <iostream> {

using namespace std; // skip the iteration.

int main () a = a + 1;

{ goto LOOP;

// Local variable declaration: }

int a = 10; cout << "value of a: " << a << endl;

// do loop execution a = a + 1;

LOOP:do }while( a < 20 );

{ return 0;

if( a == 15) }

When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 16
value of a: 11 value of a: 17
value of a: 12 value of a: 18
value of a: 13 value of a: 19
value of a: 14

Prepared by: Tesfamariam G. Page 45


Learning module for C++ 2015 E.C

Chapter Four

Functions

4.1 Definition of function


A function is a group of statements or routines that together perform a specific task. Every
C++ program has at least one function, which is main(), and all the most trivial programs
can define additional functions.

4.2 Function prototype


A function declaration (prototype) tells the compiler about a function's name, return type, and
parameters. This declaration of function only used for declaring a parameter (variables). The
syntax is as follows:

return_type function_name( parameter list );

For the above defined function max(), following is the function declaration:

int max(int num1, int num2);

Example 1:

// declaring functions prototypes cin >> i;

#include <iostream> odd (i);

using namespacestd; } while(i!=0);

voidodd (inta); return0;

voideven (inta); }

intmain () voidodd (inta)

{ {

int i; if((a%2)!=0) cout << "Number is odd.\n";

do{ elseeven (a);

cout << "Type a number (0 to exit): "; }

Prepared by: Tesfamariam G. Page 46


Learning module for C++ 2015 E.C

voideven (inta) elseodd (a);

{ }

if((a%2)==0) cout << "Number is even.\n";

The output of the above code is:

Type a number (0 to exit): 9 Type a number (0 to exit): 1030

Number is odd. Number is even.

Type a number (0 to exit): 6 Type a number (0 to exit): 0

Number is even. Number is even.

4.3 Function definition


A function definition provides the actual body of the function and task execution takes place in
this body. The C++ standard library provides numerous built-in functions that your program
can call. For example, function strcat() to concatenate two strings, function memcpy() to copy
one memory location to another location, and many more functions.

The general form of a C++ function definition is as follows:

return_type function_name( parameter list )

body of the function

A C++ function definition consists of a function header and a function body.

Here are all the parts of a function:

• Return Type: A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.

Prepared by: Tesfamariam G. Page 47


Learning module for C++ 2015 E.C

• Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
• Parameters: A parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
• Function Body: The function body contains a collection of statements that define what the
function does.

4.4 Calling a Function


While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function. When a program calls a function, program
control is transferred to the called function. A called function performs defined task and when
it’s return statement is executed or when its function-ending closing brace is reached, it
returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.

For example:

#include <iostream> ret = max(a, b);

using namespace std; cout << "Max value is : " << ret << endl;

// function declaration return 0;

int max(int num1, int num2); }

int main () // function returning the max between two


numbers
{
int max(int num1, int num2)
// local variable declaration:
{
int a = 100;
// local variable declaration
int b = 200;
int result;
int ret;
if (num1 > num2)
// calling a function to get max value.
result = num1;

Prepared by: Tesfamariam G. Page 48


Learning module for C++ 2015 E.C

else return result;

result = num2; }

The output of the above sample code is:

Max value is : 200

Arguments passed by value and by reference.

Until now, in all the functions we have seen, the arguments passed to the functions have been
passed by value. This means that when calling a function with parameters, what we have passed
to the function were copies of their values but never the variables themselves.

4.4.1 Call by Value


The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.

Example 1:

#include <iostream> cout << "Before swap, value of a :" << a <<
endl;
using namespace std;
cout << "Before swap, value of b :" << b <<
// function declaration endl;

void swap(int x, int y); // calling a function to swap the values.

int main () swap(a, b);

{ cout << "After swap, value of a :" << a << endl;

// local variable declaration: cout << "After swap, value of b :" << b << endl;
int a = 100; return 0;

int b = 200; }

The output of the above code will be:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :100

Prepared by: Tesfamariam G. Page 49


Learning module for C++ 2015 E.C

After swap, value of b :200

4.4.2 Call by Reference


The call by reference method of passing arguments to a function copies the reference of an
argument into the formal parameter. Inside the function, the reference is used to access the
actual argument used in the call. This means that changes made to the parameter affect the passed
argument.

Example 1:

#include <iostream> cout << "Before swap, value of a :" << a <<
endl;
using namespace std;
cout << "Before swap, value of b :" << b <<
// function declaration endl;

void swap(int &x, int &y); /* calling a function to swap the values using
variable reference.*/
int main ()
swap(a, b);
{
cout << "After swap, value of a :" << a << endl;
// local variable declaration:
cout << "After swap, value of b :" << b << endl;
int a = 100;
return 0;
int b = 200;
}

The output becomes:

Before swap, value of a :100

Before swap, value of b :200

After swap, value of a :200

After swap, value of b :100

Example 2:

// passing parameters by reference void duplicate (int& a, int& b, int& c)

#include <iostream> {

using namespacestd; a*=2;

Prepared by: Tesfamariam G. Page 50


Learning module for C++ 2015 E.C

b*=2; Int x=1, y=3, z=7;

c*=2; duplicate (x, y, z);

} cout << "x="<< x << ", y="<< y << ", z="<< z;

Int main () return0;

{ }

The output will be:

x=2, y=6, z=14

Default values in parameters.

When declaring a function we can specify a default value for each of the last parameters. This
value will be used if the corresponding argument is left blank when calling to the function. To do
that, we simply have to use the assignment operator and a value for the arguments in the function
declaration. If a value for that parameter is not passed when the function is called, the default value
is used, but if a value is specified this default value is ignored and the passed value is used instead.

Example 1:

// default values in functions }

#include <iostream> Int main ()

using namespacestd; {

int divide (int a, int b=2) cout << divide (12);

{ cout << endl;

intr; cout << divide (20,4);

r=a/b; return0;

return(r); }

The output will be:


6
5

Prepared by: Tesfamariam G. Page 51


Learning module for C++ 2015 E.C

4.5 Overloaded functions


In C++ two different functions can have the same name if their parameter types or number are
different. That means that you can give the same name to more than one function if they have
either a different number of parameters or different types in their parameters.

For example:

// overloaded function intmain ()

#include <iostream> {

using namespacestd; Int x=5,y=2;

int operate (int a, int b) float n=5.0,m=2.0;

{ cout << operate (x,y);

return(a*b); cout << "\n";

} cout << operate (n,m);

Float operate (float a, float b) cout << "\n";

{ return0;

return(a/b); }

Here is the output: 10, 2.5

Prepared by: Tesfamariam G. Page 52


Learning module for C++ 2015 E.C

Chapter Five

Array and Structure

5.1 Introduction to array


An array is a series of elements of the same type placed in contiguous memory
locations that can be individually referenced by adding an index to a unique
identifier.

5.2 Declaring Arrays


To declare an array in C++, the programmer specifies the type of the elements and
the number of elements required by an array as follows:

type arrayName [ arraySize ]; or double balance[10];

2.3 Array initialization


When declaring a regular array of local scope (within a function, for example), if we
do not specify otherwise, its elements will not be initialized to any value by default,
so their content will be undetermined until we store some value in them. For
example:

Int bill[7]={3,4,5,6,7,7,6}; int bill[7]={3,4,5,6,7}; or Int bill[]={3,4,5,6,7,7,6};

Bill Index 0 1 2 3 4 5 6
Value 3 4 5 6 7 7 6

5.4 Accessing array element


An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example:

Prepared by: Tesfamariam G. Page 53


Learning module for C++ 2015 E.C

double salary = balance[9];

This is simple example.

#include <iostream> }

using namespace std; cout << "Element" << setw( 13 ) << "Value" <<
endl;
#include <iomanip>
// output each array element's value
using std::setw;
C++
int main ()
100
{
for ( int j = 0; j < 10; j++ )
int n[ 10 ]; // n is an array of 10 integers
{
// initialize elements of array n to 0
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] <<
for ( int i = 0; i < 10; i++ ) endl;

{ }

n[ i ] = i + 100; // set element at location i to i + return 0;


100
}

This program makes use of setw() function to format the output. When the above code is
compiled and executed, it produces the following result: Element Value

0 100 5 105
1 101 6 106
2 102 7 107
3 103 8 108
4 104 9 109
Arrays in C++

Arrays are important to C++ and should need lots of more detail. There are following few
important concepts, which should be clear to a C++ programmer:

Multi-dimensional Arrays

C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:

Prepared by: Tesfamariam G. Page 54


Learning module for C++ 2015 E.C

type name[size1][size2]...[sizeN];

For example: int threedim[5][10][4];

5.5 Two-Dimensional Arrays


The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays.

Example: type arrayName [ x ][ y ]; Where type can be any valid C++ data type and arrayName
will be a valid C++ identifier. A two-dimensional array can be think as a table, which will
have x number of rows and y number of columns.

Initializing Two-Dimensional Arrays

Multidimensional arrays may be initialized by specifying brackets values for each row. Following
is an array with 3 rows and each row has 4 columns.

int a[3][4] = {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */

};

Or alternatively we can initialize as: int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array. For example:

Prepared by: Tesfamariam G. Page 55


Learning module for C++ 2015 E.C

int val = a[2][3];

The above statement will take 4th element from the 3rd row of the array. You can verify
it in the above diagram.

#include <iostream> {

using namespace std; cout << "a[" << i << "][" << j << "]: ";

int main () cout << a[i][j]<< endl;

{ }

// an array with 5 rows and 2 columns. C++

int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; 103

// output each array element's value return 0;

for ( int i = 0; i < 5; i++ ) }

for ( int j = 0; j < 2; j++ )

When the above code is compiled and executed, it produces the following result:

a[0][0]: 0 a[2][1]: 4

a[0][1]: 0 a[3][0]: 3

a[1][0]: 1 a[3][1]: 6

a[1][1]: 2 a[4][0]: 4

a[2][0]: 2 a[4][1]: 8

5.6 Pointer to an array


An array name is a constant pointer to the first element of the array. Therefore, in the declaration:

double balance[50]; balance is a pointer to &balance[0], which is the address of the first element
of the array balance. Thus, the following program fragment assigns p the address of the first
element of balance:

#include <iostream> // an array with 5 elements.

using namespace std; double balance[5] = {1000.0, 2.0, 3.4, 17.0,


50.0};
int main ()
double *p;
{

Prepared by: Tesfamariam G. Page 56


Learning module for C++ 2015 E.C

p = balance; cout << "Array values using balance as


address " << endl;
// output each array element's value
for ( int i = 0; i < 5; i++ )
cout << "Array values using pointer " << endl;
{
for ( int i = 0; i < 5; i++ )
cout << "*(balance + " << i << ") : ";
{
cout << *(balance + i) << endl;
cout << "*(p + " << i << ") : ";
}
cout << *(p + i) << endl;
return 0;
}
}

When the above code is compiled and executed, it produces the following result:

Array values using pointer

*(p + 0) : 1000 Array values using balance as address

C++ *(balance + 0) : 1000

105 *(balance + 1) : 2

*(p + 1) : 2 *(balance + 2) : 3.4

*(p + 2) : 3.4 *(balance + 3) : 17

*(p + 3) : 17 *(balance + 4) : 50

*(p + 4) : 50

5.7 Passing Arrays to Functions


C++ does not allow to pass an entire array as an argument to a function. However, You
can pass a pointer to an array by specifying the array's name without an index. Now, let us
call the function as follows:

#include<iostream> int balance[5] = {1000, 2, 3, 17, 50};

using namespace std; double avg;

// function declaration: // pass pointer to the array as an argument.

double getAverage(int arr[], int size); avg = getAverage( balance, 5 ) ;

int main () // output the returned value

{ cout << "Average value is: " << avg << endl;

// an int array with 5 elements. return 0;

Prepared by: Tesfamariam G. Page 57


Learning module for C++ 2015 E.C

It produces the following result:

Average value is: 214.4

5.8 Structure
C/C++ arrays allow you to define variables that combine several data items of the same
kind, but structure is another user defined data type which allows you to combine data items of
different kinds. Structures are used to represent a record, suppose you want to keep track
of your books in a library. You might want to track the following attributes about each
book:

• Title
• Author
• Subject
• Book ID

5.9 Defining a Structure


To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member, for your program. The format of the struct statement is
this:

struct [structure tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; Here is the way you would declare the Book structure:

Prepared by: Tesfamariam G. Page 58


Learning module for C++ 2015 E.C

struct Books

char title[50];

char author[50];

char subject[100];

int book_id;

}book;

5.10 Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use struct keyword to define variables of structure
type. Following is the example to explain usage of structure:

#include <iostream> strcpy( Book1.author, "tesfa.a");

#include <cstring> strcpy( Book1.subject, "C++ Programming");

using namespace std; Book1.book_id = 6495407;

struct Books // book 2 specification

{ strcpy( Book2.title, "Telecom Billing");

char title[50]; strcpy( Book2.author, "tesfa.a");

char author[50]; strcpy( Book2.subject, "Telecom");

char subject[100]; Book2.book_id = 6495700;

int book_id; // Print Book1 info

}; cout << "Book 1 title : " << Book1.title <<endl;

int main( ) cout << "Book 1 author : " << Book1.author


<<endl;
{
cout << "Book 1 subject : " << Book1.subject
struct Books Book1; // Declare Book1 of type <<endl;
Book
cout << "Book 1 id : " << Book1.book_id
struct Books Book2; // Declare Book2 of type <<endl;
Book
// Print Book2 info
// book 1 specification
cout << "Book 2 title : " << Book2.title <<endl;
strcpy( Book1.title, "Learn C++
Programming");

Prepared by: Tesfamariam G. Page 59


Learning module for C++ 2015 E.C

cout << "Book 2 author : " << Book2.author cout << "Book 2 id : " << Book2.book_id
<<endl; <<endl;

cout << "Book 2 subject : " << Book2.subject return 0;


<<endl;
}

When the above code is compiled and executed, it produces the following result:

Book 1 title : Learn C++ Programming

Book 1 author : tesfa..a

Book 1 subject : C++ Programming

Book 1 id : 6495407

Book 2 title : Telecom Billing

Book 2 author : tesfa.a

Book 2 subject : Telecom

Book 2 id : 6495700

Exercise: write a c++ code for the above structure as a function and structure as a pointer?

Prepared by: Tesfamariam G. Page 60


Learning module for C++ 2015 E.C

Chapter Six

Strings and Pointers

6.1 Strings
C++ provides following two types of string representations:

1. The C-style character string.


2. The string class type introduced with Standard C++.

6.2 The C-Style Character String


The C-style character string originated within the C language and continues to be supported
within C++. This string is actually a one-dimensional array of characters which is terminated
by a null character '\0'. Thus a null-terminated string contains the characters that comprise the
string followed by a null.

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization, then you can write the above statement as
follows:

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C/C++:

Easy example

#include <iostream> using namespace std;

Prepared by: Tesfamariam G. Page 61


Learning module for C++ 2015 E.C

int main () cout << greeting << endl;

{ return 0;

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; }

cout << "Greeting message: ";

When the above code is compiled and executed, it produces the following result:

Greeting message: Hello

C++ supports a wide range of functions that manipulate null-terminated strings:

S.n Functions Purpose

1 strcpy(s1, s2); Copies string s2 into string s1.

2 strcat(s1, s2); Concatenates string s2 onto the end of string s1.

3 strlen(s1); Returns the length of string s1.

4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than
0 if s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in
string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in
string s1.

Following example makes use of few of the above-mentioned functions:

#include <iostream> {

#include <cstring> char str1[10] = "Hello";

using namespace std; char str2[10] = "World";

int main () char str3[10];

Prepared by: Tesfamariam G. Page 62


Learning module for C++ 2015 E.C

int len ; cout << "strcat( str1, str2): " << str1 << endl;

// copy str1 into str3 // total lenghth of str1 after concatenation

strcpy( str3, str1); len = strlen(str1);

cout << "strcpy( str3, str1) : " << str3 << endl; cout << "strlen(str1) : " << len << endl;

// concatenates str1 and str2 return 0;

strcat( str1, str2); }

The above produces result something as follows:

strcpy( str3, str1) : Hello

strcat( str1, str2): HelloWorld

strlen(str1) : 10s

6.3 The String Class in C++


The standard C++ library provides a string class type that supports all the operations
mentioned above, additionally much more functionality. Let us check the following example:

#include <iostream> str3 = str1;

#include <string> cout << "str3 : " << str3 << endl;

using namespace std; // concatenates str1 and str2

int main () str3 = str1 + str2;

{ cout << "str1 + str2 : " << str3 << endl;

string str1 = "Hello"; // total length of str3 after concatenation

string str2 = "World"; len = str3.size();

string str3; cout << "str3.size() : " << len << endl;

int len ; return 0;

// copy str1 into str3 }

When the above code is compiled and executed, it produces result something as follows:

str3 : Hello

str1 + str2 : HelloWorld

Prepared by: Tesfamariam G. Page 63


Learning module for C++ 2015 E.C

str3.size() : 10

6.4 Pointers
A pointer is simply the address of a memory location and provides an indirect way of accessing
data in memory. A pointer variable is defined to ‘point to’ data of a specific type. For example:

int *ptr1; // pointer to an int

char *ptr2; // pointer to a char

The value of a pointer variable is the address to which it points. For example, given the definitions

int num; then we can write as ptr1 = &num;

The symbol & is the address operator; it takes a variable as argument and returns the memory
address of that variable. The effect of the above assignment is that the address of num is assigned
to ptr1. Therefore, we say that ptr1 points to num.

Given that ptr1 points to num, the expression *ptr1 dereferences ptr1 to get to what it points to,
and is therefore equivalent to num. The symbol * is the dereference operator; it takes a pointer as
argument and returns the contents of the location to which it points.

6.5 Pointer arithmetic


Pointer arithmetic is not the same as integer arithmetic, because the outcome depends on the size
of the object pointed to. For example, suppose that an int is represented by 4 bytes. Now, given

char *str = "HELLO";

int nums[] = {10, 20, 30, 40};

int *ptr = &nums[0]; // pointer to first element

Prepared by: Tesfamariam G. Page 64


Learning module for C++ 2015 E.C

str++ advances str by one char (i.e., one byte) so that it points to the second character of
"HELLO" , whereas ptr++ advances ptr by one int (i.e., four bytes) so that it points to the second
element of nums . The following figure illustrates this diagrammatically.

Another form of pointer arithmetic allowed in C++ involves subtracting two pointers of the same
type. For example:

int *ptr1 = &nums[1];

int *ptr2 = &nums[3];

int n = ptr2 -ptr1; // n becomes 2

Example: incrementing a pointer.


#include <iostream> {

using namespace std; cout << "Address of var[" << i << "] = ";

const int MAX = 3; cout << ptr << endl;

int main () cout << "Value of var[" << i << "] = ";

{ cout << *ptr << endl;

int var[MAX] = {10, 100, 200}; // point to the next location

int *ptr; ptr++;

// let us have array address in pointer. }

ptr = var; return 0;

for (int i = 0; i < MAX; i++) }

When the above code is compiled and executed, it produces result something as follows:

Address of var[0] = 0xbfa088b0 Value of var[1] = 100

Value of var[0] = 10 Address of var[2] = 0xbfa088b8

Address of var[1] = 0xbfa088b4 Value of var[2] = 20

Prepared by: Tesfamariam G. Page 65


Learning module for C++ 2015 E.C

Chapter Seven

Input/output with files

7.1 Classes
C++ provides the following classes to perform output and input of characters to/from files:

• ofstream: Stream class to write on files


• ifstream: Stream class to read from files
• fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream and ostream. We have
already used objects whose types were these classes: cin is an object of class istream and cout is
an object of class ostream. Therefore, we have already been using classes that are related to our
file streams. And in fact, we can use our file streams the same way we are already used to
use cin and cout, with the only difference that we have to associate these streams with physical
files. For example:
// basic file operations myfile.open ("example.txt");
#include <iostream> myfile << "Writing this to a
#include <fstream> file.\n";
using namespace std; myfile.close();
return 0;
int main () { }
ofstream myfile;
The output as follows:

[file example.txt]
Writing this to a file.

7.2 Open file


The first operation generally performed on an object of one of these classes is to associate it to a
real file. This procedure is known as to open a file. An open file is represented within a program
by a stream (i.e., an object of one of these classes; in the previous example, this was myfile).

Prepared by: Tesfamariam G. Page 66


Learning module for C++ 2015 E.C

In order to open a file with a stream object we use its member function open:

open(filename,mode);

Where filename is a string representing the name of the file to be opened, and mode is an
optional parameter with a combination of the following flags:

All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open:

1 ofstream myfile;
2 myfile.open ("example.bin", ios::out | ios::app | ios::binary);

7.3 Closing files


When we are finished with our input and output operations on a file we shall close it so that the
operating system is notified and its resources become available again. For that, we call the stream's
member function close. This member function takes flushes the associated buffers and closes the
file:

myfile.close();
Text file: Text file streams are those where the ios::binary flag is not included in their opening
mode. These files are designed to store text and thus all values that are input or output from/to
them can suffer some formatting transformations, which do not necessarily correspond to their
literal binary value.
// writing on a text file using namespace std;
#include <iostream>
#include <fstream> int main () {

Prepared by: Tesfamariam G. Page 67


Learning module for C++ 2015 E.C

ofstream myfile ("example.txt"); myfile.close();


if (myfile.is_open()) }
{ else cout << "Unable to open
myfile << "This is a line.\n"; file";
myfile << "This is another return 0;
line.\n"; }
The output is as follows:
[file example.txt]
This is a line.
This is another line.

Reading from a file can also be performed in the same way that we did with cin:
// reading a text file {
#include <iostream> cout << line << '\n';
#include <fstream> }
#include <string> myfile.close();
using namespace std; }

int main () { else cout << "Unable to open


string line; file";
ifstream myfile ("example.txt");
if (myfile.is_open()) return 0;
{ }
while ( getline (myfile,line) )
The output as follows
This is a line.
This is another line.

Prepared by: Tesfamariam G. Page 68


Learning module for C++ 2015 E.C

Chapter Eight

Object Oriented Programming

8.1 Classes
A classis an expanded concept of a data structure: instead of holding only data, it can hold both
data and functions.

An object is an instantiation of a class. In terms of variables, a class would be the type, and an
object would be the variable.

Classes are generally declared using the keyword class, with the following format:

class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
All is very similar to the declaration on data structures, except that we can now include also
functions and members, but also this new thing called access specifier. An access specifier is one
of the following three keywords: private, public or protected. These specifiers modify the access
rights that the members following them acquire:

• Private members of a class are accessible only from within other members of the same
class or from their friends.
• Protected members are accessible from members of their same class and from their friends,
but also from members of their derived classes.
• Finally, public members are accessible from anywhere where the object is visible.

Prepared by: Tesfamariam G. Page 69


Learning module for C++ 2015 E.C

By default, all members of a class declared with the class keyword have private access for all its
members. Therefore, any member that is declared before one other class specifier automatically
has private access. For example:

classCRectangle {

int x, y;

public:

voidset_values (int,int);

intarea (void);

} rect;

Here is the complete example of class CRectangle:

// classes example voidCRectangle::set_values (inta, intb) {

#include <iostream> x = a;

using namespace std; y = b;

class CRectangle { }

intx, y; intmain () {

public: CRectangle rect;

void set_values (int,int); rect.set_values (3,4);

int area () { cout << "area: "<< rect.area();

return(x*y);} return0;

}; }

The output becomes: area: 12

The most important new thing in this code is the operator of scope (::, two colons) included in the
definition of set_values(). It is used to define a member of a class from outside the class definition
itself.

One of the greater advantages of a class is that, as any other type, we can declare several objects
of it. For example, following with the previous example of class CRectangle, we could have
declared the object rectb in addition to the object rect:

Prepared by: Tesfamariam G. Page 70


Learning module for C++ 2015 E.C

// example: one class, two objects y = b;

#include <iostream> }

using namespacestd; Int main () {

CRectangle rect, rectb;


class CRectangle {
rect.set_values (3,4);
int x, y;
rectb.set_values (5,6);
public:
cout << "rect area: "<< rect.area() << endl;
void set_values (int,int);
cout << "rectb area: "<< rectb.area() << endl;
int area () {return(x*y);}
return0;
};
}
Void CRectangle::set_values (inta, intb) {

x = a;

The output will be the following:

rect area: 12
rectb area: 30

8.2 Constructors and destructors


Constructer: it used in the class to declare or instantiate class parameters. It is automatically called
whenever a new object of this class is created. This constructor function must have the same name
as the class, and cannot have any return type; not even void. For example;

// example: class constructor width = a;

#include <iostream> height = b;

using namespacestd; }

classCRectangle { Int main () {

int width, height; CRectangle rect (3,4);

public: CRectangle rectb (5,6);

CRectangle (int,int); cout << "rect area: "<< rect.area() << endl;

Int area () {return(width*height);} cout << "rectb area: "<< rectb.area() << endl;

}; return0;

CRectangle::CRectangle (inta, intb) { }

Prepared by: Tesfamariam G. Page 71


Learning module for C++ 2015 E.C

The output as follows:

rect area: 12
rectb area: 30
Destructor: It is automatically called when an object is destroyed, either because its scope of
existence has finished (for example, if it was defined as a local object within a function and the
function ends) or because it is an object dynamically assigned and it is released using the operator
delete. The destructor must have the same name as the class, but preceded with a tilde sign (~) and
it must also return no value. The use of destructors is especially suitable when an object assigns
dynamic memory during its lifetime and at the moment of being destroyed we want to release the
memory that the object was allocated. For example:

// example on constructors and destructors *width = a;

#include <iostream> *height = b;

using namespacestd; }

class CRectangle { CRectangle::~CRectangle () {

int*width, *height; Delete width;

public: delete height;

CRectangle (int,int); }

~CRectangle (); int main () {

int area () {return(*width * *height);} CRectangle rect (3,4), rectb (5,6);

}; cout << "rect area: "<< rect.area() << endl;

CRectangle::CRectangle (inta, intb) { cout << "rectb area: "<< rectb.area() << endl;

width = new int; return0;

height = new int; }

The result of the above as follows:

rect area: 12

rectb area: 30

Prepared by: Tesfamariam G. Page 72


Learning module for C++ 2015 E.C

8.3 Overloading Constructors


Like any other function, a constructor can also be overloaded with more than one function that
have the same name but different types or number of parameters. Remember that for overloaded
functions the compiler will call the one whose parameters match the arguments used in the function
call. In the case of constructors, which are automatically called when an object is created, the one
executed is the one that matches the arguments passed on the object declaration. For example:

// overloading class constructors }

#include <iostream> CRectangle::CRectangle (inta, intb) {

using namespacestd; width = a;

class CRectangle { height = b;

int width, height; }

public: int main () {

CRectangle (); CRectangle rect (3,4);

CRectangle (int,int); CRectangle rectb;

int area (void) {return(width*height);} cout << "rect area: "<< rect.area() << endl;

}; cout << "rectb area: "<< rectb.area() << endl;

CRectangle::CRectangle () { return0;

width = 5; }

height = 5;

Then the output will likes:


rect area: 12
rectb area: 25

Prepared by: Tesfamariam G. Page 73

You might also like