Vous êtes sur la page 1sur 134

FACULTY OF ENGINEERING TECHNOLOGY

DEPARTMENT OF MECHANICAL ENGINEERING


OPEN
UNIVERSITY DIPLOMA IN TECHNOLOGY – LEVEL 3
OF SRI LANKA MEK3170 – C PROGRAMMING

BOOK 1

C PROGRAMMING
Author

Ms. W. Sheranga Ayeshi Nanayakkara

Editor
Mr. W. Hasala Peiris

Open University of Sri Lanka


Nawala Nugegoda, Sri Lanka

First published in 2007

© 2007 Open University of Sri Lanka


All rights reserved. No part of this course book may be reproduced or
transmitted in any form or by any means, electronic or mechanical,
including photocopying and recording or from any information stored
in a retrieval system, without permission in writing from the Open
University of Sri Lanka.
UNIT 1

Basics of programming

Session 1
Introduction to C++ Programming 1

Session 2
C++ Data types and Variables 12

Session 3
Basic Input Output & C++ Programming Techniques 24

Session 4
C++ Operators and Expressions 36

Session 5
C++ Control Structures 49

Session 6
More Control Structures 63

Session 7
Basics of Functions 75
Session 8 87
Arrays

Session 9
Pointers 102

Session 10
More on Functions and Strings 117
Session 1
Introduction to C++ Programming
Contents
Objectives
Introduction
1.1 What is a programming language?
1.1.1 A brief history of programming languages
1.2 Programming in C++
1.2.1 Characteristics of C++
1.3 What is a programme?
1.4 Compiling and Executing a C++ programme
1.4.1 How to develop C++ programmes
1.4.2 A simple C++ programme
1.4.3 Program explanation
1.5 Compile errors
1.6 C++ Case sensitivity
Summary

Objectives

After reading this lesson you should be able to:

¾ Understand what is a programming language and the evolution of it

¾ The characteristics of a programming language

¾ What is a programme and what are the basic tasks of a programme

¾ How to enter, compile, link, and run a simple C++ program.

¾ Find out the compile errors in a simple C++ programme and correct them

Introduction
In the fast moving world, almost in every activity computers are being used. Since we
give instructions to computers by means of programmmes, developing programs have
also become a vital part. In order to develop programs, programming languages are being
used. Since the evolution of programming languages in 1940’s, different programming
languages were developed to serve different purposes. Among them, C++ is one of the

1
most popular programming languages and this book intends to cover most of the aspects
of C++ programming.

This session is an introductory session, which is designed to provide some background


knowledge on programming. It also discusses the evolution of programming languages in
brief and introduces C++, by emphasizing its characteristics and the importance of those
characteristics.

In addition, it is essential to know what is meant by a programme and the basic tasks of a
programme in general. This session covers up the above information as well as step by
step procedures needed to follow in order to develop a simple C++ programme. This
session also helps to understand the common programming errors and how to locate them
and correct them and run a programme successfully.

1.1 What is a Programming Language?


A programming language is an artificial human-created language, which translates
instructions from a human readable format to a computer readable format.

It has become a main method of instructing a computer to perform specific tasks. Each
language has its own special set of keywords and syntax, which makes each
programming language unique.

1.1.1 A brief history of Programming Languages

In 1946, a German Engineer called Konrad Zues, developed the first programming
language called ‘Plankalkül’. However the world’s first commonly used programming
language ‘Short Code’ was developed three years after that. Since then the innovation of
programming languages began.

In 1951, Grace Hopper began designing the world’s first compiler. In 1954, IBM began
the development of FORTRAN. FORTRAN became the first commercial high level
programming language. FORTRAN II was presented in 1958 with new features.
COBOL (Common Business Oriented Language) was created in 1959, which is still used
in many companies. Some of the programming languages like ALGOL 60, APL,
SNOBOL, BASIC and Pascal appeared later.

In 1972, Dennis Ritchie created the C-language and its documentation appeared after two
years. Today the world has come a long way and we have very powerful programming
languages like C++, Java with object oriented programming features.

2
1.2 Programming in C++
C++ is an object-oriented programming (OOP) language, developed by Bjarne Stroustrup
at Bell Labs during 1983-1985. It can be considered as an enhancement to the C
programming language. Since C++ has absorbed features and concepts of more than forty
years of language design, it has become an extremely powerful programming language.

After the introduction of C++ in 1990, it has become one of the most popular commercial
programming languages. It also runs on most computers, from PCs to the most powerful
supercomputers and C++ is viewed by many as one of the best languages for creating
large-scale applications.

1.2.1 Characteristics of C++

C++ has certain characteristics over other programming languages. The most remarkable
ones are:

¾ Supports Object-oriented programming


Object-oriented programming allows the programmer to design applications based
on the concept of “objects” and interactions between them, simplifying the
programming task. This makes it easier to solve larger and more complex
problems. (Object oriented programming will be discussed in detail later in this
book.)

¾ Generality
Apart from the normal computation tasks, C++ can be used to develop databases,
business applications as well as graphical applications.

¾ Portability
A C++ code can be successfully compiled and run in almost any type of
computing environment or operating system with or without minimum changes to
the source code.

¾ Reusability
C++ programs allow a greater re-usability of code. Therefore, new functionality
can be added to the existing code with or without minimum changes to the
original code.

¾ Modular programming
A C++ application that has been made up of different individual components can
be modified and maintained independent of the other components. So the whole
application need not be compiled when making changes to a single component,
saving programmer’s effort and time.

3
¾ Concision
Codes written in C++ are very short in comparison with other languages because
of the use of special characters and keywords and this saves some effort of the
programmer too.

¾ C Compatibility
C++ is backward compatible with C language, which means a code written in C
can easily be included in a C++ program without making any change.

¾ Speed
The resulting code from a C++ compilation is very efficient and hence it produces
efficient programs.

¾ Maintainability
C++ programmes are easy to maintain. (e.g., when the business requirements
change, the program can be extended and enhanced without a great expense.)

1.3 What is a Programme?


A computer programme is a collection of instructions that describe a task or set of tasks
to be carried out by a computer. Computer programs are normally designed for problems
that would be difficult or impossible to solve by other ways or to solve a certain problem
more efficiently and effectively. These programmes can be simple or very complex
depending on the requirements. Programmes can be developed for straightforward
calculations like adding two numbers or for more complicated problems like guiding a
satellite into the right orbit and handling the transmission of data.

Almost every programme performs 3 basic tasks in solving problems, irrespective of


whether it is simple or more complex.

1. Manipulate data
2 Perform operations
3. Provide results

Manipulate Data
Programs manipulate data by accepting data from inputs (e.g., keyboard), creating new
data and storing them, or modifying existing data.

There are two fundamental forms of data that are facilitated by the programming
languages.
¾ Textual data – Characters and strings
(e.g., A person’s name)
¾ Numerical data - numbers.
(e.g., A persons age)

4
In addition to these types of data, C++ facilitates more complex data types and these will
be discussed in detail in the sessions to come.

Perform Operations
In order to produce results from data, operations are being used. Programming languages
are used to give instructions to perform operations. A simple example of an instruction
would be adding two numbers.

Provide results
After performing operations, results are generated and it can be information or data to
another operation. It can be displayed on a screen, stored in databases, used to produce
reports or it can be transmitted to another computer.

1.4 Compiling and Executing a C++ Programme


C++ is considered as a high-level programming language. They are English-like and
closer to human language, which is easy to read, write, and maintain. Since the computer
can understand only the machine language, a programme that is written using C++ needs
to be translated into the machine language before executing. This translation is performed
by a very specialized computer program called a compiler.

The programming code that is written is called the source code, hence for the compiler
the input is the source code and the output is the machine code or object code.

We can argue that the compiler translates the source code into an intermediary form, as
the object code cannot be run in the computer. Therefore, we need another program
called a linker, which is invoked by the compiler, in order to translate the object file into
an executable program. Only an executable program can be run on the computer.

Here, the compiled object file is also linked with a function library in order to produce
the executable program. A library is a collection of linkable files, which can be linked to
a programme. These libraries are supplied with the C++ compiler but a progammer can
also create his own set of libraries to be linked with the programme.

1.4.1 How to develop C++ Programmes

There are several tools available for developing C++ programs. These tools make
developing easier and more productive. Currently, the tools given below are popular
among them.

C++ Builder by Borland


Visual C++.NET by Microsoft

5
You can use a specific tool or even a text editor like Windows Notepad or the DOS Edit
command to write your source code. Source code is the series of C++ statements that you
have written and it can be a single file or a combination of several text files.The text files
has to be saved with the extension .cpp,.cp or .c and the source code has to be compiled
using the compiler.

For different compilers the compiling commands are different. So you have to use your
compiling command according to the type of compiler you have. A successfully
compiled programme produces the object file which has the .obj extension.

Since the compiler invokes the linker, the programme is linked with the needed libraries
and produces the executable file with the extension .exe.

The diagram given below shows the steps involved in developing a C++ programme and
the files that are involved in each operation.

Figure 1.1 - Compiling and running C++ programs

In figure 1.1 the programmer can write the source code using any kind of a C++ editor
and save the file. Here, the file is saved as Hello.cpp. When the programmer compiles the
programme, it generates both the object file (hello.obj) and the executable file (hello.exe).
When the programmer run the programme the executable file is loaded and executed.

6
1.4.2 A simple C++ programme

1. #include<iostream.h>
2. #include <conio.h>
3. void main()
4. {
5. clrscr();
6. cout<<"Open University, Nawala.";
7. getch();
8. }

Output:
Open University, Nawala.

Note: Most of the programmes in this book contain line numbers on the left. These
numbers are only for reference within the book and should not be included in your
programme.

1.4.3 Programme Explanation

¾ #include <iostream.h>
#include <iostream.h> tells the C++ compiler's preprocessor to include the
iostream standard header file in the programme. The .h extension stands for the
word 'header’. This iostream file includes the declarations of the basic standard
input-output library in C++. We have included this file in our programme
because its functionality is going to be used later in the programme ('iostream.h' is
used for 'cout' operation)

¾ #include <conio.h>
This is another header file used in C++ programming. ('conio.h' is used for the
functions 'clrscr()' and 'getch)

clrscr() - This is a function used for clearing the output screen.


getch() - This will pause the program while the output window is visible until the
user hits any key.(This is not a standard C++ feature. You have to use this feature
if you are using Turbo, Borland C++)

¾ void main ()
In all C++ programs it is necessary to have a main function. Independently of its
location within the source code, main function will always be the first one to be
executed in any C++ program.

A pair of parentheses (()) indicates a function declaration. Every function has a


function name (e.g., main) and a pair of parentheses that follow its name.

7
Curly braces ({}) shows the body of the main function. What is contained within
these braces is what the function does when it is executed. (Here line 5,6 and 7 is
the body of the main function which is contained within the braces in line 4 and 8)

¾ cout << " Open University, Nawala.";


This line is a C++ statement. cout is declared in the iostream standard file which
we have included at the beginning of the programme. This statement generates the
visible effect that we can see as the output, ‘Open University, Nawala.’

¾ Semicolon character (;)


In line 5, 6 and 7 the statements ends with a semicolon character (;). This
character is used to mark the end of the statement and it is essential to include this
at the end of all expression statements in C++ programs.

1.5 Compile Errors


Compile errors occur during the compilation process of a programme. Compile-time
errors can occur either due to errors from the compiler itself or more likely syntax errors
in the code.

Nowadays new compilers highlight the errors in a programme, and also point out the
exact place in the code where the mistake is. The programme given below shows a
demonstration on compile errors.

1. #include <iostream.h>
2. #include <conio.h>

3. void main()
4. {
5. clrscr();
6. cout << "Mechatronics Programme!\n";
7. getch();

In the above programme the closing parenthesis ( }) of the main function is missing.
Hence the compiler will generate a compile error like:
Error Mechatronics.cpp, line 8: Compound statement missing }

Mechatronics.cpp is the file name and it shows the line number and also the problem.
Compiler assists in finding most of the common compile errors but sometimes the
compiler finds it unable to report complex user errors. In addition, in every identified
compile error it doesn’t show the correct line numbers. So it is the programmers
responsibility to locate the errors and correct them.

8
Activity 1.1 – Analyzing the tasks of functions

This activity is intended to analyse the tasks and the importance of clrscr() and getch()
functions, as they are used in every programme. First, type the above program into your
editor, compile and execute it.

1. Remove the clrscr() function and recompile. Now run the programme several
times and explore the output screen.

2. Remove the getch() function and recompile and run the programme. Observe the
execution of the programme carefully.

1.6 C++ Case Sensitivity


C++ is a case sensitive language. Hence, uppercase and lowercase letters are considered
to be different.

e.g., In declaring variable names the word ‘age’ is different from ‘Age’, which are
different from ‘AGE’. (Variables will be discussed later in this book)

Therefore, the programmer should be cautious about this factor and use correct uppercase
and lowercase letters when writing C++ coding.

Activity 1.2 – Correcting errors in a programme

This activity is intended to locate the compile errors that the C++ editor produces, and
find the location and the nature of the error and correct them in order to provide an
executable programme. First, type the program given below directly into your editor,
exactly as shown and compile the programme.

#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();
cout < "C++ Programming ----";
cout << " Session 1 ----;
cout << " Second Programme!!!"
getch();
}

9
You will get number of compile error statements. Read the compilation errors carefully
and fix the errors and run the programme.

Summary

¾ A programming language is an artificial, human-created language, which


translates instructions from human readable format to a computer readable format.

¾ C++ supports Object-oriented programming. In addition Generality, Portability,


Reusability, Maintainability, Efficiency are some of the characteristics of C++.

¾ A computer program is a collection of instructions that describe a task or set of


tasks to be carried out by a computer. Every programme has 3 basic tasks.
• Manipulate data
• Perform Operations
• Provide results

¾ To Create an executable C++ programme you should,


• Create a source code file, with a .CPP extension.
• Compile the source code into a file with the .OBJ extension.
• Link your OBJ file with any needed libraries to produce an executable
program.

¾ Compile errors occur during the complication process in a programme. The


programmer should locate them and correct them in order to successfully run the
programme.

¾ C++ is case sensitive.

10
Session 1 - Answers

Activity 1.1 – Answer

1. The output of the programme will be printed without clearing the screen.
Example: If you run the programme 3 time, the output will be
Mechatronics Programme!Mechatronics Programme!Mechatronics Programme!
2. The output screen will be opened but will be closed immediately before waiting
for you to press any key on the key board. Hence it is not possible to observe the
programme output.

Activity 1.2 - Answer

#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();
cout <<"C++ Programming ----";
cout <<" Session 1 ----";
cout <<" Second Programme!!!";
getch();
}

Output:

C++ Programming ---- Session 1 ---- Second Programme!!!

11
Session 2
C++ Data types and Variables
Contents
Objectives
Introduction
2.1 What are variables and data types?
2.1.1 Fundamental variable types in C++
2.1.2 Declaration of variables
2.1.3 Assigning values to variables
2.1.4 Demonstration of the use of variables
2.2 C++ Constants
2.2.1 Literal constants
2.2.2 Symbolic constants.
2.2.3 Demonstration of the use of constants
2.3 Enumeration type
2.3.1 A Demonstration of the use of enumerations
2.4 The typedef keyword
2.4.1 A demonstration of the use of typedef keyword
Summary

Objectives

After reading this lesson you should be able to:

¾ Declare and define variables.

¾ Assign values to variables and to manipulate those values.

¾ Correctly use constants, enumerations and the typedef keyword in your


programmes.

¾ Write the value of a variable to the screen.

Introduction
In the previous session we developed a simple C++ programme which displayed a certain
text. However, as you all know programmes are not limited only to printing simple texts
on the screen. Programmes should be able to perform useful operations in order to
produce valuable results. Hence in this session we introduce the concepts of ‘variables’
and ‘data types’ available in C++.

12
These variables are used to store data and retrieve them later in order to perform
operations. This session also covers C++ basic data types and their technical details like
their sizes and ranges. In addition, this session is also devoted to explain C++ constants.

Both variables and constants offer various ways to represent and manipulate data in C++
applications. In developing these applications it is important to choose the proper data
type in defining variables and constants. In addition, values should be assigned to the
variables and constants according to their data types. Failing to do so will result in
compile errors, unexpected and incorrect outputs and inefficient programmes. Hence this
session provide guidance to take the right decision to choose the proper data types and to
assign correct values to them.

2.1 What are Variables and Data Types?


Programs need a way to store the data they use. Variables and data types are used for this
purpose.

Variable: Variable is a location in the computer’s memory, where information can be


stored. After storing, these information can be retrieved and used later.

Data type: In defining variables to store data first we have to define which type of data
we want to store. The data type will have characteristics such as the range of values that
can be stored and the operations that can be performed on variables of that type. In
defining variables, each variable takes up a fixed amount of space in the computer’s
memory.

2.1.1 Fundamental Variable types in C++

1. Integer variables - Positive or negative whole numbers. Integer values come in


three sizes. They are int, short int and long int.
2. Floating point variables - Floating point decimal numbers. There are in three
sizes, float (single-precision), double (double-precision) and long double
(extended-precision).

3. Character variables - Characters ( It can be a single letter, number, or a symbol)


4. Boolean Variables – Only hold a ‘true’ or ‘false’ value. (returns 0 when its false
and returns 1 when its true)

All the variables (except Boolean) can be divided into two types called signed and
unsigned variables
1. Signed integers - either negative or positive.
2. Unsigned integers- always positive

13
The table given below illustrates the data types used in C++ and their size and range.
Name Description Size* Range*
signed: -128 to 127
char Character or small integer. 1byte
unsigned: 0 to 255
Signed short -32768 to 32767
Short Integer. 2bytes
int/short int
Unsigned short
Unsigned short Integer. 2bytes 0 to 65535
int
-2147483648 to 2147483647
Signed int Integer. 4bytes
Unsigned int Unsigned Integer. 4bytes 0 to 4294967295
long int -2147483648 to 2147483647
Long integer. 4bytes
Unsigned long int Unsigned Long integer. 4bytes 0 to 4294967295
Boolean value. It can take one
bool 1byte true or false
of two values: true or false.
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)
Double precision floating point
double 8bytes 1.7e +/- 308 (15 digits)
number.
Long double precision floating
long double 8bytes 1.7e +/- 308 (15 digits)
point number.
wchar_t Wide character. 2bytes 1 wide character

Table 2.1-Data types used in C++

Note: The values of the columns ‘Size’ and ‘Range’ depend on the architecture of the
system where the program is compiled and executed.

2.1.2 Declaration of variables

In order to create a variable in C++, you must declare its type followed by the name of
the variable.

The variable type can be specified according to the type of data that are going to use in
the programme. Variable names can be declared using any combination of letters, without
any spaces between the letters. In general, meaningful and expressive names are being
used in defining variable names in order to easily understand the flow of the program.
Once the variables are declared they can be used within the rest of the program.

Example 2.1: Suppose Mathematics marks of a student needs to be stored. In general,


marks are positive values without decimal points. Hence the variable can be declared as
below.
int marks;

14
Example 2.2: Suppose average mark of a student needs to be stored. As it can have a
decimal value it can be declared as:
float average;

Example 2.3: Character variables can be used to store characters as shown below.
char name;

Example 2.4: In order to declare more than one variable of the same type, it can be
declared as separate statements or in a single statement as shown below. In the three
variables mark1, mark2 and mark3, marks of three subjects can be stored.
int mark1;
int mark2;
int mark3;
int mark1, mark2, mark3;

Example 2.5: Variables without the word "unsigned" are assumed to be signed. Hence
both declarations given below are the same.
signed int mySalary;
int mySalary;

Example 2.6: An exception to this general rule is the char type, as we can declare
variables to store even numeric values. Here it is necessary to use either signed or
unsigned keyword in declaring char-sized variable.
unsigned char total;
signed char value;

Example 2.7: In declaring short and long variables, we assume that short is equivalent to
short int and long is equivalent to long int. Therefore, the declarations given below are
equivalent:
Short month;
Short int month;

2.1.3 Assigning Values to Variables

Depending on the data type of the variable, a value can be assigned to it using the
assignment (=) operator. Variables can be defined and initialized separately or both steps
can be done in one sentence.
int age; age=25; or int age=25;

¾ Assigning values to integer variables.


signed int salary = 25750;
signed int temperature = -10;
unsigned int start = 0;
int width = 85;
As integers comes in short and long values:

15
short int lastValue = 175;
long int Total = 25000;
unsigned long bigValue = 22411;
signed short smallValue= -5;

¾ Assigning values to float variables.


float interestRate = 0.05;
float calculation= -99.99
double fahrenheit = 99.876;
long double Balance = 50899.90;

¾ Assigning values to char variables.


When assigning a character to a char variable, it is enclosed within single quotes.
char letter = 'k';
char user_input = '7';
As numeric values also can be assigned to variables of character type:
char value = 89;

We can declare signed and unsigned characters as well.


signed char firstValue = 110;
signed char myKey = -25;
unsigned char start = 500;
Note: Plain ‘char’, is neither signed nor unsigned:

¾ Assigning values to Boolean variables.


bool correct_name = false;
bool password = true;

2.1.4 Demonstration of the use of variables


1. #include <iostream.h>
2. #include<conio.h>

3. void main()
4. {
5. clrscr();

6. unsigned short int workDays=5;


7. float workHours=8.5;
8. float payRate=90.50;
9. float weeklyPay=workDays*workHours*payRate;

10. cout<<"Weekly pay = Rs "<<weeklyPay;

11. getch();
12. }

16
Output:

Weekly pay = Rs 3846.25

Activity 2.1- Working with variables

Using a suitable variable declaration, write a programme which calculates the area of a
triangle and displays the following output.
Area of the Triangle is 27.5

Use the data and the formula given below in writing your programme:
Height of the triangle is11 and the base of the triangle is 5.
Area = 0.5 * height * base

2.2 C++ Constants


Like variables, constants are data storage locations, but once a value is being initialized to
a constant it cannot be changed later in the programme. There are two types of constants
in C++ named literal and symbolic.

2.2.1 Literal Constants

A literal constant is a value typed directly into the program.


e.g., int age =25;
Here, age is assigned to value 25 and it is a constant fix value. In the variable age the
value will be always 25. Hence it s a literal constant.

2.2.2 Symbolic Constants.

A symbolic constant is a constant that is represented by a name, just like variables are
represented. But, once a symbolic constant is assigned it cannot be changed.

After assigning a value to a constant in a programme, it cannot be reassigned. If you try


to do so the compiler gives an error message.

There are two ways to declare a symbolic constant in C++ using the #define keyword and
the const keyword.

17
¾ #define keyword
Example: #define maximum 20;
Note that the variable ‘maximum’ doesn’t have a specific type (int, float or char
etc)

¾ const keyword
In defining a constant with the use of ‘const’ keywork, a type needs to be
specified.
Example: const int FUTURE = 2025;
This is a better way to define constants and it makes it easier to maintain the code
as well as it prevents errors that can happen.

2.2.3 Demonstration of the use of Constants

1. #include <iostream.h>
2. #include<conio.h>

3. void main()
4. {
5. clrscr();

6. const int FUTURE = 2025;


7. int year_of_birth, age_in_2025;

8. cout<<"Enter your year of birth:";


9. cin>>year_of_birth;
10. age_in_2025 = FUTURE - year_of_birth;
11. cout<<"\nIn 2025 you will be "<<age_in_2025<<" years old.";

12. getch();
13. }

Output: Enter your year of birth: 1990


In 2025 you will be 35 years old.

The main advantage in using symbolic constants is, if a certain value needs to be
changed, it can be done efficiently and effectively as there’s no need to make a change in
every place that the value is being used.

Example: Suppose in the above programme that you need to calculate your age in 2050.
Here if you change the constant to const int FUTURE = 2050, it will be effective though
out the whole programme.

This is more effective in larger programmes where the programmers do not have to go
through all the coding thus saving time and minimizing errors that can occur.

18
2.3 Enumeration Type
Enumeration is a user defined variable type that enables the user to define values for the
type. Enumerations are declared using the enum key word followed by the enumeration
name. An enumeration value has to be included inside curly braces.
Example: enum working day {Monday, Tuesday, Wednesday, Thursday, Friday};
Every enumeration has an integer value. The default starts with 0 and the rest will count
up from there. Monday has a value of 0, Tuesday has the value 1 Wednesday has the
value 1 etc.

A value can also be initialized to an enumeration.


Example: enum workingday { Monday=50, Tuesday, Wednesday=88, thursday,
Friday=900 };

Here : Monday=50, Tuesday=51, Wednesday=88, Thursday=89, Friday=900

Note: enumerator variables actually are of type unsigned int.

2.3.1 A Demonstration of the use of Enumerations

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

enum cards{
spades=5,
hearts,
clubs=10,
diamonds
};
cout<<"Spades value:"<<spades<<endl;
cout<<"Hearts Value:"<<hearts<<endl;
cout<<"Clubs value:"<<clubs<<endl;
cout<<"Diamonds value:"<<diamonds;

getch();
}
Output:

Spades value: 5
Hearts Value: 6
Clubs value: 10
Diamonds value: 11

19
In the above programme, when ‘spades’ is assigned to 5, the next value is automatically
assigned to 6. When clubs is assigned to 10, Diamonds will be automatically assigned to
11.

2.4 The typedef keyword


The typedef keyword enables to create a synonym for an existing data type. A typedef
declaration contains the typedef keyword followed by a name in the position of a variable
name.
Example: typedef unsigned long int UNLONG

2.4.1 A demonstration of the use of typedef keyword

#include <iostream.h>
#include<conio.h>

1. void main()
2. {
3. clrscr();

4. typedef unsigned short int USHORT;

5. USHORT val1 = 4;
6. USHORT val2 = 688;
7. USHORT val3 = 34;
8. USHORT total = val1+val2+val3;

9. cout << "Total of the values = " << total <<endl;

10. getch();
11 }

Output:

Total of the values = 726

In the above example total of three values are being calculated. In line 4, USHORT
creates a synonym for ‘unsigned short int’. This has reduced the tedious, repetitious
writing ‘unsigned short int’ in line 5,6,7 and 8. This also reduces the user errors that can
happen in writing the same words over again in the programme.

20
Activity 2.2-Using ‘typedef’ and ‘Const’ keywords

Rewrite the programme in Activity 2.1 using the typedef and const key words.

Use the keyword typedef in declaring the height of the triangle and use the const key
word in calculating the area. (0.5 should be defined as a symbolic constant)

Summary

¾ In C++, there are four main data types. They are int, float, char and double.

¾ We define variables stating its type followed by the name of the variable. Then
values are assigned to those variables using the assign (=) operator.

¾ Constants are C++ data storage locations like variables, but once defined constant
cannot be changed. There are two types of constants in C++ named, literal and
symbolic.

¾ Enumeration is a user defined variable type that enables the user to define values
for the type.

¾ The typedef keyword enables to create a synonym for an existing data type.

21
Session 2 - Answers

Activity 2.1 - Answer

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

unsigned short int height,base;


float area;
height=11;
base=5;

area=0.5*height*base;
cout<<"Area of the triangle is "<<area;

getch();
}
Output:

Area of the triangle is 27.5

Activity 2.2 - Answer

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

typedefunsigned short int USHORT;


const float fix =0.5;

USHORT height,base;
float area;
height=11;
base=5;

22
area=fix*height*base;
cout<<"Area of the triangle is "<<area;
getch();
}
Output:

Area of the triangle is 27.5

23
Session 3
Basic Input Output & C++ Programming
Techniques
Contents
Objectives
Introduction
3.1 Basic Input/Output
3.1.1 Basic Output
3.1.2 Basic Input
3.1.2 A demonstration of basic input and output
3.2 Special formatting characters
3.3 Whitespace
3.4 Finding the size of variable types
3.4.1 A demonstration of the ‘size of’ operator
3.5 Simple type conversions
3.5.1 Explicit type conversion
3.5.2 Implicit type conversion
3.5.3. A demonstration of the type conversions
3.6 C++ Comments
3.6.1 A demonstration of the use of C++ comments
Summary

Objectives

After reading this session you should be able to:

¾ Develop interactive programmes using basic input and output operations.

¾ Use special formatting characters and whitespace in your programmes.

¾ Find the size of any data item or type using the sizeof operator.

¾ Perform simple type conversions.

¾ Properly document a programme using C++ comments.

¾ Identify different types of keywords used in C++.

24
Introduction
Programs given as examples in the previous sessions provided very little interaction with
the user. Using the standard input and output library (iostream), which we have already
used, we will be able to interact more with the user by printing messages on the screen
and getting the user's input from the keyboard. This session outlines these basic input and
output operations used in C++.

In C++, there are special formatting characters which help to increase the readability of a
programme and it also assists in producing special effects in the programme like making
an alert sound etc. Whitespace in C++ also helps to increase the readability and
comments helps to properly document a programme.

In the previous session, C++ data types were introduced stating their data type and size in
bytes. The ‘sizeof’ operator introduced in this session assist in finding the size of these
data types and even the size of any data item. In this session, we will also introduce
simple type conversions which help in converting one data type to another.

3.1 Basic Input/Output

Input and output operations are used to interact with the user. Using the standard input
and output library called iostream, messages can be written on the screen and the user's
input can be taken from the keyboard.

3.1.1 Basic output

The cout operator is used to print messages and data to the standard output which is the
screen. (cout operator was used in programming demonstrations in the previous sessions)

The insertion operator (<<) may be used more than once in a single statement:
cout << “Open University, “<< “Nawala, ”<<”Nugegoda.”;

In the above example, the output will be printed in a single line. In order to print this in
separate sentences, endl manipulator can be used to add a new line.
cout <<” Open University,”<< endl;
cout <<” Nawala,”<< endl;
cout <<” Nugegoda.”<< endl;

In using a string of characters, it is enclosed between double quotes. When it is not


enclosed they are considered as variables names.
cout<<x; //This prints the content of x where x is a variable
cout<<”Value is ”<<b; << This prints the string ‘Value is’ and the content of b

25
3.1.2 Basic input

The standard input device is usually the keyboard. The cin operator is used for inputting
data from the keyboard. In using the cin operator it must be followed by a variable that
will store the data that is going to be entered by the user.
int number;
cin>>number;

In the above example, first statement declares int variable called number, and the second
statement (cin) waits for an input from the keyboard. When the user enters an integer
value while the programme is running, it will be stored in the variable called number.

In defining variables for input, it is necessary to define the exact type of variables
depending on the type of data that is going to input from the keyboard.
e.g., If the input value needs to be a character, a char type variable should be declared.

3.1.2 A demonstration of basic input and output

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

char name1,name2;
unsigned int num1,num2,total;

cout<<"Enter the first letter of a subject:";


cin>>name1;
cout<<"Enter marks of subject "<<name1<<" ";
cin>>num1;

cout<<"\nEnter the first letter of another subject:";


cin>>name2;
cout<<"Enter marks of subject "<<name2<<" ";
cin>>num2;
total=num1+num2;
cout<<"\nThe total is "<<total;
getch();
}

26
Output:

Enter the first letter of a subject: a


Enter marks of subject a 60

Enter the first letter of another subject: b


Enter marks of subject b 88

The total is 148

Activity 3.1 – Practicing Basic input and output operations

Modify the programmes in Session 2 activity 2.2 (Calculating the area of a triangle) to
ask the user to enter the height and the base of the triangle.
Output should be as below:
Enter the height of the triangle:
Enter the base of the triangle:
Area of the triangle is ---

3.2 Special formatting characters


The backslash character (\) is used as an escape character, allowing a programmer to
include characters that would normally have a special meaning for the compiler. A list of
characters and their operations are given below.

Sequence Meaning
\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)

Table 3.1 – Special for matting Characters

27
¾ These characters can be used in the programme by typing the backslash followed
by the character in a cout statement.
cout<<”\n”; //This means a new line (The cursor will prompt to the next line)

¾ They are also can be defined as char variables.


char tabCharacter = `\t';

3.3 Whitespace
Whitespace (tabs, spaces, and newlines) is generally ignored by the C++ compiler.
x=2+y;
The above statement is same as
x =2
+y;

Mainly we don’t write programmes as given above as it will reduce the readability. We
can use white space to make the programs more readable and easy to maintain.
cout<<”Value of the programme =”<<value1;
cout<<”Value of the last programme =”<<value2;

Activity 3.2 – Structuring a Programme

Write a programme which produces the following output as a chart:

“Subjects and Marks Chart”

Subject Marks
A 45
B 67
C 90

Total ‘202’

User needs to be prompted to enter three subject names (single character) and their
marks. The programme should calculate the total of the subjects and it should be
displayed as shown above.

28
Note: Subject and their marks need to be displayed first and total should be displayed in
the given place with an alert only when the user presses any key in the keyboard. The
screen (user interaction messages and user inputs) should be cleared when displaying the
chart.

Hint: Use special formatting characters, and white space to make the output more
consistent. Use getch(),clrscr() functions in getting the expected output.

3.4 Finding the size of variable types


As discussed in session-2 every data type has a size (in bytes) depending on the
architecture of the computer. C++ provides a useful operator called ‘sizeof’ for
calculating the size of any data item or type. It takes a single operand which may be a
type name or an expression and returns the size of the data type in bytes.

3.4.1 A demonstration of the ‘sizeof’ operator

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

cout<<"char size = "<<sizeof(char)<<"bytes\n";


cout<<"short size = "<<sizeof(short)<<"bytes\n";
cout<<"int size = "<<sizeof(int)<<"bytes\n";
cout<<"long size = "<<sizeof(long)<<"bytes\n";
cout<<"float size = "<<sizeof(float)<<"bytes\n";
cout<<"double size = "<<sizeof(double)<<"bytes\n";

cout<<"2.77 size = "<<sizeof(2.77)<<"bytes\n";


cout<<"MECHATRONICS size= "<<sizeof("MECHATRONICS")<<"bytes\n";

getch();
}

29
Output:
char size = 1 bytes
short size = 2 bytes
int size = 2 bytes
long size = 4 bytes
float size = 4 bytes
double size = 8 bytes
2.77 size = 8 bytes
MECHATRONICS size = 13 bytes

3.5 Simple type conversions


Type conversion means changing an entity of one data type into another.

3.5.1 Explicit type conversion

Explicit type conversion is a special programming instruction, which specifies what data
type to treat a variable in a given expression. Here, the value of the data types can be
converted (typecast) to any of the other types.

int i = 10;
float r = float(i);
It can be also written as
float r = (float)i;

(int) 5.67 //convert 5.67 to an int. Then the value will be 5.


(double) 5 //convert 5 to a double to give 5.0
(char) 122 //convert 122 to a char whose code is 122.
(unsigned short) 5.67 //convert 5.67 to unsigned short. Then the value will be 5.

3.5.2 Implicit type conversion

Implicit conversions do not require any operator. They are automatically performed by
the compiler.
short x=5;
int y;
y=x;

In the above statement a type casting operator need not be specified. This is known as a
standard conversion. C++ allows standard conversions between numerical types (short to
int, int to float, double to int etc), and to type bool and from bool to numeric values.
Some of these conversions may imply a loss of precision.

30
This can also be used when values of different types are mixed in an expression as given
below.

double d=1;
int i=10.5
i=i+d;

3.5.3. A demonstration of the type conversions

1 #include<iostream.h>
2 #include <conio.h>

3 void main(){
4 clrscr();

5 float tax_amount;

6 tax_amount=2556.22;
7 tax_amount=(int)2556.22;
8 cout<<"\nTax Payable =Rs."<<tax_amount;

9 getch();
10 }

Output:

Tax Payable =Rs 2556

In the above programme tax amount is 2556.22. In real world 22cents cannot be paid. So
it has been converted to a value that is payable which is 2556.

3.6 C++ Comments


C++ comments are used in order to properly document a programme, as it increases the
readability. On the other hand when a programme is properly commented a programmer
can understand the programme without much effort saving his time. In addition, it will be
useful for the programme’s future references.

A C++ comment starts with `//’ (Forward slashes) and goes till the end of the line. In
order to comment on multiple lines, start the comments with /* and end the comments
with */. The C++ compiler ignores any text in the same line after the ‘//’ and also ignores
the text between /* and */.

31
3.6.1 A demonstration of the use of C++ comments

1. #include<iostream.h>
2. #include<conio.h>

3. void main(){
4. clrscr();

5. /*This programme calculates the area of a circle


6. when the user inputs the radius value.
7. Variable declaration*/
8. int radius;
9. float area;

10. //Taking user input


11. cout<<"Enter radius value:";
12. cin>>radius;

13. //Calculating the area value


14. area=3.14159*radius*radius;
15. cout<<"\nArea is:"<<area;

16. getch();
17. }

Output:

Enter radius value: 12


Area is: 452.388947

3.7 C++ keywords


Certain words are reserved by C++ for specific purposes and they are called keywords in
C++. Every language has these reserved key words.
asm auto case catch char class const
cons_cast continue default delete do double dynamic_cast
else enum explicit export extern false float
for friend goto if inline int long
mutable namespace new operator private protected public
register reinterpret_cast return short signed sixeof static
static_cast struct switch template this throw true
try typedef typeid typename union unsigned using
virtual void volatile wchar_t while
Table 3.2 – C++ reserved key words

32
Additionally, alternative representations for some operators are reserved words under
some circumstances. Some of them are given below.
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Compiler may also include some additional specific reserved keywords and it can differ
in different compilers.

Note: C++ keywords cannot be used as identifiers. (As variables, constants etc)

Summary

¾ Input output operations are used to interact with the user. The cout operator is
used for standard output operations and the cin operator is used for standard input
operations.

¾ Special formatting characters have a special meaning for the compiler. There are
several formatting characters and each performs a different task.

¾ Whitespace (tabs, spaces, and newlines) are generally ignored by the C++
compiler.

¾ C++ provides a useful operator called ‘sizeof’ for calculating the size of any data
item or type.

¾ Changing an entity of one data type into another is called ‘type conversion’. There
are two basic types of type conversions called explicit and implicit.

¾ C++ comments are used in order to properly document a programme, as it


increases the readability. It is a good programming technique to include
comments in every programme.

¾ Some words are reserved in C++ as ‘keywords’ and they cannot be used as
identifiers in programmes.

33
Session 3 - Answers

Activity 3.1- Answer

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

typedefunsigned short int USHORT;


const float fix =0.5;

USHORT height,base;
float area;
cout<<"Enter the height of the triangle:";
cin>>height;
cout<<"Enter the base of the triangle:";
cin>>base;

area=fix*height*base;
cout<<"Area of the triangle is "<<area;

getch();
}
Output:

Area of the triangle is 27.5

Activity 3.2- Answer

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

char name1,name2,name3;
unsigned int num1,num2,num3,total;

cout<<"Enter the first letter of a subject 1:";

34
cin>>name1;
cout<<"Enter marks of "<<name1<<":";
cin>>num1;

cout<<"\nEnter the first letter of subject 2:";


cin>>name2;
cout<<"Enter marks of "<<name2<<":";
cin>>num2;

cout<<"\nEnter the first leter of subject 3:";


cin>>name3;
cout<<"Enter Marks of "<<name3<<":";
cin>>num3;

total=num1+num2+num3;
clrscr();
cout<<"\n \"Subjects and Marks\"\n";
cout<<"\n\tSubject"<<"\tMarks\n";
cout<<"\n\t"<<name1<<"\t"<<num1;
cout<<"\n\t"<<name2<<"\t"<<num2;
cout<<"\n\t"<<name3<<"\t"<<num3;
getch();
cout<<"\a\n\n\tTotal\t\'"<<total<<"\'";

getch();
}
Output:

Enter the first letter of a subject 1:A


Enter marks of A:
Enter the first letter of a subject 1:B
Enter marks of B:
Enter the first letter of a subject 1:C
Enter marks of C:

“Subjects and Marks Chart”

Subject Marks
A 45
B 67
C 90

Total ‘202’

35
Session 4
C++ Operators and Expressions
Contents
Objectives
Introduction
4. 1 Operators in C++
4.1.1 Assignment Operator
4.1.2 A Demonstration of the use of assignment operator
4.1.3 Arithmetic Operators
4.1.4 Relational Operators
4.1.5 A demonstration of the use of the Relational operators
4.1.6 Logical Operators
4.1.7 A demonstration of the use of the Logical operators
4.1.8 Increment and Decrement Operators
4.1.9 A demonstration of the use of the decrement operators
4.1.10 Conditional (Ternary) Operator
4.2 Precedence of operators

Summary

Objectives

After reading this lesson you should be able to:

¾ Manipulate data using C++ operators.

¾ Evaluate expressions using precedence of operators.

Introduction
In order to work with variables and constants and manipulate data, we need a way to
operate with them. C++ provides ‘operators’ for this purpose and keyboard symbols are
used to denote them. This session is designed to introduce different types of operators
used and the different actions they perform on data.

The most commonly used one is the assignment operator, which mainly deals with
assigning values to variables. In addition, this session outlines arithmetic operators,
which are the common mathematical operations found on a calculator. Logical

36
calculations also can be performed using the logical operators. Furthermore, C++
provides relational operators mostly to compare different types of values in order to
execute statements.

In addition, there are special types of operators which are unique to most programming
languages. They are called increment and decrement operators which helps in
incrementing and decrementing a given value.

Each operator is assigned a priority and this is called the ‘precedence of operators’ which
is one of the most important aspects in working with different types of operators.

4. 1 Operators in C++
An operator is a symbol, which performs a certain action in a programme. The symbols
are mostly made of signs that are available in all keyboards. The actions are performed
using a certain value or values. Theses values are mostly variables or constants and are
called operands.

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.

4.1.1 Assignment Operator

The assignment operator (=) assigns a value to a variable. (This has been used in the
programme demonstrations given in the previous sessions). Assignment operator helps
you to perform several operations on variables.

¾ This operator operates in a right-to-left rule:


Example 1: a=b; Here b is assigned to the variable a, which means the right value
is assigned to the left value and never the other way.

¾ This is useful even in assigning the same value to couple of variables.


Example 2: x = y = z = 7; This expression is equal to x=7, y=7, z=7.

¾ Assignment operator in C++ can also be used as the right operand of another
assignment operation.
Example 3: x=3+( y=7) is equal to y=7; x= 3+ y

37
4.1.2 A Demonstration of the use of assignment operator

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();
int a, b;
x = 25;
y = 10;
x = y;
y = 6;

cout << "The value of x is ";


cout << a;
cout << " and the value of y is ";
cout << b;
getch();
}

Output:
The value of x is 10 and the value of y is 6

4.1.3 Arithmetic Operators

C++ has 5 basic arithmetic operators.

Operator Symbol Action Example


Addition + Adds two operands x+y
Subtraction - Subtracts the second operand from the first x-y
operand
Multiplication * Multiplies two operands x*y
Division / Divides the first operand by the second operand x/y
Modulus % Gives the remainder when the first operand is x%y
divided by the second operand

Table 4.1 – Arithmetic operators

Operations of addition and subtraction are performed using their respective mathematical
operators and for multiplication and division, computing symbols * and / are used.

38
Modulo performs a bit different operation. It gives the remainder of a division of two
values.

¾ int value= 10 % 3 result in giving 1 as the answer since 1 is the remainder from
dividing 10 from 3.
100 modulus 9 equals 1
40 modulus 6 equals 4

¾ In using arithmetic operators, a suitable data type needs to be chosen in defining


variables.
e.g., unsigned int difference;
unsigned int num1= 7;
unsigned int num2= 9;
difference = num1- num2;

Here you would expect -2 as the answer, but -2 cannot be stored in the unsigned
int variable. Just like we have explained in session 2 unsigned variables doesn’t
hold negative values. Hence this can lead to unexpected, incorrect outcomes.

¾ int num1= 5
int num2 = 2
int division;
division = num1/num2;

You would expect an answer as 2.5 but as ‘division’ is defines as an int type
variable; it cannot hold a number with a fraction. Here you get the answer as 2,
which is incorrect. As a solution ‘division’ can be defined as a floating point
variable.
Float division;

¾ answer= 3/0;
Above statement is incorrect because it is illegal to divide a number by zero. This
results in a runtime ‘division-by-zero failure’ which typically causes the
programme to terminate.

Activity 4.1 – Working with Arithmetic Operators

Write a programme, which ask the user to input 2 integer values. Then your programme
should perform addition, subtraction, multiplication, and division on the values the user
entered and display the results on the screen.

39
4.1.4 Relational Operators

C++ provides 6 relational operators for comparing numeric quantities.

Operator Symbol Action Example


Equal == Is operand 1 equal to operand 2? x==y
Greater than > Is operand 1 greater than operand x>y
2?
Less than < Is operand 1 less than operand 2? x<y
Greater than or >= Is operand 1 greater than or equal x >= y
equal to to operand 2?
Less than or equal <= Is operand 1 less than or equal to x <= y
to operand 2?
Not equal != Is operand 1 not equal to operand x != y
2?

Table 4.2 – Relational operators

¾ In order to evaluate a comparison between two expressions relational operators


are being used. The result of a relational operation is a boolean value that can only
be true or false.

(4 = = 3) // boolean value is false as 4 is not equal to 3


(8 > 2) // boolean value is true as 8 is greater than 2
(4 != 9) // boolean value is true as 4 not equals to 9.
(10 >= 10) // boolean value is true as 10 is eqals to 10.
(11 >= 10) // Here this expression also gives the boolean value as true since 11
is greater than 10.
(6 < 6) // boolean value is false as 6 is not less than to 6.

¾ ‘Greater than or equal to’ and ‘Less than or equal to’ operators have to be used
exactly as shown in the above table. Expressions like => and =< are invalid.

¾ Characters are valid operands since they are represented by numeric values. (e.g.,
ASCII coding) Hence,‘A’<’F’ is a valid expression.

Note: Strings cannot be compared using the comparison operators. C++ provides
separate functions to compare strings.

40
4.1.5 A demonstration of the use of the Relational operators

#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();

int x,y;

cout<<"Enter value1:";
cin>>x;
cout<<"Enter value2:";
cin>>y;
cout<<"\n";

if(x>y)
cout<<"Value1 is larger than value2";
else if (x<y)
cout<<"Value2 is larger than value1";
else
cout<<"Value1 is eqal to value2";

getch();
}

Output:
Enter value1: 56
Enter value2: 23

Value1 is larger than value2

4.1.6 Logical Operators

Logical operators also evaluate to Boolean value true or false.


Operator Symbol Action Example
Logical And && True only if both exp1 and exp2 exp1 &&
(AND) are true; false otherwise exp2
Logical or (OR) || True only if both exp1 and exp2 exp1 ||
or either exp1 or exp2 is true; exp2
false otherwise
Logical ! False if exp1 is true; true if exp1 !exp1
negation (NOT) is false
Table 4.3 – Logical operators

41
¾ The operator && denotes Boolean logical operation AND.
x y x && y
true true true
true false false
false true false
false false false

( (7 == 7) && (5 > 7) ) // boolean value is false (true && false)

¾ The operator || denotes Boolean logical operation OR.


x y x || y
true true true
true false true
false true true
false false false

( (7 == 7) || (5 > 7) ) // boolean value is true (true || false).

¾ The negation operator performs the Boolean operation NOT.


!(10= =10) // Boolean value is false because the expression at its right (10 is equal
to 10) is true.
!(8<=2) // Boolean value is true because the expression at its right (8 is not less
than 2) is false.

4.1.7 A demonstration on the use of the Logical operators

1. #include<iostream.h>
2. #include<conio.h>

3. void main()
4. {
5. clrscr();
6. int eligib, final;

7. cout<<"Enter your Eligibility marks:";


8. cin>>eligib;
9. cout<<"Enter final exam marks:";
10. cin>>final;
11. cout<<"\n";

12. if((eligib>=40) && (final>=40))


13. cout<<"You have passed the subject";
14. else
15. cout<<"You have not passed the subject";
16. getch();
17. }

42
Output:

Enter your Eligibility marks: 55


Enter final exam marks: 40

You have passed the subject

In the above programme only if both the eligibility marks and final exam marks are more
than 40, it will display the message as passing the subject.

Note: If and else statements (line 12 and 14) will be discussed in future sessions.

4.1.8 Increment and Decrement Operators

Operator Symbol Action Example


Auto Increment ++ Increment occurs before the ++x
(prefix) variable value is used
Auto Increment ++ Increment occurs after the x++
(postfix) variable value is used
Auto decrement -- decrement occurs before the --x
(prefix) variable value is used
Auto decrement -- decrement occurs after the x--
(postfix) variable value is used

Table 4.4 – Increment and Decrement Operators

The increase operator (++) and the decrease operator (--) increase or decrease the value
stored in a variable.

¾ In prefix form, the operator is applied first and the outcome is then used. In
postfix form, expression is evaluated first and then the operator is applied.
x=2;
y=++x; // After one execution x=3 and y=3.
x=2;
y=x++;//after one execution y=2 and x=3

¾ In increment/decrement operators, the variable can only be incremented or


decremented by one value. To increment or decrement a value in a variable by a
larger or smaller value, it should be stated as below.
x += 3; //this is equal to x=x+3
amount -= 2; //this is equal to amount=amount – 2

Note: increment and decrement operators work only with integer variables

43
4.1.9 A demonstration on the use of the decrement operators

1. #include <iostream.h>
2. #include <conio.h>

3. int a,b;

4. void main()
5. {

6. clrscr();
7. //Set a and b both equal to 9

8. a=b=9;
9. // Print them, decrementing each time.
10. cout<<"\n"<<a--<<"\t"<<--b;
11. cout<<"\n"<<a--<<"\t"<<--b;
12. cout<<"\n"<<a--<<"\t"<<--b;

13. getch();
14. }

Output:
9 8
8 7
7 6

4.1.10 Conditional (Ternary) Operator

The conditional operator takes three expressions and returns a value. If the condition is
true it returns one value and if the condition is false it returns a different value.
condition ? result1 : result2

If condition is true the expression will return result1, if it is not it will return result2.
4= =6 ? 5: 7 // returns 7 as the condition is false (4 is not equal to 6)
8>6 ? x:y //returns x as condition is true (8 is greater than 6)
8= =4+4 ? 6:9 //returns 6 as condition is true. (4+4 is real to 8)

44
4.2 Precedence of operators
In C++ there is an established order for the priority of each operator. This is called the
precedence of operators. The precedence is established for all the operators which can
appear in C++.

From greatest to lowest priority, the priority order is shown in the table given below.

Rank Name Operator


1 scope resolution ::
2 member selection, subscripting, . ->
function calls, postfix increment and decrement ()++ --
3 sizeof, prefix increment and decrement, sizeof() ++ -- ^ ! - +
complement and not, unary minus and plus, address & * new[] delete[] ()
of and dereference, new, delete, casting
4 member selection for pointer .* ->*
5 multiply, divide, modulo */%
6 add, subtract +-
7 shift << >>
8 inequality relational < <= > >=
9 equality, inequality == !=
10 bitwise AND &
11 bitwise exclusive OR ^
12 bitwise OR |
13 logical AND &&
14 logical OR ||
15 conditional ?:
16 assignment operators = *= /= %=
+= -= <<= >>=
&= |= ^=
17 throw operator throw
18 comma ,

Table 4.5 – Precedence of operators

Operator precedence is defined in order to overcome some of the problems in performing


calculations. For example, sometimes it is difficult to decide which operation to perform
first.
Ex. a= (3+5)*7. According to the above table () has a higher precedence than
multiplication. Hence expression inside the () should be performed first (3+5=8) and then
the multiplication. The answer is 56.

45
Activity 4.2 – The use of Conditional (Ternary) Operator

Write a programme, which asks the user to input 2 integer values. Then your programme
should identify the largest value (using the conditional operator) out of the two integers
and display it on the screen.

Summary

¾ An operator is a symbol, which performs a certain action in a programme. Mainly


there are 5 categories of operators namely, assignment operator, arithmetic
operator, logical operator, relational operator, increment and decrement operator.

¾ The assignment operator (=) assigns a certain value to a variable.

¾ There are 5 basic arithmetic operators. They are addition (+), subtraction (-),
multiplication (*), division (/) and modulus (%).

¾ Relational operators are used for comparing numeric quantities. There are 6
relational operators, which are equal, greater than, less than, greater than or equal
to, less than or equal to and not equal.

¾ Logical operators in C++ evaluate to Boolean value true or false. Three basic
logical operators are logical AND (&&), Logical OR (||), Logical negation (!)

¾ The increase operator (++) and the decrease operator (--) increase or reduce the
value stored in a variable.

¾ The conditional operator takes three expressions and returns a value.


condition? result1: result2

¾ In C++ there is an established order for the priority of each operator. This is
called the precedence of operators.

46
Session 4 - Answers

Activity 4.1- Answer

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();
float val1,val2,tot,sub,mul,div;

//take the user input


cout<<"Enter an integer:";
cin>>val1;
cout<<"Enter another integer ";
cin>>val2;
//Calculate values
tot=val1+val2;
sub=val1-val2;
mul=val1*val2;
div=val1/val2;

//Displaying the output


cout<<"\nAddition:"<<tot;
cout<<"\nSubtraction:"<<sub;
cout<<"\nMultiplication:"<<mul;
cout<<"\nDivision:"<<div;

getch();
}
Output:

Enter an integer:10
Enter another integer:3

Addition:13
Subtraction:7
Multiplication:30
Division:3.333333

47
Activity 4.2 - Answer

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int x,y;

//take the user input


cout<<"Enter value1:";
cin>>x;
cout<<"Enter value2:";
cin>>y;

//finding the largest value


int answer=(x>y ? x:y);

//displaying the output


cout<<"\n"<<answer<<" is the largest value.";
getch();
}
Output:
Enter value1:67
Enter value2:78

78 is the largest value.

48
Session 5
C++ Control Structures
Contents
Objectives
Introduction
5.1 Conditional Statements
5.1.1 The if statement
5.1.2 The else statement
5.1.3 The else if statement
5.1.4 A demonstration on use of if and else statements.
5.2 Iteration Structures (loops)
5.2.1 The while loop
5.2.2 Demonstration on use of while loop
5.2.3 The do-while statement
5.2.4 A demonstration on use of do-while statement
5.2.5 The for loop
5.2.6 A demonstration on use of for loop
5.2.7 Multiple initializations and increments
5.2.8 A demonstration on the use of multiple initializations and increments
5.3 Nested Control Statement
5.3.1 A Demonstration on use of nested loops
5.3.2 A Demonstration on the use of loops and conditional statments

Summary

Objectives
After reading this lesson you should be able to:

¾ Branch your programming code based on conditions

¾ Understand what loops are and how they are used

¾ Build various types of loops.

49
Introduction
Usually a programme is not limited to a linear sequence of instructions. During
execution, it may branch off to different parts of a programme, repeat code or take
decisions. ‘Control structures’ assist in serving these kinds of special purposes. This
session introduces various forms of C++ control structures for composing programmes.

These conditional statements and iteration structures are used almost in every
programme. In addition they are nested in order to produce more complex and powerful
programmes.

5. 1 Conditional Statements
The conditional statements are used to make an execution choice in a programme based
on a given condition. The if and else statements are the main conditional statements in
C++.

5.1.1 The if statement

The ‘if’ statement enables to check for a given condition and it also helps to branch to
different parts of the programme depending on the result. The general format of the if
statement is:
if (condition)
Statement;

The programme checks for the condition and when the condition is true, the statement is
executed and when the condition is false, the statement is ignored (not executed) and the
program continues.

Example 1: if (balance>0)
interest = balance * credit rate;

The if statement can control the execution of multiple statements by the use of a
compound statement, or block. (A block is a group of two or more statements enclosed in
curly braces) Any number of statements can be included inside this block.
if (condition){
Statement 1;
Statement 2;
}

Example 2: if (balance>0) {
Interest = balance * credit_rate;
balance = balance + interest;
}

50
5.1.2 The else statement

Additional operations can be specified using the keyword ‘else’.


if (condition) {
Statement 1;
}
else
Statement 2;

When the condition in the if statement is evaluated as true, statement1 is executed.


Otherwise the else statement is evaluated and the statement 2 is executed. The else
statement can also have multiple statements to execute. We use a block for this purpose.
else {
Statement 1;
Statement 2;
}

5.1.3 The else if statement

In C++ programming, a nested if statements can be used.


if ( ch>=’0’ && ch<=’9’ )
type = digit;
else{
if ( ch>= ‘A’ && ch<= ‘Z’ )
type = capital_letter;
else {
if ( ch>= ‘a’ && ch<= ‘z’ )
type = simple_letter;
else
type = special;
}
}

Compound statements given above are complex to understand. Hence, the else if
statements are used.

if ( ch>=’0’ && ch<=’9’ )


type=digit;
else if ( ch>= ‘A’ && ch<= ‘Z’ )
type = capital_letter;
else if ( ch>= ‘a’ && ch<= ‘z’ )
type = simple_letter;
else
type = special;

51
5.1.4 A demonstration of the use of if and else statements.

#include <iostream.h>
#include<conio.h>

int x, y;
void main()
{
clrscr();

// Input the two integer values


cout<<"Enter an integer value1: ";
cin>>x;
cout<<"Enter another integer value2: ";
cin>>y;

// Test values and print result


if (x == y)
cout<<"\nValue1 is equal to value2\n";
else if (x > y)
cout<<"\nValue1 is greater than value2\n";
else
cout<<"\nValue1 is smaller than value2\n";

getch();
}
Output:
Enter an integer value1: 35
Enter another integer value2: 35

Value1 is equal to value2

Activity 5.1 – Examining the ‘else if statement’

Write a programme which inputs a person’s height (in meters) and weight (in kilograms)
and the output as one of the messages: underweight, normal or overweight.
Underweight: BMI<18.5
Normal: 18.5<= BMI <=25
Overweight BMI>25

Use the formula given below to calculate a persons BMI value:


BMI (Body Mass Index): (weight) kg/ (height*height)m

52
5.2 Iteration Structures (loops)
Iteration structures or loops are used to repeat one or more steps in a programme
depending on conditions. In C++ there are three basic iterations structures. They are the
while loop, do-while loop and the for loop.

The diagram given below shows the iteration structure of a loop in general.

Figure 5. 1: The operation of C++ loops

5.2.1 The while loop

The while loop first check the given condition and when the condition is true, it executes
the statement or statements and exit the loop when the condition becomes false.
The general form of while statement is:
while (condition)
Statement;

The while loop consists of either a single statement or multiple statements. When there is
more than one statement it has to be included inside curly braces which we call a block.
while (condition) {
Statement1,
Statement2;
}

53
5.2.2 Demonstration of the use of while loop

1. #include<iostream.h>
2. #include<conio.h>

3. void main()
4. {
5. clrscr();

6. int x = 0;
7. while (x<3) {
8. cout<<"Before increment:"<<x<<"\t";
9. x++;
10. cout<<"After Increment:"<<x<<"\n";
11. }

12. getch();
13. }

Output:

Before increment: 0 After Increment: 1


Before increment: 1 After Increment: 2
Before increment: 2 After Increment: 3

The table given below illustrates the operations of a while loop.

Iteration Value of X Check for x<3 Increment Value of x


(Before) (After)
First 0 0<3-condition true 0++ 1
Second 1 1<3-condition true 1++ 2
Third 2 2<3-condition true 2++ 3
Forth 3 3<3-condiiton false Exit while loop

Table 5. 1 - The operation of a while loop.

In line 6 of the example given above, x is assigned to 0. In the first iteration the condition
(0<3) is initially checked (line 7). As the condition becomes true it starts executing the
statements inside the block. It prints the value 0 (line 8) and increment the value of x by
1(line 9). After the increment x becomes 1 and the printed output in line 10 verifies it.
(Refer the programme output-after increment:1).

The while loop checks for the condition again as the value of x is now 1. Hence it checks
whether 1<3. Then it executes the statements inside the block and prints the values and

54
increment x again. This loop continues until the condition being false when x becomes 3
and 3<3 statements is false. Then the programme exit from the loop

Every while loop has to end at some point. Therefore, there should be a method which
makes the while statement false at a given point (when x becomes 3), otherwise the loop
will continue looping forever.

5.2.3 The do-while statement

The do-while loop and the while loop is similar in nature except for a minor difference.
In the while loop it is possible that the body of it will never be executed, if the condition
becomes false, but using the do-while loop the body of the loop will be executed at least
one time.

Hence in do-while loops the body is executed first and then the condition is checked. The
general format of do-while is:
do statement
while (condition);

Do while loop also can have a single statement or multiple statements to execute.

5.2.4 A demonstration of the use of do-while statement

1. #include<iostream.h>
2. #include<conio.h>

3. void main()
4. {
5. clrscr();

6. unsigned short number;


7. do {
8. cout << "Enter number (0 to 65535): ";
9. cin >> number;
10. cout << "You entered: " << number << "\n\n";
11. } while ( number!=100 );

12. getch();
13. }

Output:
Enter number (0 to 65535): 3344
You entered: 3344

Enter number (0 to 65535): 100


You entered: 100
55
In the above programme, every time the message in line 8 will be displayed for the user
to enter a value and then it will be displayed as ‘You entered ’(line 10), followed by the
number the user entered. This continues until the user enters the value 100. Then it will
also be displayed as ‘You entered: 100’ and only after displaying the message it will
check for the condition whether 100!=100. Here as the condition becomes false it will
exit the loop and the programme will be terminated.

5.2.5 The for loop

This is also similar to the while loop and its main function is also to repeat statements,
but the for loop is powerful and flexible to use. In addition, it provides a specific location
for the initialization, condition and for the increase or decrease operator.

The general format of the for loop is:


for (initialization; condition; increase/decrease)
statement;

The most common use of for loops is for situations where a variable is incremented or
decremented with every iteration of the loop.

5.2.6 A demonstration of the use of for loop

1. #include<iostream.h>
2. #include<conio.h>

3. void main()
4. {
5. clrscr();
6. int total = 0;
7. for (int x=0;x<=5;++x){
8. total = total + x;
9. cout<<"\nTotal is: "<<total;
10. }
11. getch();
12. }

Output:
Total is: 0
Total is: 1
Total is: 3
Total is: 6
Total is: 10
Total is: 15

56
The for loop also operates in a similar way to the while loop. In line 7, the loop first
initialize x to 0. Then it checks for the condition and if the condition is true it performs
the operations inside the body. (Lines 8 & 9). Then it comes to line 7 again and increment
the value of x by 1 and then checks the condition (whether 1<=5) and this continues until
the condition becomes false.

5.2.7 Multiple initializations and increments

In the above example, only a single variable is initialized and incremented in a for loop,
but it is possible to initialized multiple variables and they can be incremented or
decremented accordingly.

5.2.8 A demonstration of the use of multiple initializations and


increments

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

for (int a=0, b=3; a<3; a++, b--) {


cout<<"a="<<a<<"\t b="<<b<<"\n";
}

getch();
}
Output:

a=0 b=3
a=1 b=2
a=2 b=1

In the above example ‘a’ is incremented and ‘b’ is decremented at the same time and
when variable ‘a’ becomes 3 the condition becomes false and the programme exits from
the for loop.

57
5.3 Nested Control Structures
Control structures can be nested to produce more complex programmes. Here the Loops
can be nested, which means one loop can appear inside another loop. The conditional
statement can also appear inside the loops.

5.3.1 A Demonstration of the use of nested loops

The programme given below, produce the product of set {1, 2, 3}

#include<iostream.h>
#include<conio.h>

void main()
Output: (1,1)
{ (1,2)
clrscr(); (1,3)
(2,1)
for (int x=1;x<=3;++x){ (2,2)
for(int y=1;y<=3;++y) (2,3)
cout<<"("<<x<<","<<y<<")\n"; (3,1)
} (3,2)
getch(); (3,3)
}

5.3.2 A Demonstration of the use of loops and conditional statements

1. #include<iostream.h>
2. #include<conio.h>
3. #include<stdlib.h>

4. void main()
5. {
6. clrscr();

7. int code=1122;
8. int user;
9. cout<<"You are given only 3 attempts to enter the 4 digit code.\n";

10. for (int a=0;a<3;a++){


11. cout<<"Enter the code:";
12. cin>>user;

13. if (code==user){
14. cout<<"Congratulations….Code is correct!\n";
15. getch();

58
16. exit(0);
17. }

18. else {
19. cout<<"Code is incorrect!\n\n";
20. }
21. }

22. getch();
23. }

Output:
You are given only 3 attempts to enter the correct code.
Enter the code: 1178
Code is incorrect!

Enter the code: 5678


Code is incorrect!

Enter the code: 1122


Congratulations….Code is correct!

The above programme is similar to a typical password checking programme. The user is
given 3 attempts to enter the correct code and this is done by the use of a for loop. When
the user is unable to enter the correct code in 3 attempts, the programme terminates as it
exits from the for loop. If the user enters the correct code in any of the given attempts, it
will display the message ‘Congratulations….Code is correct!’ in line 14. Then it exits the
programme because of the ‘exit (0)’ statement in line 16, which is defined in the
<stdlib.h> library.(line 3)

Activity 5.2

Write a programme, which produces the following output.

******
******
******
******
******

Hint: Use nested loops.

59
Summary
¾ Conditional statements are used to make an execution choice in a programme
based on a given conditions. There are two main control structures: if and else.

¾ The else if statements are used to reduce the complexity of compound statements.

¾ The iteration structures help to execute a set of statements repeatedly. There are
three main iteration structures, while loop, do-while loop and the for loop.

¾ All the iteration structures first perform the operations in the initialization, and
then evaluate the condition. If the condition is true, it executes the action
statement and the loop. When the condition becomes false it exits the loop.

¾ There are three iteration structures in C++ and they are slightly different in nature
because of their operation and use.

¾ The while loop first checks the given condition, and when the condition is true, it
executes the statement or statements inside the block.

¾ The do while loop first execute the statements and then check whether the given
condition is true. Hence in do-while loops the statements are being evaluated at
least once.

¾ For loop is more flexible to use than the other iteration structures.

¾ When a loop appears inside another loop we call them nested control statements
and conditional statements can also be included inside loops.

60
Session 5 - Answers

Activity 5.1 - Answer

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

//defining variables
float height,weight,bmi;

//taking user input (weight and height)


cout<<"Enter your height(in meters):";
cin>>height;
cout<<"Enter your weight(in kilograms):";
cin>>weight;

//Calculating BMI value


bmi=weight/(height*height);

//when BMI value is less than 18.5


if (bmi<18.5)
cout<<"You are underweight!";
//when BMI value is between 18.5 and 25
else if(bmi<=25)
cout<<"You are Normal!";
//When BMI value is more than 25
else
cout<<"You are Overweight!";

getch();
}

Output:
Enter your height (in meters): 1.8
Enter your weight (in kilograms): 60

You are Normal!

61
Activity 5.2- Answer

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
for (int x=1;x<=5;x++){
for(int y=6;y>0;y--){
cout<<"*";
}
cout<<"\n";
}

getch();
}
Output:

******
******
******
******
******

62
Session 6
More Control Structures
Contents
Objectives
Introduction
6.1 Jump Statements
6.1.1 The Break statement
6.1.2 A demonstration on the use of break statement
6.1.3 The continue statement
6.1.4 A demonstration on the use of continue statement
6.1.5 The goto statement
6.1.6 A demonstration on the use of goto statement
6.2 The switch statement
6.2.1 A demonstration on the advantage of the break statement inside a switch
6.2.2 A demonstration on the use of goto statement
Summary

Objectives
After reading this lesson you should be able to:

¾ Understand what jumping statements are and how they are used.

¾ Branch your programming code in to different parts of the programme using these
statements.

¾ Build various types of switches depending on the programme need.

Introduction
The previous session introduced the conditional statements used in C++, which help in
taking decisions, and also the iteration structures which assist in repeating a written code.
This session focuses on the jumping statements in C++ which is another form of control
structures that are used in writing programmes. Most of these jumping statements need to
be included inside a while, do-while or a for loop.

In general a programme has a sequential flow but using these statements it is possible to
change the flow of the programme in order to serve a specific purpose that we require.
This session also introduces the switch statement which is similar to the else-if statement
we learned in the previous session.

63
6.1 Jump Statements
These statements assist in changing the direction of the execution of programmes by
jumping from one part of the programme to another part. There are three main jump
statements in C++. They are the break statement, the continue statement and the goto
statement.

6.1.1 The Break statement


A break statement should be included inside a loop (whole, do-while, for) or inside a
switch. This statement can be used to end an infinite loop, or to force it to end before its
natural end. Including this in a loop or in a switch makes the execution jumps to the
closing braces of the loop or the switch.

6.1.2 A demonstration of the use of break statement

1. #include<iostream.h>
2. #include <conio.h>

3. void main ()
4. {
5. clrscr();

//A counter which counts from 10 to 0


6. for (int counter=10; counter>0; counter--){
7. cout << counter<< "\n";
8. if (counter==5) {
9. cout << "Counting END!\n";
10. break;
11. }
12. }

13. getch();
14. }

Output:
10
9
8
7
6
5
Counting END!

64
In the above programme the counter starts from 10 (line 6) and in each iteration decrease
its value by 1. In every iteration when it comes inside the for loop, it checks whether the
counter value is equal to 5 and when it becomes true, it prints the message in line 9 and
exits the loop.

Note: Even though the for loop is initialized to iterate 10 times (10 to 0), the programme
exits the loop because of the break statement in line 10.

In the previous session in the demonstration 5.3.2 the exit function is used to exit from
the programme when the user enters the correct code. This same action can be achieved
with the use of the ‘break’ statement as shown below. .

if (code==user){
cout<<"Congratulations….Code is correct!\n";
break;
}

Activity 6.1 – Analysing the behavior of the ‘break’ statement

Write the above prgramme (6.1.2) using your text editor, remove the break statement,
compile and run the programme. What is the output?

6.1.3 The continue statement


The continue statement should also be included inside a loop. This statement terminates
the current iteration of a loop and instead jumps to the next iteration. It applies to the loop
immediately enclosing the continue statement, and not to the outer loops.

Example below shows a part of a programme.


while (category) {
for (int a=0;a<b; ++a) {
cin>>num;
if(num<0) continue;
// statements …….
}
//statements
}
In the above example the continue statement applies to the for loop. (not to the while
loop)

65
6.1.4 A demonstration of the use of continue statement

1. #include<iostream.h>
2. #include <conio.h>

3. void main()
4. {
5. clrscr();
6. int x=0;
7. do
8. {
9. x++;
10. cout<<"Value of x is "<<x<<"\n";
11. continue;
12. cout<<"After the continue statement";
13. } while (x < 3);

14. cout<<"After the do loop!";

15. getch();
16. }

Output:
Value of x is 1
Value of x is 2
Value of x is 3
After the do loop!

In the above programme, x in initialized to 0. When the programme is executing and


when it comes inside the do-while loop it first increments the value of x by 1. Then it
prints the massage ‘Value of x is 1’ and because of the continue statement in line 11, it
skips printing the massage ‘after the continue statement’.

Next, the programme comes to the loop condition in line 13 and check for the condition
whether 1<3. As the condition becomes true it starts its second iteration. The loop
continues until x becomes 3 and the condition in line 13 becomes false when 3<3 is false.
Then, it exits the loop and print the message ‘After the do loop!’ and the programme
ends.

Notice that inside the do-while loop, the line 12 will never be executed because of the
continue statement in line 11 terminated the current iteration of the do-while loop.

Note: In compiling the above programme a warning message will be displayed as


’Unreachable code’ since line 12 will not be executed.

66
6.1.5 The goto statement
The goto statement allows jumping from one point of the programme to another point. A
goto statement consists of a label, some statements, and a jump. It has a general form:
goto label:

The label is the identifier, which marks the jump destination of goto statement. This
statement can causes a jump to any location in the source code, backward or forward but
it should be used with caution since its execution causes an unconditional jump.

6.1.6 A demonstration of the use of goto statement

1. #include<iostream.h>
2. #include<conio.h>

3. void main()
4. {
5. clrscr();

6. int num,square;
7. start:
8. cout<<"Enter an integer less than 10:";
9. cin>>num;

10. if (num<10){
11. square=num*num;
12. cout<<"Square of "<<num<<" is "<<square;
13. }
14. else{
15. cout<<"Illegal number!\n\n";
16. goto start;
17. }

18. getch();
19. }

Output:

Enter an integer less than 10: 88


Illegal number!

Enter an integer less than 10: 9


Square of 9 is 81

67
In the above programme the user is asked to input only a number less than 10 and
calculates its square. If the user enters a value which is more than 10 it execute the else
statement (line 14), prints the massage in line 15 and execute the goto statement in line
16, which makes the programme jump back to line 7. Then it begins executing the
programme from line 8.

Note: In the above programme the use of the goto statement prevents the programme
from terminating until the user enters a value which is less than 10.

6.2 The switch statement


Switch statements are also called ‘case statements’ which provides a way of choosing
between a set of alternatives based on a value of an expression. It also helps to control the
flow of program execution. The general form of a switch statement is.

switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
-
-
default:
default group of statements;
break;
}

Each block begins with a line containing the case keyword followed by an expression.
The expression is evaluated and the outcome is compared to each of the constants. If the
expression outcome matches the constant, the execution jumps to those statements which
is under the particular constant and continues to execute the ‘group of statements’. When
the programme reaches the break statement under that particular constant, it exits from
the switch statement.

It is necessary to include the break statement after the group of statements in every case.
If the break statement wasn’t included the program will continue executing the rest of
statements until it reaches either a break instruction or the end of the switch statement.

We can take advantage of this feature in writing programmes.

68
6.2.1 A demonstration of the advantage of the break statement
inside a switch

1. #include<iostream.h>
2. #include <conio.h>

3. void main()
4. {
5. clrscr();
6. int day;
7. cout<<"Enter a number between 1 and 7:";
8. cin>>day;

9. switch (day) {
10. case 1:
11. case 2:
12. case 3:
13. case 4:
14. case 5:
15. cout << "Week Day!";
16. break;

17. case 6:
18. case 7:
19. cout << "Week end!";
20. break;

21. default:
22. cout << "Illegal day number!";
23. }

24. getch();
25. }

Output:

Enter a number between 1 and 7: 6


Week day!

In the above programme, for any of the constants 1, 2, 3, 4, 5 it prints the output as
‘Week Day’ and exit the switch because of the break statement. For both constants 6 and
7 it prints Weekend. If the user enters any other value it executes the default statement
and prints the message in line 22 as ‘Illegal day number!’.

69
In C++ , a case can be left as blank but there is no point in having a case blank unless
there is a useful action to be performed. For example, in the above programme case
1,2,3,4 and 6 are blank because the same operation is required to perform for each of the
cases. Here the programmer doesn’t need to specify the group of statements under each
constant saving the programmers effort and time.

In switch statements, if the expression doesn’t match any of the constants, the programme
branches to the optional default statement. If there is no default and there is no matching
value, execution falls through the switch statement and the statement ends.

6.2.2 A demonstration of the use of switch statement

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

int day;
cout<<"Enter a number between 1 and 7:";
cin>>day;

switch (day)
{
case 1 : cout << "Sunday";
break;
case 2 : cout << "Monday";
break;
case 3 : cout << "Tuesday";
break;
case 4 : cout << "Wednesday";
break;
case 5 : cout << "Thursday";
break;
case 6 : cout << "Friday";
break;
case 7 : cout << "Saturday";
break;

default : cout << "Illegal day number!";


break;
}
getch();
}

70
Output:

Enter a number between 1 and 7: 6


Friday

Here the switch statement is similar to an ‘else if’ statement (refer session 5), hence the
above programme can be written as given below.

if (day==1)
cout<<”Sunday”;
else if (day==2)
cout<<”Monday”:
else if (day==3)
cout<<”Tuesday”;
else if (day==4)
cout<<” Wednesday”;
else if (day==5)
cout<<” Thursday”;
else if (day==6)
cout<<” Friday”;
else if (day==7)
cout<<” Saturday”;
else
cout<<” Illegal day number!”;

However the ‘switch’ statement is flexible to use than the ‘else if’ statements. Hence it is
advisable to use else-if statements only on the circumstances where the switch statements
cannot be used. For example when the conditions involve are not equality expressions etc

Activity 6.2 – Writing a programme using the ‘switch’ statement

Write a programme which asks the user to input a grade (A,B,C or D). Display the
following messages depending on the input.

A or a=Your average must be between 90 – 100


B or b=Your average must be between 80 – 89
C or c=Your average must be between 70 – 79
D or d=Your average must be between 60 – 69
If the user enters any other grade the programme should display:
Your average must be below 60.

Note: If the user enters even a lower case letter (a,b,c,d), the programme should display
the same messages.

71
Summary

¾ Jumping statements assist in changing the direction of the execution of


pogrammes by jumping from one part of the programme to another part. Break,
continue and goto statements are mainly used in this purpose.

¾ A break statement should be included inside a loop (whole, do-while, for) or


inside a switch. This statement is used to exit the loop before the exit conditions
are met.

¾ The continue statement helps to jump back to the top of the loop, before the entire
set of statements in the loop is executed. This should be also included inside a
loop.

¾ The goto statement is used to jump from one point of the programme to another
point. These statements should be used with care and use it only when it is
essential.

¾ Switch statements or case statements are one of the most frequently used
programming techniques in C++ in choosing between a set of alternatives based
on a value of an expression. This is also an alternative to deeply-nested if/else
statements.

72
Session 6 - Answers

Activity 6.1 Answer

Output: 10
9
8
7
6
5
Counting END!
4
3
2
1

Activity 6.2- Answer

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

char grade;
cout << "Enter your grade: ";
cin >> grade;

switch (grade)
{
case 'a':
case 'A':
cout << "Your average must be between 90 - 100";
break;
case 'b':
case 'B':
cout << "Your average must be between 80 - 89";
break;
case 'c':

73
case 'C':
cout << "Your average must be between 70 - 79";
break;
case 'd':
case 'D':
cout << "Your average must be between 60 - 69";
break;
default:
cout << "Your average must be below 60";
}
getch();
}

Output:

Enter your grade: B


Your average must be between 80 - 89

74
Session 7
Basics of Functions
Contents
Objectives
Introduction
7.1 What is a function?
7.2 Declaring and defining a function
7.2.1 A demonstration of the use of functions
7.2.2 Declaring a function
7.2.3 Defining a function
7.2.4 The return statement
7.2.5 Calling a Function
7.3 The execution of a function
7.4 Assigning default values to parameters
7.5 Advantages in using functions
Summary

Objectives
After reading this lesson you should be able to:

¾ Understand what is a function is and what its components are.

¾ Declare and define functions.

¾ Pass parameters into functions.

¾ Return a value from a function.

Introduction
Functions are one of the most important aspects of program design. Using functions a
programme can be properly structured. A function is a piece code that performs a specific
task. Some functions are supplied as part of the compiler package but this session mainly
focuses on the functions that the user can create.

In writing a function, the first step is to know what tasks the function needs to perform. In
addition, a function has a specific format and it needs to be followed in creating
functions.

75
7.1 What is a function?
A function can be called as a sub programme which manipulates data and performs a
specific task in a programme. Every program has at least a single function. For example
every programme contains the function called main(). (main() function was discussed in
session1)

There are two types of functions:


1. User-defined: The programmer can define his or her own functions.
2. Built-in: These functions are part of the compiler package, which are supplied by the
manufacturer and can be used in writing programmes. (Ex main (), getch(), clrscr()
etc)

The general format of a function is:


return_data_type function_name ( parameter1, parameter2, ...) {
statements;
}

¾ The ‘return_data_type’ is the data type that is returned by the function.


¾ The ‘function_name’ is the name or the unique identifier of the function.
¾ The ‘parameters’ consists of a data type followed by the name of the parameter,
(example: int x) A function can have zero or any number of parameters separated by
commas.
¾ The ‘statements’ are called the body of the function. It is a block of statements
surrounded by braces { }.

7.2 Declaring and defining a function


In creating functions they need to be declared and defined. These concepts will be
covered using the example programme given below.

7.2.1 A demonstration of the use of functions

1. #include<iostream.h>
2. #include <conio.h>
3. int addition (int x, int y);

4. void main ()

5. {
6. clrscr();

76
7. int answer;
8. answer = addition (4,5);
9. cout << "The result is " << answer;

10. getch();
11. }

12. int addition (int x, int y)


13. {
14. int total;
15. total=x+y;
16. return total;
17. }

Output:
The result is 9

7.2.2 Declaring a function

The declaration includes the function return type, function name, and parameter list. This
is also called the prototype of the function.

There are three ways to declare a function:

1. Write the prototype into a file, and then use the #include directive to include the
function in the program.

Example 7.1: In the programme given above the functions like clrscr() (line 6),
getch() (line 10) are included in the <conio.h> file and we include it in our
programme using ‘#include’ (line 2).

2. Write the prototype at the beginning of the file (before the main method) in which
the function is used.

Example 7.2: In the above programme the prototype of the function is given in
line 3: int addition (int x, int y);

3. Define the function before it is called by any other function. Here the definition of
the function acts as its own declaration.

Example 7.3: The above programme can be written without a prototype

#include<iostream.h>
#include <conio.h>

77
int addition (int x, int y) {
//statements
}

void main() {
//statements
}

In the above programme the function can be included before the main () function. In a
situation like this there’s no need of a prototype, but it is advisable to use a prototype in
programmes for many reasons. Some of the reasons are given below.

1. If a prototype is not used, the functions need to be included in a particular order


making it difficult to maintain and change the programme in the long run.

2. Sometimes a function may call another function and that function in return can
call the first function (function x calls function y and function y can call function
x again) In these complex situations it is hard to decide which function should be
included first. Hence the function prototype needs to be declared.

7.2.3 Defining a function

The definition of a function includes the header and its body. The header is the ‘function
return type’, ‘function name’ and ‘parameter list’.
Example 7.4: int addition (int x, int y) (line 12)

The function return can be a null value, which means there can be functions, which do
not return any value. These functions are declared using the keyword ‘void’.
Example 7.5: The main function that is been used so far is a function, which does not
return any value.

These functions are mostly used when we want to print a message on the screen. Here no
value needs to be returned in order to print a message. In addition, the parameter list can
be left blank if the function needs no parameters. The example given below is also a user
defined function which prints the message “This is a function!”

Example 7.6: void message ()


{
cout << "This is a function!";
}

The void keyword can also be used in the function's parameter list to explicitly specify
that the function does not take any actual parameters when it is called. For example,
function message could have been declared as:

78
void message (void)
{
cout << "This is a function!";
}

Even though some functions don’t return any value, they can contain a parameter or a list
of parameters.

Example 7.8: void PrintMessage(int messageSelect)


{
if (messageSelect == 0)
cout << "Start of Programme.\n";
if (messageSelect == 1)
cout << "End of programme.\n";
}

The body of a function includes the statements (computation steps) inside the curly
braces {} which contains the instructions on how to perform a specific task.

Example 7.9: In the programme given in 6.2.1, line 13 to 17 is the body of the function.
{
int total;
total=x+y;
return total;
}

7.2.4 The return statement

In the example given above, in line 16, the return keyword has been used followed by an
expression. This is called the ‘return statement’. It should be declared inside the function
body. The return statement has a general format.
return expression;

Expression is the value returned by the function. The type of this value should be same as
the return type of the function.

Example 7.10: In the programme given above the type of the function is an integer. (int
addition) hence the return value ‘total’ should also be an integer value.

For a function who’s return type is void, expression should also be 0 or empty. The main
function can also be written as below.
int main(void){
cout<<”Open University”;
return 0;

79
Note: In declaring the prototype of a function, it is not necessary to include the names of
the parameters. The type of the parameter list is also sufficient.
Example: int calculate (int ,int);

7.2.5 Calling a Function

Using a function involves calling the function. A function call consists of function name
followed by the call operator brackets’ ()’. Inside the call operator brackets a function
arguments appears. The value that is returned by the return statement is the point where
the call occurs.

Example 7.11: calculate (5, 6);


Here the number of arguments should match the number of function parameters.

Example 7.12: int calculate function has only two parameters which is int x and int y. In
the calling function inside the call operator brackets’ ()’ there should be only two
arguments which are 5 and 6.

Not only the parameters but also the type of the parameter should match the function
parameters.
Example 7.13: Both function parameters x and y are of type int. Hence the argument
values also should be of type int. (5, 6). It cannot be a floating point or other type of a
value.

7.3 The execution of a function


Regardless of whether a function is declared before the main function, or a function
prototype is declared before the main function, the execution of all C++ programmes start
from the main function.

The general executions of functions are given below.


main (){ Function 1 Function2 Function 3
Statements;
------------- -------------
Function1; ------------- Statement; -------------
Statement1; return Function3; return
-------------
Function2; -------------
Statement2; return
Function 4
Function4;
Statement4; -------------
} -------------
return

Figure 7.1-Execution of functions


80
Consider the example programme in 7.2.1. First it declares the variable ‘answer’ of type
int. Then it branches to the prototype of the function called ‘addition’ in line 3.
int addition (int x, int y);

When the ‘first' time the function is identified by the program, the above function
prototype tells the compiler that the program passes the value of two integers to the
function and that the ‘return value’ must be assigned to an integer variable. Then the
programme execution passes to the function definition.

The arguments are evaluated and their resulting values are assigned to the corresponding
parameters. (Here 4 and 5 are passed to int x and y respectively) The body of the function
is then executed. (add x and y and store 9 in the variable ‘total’). Finally if there is a
value to be returned, it is passed to the caller. (Finally 9 is returned to the variable
answer)

answer = addition ( 4, 5 )
9
5
4
int addition ( int x, int y )

After the last statement of the function has been processed (the return statement), the
execution resumes on the next line after the call to the function and print the answer.
(return to line 9, cout << "The result is " << answer;)

Activity 7.1 – Creating a simple function

Write a programme which inputs an integer value between 1 and 10 and output its
factorial.
Use the formula given below:
Factorial(0)=1;
Factorial(n)=n*factorial(n-1)

Note: When the user enters a value out of the given range it should display an error
message and the programme should again ask the user to input a valid integer.

81
7.4 Assigning default values to parameters
In the beginning of this session we mentioned that the number of arguments in a function
call should match the number of function parameters in the given function.

Example 7. 14: average (20,1,6)

int average (int a, int b, int c)

A programmer can break the above rule by defining default parameter values in the
function declaration using the assignment operator, default values can be assigned to the
function parameters. Any or all of the function's parameters can be assigned default
values.

Example 7.15: int add (int x, int y=5, int z=8)


When sufficient number of arguments are not supplied for the function, the default
parameter values are being used but if a value is specified, this default value is ignored
and the passed value is used instead.

Note: If any of the parameters do not have a default value, no previous parameters may
have a default value.

Example 7.16: int add (int x, int y, int z)


A default value to x can be assigned only after assigning default values to both y and z.
A default value to y can be assigned only after assigning a default value to z.

7.4.1 A demonstration on the use of default parameters

1. #include<iostream.h>
2. #include <conio.h>

3. //function prototype
4. int average (int a, int b=2, int c=10);

5. void main ()
6. {
7. clrscr();

8. //function call and result display


9. cout<< "First average: "<<average (12)<<endl;
10. cout<< "Second average:"<<average (20,1,6)<<endl;
11. cout<< "Third average: "<<average(1,4);

12. getch();
13. }

82
14. //function declaration
15. int average (int a, int b, int c)
16. {
17. int result;
18. result=(a+b+c)/3;
19. return result;
20. }

Output:

First average: 8
Second average: 9
Third average: 5

In the example given above, in line 4, for b and c default parameters have been assigned.
In the first function call (line 9), since 12 is passed as argument to the function, ‘a’ is
assigned to the value 12. Since there are no values passed for b and c, it takes the default
values which is b=2 and c=10. Then in the first average calculation the result becomes 8.
(line 18 -12+2+10/3=8).

In the second function call, since all the values have been passed as an argument the
compiler ignores the default values and the answer becomes 9. (20+1+6/3 =9). In the
third function call, values 1 and 4 are assigned to ‘a’ and b respectively and the default
value of 10 is assigned to c. Here also the default value of b is ignored since a value has
been passed by the function call.

Activity 7.2 – The use of default parameters

Write a function which calculates a volume of a cube. Assign default parameters only to
width and length.

Call the function 3 times inside the main method.


1. Pass only one argument (both default parameters will be called)
2. Pass two arguments (only one default parameter will be called)
3. Pass all three arguments

Write a separate function which prints the message “Volume of the cube”. The output of
the programme should appear as given below.
Example output: Volume of the cube: 300
Volume of the cube: 3744
Volume of the cube: 1190

83
7.5 Advantages in using functions
¾ Enable reuse of code across multiple programs

¾ Reduce the duplication of code in a program (Example: by replicating useful


functionality, such as mathematical functions)

¾ decomposing complex problems into simpler pieces (this improves


maintainability and ease of extension of the programme).

¾ Improve readability of a program.

¾ Hiding part of the program (Information hiding)

Summary

¾ A function can be called as a sub programme which manipulates data and


performs a specific task in a programme.

¾ There are two types of functions. They are User-defined functions and build in
functions.

¾ There is a general format for a function. This includes


TTTTTTTTTTTTTTTTTfunction name, return data type, parameters and a set of
statements which is the body of a function. Some functions don’t contain any
parameters and every function doesn’t return a value.

¾ In creating functions they need to be declared and defined. The definition of a


function includes the header and its body.

¾ There are three ways to declare a function. They are, writing the prototype at the
beginning the file, defining the function before it is called by any other function
and using the use the #include directive

¾ Function call consists of function name followed by the call operator brackets’ ()’.

¾ The execution of every C++ programme start from the main function.

¾ The programmer can define default parameter values in the function declaration.

¾ There are many advantages in using functions.

84
Session 7 - Answers

Activity 7.1 - Answer

#include<iostream.h>
#include <conio.h>

void main()
{
clrscr();

// Function prototype
int factorial(int value);

int number, result;


start:
cout << "Enter an Integer number between 1 and 10:";
cin >> number;

if(number>0 && number<=10)


{
// Function call and assignment of return value to result
result = factorial(number);

//Output result
cout << "Factorial of "<<number<<" is "<<result << endl;
}

else{
cout<<"Illegal number!\n\n";
goto start;
}
getch();
}

/*Function definition
An integer is passed from caller function.*/
int factorial(int value)
{
int fact=1;

// Calculate the factorial with a FOR loop


for(int x=1; x<=value; x++)
{
fact = fact * x;

85
}
return fact; // This value is returned to caller
}
Output: Enter an Integer number between 1 and 10: 6
Factorial of 6 is 720

Activity 7.2- Answer

#include<iostream.h>
#include<conio.h>

//function prototypes
int volume(int height, int width=5, int length=12);
void msg();

void main()
{
clrscr();
//calling functions
msg();
cout<<volume(5)<<endl;
msg();
cout<<volume(4,78)<<endl;
msg();
cout<<volume(34,5,7);

getch();
}

//function which calculates the volume of the cube


int volume(int height, int width, int length){
int answer;
answer= height*width*length;
return answer;
}

//function which prints the message


void msg(){
cout<<"Volume of the Cube:";
}

Output:
Volume of the Cube: 300
Volume of the Cube: 3744
Volume of the Cube: 1190
86
Session 8
Arrays
Contents
Objectives
Introduction
8.1 What is an array?
8.1.1 Declaring Arrays
8.1.2 Array elements
8.1.3 A demonstration of the use of an integer array
8.1.4 Initializing Arrays
8.2 Multidimensional Arrays
8.2.1. Declaring a two dimensional array
8.2.2 Initializing Multidimensional Arrays
8.2.3 A demonstration of the use of a two dimensional array
8.3 Arrays as parameters to functions
8.3.1 A demonstration of passing an array as a parameter to a function
Summary

Objectives

After reading this lesson you should be able to:

¾ Understand what arrays are and the correct use of them

¾ Declare and initialize arrays

¾ Work with two dimensional arrays

¾ Pass arrays as parameters into a function

Introduction
In the previous sessions we understood that it is essential to declare variables in order to
store data. Hence separate variables were created for each data item that needs to be used
in programmes. In real world situations it is essential to store not only a couple of data
items but hundreds and thousands of data items in a single programme. If we try to
declare separate variables for each data item, writing programmes will be a time
consuming and tiresome activity. In circumstances like this we cannot merely adopt the
approaches we have already learnt.

87
This session introduces a method that is used almost in all the programming languages, to
overcome the above mentioned problems. If large number of data items needed to be
stored, they can be grouped together, using ‘arrays’. In an array any number of data items
can be stored.

8.1 What is an array?


An array is a set of elements, each of which holds the same type of data. These data
elements are stored continuously in the memory.

8.1.1 Declaring Arrays

Arrays must be declared before it is used. In declaring arrays two things needed to be
taken into consideration. That is:

¾ The type of data items that are required –In a single array all the elements consists
of the same data type so the type needs to be specified.
¾ The number of data items required – arrays have a fixed size after declaring it.
Hence an array size needs to be specified in advance.

The general format of declaring an array is:


data type, array name [number of array elements];

In declaring arrays, an array type needs to be declared first (int, char, float etc) followed
by the name of the array. In addition, inside square brackets, the exact number of
elements needs to be specified.

Example 8.1: int marks [5];

The above array declares integer type array named, ‘marks’ which allows storing 5
integer values.

In each time an array is declared the memory is separately allocated for each element.

Example: 8.2: In the above programme since there are 5 integer elements 20 bytes of
memory is allocated continuously in the memory. (One integer is 4 bytes in size; refer
session 2) In the diagram given below each blank section represents an element of the
array.

4 bytes

20 bytes
Figure 01 – Allocation of memory in an array

88
8.1.2 Array elements
An array has a unique identifier which is the name of the array. Hence there should be a
mechanism to address the array members separately. To access these members
individually, the array elements are numbered. Here the first elements always start at 0.

Example 8.3: In the example given above, the array contained 5 elements. Hence it can
be represented as given below.
0 1 2 3 4
marks
Figure 02 – Numbered array elements

Each member can be accessed as given below.


First element: marks [0]
Second: marks [1]
Third: marks [2]
Fourth: marks [3]
Fifth: marks [4]

A programmer should be careful in accessing the array elements, since it is somewhat


confusing as it always starts from 0 not from 1. In general if an array contains n number
of elements the elements are numbered from 0 to n-1.

Example 8.4: According to the above example even if the array has 5 elements, it is
numbered from marks [0] to marks [4]. Hence if the 3rd element needs to accessed it is
marks [2] not marks [3]

8.1.3 A demonstration of the use of an integer array

1. #include<iostream.h>
2. #include <conio.h>
3. void main ()
4. {
5. clrscr();
6. int marks[5];
7. cout<<"Please enter 5 integer values for marks...\n";
8. for ( int x=0; x<5; x++) {
9. cout<<"marks["<<x<<"]:";
10. cin>>marks[x];
11. }
12. cout<<"\nThe 5 values you entered are...\n";
13. for ( int y=0; y<5; y++) {
14. cout<<y<<":"<<marks[y]<<"\n";
15. }
16. getch();
17. }

89
Output:

Please enter 5 integer values for marks...


marks [0] : 25
marks [1] : 85
marks [2] : 78
marks [3] : 19
marks [4] : 56

The 5 values you entered are...


0 : 25
1 : 85
2 : 78
3 : 19
4 : 56

In the above example, an array is declared which can store 5 integer values (line 6). In
line 8, a for loop is defined which counts from 0 to 4. Using the first for loop the user is
given the opportunity to enter 5 integer values and these values are stored in the array.
Using the second for loop all the values that has been stored in the array are displayed.

Note: Loops will be used in order to store or display values in arrays. According to the
number of elements in the array, the for loop should be correctly initialized and the loop
condition should be properly defined.

8.1.4 Initializing Arrays

Using the assignment operator (=) values can be initialized to an array just like
initializing values to variables. These values should be included inside curly braces and
should be separated by commas.

Example 8.5: int marks [5] = {34, 89, 67, 45, 50};

0 1 2 3 4
marks 34 89 67 45 50

Figure 03 –The storage of array elements

Elements will be stored in the computer memory in a similar manner to the figure given
above. Element that is initialized first will be stored in the first location (0th position) in
the array and other elements one after the other according to the way it is initialized.

90
An array can be declared by leaving the square brackets empty [ ]. In such a case, the
compiler assumes the size of the array is equal to the number of values that has been
initialized between the curly braces.

Example 8.6: int marks [] = {34, 89, 67, 45, 50};


Since there are 5 values inside the square brackets, the compiler assumes the array has 5
elements and creates an integer array which can store 5 integer values.

In addition to the methods given above, elements can be assigned separately to an array.
Example 8.7: marks [0] = 34;
marks [1] = 89;
marks [2+1] = 45; This initialization represents marks [3]

In properly initializing an array, the amount of values between braces { } must not be
larger or smaller than the number of elements that we declare for the array. If the number
of values that has been initialized is larger than the number of elements that has been
specified in declaring the array, it will generate compile errors.

If the amount of values between braces are smaller than the number of elements, which
means if all the array members are not initialized, values of uninitialized members will be
set to 0.

Example 8.8: marks [5] = {55, 72, 88};


0 1 2 3 4
marks 55 72 88 0 0

Activity 8.1 – Declaring and initializing array

Write a programme which declares a floating point array which can store 5 elements.
Initialize the first two elements of the array to 55.5 and 6.8. Let the user input the values
for other 3 elements.
User input values

55.5 6.8

The programme output should display only the values of each and every number, which
has a value more than 50.

91
8.2 Multidimensional Arrays
So far this session explained only about one dimensional arrays, but it is possible to have
arrays of more than one dimension. Each dimension is represented as a subscript in the
array. Therefore, a two-dimensional array has two subscripts and a three-dimensional
array has three subscripts etc. Arrays can have any number of dimensions, but in writing
programmes normally one dimensional and two dimensional arrays are used.

8.2.1. Declaring a two dimensional array

In declaring two dimensional arrays, same format and the basic rules apply just like in
declaring a one dimensional array, but since there are two dimensions two square braces
need to be used to declare the two dimensions.
Example 8.9: int array [3][5];

The easiest way to work with the two dimensional array is, visualizing the array as a table
with rows and columns. The value declared in the first square braces represent the
number of rows and the second square braces represent the number of columns. Just like
in one dimensional array, each element starts with 0.
int array [3][5] ;
0 1 2 3 4

0
1
2
Figure 04 – Numbered array elements in a two dimensional array

8.2.2 Initializing Multidimensional Arrays


Values can be initialized to a multidimensional array just like we initialize values to one
dimensional array using the assignment operator. The number of array elements need to
be calculated in order to assign values to them.

According to the above example the resulting array has 15 elements. (3 x 5). Hence 15
values need to be stored.
int array [3][5] = {23,56,5,77,45,2,3,90,65,45,7,11,24,89,10};

In the above initialization it is not an easy task to recognize the values that have been
initialized to each position of the array. To improve the readability of the programme as
well as for clarity, the values of the elements can be grouped together using curly braces
according to the number of rows and columns.

92
The above array contains 5 columns. Hence 5 values can be grouped together. The array
contains 3 rows; hence 3 value sets should be there.

int array [3] [5] = {{23, 56, 5, 77, 45},


{2, 3, 90, 65, 45},
{7, 11, 24, 89, 10}};

Elements of the array will be stored in the computer memory just like in the figure given
below.

0 1 2 3 4
0 23 56 5 77 45
1 2 3 90 65 45
2 7 11 24 89 10

Figure 05 –Storage of elements in a two dimensional array

There are 3 rows and since each row starts with 0, array elements are numbered from 0 to
2. Since there are 5 columns they are numbered from 0 to 4. Every element can be
accessed using both the row number followed by the column number.
.
Example 8.9: Value 23: marks [0,0]
Value 77: marks [0,1]
Value 3: marks [0,2]
Value 56: marks [1,0]
Value 2: marks [2,1]
Value 10: marks [2,4]

The example given below further explains the use of the two dimensional arrays.

8.2.3 A demonstration of the use of a two dimensional array

1. #include <iostream.h>
2. #include <conio.h>

3. void main(){
4. clrscr();

5. const int row = 3;


6. const int col = 5;

7. int array[row][col] = {{23,56,5,77,45},


8. {2,3,90,65,45},
9. {7,11,24,89,10}};

93
10. for (int i = 0; i<row; i++)
11. for (int j=0; j<col; j++)
12. {
13. cout << "array[" << i << "][" << j << "]: ";
14. cout << array [i][j]<< endl;
15. }
16. getch();
17. }

Output:

array [0][0] : 23
array [0][1] : 56
array [0][2] : 5
array [0][3] : 77
array [0][4] : 45
array [1][0] : 2
array [1][1] : 3
array [1][2] : 90
array [1][3] : 65
array [1][4] : 45
array [2][0] : 7
array [2][1] : 11
array [2][2] : 24
array [2][3] : 89
array [2][4] : 10

In creating and accessing one dimensional arrays, a ‘for loop’ is used. Since a two
dimensional array has two dimensions, two loops need to be used. In the above example,
in line 5 and 6 two constants are assigned for the number of elements in the array. The
first for loop in line 10 counts from 0 to 2 which is equal to the number of rows in the
array and the second for loop in line 11 counts from 0 to 4 which is equal to the number
of columns in the array.

When the two for loops are executed, the elements will be printed row by row. The first
row of elements will be printed first and then the second row of elements followed by the
third row of elements.

Note: It is always a good practice to use constants in defining the number of elements in
an array. It will help in making modifications to the program easily. For example, if the
number of elements in the array needs to be increased or decreased this can be easily
achieved by changing only the constants in line 5 and 6 and initializing required
elements. The loops need not to be changed. This saves the programmers time a lot
specially when modifying large programmes.

94
8.3 Arrays as parameters to functions
In certain situations arrays needed to be passed as parameters to a function. In passing the
array as a parameter to a function, the type of the array, array name and the number of
array elements needs to be specified.

Example 8.10: int total (int array [])

Note: The number of array elements can also be passed to the array as another parameter
to the function.

This will be discussed in more detail from the example given below.

8.3.1 A demonstration of passing an array as a parameter to a


function

1. #include <iostream.h>
2. #include <conio.h>

3. int total(int array[],int length);

4. void main(){
5. clrscr();

6. int array_one[]={5,8,7};
7. int array_two[]={30,5,2,3,4};

8. cout<<"Total of array one = "<<total(array_one,3)<<endl;


9. cout<<"Total of array two = "<<total(array_two,5)<<endl;

10. getch();
11. }

12. int total(int array[],int length){

13. int result=0;


14. for (int n=0; n<length; n++)
15. {
16. result = result + array[n];
17. }
18. return result;
19. }

Output: Total of array one = 20


Total of array two = 44

95
In the example given above, the function called ‘total’ calculates the sum of the array
elements that has been stored in the array. In line 12, the function that has been defined
can accept an array with any length because the number of array elements has not been
specified in the array that has been passed as a parameter to the function. As the second
parameter an array length has been also specified in order for the ‘for loop’ to know the
exact number of elements to be printed.

In the first function call (line 8), the elements of the array one (5, 8, 7) has been passed to
the function and the length of the array (3) is also passed to the function. The variable
called ‘result’ is assigned to 0 at the beginning of the function (line 13) and when the for
loop iterates it calculates the sum of the array elements and stores it in the variable called
‘result’ (line 16). Then the answer is returned to the function call (line 18) and the answer
is printed as 20 (line 8). The second function call in line 9 also operates in the same
manner and prints the answer 44.

Activity 8.2 – Passing a two dimensional array into a function

The table given below shows the average seasonal temperatures for three major capital
cities in America in the year 2000.

Spring Summer Autumn Winter


New York 23 28 13 2
Los Angeles 28 32 15 -3
Chicago 19 27 20 -7

(a) Create a two dimensional float array which stores the above information. Write a
function which will find the largest value out of the defined temperatures. Display the
answer.

(b) Modify the programme you have written in (a), in a manner which let the user to input
the temperature values from the keyboard. Then find the largest value out of the
temperatures that the user entered and display the answer.

Note: In modifying the programme for question 8.2 (b), let the user enter only positive
values as temperature values.

96
Summary

¾ An array is a set of elements, each of which holds the same type of data. These
data elements are stored continuously in memory.

¾ In declaring an array, the type of the array, the array name and the number of data
items required need to be specified.

¾ The array members are numbered in order to access them individually. Note that
first elements always start at 0 not from 1.

¾ Values can be initialized to an array using the assignment operator (=).

¾ It is possible to have arrays of more than one dimension but the mostly used
arrays are one dimensional arrays and two dimensional arrays.

¾ Two dimensional arrays will also be defined and declared similar to the one
dimensional arrays but it has two subscripts.

¾ Arrays can be passed as parameters to a function.

97
Session 8 – Answers

Activity 8.1 - Answer

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

//Initialising first two array elements


float value[5]={55.5,6.8};
cout<<"Enter 3 floating point values...\n";

//Taking user input for 3,4 & 5 array elements


for(int i=2;i<5;i++){
cin>>value[i];
}

//Displaying values which are more than 50


cout<<"\nThe values are...\n";
for (int x=0;x<5;x++){
if(value[x]>50)
cout<<"array["<<x<<"]:"<<value[x]<<"\n";
}

getch();
}

Output:
Enter 3 floating point values...
67.1
7.5
89.3

The values are...


value[0] : 55.5
value[2] : 67.1
value[4] : 89.3

98
Activity 8.2 – Answer (a)

#include <iostream.h>
#include <conio.h>

int maximum(int array[3][4]);

void main(){

clrscr();

int array[3][4]={{23, 28, 13,2},


{28, 32, 15, -3},
{19, 27, 20, -7}};

int max_2000=maximum(array);
cout<<"Maximum temperature Value is "<<max_2000;

getch();
}

int maximum(int array[3][4]){

int max=-50;
for (int x=0; x<3; x++)
for(int y=0;y<4;y++)
{
if (array[x][y]>max)
max=array[x][y];
}
return max;
}

Output:
Maximum temperature Value is 32

99
Activity 8.2 – Answer (b)

#include <iostream.h>
#include <conio.h>

int maximum(unsigned int array[3][4]);

void main(){

clrscr();

unsigned int array[3][4];


cout<<"Please enter 12 positive temperature values...\n\n";

for(int i=0;i<3;i++)
for(int j=0;j<4;j++){
cout<<"array["<<i<<"]["<<j<<"]:";
cin>>array[i][j];
}

int max_2000=maximum(array);
cout<<"\nMaximum temperature Value is "<<max_2000<<endl;

getch();
}

int maximum(unsigned int array[3][4]){

int max=0;
for (int x=0; x<3; x++)
for(int y=0;y<4;y++)
{
if (array[x][y]>max)
max=array[x][y];
}
return max;
}

100
Output:

Please enter 12 positive temperature values...

array [0][0] : 23
array [0][1] : 56
array [0][2] : 5
array [0][3] : 77
array [1][0] : 2
array [1][1] : 3
array [1][2] : 90
array [1][3] : 65
array [2][0] : 7
array [2][1] : 11
array [2][2] : 24
array [2][3] : 89

Maximum temperature Value is 90

101
Session 9
Pointers
Content

Objectives
Introduction

9.1 What is a pointer?


9.1.1 Declaring Pointers
9.1.2 Initializing Pointers
9.1.3 A demonstration on the use of pointers
9.1.4 A demonstration on assigning values to variables using pointers
9. 2 Pointers and arrays
9.2.1 Calculations using pointers
9.2.2 A demonstration on the use of pointers to assign members to an array
9.3 Pointers to pointers
9.4 Pointers to functions
9.4.1 A demonstration on the use of pointers in functions
Summary

Objectives
After reading this lesson you should be able to:

¾ Understand what pointers are


¾ Declare, initialise and use pointers
¾ Declare pointers to functions and to arrays
¾ Declare a pointer to another pointer

Introduction
In working with variables, regardless of the physical location of the data within the
memory, we simply use its identifier whenever we want to refer to the content of the
variable. Using pointers it is possible to directly manipulate with computer memory.
Hence pointers can be considered as one of the most powerful programming techniques
available in C++.

To understand pointers, it is vital to have knowledge about computer memory. A


computer’s memory consists of thousands of sequential storage locations and each
location is identified by a unique memory address. The memory addresses in a given
computer range from 0 to a maximum value. The maximum value depends on the amount
of memory installed in a given computer. Using pointers it is possible to manipulate
directly with these memory addresses. This session explains how to manipulate data
using pointers.

102
Working with pointers can be sometimes confusing. Pointer bugs can crash in random
ways that makes it more difficult to correct them. Hence, in order to work with pointers
you should have a clear understanding of how to manipulate them correctly.

9.1 What is a Pointer?


A pointer is a reference whose value refers or point directly to another value stored
elsewhere in the computer memory. Pointers do not store a value directly just like normal
variables store values. Instead, a pointer stores a reference of another value.

A pointer contains the address of a data construct. Therefore, pointers are of the same
size regardless of what they are pointing to.

9.1.1 Declaring Pointers


A pointer must be declared before it is used.

The general format of declaring a pointer is:


data_type *pointer_name;

In declaring pointers, the pointer type needs to be declared first (int, char, float etc),
followed by the name of the pointer. Before the pointer name, an asterisk (*) is used to
denote that this is a pointer and not a variable. This asterisk mark is also called the ‘value
of operator’.

Example 9.1: int *p1;


The integer type pointer declared above is named, ‘p1’

Number of pointers and variables can also be declared at the same time.
Example 9.2: int *p1, *p2, result;

9.1.2 Initializing Pointers


A pointer cannot perform any task until it is initialized. Until a pointer holds the address
of a variable, it isn't useful. Here the ampersand (&) operator is used to assign the address
on a variable to the pointer. The ampersand mark is also called the ‘address operator’.

Example 9.3 : int *p1, result;


result =10;
p1 = &result;

In the example given above, first an integer type pointer (*p1) and a variable called
‘result’ are declared. Then the variable is assigned the value 10 and the address of the
variable (&result) is assigned to the pointer p1. This is further explained using the
diagram given below using the concept how the pointers are arranged in the computer
memory.

103
0
1
2
3 10 Variable ‘value’
: :
: :
: :
42642281
42642282 3 ‘p1’ pointer
42642283
42642284

Computer Memory

Figure 9.1- How pointers are arranged in the computer memory

According to figure 9.1, when the variable is declared, it is assigned the memory location
3, and when the pointer is declared it is assigned the memory location 42642282 (Also
refer the example 9.3). When the variable is initialized to 10, the value 10 is stored in that
memory location assigned to the variable (memory address 3). After that when the
address of the variable is assigned to the pointer using the address of (&) operator, the
pointer called p1 points to the variable called ‘result’. The pointer points to the variable
by storing the address of the variable (address 3) in the pointer’s memory location, which
is 42642282.

¾ The content of the variable result is 10.


¾ The memory address of the variable result is 3.
¾ The content of the pointer p1 is 3 because it has stored the address of the variable
result.

Note: The memory addresses that are used in figure 9.1 are just arbitrary assumption
values.

9.1.3 A demonstration on the use of pointers


1. #include<iostream.h>
2. #include <conio.h>

3. void main ()
4. {
5. clrscr();

6. int var = 1;
7. int *ptr;
8. ptr = &var;//Initialize ptr to point to var

104
9. cout<<"Content of the variable (Direct Access) : "<<var<<endl;
10. cout<<"Content of the variable (Indirect Access): "<<*ptr<<endl;
11. cout<<"\n";

12. //Accessing memory address of the variable in two ways


13. cout<<"Memory address of the variable (using the variable): "<<&var<<endl;
14. cout<<"Memory address of the variable (using the pointer) : "<<ptr;

15. getch();
16. }

Output:
Content of the variable (Direct Access) : 1
Content of the variable (Indirect Access): 1

Memory address of the variable (using the variable): 0x8fc7fff4


Memory address of the variable (using the pointer) : 0x8fc7fff4

In the programme given above, in line 6 an integer variable called var is declared and it is
initialized to 1. In line 7, a pointer of type int is declared and named as ‘ptr’. In line 8, the
pointer ptr is assigned the address of var using the address of operator (&). The rest of the
program prints the values and addresses of the variable and the pointer.

Line 9 prints the value of var just like printing a value stored in a normal variable and it is
called ‘direct access’ because the content of a variable is accessed using the variable
name. In line 10, it prints the value stored in var, pointed by ptr (Using the value of
operator *) and this is called ‘indirect access’ because the content of a variable is
accessed using a pointer. In this program, the value is equal to 1.

Line 13 prints the address of var using the address-of operator (&). This is equal to the
value printed by line 14 using the pointer variable ptr because the value that is stored in
the pointer is the address of the variable. A pointer name without the ampersand operator
accesses the pointer value itself, which is the address of the variable pointed to.

¾ *ptr and var both refer to the contents of var (that is, whatever value the program
has stored in the variable).
¾ ptr and &var refer to the address of var.

Note: The pointer should be of the same type as the variable that needs to be pointed.
int *p1- This pointer can point only to an integer value
Char *p2- This pointer can point only to an char value

Values can also be assigned to variables using pointers. The example given below shows
how pointers can be used to assign values to variables.

105
9.1.4 A demonstration on assigning values to variables using
pointers

1. #include<iostream.h>
2. #include <conio.h>

3. void main ()
4. {
5. clrscr();

6. float height, length;


7. float *h, *l;

8. height=5.5;
9. length=8.3;

10. h= &height;
11. l= &length;

12. cout<<"Height is "<<*h<<endl;


13. cout<<"Length is "<<*l<<endl;

14. *h = 10.55;
15. *l = 18.33;

16. cout<<"\nNew height is "<<height<<endl;


17. cout<<"New length is "<<length<<endl;

18. getch();
19. }

Output:
Height is 5.5
Length is 8.3

New height is 10.55


New length is 18.33

In the example given above, the variables ‘height’ and ‘length’ are first assigned to 5.5
and 8.3 respectively (line 8 and 9). Then using the two pointers ‘h’ and ‘l’, different
values are reassigned to the variables. (line14 and 15). When the pointer is used with the
asterisk (*), it always refers to the content of the variable that the pointer refers to. Hence
values can be assigned to the variables using the pointers. After assigning values using
pointers, the content of the variables have been changed to 10.55 and to 18.33. This is
evident from the programme output. (refer line 16 and 17)

106
It is possible to assign more than one pointer which points to a same variable.

Example 9.4: int marks=20;


int *p1, *p2;
p1=&marks;
p2=&marks;

marks 20 Memory address: 456788

p1 456788 456788 p2

Figure 9.2- Two pointers, pointing to a same variable

In figure 9.2 both pointers (p1and p2) hold the memory address of the variable marks.

9. 2 Pointers and arrays


Array elements can also be accessed using pointers. When an array is assigned to a
pointer it points to the first element of the array.

Example 9.5: int marks [10];


int *p;
p=marks;
The array can also be assigned to the pointer as p = &marks [0];

9.2.1 Calculations using pointers


Meaningful arithmetic operations can be done using pointers, but only addition and
subtractions are allowed. Hence this mechanism can be used in assigning values to an
array and to access these members separately.

The members of an array can be accessed in different ways using pointers. Check the
example given below.

9.2.2 A demonstration on the use of pointers to assign members


to an array
1. #include<iostream.h>
2. #include <conio.h>

3. void main ()
4. {
5. clrscr();

107
6. int marks[6];
7. int *p;
8. p=marks;

9. *p=45; //allocating marks[0]=45


10. p++;
11. *p=55; //allocating marks[1]=55
12. p=&marks[2];
13. *p=65; //allocating marks[2]=65
14. p=marks;
15. *(p+3)=75; //allocating marks[3]=75
16. marks[4]=85; //allocating marks[4]=85
17. p=marks;
18. p=p+5;
19. *p=95; //allocating marks[5]=95

20. for (int x=0;x<=5;x++)


21. {
22. cout<<marks[x]<<"\n";
23. }

24. getch();
25. }

Output:
45 0 1 2 3 4 5
55
65 marks 45 55 65 75 85 95
75
85
95 P (P+3) P=P+5
P++
P=&marks[2]

Figure 9.3 – Assigning values to an array using a pointer

Since a pointer is first pointed to the first element of the array, a value to the first element
can be easily assigned (line 9). Another simple way to access an array element is the use
of the ++ operator. Using the ++ operator, 55 is allocated as the second element of the
array. (line 10 and 11) Then a value needs to be assigned to the next position of the array,
which is marks [2.] Since the use of the ‘address of’ operator (&), the pointer points to
the address of the element marks [2] (line 12) and the value 65 is allocated to that
position. Refer line 13 in the above programme.

108
As the next step in line 14 the array is again assigned to the pointer, which means the
pointer points to the first element of the array again (line 14). Then straight away by
adding 3 to the pointer it points to the 4th position on the array and 75 is allocated to that
position. (line 15 and 16) This can be done in another similar manner which is shown in
line 17,18 and 19. After assigning the array again to the pointer, (line 17) 5 is added to
the pointer which makes it point to the 5th position of the array and 95 is assigned to the
position.

In addition to assigning values to an array using pointers, values in an array can also be
accessed using pointers. Values can also be subtracted from the pointer and can be used
to access elements in an array.

Note: In increasing or decreasing the value that a pointer points to, always use
parenthesis () to make sure that the addition and subtraction is applied to the pointer and
not to its value.
*(p-2) //correct
*p-2 //incorrect

Activity 9.1 – Storing and accessing elements of an array using pointers

Declare the integer array given below, which can hold 5 elements.
int salary[5];

(a) Assign the values given below to the array using a pointer.
32700, 15000, 7500, 28000, 10000
Display the above values using a loop. (refer example 9.2.2)
Hint: You can use one or more methods that were discussed in example 9.2.2, to
assign values to the array.

(b) Modify the above programme in order to display the values that are stored in the
array using a pointer and a loop (either a while loop or a for loop)

9.3 Pointers to pointers


A pointer can be pointed not only to a pointer, it also can point to another pointer.

Example 9.6: char letter=’a’;


char *p1,*p2;
p1=&letter;
p2=&p1;

109
letter p1 p2
a 23 3876

234 3876 10100

Figure 9.4 – Pointer that points to another pointer

9.4 Pointers to functions


Many operations can be performed using pointers and functions. A pointer to a function
holds the starting address of a function. Hence, this is a more flexible way of calling a
function. This feature can be used to point to different functions depending on the
program conditions.

Here also the pointer needs to be declared before it is been used. The general format of
the declaration is:
data_type (*pointer_to_function)(parameter1, parameter2, …);

According to the above format, type of the pointer should be declared first, followed by
the pointer name. Next, the parameter list of the function needs to be declared enclosed
between parentheses. The data type of the pointer and the parameter list should also
match the return type and the parameter list of the function or functions that it points to.

Example 9.7: int (*ptr)(int x, int y);


void (*p)(float y, float z);

9.4.1 A demonstration on the use of pointers in functions


1. #include<iostream.h>
2. #include <conio.h>

3. float area(float radius); //Prototype of the function


4. float (*p)(float radius); //Declaration of the pointer

5. void main(){

6. clrscr();

7. p = area;//Initilising pointer 'p' to point to function 'area'


8. float answer=p(8.1); //Calling the function using the pointer
9. cout<<"Area of the circle is "<<answer;

10. getch();
11. }

110
12. //Function Definition
13. float area(float radius)
14. {
15. return 3.14159*radius*radius;
16. }

Output: Area of the circle is 206119736

The programme given above calculates the area of a circle. First, the prototype of the
function is declared (refer line 3). In line 4 the pointer is declared and it is initialized to
the function in line 7. After the function call in line 8, the area of the circle is displayed
using the pointer.

Activity 9.2 – Using a pointer to a function to call different functions depending on


the program conditions

Create the following menu.

----------------Menu-----------
1.Calculating the factorial value
2.Calculating the sqaure value
3.Exit programme

Write a programme, which gives the user the opportunity to enter either option. When the
user selects option 1, your programme should request the user to enter an integer value.
Then the factorial should be calculated and answer should be displayed according to the
value that the user entered. Similarly, when the user selects option 2, the square value
should be calculated and the answer displayed according to the value that the user
entered.

Use a pointer to call different functions depending on the option that user has entered.
When the user selects option 3, your programme should exit.

111
Summary
¾ Pointers are variables that point to an area in memory. A pointer is defined by
adding an asterisk (*) in front of a variable name. The asterisk mark is also called
the ‘value of operator’.

¾ A pointer needs to be assigned before it is been used. The ampersand (&) operator
is used to assign the address on a variable to the pointer. The ampersand mark is
also called the ‘address of operator’.

¾ ‘*pointer_name’ and ‘variable_name’ both refer to the contents of the variable


whereas ‘pointer_name’ and ‘&variable_name’ refer to the address of the
variable.

¾ It is possible to assign more than one pointer which points to the same variable.

¾ Arithmetic operations addition and subtraction can be performed with pointers.

¾ It is possible to store and access elements of an array using pointers.

¾ Many operations can be performed using pointers, which points to functions.

112
Session 9 – Answers

Activity 9.1 – Answer (a)

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

int salary[5];
int *p;
p=salary;

*p=32700; //Assigning salary[0]=32700


p++;
*p=15000; //Assigning salary[1]=15000
p=salary;
*(p+2)=7500; //Assigning salary[2]=7500
p=&salary[3];
*p=28000; //Assigning salary[3]=28000
p=salary;
p=p+4; //Assigning salary[4]=10000
*p=10000;

cout<<"Values of the array:\n\n";


for(int x=0;x<5;x++){
cout<<"salary["[x]<<"]="<<salary[x]<<endl;
}

getch();
}

Output:

Values of the array:

Salary[0] = 32700;
Salary[1] = 15000;
Salary[2] = 7500;
Salary[3] = 28000;
Salary[4] = 10000;

113
Activity 9.1 – Answer (b)

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

int salary[5];
int *p;
p=salary;

*p=32700; //Assigning salary[0]=32700


p++;
*p=15000; //Assigning salary[1]=15000
p=salary;
*(p+2)=7500; //Assigning salary[2]=7500
p=&salary[3];
*p=28000; //Assigning salary[3]=28000
p=salary;
p=p+4; //Assigning salary[4]=10000
*p=10000;

p=salary; //Pointer points to the first element of the array


cout<<"Values of the array:\n\n";

for(int x=0;x<5;x++){
cout<<"Salary["<<x<<"]="<<*p<<endl;
p=p+1;
}
getch();
}

Output:
Values of the array:

Salary[0] = 32700;
Salary[1] = 15000;
Salary[2] = 7500;
Salary[3] = 28000;
Salary[4] = 10000;

114
Activity 9.2 – Answer

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

int factorial (int x);


int square(int y);
int (*ptr)(int);

void main() {
clrscr();

int option,value,answer;
cout<<"---------------Menu--------------\n";
cout<<"1.Calculating the factorial value;\n";
cout<<"2.Calculating the sqaure value\n";
cout<<"3.Exit programme\n\n";
cout<<"Enter your option:";
cin>>option;

if(option!=3){
cout<<"Enter an integer value:";
cin>>value;

if (option == 1){
ptr = factorial;
answer=ptr(value);
cout<<"Factorial of "<<value<<" is "<<answer;
}
else if (option == 2){
ptr = square;
answer=ptr(value);
cout<<"Square of "<<value<<" is "<<answer;
}
}
else
exit(0);

getch();
}

115
int factorial (int x)
{
int fact=1;
for(int a=1;a<=x;a++){
fact=fact*a;
}
return fact;
}

int square(int y)
{
return y*y;
}

Output:

---------------Menu--------------
1. Calculating the factorial value
2. Calculating the sqaure value
3. Exit programme

Enter your option: 2


Enter an integer value: 10
Square of 10 is 100

116
Session 10
More on Functions and Strings
Content
Objectives
Introduction
10.1 Local and Global variables
10.1.1 A demonstration on the use of local and global variables
10.2 Arguments passed by value and by reference
10.2.1 A comparison on the use of passing by value and reference
10.3 Recursion
10.3.1 A demonstration on ‘Recursion’
10.4 String Functions
10.4.1 A demonstration on the use ‘char arrays’
10.4.2 A demonstration on the use of ‘gets’ function
10.5 C++ String Functions
10.5.1 A demonstration on the use of ‘strcmp’ function

Summary

Objectives
After reading this lesson you should be able to:

¾ Declare local and global variables

¾ Understand the difference between passing arguments to functions ‘by value’ and
‘by reference’

¾ Manipulate with ‘strings’ using string functions

Introduction
In session 7 we learnt the basics of functions, how they are declared, defined, and
executed. This session covers more aspects of functions. First, it introduces local and
global variables, which is an important aspect even in ‘Object Oriented Programming’,
which will be covered in the sessions to come. In addition, this session addresses the
methods that arguments can be passed into a function as well as the property called
‘recursion’ which is used in C++ programming.

117
The concepts and examples that were discussed in the previous sessions were based on
manipulating data, which hold numerical values. In addition, we learnt that by using
character variables only a single letter, number, or a symbol could be stored. This is not
sufficient in programming. Hence the concepts of ‘strings’ can be introduced, which
allow the user to store not only a single character but to store a series of non-numerical
characters. C++ has different methods to perform operations with ‘strings’ as well as a
powerful string class library where different functions are defined in order to manipulate
with them. This session covers some of these functions as well.

10.1 Local and Global variables


Local variables are variables that are declared and defined inside the body of the
function. The variables can be used to store values inside the function, as they exist only
locally within the function itself. These kinds of variables said to have a ‘local scope’,
which means the scope of local variables is limited to the same block level in which they
are declared.

Variables declared outside the body of any other function is considered as global
variables and can be accessed inside any function in the programme. These variables said
to have ‘global scope’.

Note 1: If a function has a variable with the same name as a global variable, the name
refers to the local variable (not the global variable) when used within the function.

Note 2: Un-initialized global variables are automatically initialized to zero.

Generally, the lifetime of a variable is limited to its scope. Global variables last for the
duration of programme execution, while local variables are created when their scope is
entered and destroyed when the programme exit its scope. The memory space for global
variables is reserved prior to commencing of the programme execution, whereas memory
space for local variables is allocated only for the time that the variables are being used.

10.1.1 A demonstration on the use of local and global variables

1. #include<iostream.h>
2. #include <conio.h>

3. void addFunction(); //function prototype


4. int x = 5, y = 7; //declaration of global variables

5. void main ()
6. {
7. clrscr();
8. cout << "Total (inside main function): " << x+y<< "\n\n";
9. addFunction();

118
10. getch();
11. }

12. void addFunction()


13. {
14. int y = 10;
15. int total;
16. total=x+y;
17. cout << "Total (inside add function): " <<total<< "\n";
18. }
Output:

Total (inside main function): 12

Total (inside add function): 15

In line 4, two global variables called x and y are declared and initialized to 5 and 7
respectively. Inside the function called ‘addFunction’, a variable called y is declared
again and initialized to 10. This is a local variable, which is local to the scope of the
‘addFunction’. In line 8, in adding x and y, the programme refers to the global variables
and the answer is 12 (5+7).

In the function call (line 9), y variable refers to the local variable, which is equal to 10.
Since there is no variable called x, which is defined inside the function, x refers to the
global variable as they can be accessed inside any function in the programme. Hence in
the function call the answer is 15 (5+10).

10.2 Arguments passed by value and by reference


There are two ways to pass arguments to a function. That is passing arguments by its
value and by its reference. Most of the examples that were discussed in session 7 are of
arguments that are passed by its value.

In considering passing arguments by value during the function call, what is passed to the
function are copies of their values and not the actual variables. Hence changes that have
been made to the function arguments inside the function do not affect the variables that
have been declared outside the function.

Example 10.1: int x=2, y=10;


addition(x,y); //function call

10
2
int addition(int value1,int value2)
{

119
result = value1+value2;
return result;
}

Example 10.1 shows part of a programme. During the function call, values 2 and 10 are
passed into the function arguments value1 and value2 respectively. If we make changes
to the function arguments (value1 and value2) inside the function, it does not affect the
variables x and y which are defined outside the function because x and y variables are not
passed into the function but only their values are passed.

In passing values as references to a function, ampersand (&) sign is used before the
function arguments that need to be passed as references. When passing by reference, the
variable itself is passed into the function and not the copies of their values. Hence all the
changes that have been made to the function arguments inside the function straight away
affect the variables that have been passed to the function. Check the example given
below.

Example 10.2: int x=2, y=10;


counter ( x, y);

void counter(int &value1,int &value2)


{
++value1;
++value2;
}
In the example given above, the ampersand (&) mark has been used before the function
arguments (&value1 and &value2). It specifies that the arguments need to be passed into
the function by reference instead of by value. Inside the function, both function
arguments ‘value1’ and ‘value2’ has been incremented. Those increments affect the
variables x and y which is defined outside the function. The programmes given below as
an example clarify these concepts.

10.2.1 A comparison on the use of passing by value and


reference
Passing by Value Passing by Reference
1. #include<iostream.h> 17. #include<iostream.h>
2. #include <conio.h> 18. #include <conio.h>

3. void counter(int value1,int 19. void counter(int &value1,int


value2); &value2);

4. void main () 20. void main ()


5. { 21. {

120
6. clrscr(); 22. clrscr();

7. int x=2, y=10; 23. int x=2, y=10;


8. counter(x,y); 24. counter(x,y);
9. cout<<"x="<<x<<"\ny="<<y;; 25. cout<<"x="<<x<<"\ny="<<y;;

10. getch(); 26. getch();


11. } 27. }

12. void counter (int value1, int 28. void counter (int &value1 ,int
value2) &value2)
13. { 29. {
14. ++value1; 30. ++value1;
15. ++value2; 31. ++value2;
16. } 32. }

Output: Output:
x=2 x=3
y=10 y=11

In the above example named ‘passing by value’, the values of x and y doesn’t change
even though the function is being called (line 8). This is evident from the programme
output. The reason is that only the copies of x and y are passed into the function. Hence,
it is not possible to manipulate the value of an external variable from inside a function.

In the next example where the arguments are passed by it’s reference when the function
‘counter’ is called, value1 and value2 become references to x and y variables. Hence
inside the function the changes that have been made to value1 and value2 affect x and y.
Both x and y have been incremented and values of x and y variables increased to 3 and 11
respectively.

10.3 Recursion
Recursion means the ability that the function has, which could call itself. In the function
definition there is a point where the function calls to that very same function and repeats
the same code. In programming this method is useful in many tasks like sorting and
calculating.

A recursive function should possess two main characteristics.


1. It should have an ending point – If the function doesn’t have an end point it will
be calling itself again and again and will behave like a never ending loop. Hence,
there should be a condition where the function should exit from the recursion.
2. It must make the problem simpler – The problem should become smaller on each
recursion

121
10.3.1 A demonstration on ‘Recursion’
1. #include<iostream.h>
2. #include <conio.h>

3. void main()
4. {
5. clrscr();

6. unsigned int factorial(unsigned int value);

7. int number, result;


8. cout << "Enter an Integer number between 0 and 10:";
9. cin >> number;

10. if(number>=0 && number<=10){


11. result = factorial(number);
12. cout << "Factorial of "<<number<<" is "<<result<<endl;
13. }

14. else{
15. cout<<"Illegal number!\n\n";
16. }

17. getch();
18. }

19. unsigned int factorial (unsigned int value)


20. {
21. if(value==0)
22. return 1;
23. else
24. return (value*factorial(value-1));
25. }

Output:
Enter an Integer number between 0 and 10: 3
Factorial of 3 is 6

The programme given above calculates the factorial of a given value. As an example, the
factorial value of 3 has been calculated. (3! =3*2*1=6). In line 10, it checks whether the
number that the user has entered is between 0 and 10. If the value is in the specified range
the programme calls the function called ‘factorial’ (line 11). If not, it returns an error
message. (line 15)

122
When the programme call the function ‘factorial’ inside the function definition, it first
executes the else statement since the value that the user has entered (3) is not equal to 0
(Refer line 23 & 24). When the else statement is executed, it becomes (3*factorial (3-1)),
which means the function factorial is called again by passing the value 2 as the argument
into the function. Hence the problem is getting simpler as the factorial of 2 needs to be
calculated now. In the next iteration the factorial of 1 needs to be calculated. In the last
recursion the value becomes 0 since factorial (1-1) becomes factorial 0. Then the ‘if
statement’ executes and the function return back to the main method. (line 21 & 22)

The above programme has 2 main characteristics that have been mentioned earlier. It has
an ending point where the function exits when the value becomes 0 and it also makes the
problems simpler in each iteration.

Note: Refer session 7 ‘Activity 7.1-Answer’. The factorial value of a given number is
calculated using a ‘for loop’. In 10.3.1 the recursive method is used to calculate the
factorial value, which is a much simpler method.

Activity 10.1 – The use of recursion with arrays

Write a programme, which declares an integer array, which can hold 5 elements. Let the
user enter 5 values to the array from the keyboard. Then the programme should calculate
and display the sum of the values of the elements using a recursive function.

10.4 String Functions


Variables that can store non-numerical values and values that are longer than one single
character are known as strings. Strings are of series of characters. Hence the concepts of
arrays can be used in order to create strings.

Example 10.3:
char name []= {‘O’, ’p’, ’e’, ’n’, ’ ’, ’U’, ’n’, ’i’, ’v’, ‘e’, ’r’, ’s’, ’i’, ’t’, ’y’,’\0’ }

The arrangement of the char array can be represented as given below.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

name O p e n U n i v e r s i t y \0

Figure 01 – The storage of char array elements

The declaration and initialization of a char array is similar to any other array except that
all the elements in a char array needs to be enclosed within single quotes. If an element or
a collection of elements (words) needs to be separated, a space between those words

123
should be enclosed within single quotes. The last element of the array ‘\0’ is a null
character and C++ functions recognize it as a terminator for C++ strings.

Above initialization of elements is time consuming and prone to errors since several
single quotes needs to be specified. Hence C++ provides easier way to declare elements
in a char array by including the string inside double quotes. (Curly braces need not to be
included)

Example 10.4: char name [] =”Open University”;

10.4.1 A demonstration on the use ‘char arrays’


1. #include <iostream.h>
2. #include <conio.h>

3. void main(){
4. clrscr();

5. char name[100];
6. char greeting[]="Welcome to Department of ";

7. cout<<" Please enter the name of your department:";


8. cin>>name;
9. cout<<greeting<<name;

10. getch();
11. }

Output:
Please enter the name of your department: Mechanical Engineering
Welcome to Department of Mechanical

In the above example in line 5, an array called ‘name’ is defined which can hold 100
elements. In line 6 another array is defined and a string message ‘Welcome to
Department of’ is initialized to the array. When the user enters a department name, the
programme should display a greeting followed by the name of that department.

When observing the output carefully, it is evident that part of the programme is not
working properly. The welcome message is displayed correctly but only the first part of
the word ‘Mechanical’ is displayed even though the user had entered two words which is
‘Mechanical Engineering’
The reason for this is since the user has entered a space in order to separate the two
words, the cin function assumes that it’s the end of the string when it comes to the space
after the first word. Therefore the programme displays only the first word that the user
entered.

124
To avoid this problem C++ library has a separate function called ‘gets’ function, which is
defined in the <stdio.h> header file. The general format of the gets functions is:
gets (array_name)

10.4.2 A demonstration on the use of ‘gets’ function


1. #include <iostream.h>
2. #include <conio.h>
3. #include<stdio.h>

4. void main(){
5. clrscr();

6. char name[100];
7. char greeting[]="Welcome to Department of ";

8. cout<<"Please enter the name of your department:";


9. gets(name);
10. cout<<greeting<<name;

11. getch();
12. }
Output:

Please enter the name of your department: Mechanical Engineering


Welcome to Department of Mechanical Engineering

As a result of the use of ‘gets’ function (line 9), the above problem could be easily solved
and full message that the user has entered is displayed.

In addition to the above function, the method given below can also be used to get the
input from the user.
cin>>get(array name, maximum_charaters_to_get)

Example 10.5: char name [100];


cin>>get (name, 99)

According example 10.5, ‘name’ is the name of the array and the maximum characters
that the array can hold is 99, because the last element needs to be allocated for the null
character (‘\0’).

125
10.5 C++ String Functions
In addition to the above functions, C++ provides more sophisticated methods in order to
manipulate with strings. For this purpose the C++ library has a standard string class. In
order to use the functions provide with it, the standard header file called the ‘string’
header file needs to be included in the programme. Some of the functions provided by the
string class are given below.

Function Name Operation


strlen(string) Returns the number of characters (length) in a string
strcat(string1,string2) Concatenates string2 to the end of string1
strcpy (string1,string2) Copy a string (Copy string2 to string1)
Strstr (string1, string2) Find the first occurrence of string2 in string1
strcmp(string1,string2) Compare string2 with string1
stricmp(string1,string2) Compare string2 with string1 without regard to case

Table 01 – String-Handling Functions

10.5.1 A demonstration on the use of ‘strcmp’ function


1. #include <iostream.h>
2. #include <conio.h>
3. #include<stdio.h>
4. #include<string.h>

5. void main(){
6. clrscr();

7. char password[10];
8. cout<<"Please enter your password:";
9. gets(password);

10. if(!strcmp(password,"ousl 2007"))


11. cout<<"Correct password!";
12. else
13. cout<<"Incorrect password!";

14. getch();
15. }

Output:
Please enter your password: OUSL 2007
Incorrect password!

126
Programme 10.4.1 let the user to enter a password as the input. If the password that the
user has entered is correct, the programme displays a message indicating that the
password is correct and if the password is incorrect it returns an error message indicating
that the password is incorrect.

In the above example, ‘gets’ function is used to take the user input. (line 9). When the
user enters a string, the programme compares the two strings. They are the stored
password (ousl 2007) and the password that the user has entered. (OUSL 2007). Refer
line10. Here, a not sign (!) is used before the ‘strcmp’ function because if scrcpm()
function becomes true, it returns 0 and if it becomes false it returns 1. (Normally other
functions we have leant so far operate the other way around which returns 1 if the
statement is true and 0 when the statement becomes false). Hence it is advised to use the
not sign (!) in order to get the correct output.

According to the programme, even though correct characters have been entered as the
password, it gives the output ‘Incorrect password!’ because the function checks even for
the upper and lower case letters.

Note: ‘String’ header file is included in the programme since ‘strcmp’ function is been
used and ‘stdio’ header file has been included since the ‘gets’ function is been used.

Activity 10.2 – Understanding string handling functions

Write a programme, which asks the user to enter a name of a book and a description
about the book. The name of the book should be more than 2 characters long and the
description should be more than 20 characters long.

If the user’s input doesn’t meet the above requirements, an error message should be
displayed indicating that the information entered is not sufficient. If the user enters
correct information, it should be displayed back to the user.

127
Summary
¾ Local variables are variables that are declared and defined inside the body of the
function, which has a ‘local scope’.

¾ Global variables are variables that are declared and define outside the body of the
function, which has a ‘global scope’.

¾ There are two ways to pass arguments to a function. That is passing arguments by
its value and by its reference.

¾ Recursion means the ability that the function has, which can call itself. In
programming this is useful in order to achieve many tasks.

¾ Variables that can store non-numerical values and are longer than one single
character are known as strings.

¾ C++ string library provides more sophisticated methods in order to manipulate


with strings. Some of the string handling functions are strlen, strcpy, strcmp,
strcat etc

128
Session 10 – Answers

Activity 10.1 – Answer

#include<iostream.h>
#include <conio.h>

int sum(int array[],int first,int last);

void main()
{
clrscr();

int num_array[5];

cout << "Please enter 5 numbers:"<<endl;


for(int x=0; x<5;x++)
cin>>num_array[x];

cout<<"\nThe numbers you entered are: "<<endl;


for(x = 0;x<5;x++)
cout<<num_array[x]<<" ";
cout<<"\n\n";
cout<<"The sum of the 5 numbers you entered is " <<sum(num_array,0,4);

getch();
}

int sum(int array[], int first, int last)


{
if(first==last)
return array[first];
else
return (array[first] + sum(array,first+1,last));
}
Output:
Please enter 5 numbers:
3
25
2
10
8

The numbers you entered are:


3 25 2 10 8

The sum of the 5 numbers you entered is 48

129
Activity 10.2 – Answer

#include <iostream.h>
#include <conio.h>
#include<stdio.h>
#include<string.h>

void main(){
clrscr();

char book[50];
char desc[100];
cout<<"Enter a name of a book:";
gets(book);
cout<<"Enter a description about the book:";
gets(desc);

//int temp=strlen(subject);
if ((strlen(desc)>20)&&(strlen(book)>2)){
cout<<"\nBook Name : "<<book<<"\n";
cout<<"Description: "<<desc;
}
else
cout<<"\nInformation you entered is not Sufficient!";

getch();
}

Output 1:

Enter a name of a book: C++ Programming


Enter a description about the book: This is an introductory C++ book that
introduces the concepts and features of the C++ language

Book Name : C++ Programming


Description : This is an introductory C++ book that introduces the concepts and
features of the C++ language

Output 2:
Enter a name of a book: Mechantronics
Enter a description about the book: An introductory book

Information you entered is not Sufficient!

130

Vous aimerez peut-être aussi