C - Book 01
C - Book 01
C - Book 01
BOOK 1
C PROGRAMMING
Author
Editor
Mr. W. Hasala Peiris
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
¾ 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.
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.
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.
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.
C++ has certain characteristics over other programming languages. The most remarkable
ones are:
¾ 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. 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.
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.
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.
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.
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.
¾ #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)
¾ 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.
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)
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.
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.
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
10
Session 1 - Answers
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.
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
cout <<"C++ Programming ----";
cout <<" Session 1 ----";
cout <<" Second Programme!!!";
getch();
}
Output:
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
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.
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.
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
Note: The values of the columns ‘Size’ and ‘Range’ depend on the architecture of the
system where the program is compiled and executed.
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.
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;
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;
15
short int lastValue = 175;
long int Total = 25000;
unsigned long bigValue = 22411;
signed short smallValue= -5;
3. void main()
4. {
5. clrscr();
11. getch();
12. }
16
Output:
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
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.
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.
1. #include <iostream.h>
2. #include<conio.h>
3. void main()
4. {
5. clrscr();
12. getch();
13. }
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.
#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.
#include <iostream.h>
#include<conio.h>
1. void main()
2. {
3. clrscr();
5. USHORT val1 = 4;
6. USHORT val2 = 688;
7. USHORT val3 = 34;
8. USHORT total = val1+val2+val3;
10. getch();
11 }
Output:
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
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
area=0.5*height*base;
cout<<"Area of the triangle is "<<area;
getch();
}
Output:
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
USHORT height,base;
float area;
height=11;
base=5;
22
area=fix*height*base;
cout<<"Area of the triangle is "<<area;
getch();
}
Output:
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
¾ Find the size of any data item or type using the sizeof operator.
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.
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.
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;
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.
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
char name1,name2;
unsigned int num1,num2,total;
26
Output:
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 ---
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 (\)
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)
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;
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.
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
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
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;
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;
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:
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.
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();
16. getch();
17. }
Output:
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.
¾ Some words are reserved in C++ as ‘keywords’ and they cannot be used as
identifiers in programmes.
33
Session 3 - Answers
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
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:
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
char name1,name2,name3;
unsigned int num1,num2,num3,total;
34
cin>>name1;
cout<<"Enter marks of "<<name1<<":";
cin>>num1;
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:
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
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.
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.
¾ 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;
Output:
The value of x is 10 and the value of y is 6
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
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.
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
¾ ‘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
41
¾ The operator && denotes Boolean logical operation AND.
x y x && y
true true true
true false false
false true false
false false false
1. #include<iostream.h>
2. #include<conio.h>
3. void main()
4. {
5. clrscr();
6. int eligib, final;
42
Output:
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.
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
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
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.
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
¾ 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.
¾ In C++ there is an established order for the priority of each operator. This is
called the precedence of operators.
46
Session 4 - Answers
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
float val1,val2,tot,sub,mul,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;
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:
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++.
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
Compound statements given above are complex to understand. Hence, the else if
statements are used.
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();
getch();
}
Output:
Enter an integer value1: 35
Enter another integer value2: 35
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
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.
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:
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.
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.
1. #include<iostream.h>
2. #include<conio.h>
3. void main()
4. {
5. clrscr();
12. getch();
13. }
Output:
Enter number (0 to 65535): 3344
You entered: 3344
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 most common use of for loops is for situations where a variable is incremented or
decremented with every iteration of the 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.
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.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
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.
#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)
}
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";
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!
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
******
******
******
******
******
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
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
//defining variables
float height,weight,bmi;
getch();
}
Output:
Enter your height (in meters): 1.8
Enter your weight (in kilograms): 60
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.
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.
1. #include<iostream.h>
2. #include <conio.h>
3. void main ()
4. {
5. clrscr();
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;
}
Write the above prgramme (6.1.2) using your text editor, remove the break statement,
compile and run the programme. What is the output?
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);
15. getch();
16. }
Output:
Value of x is 1
Value of x is 2
Value of x is 3
After the do loop!
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.
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.
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:
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.
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.
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:
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.
#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;
70
Output:
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
Write a programme which asks the user to input a grade (A,B,C or D). Display the
following messages depending on the input.
Note: If the user enters even a lower case letter (a,b,c,d), the programme should display
the same messages.
71
Summary
¾ 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
Output: 10
9
8
7
6
5
Counting END!
4
3
2
1
#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:
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:
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)
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. }
Output:
The result is 9
The declaration includes the function return type, function name, and parameter list. This
is also called the prototype of the 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.
#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.
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.
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!”
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.
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;
}
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);
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.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.
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;)
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.
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.
Note: If any of the parameters do not have a default value, no previous parameters may
have a default value.
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();
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.
Write a function which calculates a volume of a cube. Assign default parameters only to
width and length.
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
Summary
¾ There are two types of functions. They are User-defined functions and build in
functions.
¾ 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.
84
Session 7 - Answers
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
// Function prototype
int factorial(int value);
//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;
85
}
return fact; // This value is returned to caller
}
Output: Enter an Integer number between 1 and 10: 6
Factorial of 6 is 720
#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();
}
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
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.
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.
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.
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
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]
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:
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.
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
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.
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.
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.
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
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.
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
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.
1. #include <iostream.h>
2. #include <conio.h>
3. void main(){
4. clrscr();
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.
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.
1. #include <iostream.h>
2. #include <conio.h>
4. void main(){
5. clrscr();
6. int array_one[]={5,8,7};
7. int array_two[]={30,5,2,3,4};
10. getch();
11. }
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.
The table given below shows the average seasonal temperatures for three major capital
cities in America in the year 2000.
(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.
¾ 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.
97
Session 8 – Answers
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
getch();
}
Output:
Enter 3 floating point values...
67.1
7.5
89.3
98
Activity 8.2 – Answer (a)
#include <iostream.h>
#include <conio.h>
void main(){
clrscr();
int max_2000=maximum(array);
cout<<"Maximum temperature Value is "<<max_2000;
getch();
}
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>
void main(){
clrscr();
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 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:
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
101
Session 9
Pointers
Content
Objectives
Introduction
Objectives
After reading this lesson you should be able to:
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++.
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.
A pointer contains the address of a data construct. Therefore, pointers are of the same
size regardless of what they are pointing to.
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’.
Number of pointers and variables can also be declared at the same time.
Example 9.2: int *p1, *p2, 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
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.
Note: The memory addresses that are used in figure 9.1 are just arbitrary assumption
values.
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";
15. getch();
16. }
Output:
Content of the variable (Direct Access) : 1
Content of the variable (Indirect Access): 1
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();
8. height=5.5;
9. length=8.3;
10. h= &height;
11. l= &length;
14. *h = 10.55;
15. *l = 18.33;
18. getch();
19. }
Output:
Height is 5.5
Length is 8.3
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.
p1 456788 456788 p2
In figure 9.2 both pointers (p1and p2) hold the memory address of the variable marks.
The members of an array can be accessed in different ways using pointers. Check the
example given below.
3. void main ()
4. {
5. clrscr();
107
6. int marks[6];
7. int *p;
8. p=marks;
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]
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
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)
109
letter p1 p2
a 23 3876
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.
5. void main(){
6. clrscr();
10. getch();
11. }
110
12. //Function Definition
13. float area(float radius)
14. {
15. return 3.14159*radius*radius;
16. }
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.
----------------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’.
¾ It is possible to assign more than one pointer which points to the same variable.
112
Session 9 – Answers
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int salary[5];
int *p;
p=salary;
getch();
}
Output:
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;
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>
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
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:
¾ Understand the difference between passing arguments to functions ‘by value’ and
‘by reference’
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.
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.
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.
1. #include<iostream.h>
2. #include <conio.h>
5. void main ()
6. {
7. clrscr();
8. cout << "Total (inside main function): " << x+y<< "\n\n";
9. addFunction();
118
10. getch();
11. }
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).
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.
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.
120
6. clrscr(); 22. clrscr();
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.
121
10.3.1 A demonstration on ‘Recursion’
1. #include<iostream.h>
2. #include <conio.h>
3. void main()
4. {
5. clrscr();
14. else{
15. cout<<"Illegal number!\n\n";
16. }
17. getch();
18. }
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.
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.
Example 10.3:
char name []= {‘O’, ’p’, ’e’, ’n’, ’ ’, ’U’, ’n’, ’i’, ’v’, ‘e’, ’r’, ’s’, ’i’, ’t’, ’y’,’\0’ }
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
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)
3. void main(){
4. clrscr();
5. char name[100];
6. char greeting[]="Welcome to Department of ";
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)
4. void main(){
5. clrscr();
6. char name[100];
7. char greeting[]="Welcome to Department of ";
11. getch();
12. }
Output:
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)
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.
5. void main(){
6. clrscr();
7. char password[10];
8. cout<<"Please enter your password:";
9. gets(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.
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.
128
Session 10 – Answers
#include<iostream.h>
#include <conio.h>
void main()
{
clrscr();
int num_array[5];
getch();
}
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:
Output 2:
Enter a name of a book: Mechantronics
Enter a description about the book: An introductory book
130