Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

Fundamental of Programming Language (C++) Gollis University

www.gollisuniversity.org Page 1
Fundamental of Programming Language (C++) Gollis University

Table of Contents

Chapter 1: Introduction

1.1 Algorithms and Flowcharts

1.2 Introducing C++

1.3 The origin of C++ and History of C++

1.4 The C++ programming environment

1.5 Object Oriented Programming

1.6 C++ fundamental character set

1.7 Data types in C++

1.8 Identifiers

1.9 Declaration

1.10 Variables

1.11 Constants

1.12 Operators

1.13 Keywords and Commands

Chapter 2: Control Statement

2.1 Introduction

2.2 Selection structure (also called branching)

2.3 Looping structure (also called iteration or repetition)

2.4 Statements

2.5 Break and Continue statements

Chapter 3: Functions and Recursions

3.1 Introduction

3.2 Declarations of functions

3.3 Defining function prototype

3.4 Scope of variables

www.gollisuniversity.org Page 2
Fundamental of Programming Language (C++) Gollis University

3.5 Functions that return values

3.6 Math library functions

3.7 Recursion

3.8 Summary

Chapter 4: Arrays

4.1 Definition

4.2 Single dimensional array

4.3 Two dimensional array

Chapter 5: Files in C++

5.1 Introduction

5.2 Source file

5.3 Object file

5.4 Application file

Chapter 6: Pointers

6.1 Definition

6.2 Reference operator (&)

6.3 Dereference operator (*)

6.4 Declaring variables of pointer types

www.gollisuniversity.org Page 3
Fundamental of Programming Language (C++) Gollis University

1.1 Algorithms and Flowcharts

1.2 Introducing C++

1.3 The origin of C++ and History of C++

1.4 The C++ programming environment

1.5 Object Oriented Programming

1.6 C++ fundamental character set

1.7 Data types in C++

1.8 Identifiers

1.9 Declaration

1.10 Variables

1.11 Constants

1.12 Operators

1.13 Keywords and Commands

www.gollisuniversity.org Page 4
Fundamental of Programming Language (C++) Gollis University

CHAPTER 1: INTRODUCTION

1.1 ALGORITHMS AND FLOWCHARTS

a.Algorithms:

A typical programming task can be divided into two phases:

Problem solving phase

This phase produce an ordered sequence of steps that describe solution of problem this sequence of
steps is called an algorithm.

Implementation phase
This phase implement the program in some programming language

Steps in Problem Solving

 First produce a general algorithm (one can use pseudocode)


 Refine the algorithm successively to get step by step detailed algorithm that is very close
to a computer language.

Pseudocode is an artificial and informal language that helps programmers develops algorithms.
Pseudocode is very similar to everyday English.

Example: Write an algorithm to determine a student’s final grade and indicate whether it is passing or
failing. The final grade is calculated as the average of four marks.

Pseudocode:
 Input a set of 4 marks
 Calculate their average by summing and dividing by 4
 if average is below 50 Print “FAIL” else Print “PASS”

Detailed Algorithm
Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50)
{
cout <<“FAIL”;
}
else
{
cout << “PASS”;
}

www.gollisuniversity.org Page 5
Fundamental of Programming Language (C++) Gollis University

b. The Flowchart

Definition (Dictionary): A schematic representation of a sequence of operations, as in a manufacturing


process or computer program.

Definition (Technical): A graphical representation of the sequence of operations in an information


system or program. Information system flowcharts show how data flows from source documents through
the computer to final distribution to users. Program flowcharts show the sequence of instructions in a
single program or subroutine. Different symbols are used to draw each type of flowchart.

The Benefits of Flowchart

 shows logic of an algorithm


 emphasizes individual steps and their interconnections
 e.g. control flow from one action to the next.

Flowchart Symbols
Use in
Name Symbol
Flowchart
Denotes the beginning or end of
Oval the program

Parallelogra Denotes an input


m operation

Denotes a process to be
Rectangle carried out
e.g. addition, subtraction,
division etc.

Denotes a decision (or branch) to


Diamond be made. The program should
continue along one of two routes.
(e.g. IF/THEN/ELSE)

Hybrid Denotes an output


operation

Denotes the direction of logic flow in


Flow line the program

Example

Step 1: Input M1, M2, M3, M4


Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: if (GRADE <50) then
Print “FAIL”
else
Print “PASS”
endif

www.gollisuniversity.org Page 6
Fundamental of Programming Language (C++) Gollis University

1.2 Introducing C++

Definition:

A C++ program is a collection of commands & data, which tells the computer to do "something". This
collection of commands is usually called C++ source code or just C++ code. Commands are "keywords"
of a programme. Keywords are a basic building block of the language.

Programming is a core activity in the process of performing tasks or solving problems with the aid of a
computer. An idealised picture of this is:

[Problem or task specification] - COMPUTER - [solution or completed task]

Unfortunately things are not (yet) that simple. In particular, the "specification" cannot be given to the
computer using natural language. Moreover, it cannot (yet) just be a description of the problem or task,
but has to contain information about how the problem is to be solved or the task is to be executed. Hence
we need programming languages.

There are many different programming languages, and many ways to classify them. For example,
"high-level" programming languages are languages whose syntax is relatively close to natural language,
where as the syntax of "low-level" languages includes many technical references to the ZEROS and
ONES ( binary 0's and 1's ) of the computer.

Languages enable the programmer to minimise his or her ACCOUNT or EFFORT of how the
computer is to solve a problem or produce a particular output.

"OBJECT-ORIENTED LANGUAGES" reflect a particular way of thinking about problems and tasks
in terms of identifying and describing the behaviour of the relevant "objects".

Smalltalk is an example of a pure object-oriented language. C++ includes facilities for object-oriented
programming, as well as for more conventional procedural programming.

Proponents of different languages and styles of languages sometimes make extravagant claims. For
example, it is sometimes claimed that (well written) object-oriented programs reflect the way in which
humans think about solving problems.

1.3 The Origins of C++ & History of C++

C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early 1980's, and is
based on the C language. The "++" is a syntactic construct used in C (to increment a variable), and C++ is
intended as an incremental improvement of C. Most of C is a subset of C++, so that most C programs can
be compiled using a C++ compiler

C is in many ways hard to categorise. Compared to assembly language it is high-level, but it nevertheless
includes many low-level facilities to directly manipulate the computer's memory. It is therefore an
excellent language for writing efficient "systems" programs. But for other types of programs, C code can
be hard to understand, and C programs can therefore be particularly prone to certain types of error. The
extra object-oriented facilities in C++ are partly included to overcome these shortcomings.

www.gollisuniversity.org Page 7
Fundamental of Programming Language (C++) Gollis University

1.4 The C++ programming environment

The best way to learn a programming language is to try writing programs and test them on a computer
so to do this we need several pieces of software:

 An editor with which to write and modify the C++ programmes components or source code.
 A compiler with which to convert the source code into machine instructions which can be executed
by the computer directly.
 A linking program with which to link the compiled program components with each other and with
a selection of routines from existing libraries of computer code, in order to form the complete
machine-executable object program,
 A debugger to help diagnose problems, either in compiling programs in the first place, or if the
object program runs but gives unintended results.

Note: All these things are fund together in the c++ software to allow you to write a
programme.

a. Source code:
Definition:

Is any collection of statements or declarations written in some human-readable computer


programming language. Source code is the mechanism most often used by programmers to specify the
actions to be performed by a computer.

Source code refers to the programming language one uses to write a program. There are hundreds,
if not thousands, of forms of source code. Some computer languages include C++, Java, and UNIX.
Often people refer to source code of websites, which means programming conducted in HTML and
possibly Java.

b. C++ Compiler:
Definition:

A compiler turns the program that you write in high level language into an executable low level
language (binary format) that your computer can actually understand and run.

A compiler is a special type of computer program that translates a human readable text file into a
form that the computer can more easily understand. At its most basic level, a computer can only
understand two things, a 1 and a 0. At this level, a human will operate very slowly and find the
information contained in the long string of 1s and 0s incomprehensible. A compiler is a computer
program that bridges this gap.

www.gollisuniversity.org Page 8
Fundamental of Programming Language (C++) Gollis University

1.5 Object oriented programming

The C++ is constructed & based on the OOP (Object Oriented Programming) concepts. The C++ uses
object oriented programming environment.

Programming languages:

There are two types:

 Initial programming languages that uses machine language or binary language & called LOW
LEVEL PROGRAMMING LANGUAGES.
 Languages that use alphabets, numbers & special characters so it’s called HIGH LEVEL
PROGRAMMING LANGUAGE.

THIS HIGH LEVE PROGRAMMING LANGUAGE CAN BE:

 STRUCTURED LANGUAGE: this type has sets of rules & regulations such as C, C++
……..etc.
 UNSTRUCTURED LANGUAGE: this type doesn’t have sets of rules & regulations.

 What is Object Oriented Programming?

OBJECT ORIENTED PROGRAMMING or OOP is one model of programming language. Unlike


other examples of computer programming language, object oriented programming focuses on the use
of objects instead of actions in order to carry out tasks. This use of objects to design applications
instead of actions also involves taking an approach that is more mindful of data and less concerned
with logic, which is more commonly the case in other paradigms.

This different approach taken by object oriented programming means that the view of objects and
actions is reversed. The emphasis is on the objects themselves rather than on the execution of tasks
that employ the objects. In that manner, the structure of object oriented programming does not
consider deciding on how to employ the logic, but on the definition of the data that will be used in the
programming.

Designing computer programs with the approach of OBJECT ORIENTED PROGRAMMING


BEGINS with: 1-defining the objects that are to be manipulated by the program. Once the objects are
identified, the programmer will begin to 2- identify the relationship between each object. THIS
PROCESS IS USUALLY REFERRED TO AS DATA MODELLING.

Essentially, the programmer is seeking to place the objects into a classification, thus helping to
define the data that is part of the inheritance brought to the task by each object. In fact, the process of
defining these classes and subclasses of data is normally called inheritance.

OBJECT ORIENTED PROGRAMMING also helps to sort objects in a manner that allows for the
phenomenon of POLYMORPHISM to take place. That is, different objects will be able to respond to a
common message, but each in a different way that is unique to that object. At the same time, object

www.gollisuniversity.org Page 9
Fundamental of Programming Language (C++) Gollis University

oriented programming allows for the ENCAPSULATION of an object, effectively HIDING OR


PROTECTING the data associated with the object from easy view without security access.

One of the advantages of OBJECT ORIENTED PROGRAMMING is that the process makes good
use of modularity. ENCAPSULATION That is, objects and tasks are grouped in a way that each
module is capable of independent consideration. This can be a great help when making enhancements
to a program, as modularity makes it possible to address the task of making alternations to the setup of
one portion of the programming without impacting the structure and function of the other modules.

If you've never used an object-oriented programming language before, you'll need to learn a few
basic concepts before you can begin writing any code. This lesson will introduce you to objects,
classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to
the real world.

 OBJECT:

DEFINITION:

Object is a tangible and visible thing or entity. An object can be considered a "thing" that can
perform a set of activities. Real-world objects share two characteristics: they all have STATE &
BEHAVIOR .Objects are key to understanding object-oriented technology.

Software objects are modelled after real-world objects in that they too have state and behavior. A
software object maintains its STATE in variables and implements its behavior with METHODS.

These real-world objects share two characteristics: they all have state and they all have behavior.
For example, dogs have state (name, color, and breed, hungry) and dogs have behavior (barking,
fetching, and slobbering on your newly cleaned slacks). Bicycles have state (current gear, current
pedal cadence, two wheels, and number of gears) and behavior (braking, accelerating, slowing down,
and changing gears).

Bundling code into individual software objects provides a number of benefits, including:

1. Modularity: The source code for an object can be written and maintained independently
of the source code for other objects. Once created, an object can be easily passed around
inside the system.
2. Information-hiding: By interacting only with an object's methods, the details of its
internal implementation remain hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by another software developer),
you can use that object in your program. This allows specialists to implement/test/debug
complex, task-specific objects, which you can then trust to run in your own code.

www.gollisuniversity.org Page 10
Fundamental of Programming Language (C++) Gollis University

 DATA ABSTRACTION:

DEFINITION:

The concept of abstraction relates to the idea of hiding data that are not needed for
presentation. The main idea behind data abstraction is to give a clear separation between
properties of data type and the associated implementation details.

Reasons for the need of Abstraction?

Flexibility in approach:

By hiding data or abstracting details that are not needed for presentation, the programmer achieves
greater flexibility in approach.

Enhanced Security:

Abstraction gives access to data or details that are needed by users and hide the implementation details,
giving enhanced security to application.

Easier Replacement:

With the concept of abstraction in object-oriented programming language, it is possible to replace code
without recompilation. This makes the process easier and saves time for users.

 Encapsulation:

DEFINITION:

Encapsulation is the process of combining data and functions into a single unit called class.
Using the method of encapsulation, the programmer cannot directly access the data. Data is only
accessible through the functions present inside the class. Data encapsulation led to the important
concept of data hiding. Data hiding is the implementation details of a class that are hidden from the
user. The concept of restricted access led programmers to write specialized functions or methods for
performing the operations on hidden members of the class. Attention must be paid to ensure that the
class is designed properly.

The Benefits of Encapsulation

Encapsulating related variables and methods into a neat software bundle is a simple yet powerful
idea that provides two primary benefits to software developers:

 Modularity: The source code for an object can be written and maintained independently of the
source code for other objects. Also, an object can be easily passed around in the system. You
can give your bicycle to someone else and it will still work.

www.gollisuniversity.org Page 11
Fundamental of Programming Language (C++) Gollis University

 Information hiding: An object has a public interface that other objects can use to communicate
with it. But the object can maintain private information and methods that can be changed at any
time without affecting the other objects that depend on it. You don't need to understand the
gear mechanism on your bike in order to use it.

 CLASS:

DEFINITION:

This class describes the data properties and behaviours alone. In C++ programming language,
CLASS describes both the PROPERTIES (DATA) and BEHAVIOURS (FUNCTIONS) of objects.
Classes are not objects, but they are used to instantiate objects. A class is an extended concept similar to
that of structure in C programming language;

FEATURES OF CLASS:

Classes contain data known as members and member functions. As a unit, the collection of
members and member functions is an object. Therefore, this unit of objects make up a class.

 POLYMORPHISM:

DEFINITION:

"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object to
become totally different object by taking many different forms while using that same name. That means
having the same name and doing different tasks.

Polymorphism is the ability to use a function in different ways. It means one object name for different
functions so the same name is shared by different functions. Polymorphism gives different meanings or
functions to the operators or functions. Poly, referring to many, signifies the many uses of these operators
and functions. A single function usage or an operator functioning in many ways can be called
polymorphism. Polymorphism refers to codes, operations or objects that behave differently in different
contexts

 INHERITANCE:

DEFINITION:

Inheritance is the process by which new classes called derived classes or child class are created from
existing classes called base classes or parent class. The derived classes have all the features of the base
class and the programmer can choose to add new features specific to the newly created derived class.

FEATURES OR ADVANTAGES OF INHERITANCE:

1- Reusability:

Inheritance helps the code to be reused in many situations. The base class is defined and once it is
compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as
many derived classes from the base class as needed while adding specific features to each derived
class as needed.

www.gollisuniversity.org Page 12
Fundamental of Programming Language (C++) Gollis University

2-Saves time & Effort:

The above concept of reusability achieved by inheritance saves the programmer time and effort.
Since the main code written can be reused in various situations as they need.

3- It increases the programme structure which results in greater reliability.

 DEFINING OOP :

Object-Oriented Programming (OOP) is a type of programming that uses "objects" . In which


programmers define not only the DATA TYPE of a data structure, but also the types of
OPERATIONS (FUNCTIONS) that can be applied to the data structure or programme structure. In
addition, programmers can create relationships between one object and another. To design
applications or computer programmes. The Programming techniques that is used in OOP are DATA
ABSTRACTION, ENCAPSULATION, MODULARITY, POLYMORPHISM, and INHERITANCE.

NOTE:

In this way, the data structure becomes an object that includes both DATA and FUNCTIONS.

1.6 C++ fundamental character set

THESE ARE THE CHARACTERS THAT CAN BE USED IN C++ PROGRAMMING LANGUAGE:
 ALPHABETS: A, B, C…………X, Y, Z.

a, b, c…………..x, y, z.

 NUMBERS: 0, 1, 2, 3………………9.

 SYMBOLS OR SPECIAL CHARACTERS: +, -, (, ), *, /, =, [, ], <, >, >=,<=, {, }……… etc.

www.gollisuniversity.org Page 13
Fundamental of Programming Language (C++) Gollis University

1.7 Data Types in C++

DATA TYPE DEFINITION:

A data type in programming language is a classification identifying one of various types of data
such as floating-point number, fixed point number, text …..Etc. stating the possible values for that type,
the operations that can be done on that type, and the way the values of that type are stored.

When we wish to store data in a c++ program, such as a whole number or a character, we have to
tell the compiler 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.

Data Types in C++ are:

I. Integers:

1. Integer:

 The integer type of data is used for storing whole numbers. We can use signed or
unsigned. That means it represents the fixed numbers without decimal point.
 The integer value cane range from -2147483648 to 2147483647(signed) or 0 to
4294967296(unsigned).
 The size which is allocated to the integer number in the computer memory to store
it is 32 bits.

NOTE: REMEMBER THAT 1 BYTE = 8 BITS.

2. SHORT:
 The short type of data is used for representing or storing whole numbers. We can
use signed or unsigned. That means it represents the fixed numbers without decimal point.
 The short value range from -32768 to 32767 (signed) or 0 to 65536 (unsigned).
 The size which is allocated to the short number in the computer memory to store it
is 16 bits.
3. Long:
 The long type of data is used for representing or storing whole numbers. We can
use signed or unsigned. That means it represents the fixed numbers without decimal point.
 The long value range from more than-2147483648 to 2147483647(signed) or 0 to
4294967296(unsigned).
 The size which is allocated to the long number in the computer memory to store it is
64 bits.

www.gollisuniversity.org Page 14
Fundamental of Programming Language (C++) Gollis University

II. Floating point:

 Floating point type of data contains decimal numbers and fraction number or
decimal point .Example 1.23, -.087 , 1.97, 100.154 ……ETC .
 The floating point value range from +/- 1.4023x10-45 to 3.4028x10+38

THERE ARE THREE SIZES:

A- Float (single-precision):

The floating point (single-precision): value range from +/- 1.4023x10-45 to 3.4028x10+38

B- Double (double-precision):

The floating point (double-precision): value range from +/-1.4023x10-45 to 3.4028x10+38

C- Long double (extended-precision):

The floating point (double-precision): value range from ANY NUMBER BEYOND THAT
IN Float (single-precision) & Long double (extended-precision).

 The size which is allocated to the float (single-precision) number in the computer memory to
store it is 32 bits.
 For double (double-precision) number in the computer memory to store it is 64 bits.
 For long (extended-precision) number in the computer memory to store it is 64 bits.

III. Character Type:

The character type is used to store characters - typically ASCII characters. For example:
‘G’, ‘F’, ‘ A ‘, ‘1 ‘ , ‘5’, ‘100’, ‘7’. THE character is enclosed within single quotes.

 The size which is allocated to the character value in the computer memory to store it is 8 bits.
 The character value range from -128 to 127(signed) or 0 to 255 (unsigned)

IV. Boolean:

 Variables of type Boolean can hold either one of two values: TRUE or FALSE.
 A value of type Boolean can be promoted to an integral type. A Boolean value of false is
promoted to the value 0, and a bool value of true is promoted to the value 1.
 The size which is allocated to the Boolean value in the computer memory to store it is 8 bits.
 Boolean value range from 0 to 1.

www.gollisuniversity.org Page 15
Fundamental of Programming Language (C++) Gollis University

V. String:

 A variable of type string contains a string or text .for example: "Hello World", “Abdi”,
“WHAT IS YOUR NAME”, etc.
 The range or length of the string can change during the execution of the program.
 The size which is allocated to the string value in the computer memory to store it can change
during the execution of the program

1.8 Identifier

Definition:

Identifier is a name given to a variable, constant…..etc.

1.9 Declaration

Definition:

Declaration means assigning A NAME or GIVING A NAME TO a CONSTANT & a


VARIABLE or VALUE. That value can be a number, character, string (text or collection of
characters),…etc.

1.10 Variables

Definition:

It’s the quantity which may change during the execution of a programme & IT’S NOT
CONSTANT. The variable can be integer, float, character, string…..etc.

Variables play an important role in computer programming because they enable programmers
to write flexible programs. Rather than entering data directly into a program, a programmer can
use variables to represent the data. Then, when the program is executed, the variables are
replaced with real data. This makes it possible for the same program to process different sets of
data.

Every variable has a name, called the variable name, and a type called data type. A variable's
data type indicates what sort of value the variable represents, such as whether it is an integer, a
floating-point number, or a character.

In general there are two types of variables:

Variable (mathematics): a symbol that stands for a value that may vary

Variable (programming): a symbolic name associated with a value and whose associated
value may be changed.

www.gollisuniversity.org Page 16
Fundamental of Programming Language (C++) Gollis University

1.11 Constants

Definition:

The opposite of a variable is a constant. Constants are values that never change remains
always constant. Because of their inflexibility, constants are used less often than variables in
programming.

Definition 2:

It’s the quantity which cannot change during the execution of a programme.

1.12 Operators

Definition:

Once we know of the existence of variables and constants, we can begin to operate
with them. For that purpose, C++ integrates operators. Unlike other languages whose operators
are mainly keywords, operators in C++ are mostly made of signs that are not part of the alphabet
but are available in all keyboards. This makes C++ code shorter and more international, since it
relies less on English words, but requires a little of learning effort in the beginning.

Assignment (=)

Definition:

The assignment operator assigns a value to a variable.

a = 5;

This statement assigns the integer value 5 to the variable a. The part at the left of the
assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue (right
value). The lvalue has to be a variable whereas the rvalue can be a constant, a variable, the result
of an operation or any combination of these. The most important rule when assigning is the
right-to-left rule: The assignment operation always takes place from right to left, and never the
other way:

a = b;

This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue).
The value that was stored until this moment in and is not considered at all in this operation, and
in fact that value is lost.

Arithmetic operators (+, -, *, /, %)

www.gollisuniversity.org Page 17
Fundamental of Programming Language (C++) Gollis University

The five arithmetical operations supported by C++ language are

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo

Operations of addition, subtraction, multiplication and division literally correspond with their
respective mathematical operators. The only one that you might not be so used to see is
modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the
remainder of a division of two values. For example, if we write:

a = 11 % 3;
The variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3.

Increase and decrease (++, --)

Shortening even more some expressions, the increase operator (++) and the decrease
operator (--) increase or reduce by one the value stored in a variable. They are equivalent to
+=1 and to -=1, respectively. Thus:

c++;
c+=1;
c=c+1;

Are all equivalent in its functionality: the three of them increase by one the value of c.

A characteristic of this operator is that it can be used both as a prefix and as a suffix. That
means that it can be written either before the variable identifier (++a) or after it (a++). In the
case that the increase operator is used as a prefix (++a) the value is increased before the result of
the expression is evaluated and therefore the increased value is considered in the outer
expression; in case that it is used as a suffix (a++) the value stored in a is increased after being
evaluated and therefore the value stored before the increase operation is evaluated in the outer
expression. Notice the difference:

www.gollisuniversity.org Page 18
Fundamental of Programming Language (C++) Gollis University

Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B contains 4

In Example 1, B is increased before its value is copied to A. While in Example 2, the value of
B is copied to A and then B is increased.

Relational and equality operators (==, !=, >, <, >=, <=)

In order to evaluate a comparison between two expressions we can use the relational and
equality operators. The result of a relational operation is a Boolean value that can only be true or
false, according to its Boolean result.

We may want to compare two expressions, for example, to know if they are equal or if one is
greater than the other is. Here is a list of the relational and equality operators that can be used in
C++:

= Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Here there are some examples:

(7==5) // evaluates to false


(5>4) // evaluates to true
(3!=2) // evaluates to true
(6>=6) // evaluates to true

www.gollisuniversity.org Page 19
Fundamental of Programming Language (C++) Gollis University

Logical operators (!, &&, ||)

The operator! is the C++ operator to perform the Boolean operation NOT, it has only one operand,
located at its right, and the only thing that it does is to inverse the value of it, producing false if its
operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of
evaluating its operand.

For example:

!(6>=6) // evaluates to false

The logical operators && and || are used when evaluating two expressions to obtain a single
relational result. The operator && corresponds with Boolean logical operation AND. This operation
results true if both its two operands are true and false otherwise. The following panel shows the result
of operator && evaluating the expression a && b:

For example:

( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false ).


( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false ).

Conditional operator (?)

The conditional operator evaluates an expression returning a value if that expression is true and a
different one if the expression is evaluated as false. Its format is:

condition ? result1 : result2

If condition is true the expression will return result1, if it is not it will return result2.

7==5 ? 4:3 // returns 3, since 7 is not equal to 5.

7==5+2 ? 4:3 // returns 4, since 7 is equal to 5+2.

5>3 ? a:b // returns the value of a, since 5 is greater than 3.

a>b ? a:b // returns whichever is greater, a or b.

www.gollisuniversity.org Page 20
Fundamental of Programming Language (C++) Gollis University

Comma operator ( , )

The comma operator (,) is used to separate two or more expressions that are included where only
one expression is expected. When the set of expressions has to be evaluated for a value, only the
rightmost expression is considered.

For example:

The following code:

a = (b=3, b+2);
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would
contain the value 5 while variable b would contain value 3.

1.13 Keywords or Commands

Definition:

Keywords are reserved words or PROGRAMMING COMMANDS. It has predefined


meaning & it cannot be used as user defined name; that means it cannot be assigned by the user.
A command is a text-based interface which allows someone to interact with a system or computer
via a command line, which allows the user to type commands and hit “enter” to execute them. Each &
every programming language has its own commands or command words to help in doing the necessary
tasks.

So some of the BASIC COMMANDS are INPUT & OUT PUT commands & they are:

 cin >> it is used to get the inputs from the user.


 cout<< it is used to display the outputs to the user on the screen.

► To be able to use the above INPUT & OUTPUT commands you need to USE & WRITE
THE HEADER FILE at the beginning of your program AT THE TOP:
#include <iostream>

IMPORTANT:

►That is because the #include <iostream> activates the INPUT & OUTPUT commands that
we are using.
► I (stands for INPUT command) ; O (stands for OUTPUT command) & STREAM

www.gollisuniversity.org Page 21
Fundamental of Programming Language (C++) Gollis University

IMPORTANT NOTE:

We cannot write a C++ PROGRAMME WITHOUT USING COMMANDS BECAUSE IF WE


ARE NOT USING COMMANDS THEN WE ARE NOT ASKING THE COMPUTER TO DO SOME
THING or SOME TASK. COMMAND MEANS IMPOSING A WORK or TASK THAT HAS TO BE
DONE BY THE COMPUTER BY THE USER or PROGRAMMER.

Here below are some simple & short C++ PROGRAMMES by using only INPUT & OUTPUT commands:

Programme No: 1

The source code of the programme does the following:

THE MAIN TASK OF THE PROGRAMME IS TO display any text or statement given by the
user by using:

 This programme uses only OUTPUT COMMANDS & another command for a NEW
LINE COMMAND & then displays a statement given by the user; what ever was that
statement or statements it just displays it.

So here is the SOURCE CODE of the programme:

#include <iostream>

Void main()
{
cout << "HELLO MY DEAR FRIEND!" << endl;
}

Programme No: 2

The source code of the programme does the following:

THE MAIN TASK OF THE PROGRAMME IS TO ADD TWO NUMBERS TOGETHER by


using:

 This programme uses only OUTPUT COMMANDS & another command for a NEW
LINE COMMAND & then displays a statement given by the user; what ever was that
statement it just displays it.
 It performs an arithmetic addition operation of two numbers & then displays the
result on the screen.

www.gollisuniversity.org Page 22
Fundamental of Programming Language (C++) Gollis University

So here is the SOURCE CODE of the programme:

#include <iostream>
Void main()
{
int a = 5;
int b = 10;
int x;
int z;
x = a + b;
z=a*b;
cout << "The current value of x is: " << x << endl;
cout << "The current value of z is: " << z << endl;
}

Programme No: 3

The source code of the programme does the following:

The main task of the programme is to add two numbers together by using:

 This programme uses only OUTPUT COMMANDS & another command for a NEW
LINE COMMAND & then displays a statement given by the user; what ever was that
statement it just displays it.
 It performs an arithmetic addition operation of two numbers & then displays the
result on the screen.
 THE ONLY DIFFERENCE BETWEEN THE PREVIOUS PROGRAMME & THIS
ONE IS THAT WE ARE USING A LOT OF COUT<< STATEMENTS ; THAT
MEANS WE ARE DISPLAYING MANY STATEMENTS ON THE SCREEN
ONLY.

So here is the SOURCE CODE of the programme:

#include <iostream>
Void main()
{
int a = 5;
int b = 10;
int x;
int z;

cout << " HELLO MY DEAR FRIEND!" << endl;


cout << "we are going to make a simple calculation below" << endl;
cout << "--------------------------------------------------------" << endl;

www.gollisuniversity.org Page 23
Fundamental of Programming Language (C++) Gollis University

x = a + b;
z=a*b;

cout << "The current value of x after addition is = " << x << endl;
cout << "The current value of z after multiblication is = " << z << endl;
cout << "the programme is finished" << endl;
cout << "thank you" << endl;
}

Programme No: 4

The source code of the programme does the following:

The main task of the programme is to add two numbers together but here we are getting the two
numbers from the user so the user has to enter the two numbers by himself the so steps are:

 This programme uses only OUTPUT COMMANDS; INPUT COMMANDS &


another command for a NEW LINE COMMAND; then displays a statement given by
the user; what ever was that statement it just displays it.
 It performs an arithmetic addition operation of two numbers THAT ARE ENTERD
BY THE USER & then displays the result on the screen.

So here is the SOURCE CODE of the programme:

#include <iostream>
void main()
{

int a ;
int b ;
int x;
int z;

cout << " HELLO MY DEAR FRIEND!" << endl;


cout << " " << endl;
cout << "WE ARE GOING TO MAKE A SIMPLE CALCULATION BELOW" << endl;
cout << "--------------------------------------------------------" << endl;
cout << "ENTER THE FIRST NUMBER " ;
cin >> a;
cout << "ENTER THE SECOND NUMBER " ;
cin >> b;

www.gollisuniversity.org Page 24
Fundamental of Programming Language (C++) Gollis University

x = a + b;
z=a*b;

cout << "THE CURRENT VALUE OF X AFTER ADDITION IS = " << x << endl;
cout << "THE CURRENT VALUE OF Z AFTER MULTIBLICATION IS = " << z << endl;
cout << " " << endl;
cout << "THE PROGRAMME IS FINISHED" << endl;
cout << " " << endl;
cout << "THANK YOU" << endl;
}

www.gollisuniversity.org Page 25
Fundamental of Programming Language (C++) Gollis University

2.1 Introduction

2.2 Selection structure (also called branching)

2.3 Looping structure (also called iteration or repetition)

2.4 Statements

2.5 Break and Continue Statements

www.gollisuniversity.org Page 26
Fundamental of Programming Language (C++) Gollis University

CHAPTER 2: CONTROL STATEMENT

2.1 Introduction

Control statement also called flow of control.

The control statements are used to alter the sequence of the programme execution.

The control statements can be classified as follows:

 Sequence structure (straight line).


 Selection structure (also called branching).
 Looping structure (also called iteration or repetition).

2.2 Selection structure (also called branching):

The selection structure is used to alter the sequence of the programme execution. Branching is
deciding what actions to take and looping is deciding how many times to take a certain action. Branching is
so called because the program chooses to follow one branch or another.

There are two types of selection structure they are:

a. Unconditional control.
b. Conditional control.

a. Unconditional control:

The unconditional control statement is used to transfers the control without checking any condition.
Example: goto statement. Or goto command.

The goto statement is used to transfer the control without checking any condition.

Example programme:

#include<iostream>
void main()
{
cout<<"hellow1"<<endl;
goto ab; ► label name is ab
cout<<"hellow2"<<endl;
cout<<"hellow3"<<endl;
cout<<"hellow4"<<endl;
ab:cout<<"hellow5"<<endl;
cout<<"hellow6"<<endl;
cout<<"hellow7"<<endl;
}

www.gollisuniversity.org Page 27
Fundamental of Programming Language (C++) Gollis University

The format is goto label;


That label should start with alphabet & end with semicolon.
Then where ever we want to transfer the control in that place put the goto label;

b. Conditional control statements:

The conditional control statements are used to alter the sequence of the programme execution after
checking a condition.

The if-else statement or command; it checks the condition first. If the condition is true then it performs
some set of statements else it performs another set of statements.

There are two types of conditional control statements they are:

 If statements.
 Switch statement.
The if statements are as follows:

I. If statement:

Format is as follows:

If (condition)

Statement or statements

II. If-else statement:

Format is as follows:

If (condition)

Statement or statements

else

Statement or statements

www.gollisuniversity.org Page 28
Fundamental of Programming Language (C++) Gollis University

III. Nested if-else statements:

Format is as follows:

If (condition)

Statement or statements

Else

If (condition)

Statement or statements

else

Statement or statements

This is the simplest form of the branching statements.

It takes an expression in parenthesis and a statement or block of statements. If the expression is true then
the statement or block of statements gets executed otherwise these statements are skipped.

NOTE:

Expression will be assumed to be true if its evaluated values are non-zero.

www.gollisuniversity.org Page 29
Fundamental of Programming Language (C++) Gollis University

Programme 1:

#include <iostream>
void main()
{
float q;
float w;
float e;
float r;
float t;

cout<<"the sum will be displayed only if it's more than or equal to 100"<<endl;
cout << "ENTER THE FIRST NUMBER Q " ;
cin >> q;
cout << "ENTER THE SECOND NUMBER W " ;
cin >> w;
cout << "ENTER THE THIRD NUMBER E " ;
cin>>e;

r=q+w+e;
t=q*w*e;
if(r>=100)

{
cout << "THE CURRENT VALUE OF r AFTER ADDITION IS = " << r << endl;
}
cout << "THE CURRENT VALUE OF t AFTER MULTIBLICATION IS = " << t << endl;
}

Programme 2:

#include <iostream>

void main()
{
float q;
float w;
float e;
float r;
float t;

cout<<"the sum will be displayed only if it''s more than or equal to 100"<<endl;
cout << "ENTER THE FIRST NUMBER A " ;
cin >> q;
cout << "ENTER THE SECOND NUMBER W " ;
cin >> w;
cout << "ENTER THE THIRD NUMBER E " ;
cin>>e;
r=q+w+e;
t=q*w*e;

www.gollisuniversity.org Page 30
Fundamental of Programming Language (C++) Gollis University

if(r>=100)
{
cout << "THE CURRENT VALUE OF r AFTER ADDITION IS = " << r << endl;
}
else
{
cout << "THE SUM IS LESS THAT 100 ; THE SUM= " << r << endl;
}
cout << "THE CURRENT VALUE OF t AFTER MULTIBLICATION IS = " << t << endl;
}

Programme 3:

#include <iostream>

void main()
{
float q;
float w;
float e;
float r;
float t;

cout<<"the sum will be displayed only if it''s more than or equal to 100"<<endl;
cout << "ENTER THE FIRST NUMBER A " ;
cin >> q;
cout << "ENTER THE SECOND NUMBER W " ;
cin >> w;
cout << "ENTER THE THIRD NUMBER E " ;
cin>>e;

r=q+w+e;
t=q*w*e;

if(r>100)
{
cout << "THESUM IS GREATER THAN 100; CURRENT VALUE OF r AFTER ADDITION
IS = "
<< r << endl;
}
else if(r==100)
{
cout << "THE SUM IS EQUAL TO 100 ; THE SUM= " << r << endl;
}
else
{
cout << "THE SUM IS LESS THAN 100 ; THE SUM= " << r << endl;
}
cout << "THE CURRENT VALUE OF t AFTER MULTIBLICATION IS = " << t << endl;
}

www.gollisuniversity.org Page 31
Fundamental of Programming Language (C++) Gollis University

Logic Operators:

► && with this operator both the options and conditions should be true.
► || with this operator any one of the options or conditions should be true but not both of
them.

Programme example:

This programme is to find out the greatest number among three numbers.

#include<iostream>

void main()
{
float a,b,c;
cout<<"ENTER THE NUMBERS TO FIND OUT THE GREATES NUMBER AMONG
THEM"<<endl;
cout<<"enter the first number";
cin>>a;
cout<<"enter the second number";
cin>>b;
cout<<"enter the third number";
cin>>c;
if((a>b)&&(a>c))
{
cout<<a<<" the first number is the greatest number";
}
else if((b>a)&&(b>c))
{
cout<<b<<" the second number is the greatest number";
}
else
{
cout<<c<<" the third number is the greatest number";
}
}

www.gollisuniversity.org Page 32
Fundamental of Programming Language (C++) Gollis University

Switch-case statement:

It is a control statement which is used to select one of the available multiple choices.

Switch statement format is as follows:

Switch(expression or option)
{
Case 0:
statement or statements;
break;
Case 1:
statement or statements;
break;
Case 2:
statement or statements;
break;
.
.
.
Case N :

statement or statements;
break;
Default:
statement or statements;
}

A programme example:

This programme allows the user to select any on of the available choices.

#include <iostream>

void main()
{
int a;
cout << "Enter a number between 1-5: ";
cin >> a;
switch (a)
{
case 0: cout << "try later & enter any number between 1-5";
break;
case 1: cout << "programme1";
break;
case 2: cout << "programme2";
break;

www.gollisuniversity.org Page 33
Fundamental of Programming Language (C++) Gollis University

case 3: cout << "programme3";


break;
case 4: cout << "programme4";
break;
case 5: cout << "programme5";
break;
default: cout << "you have entered large number so please enter any number between 1-5";
}
}

2.2 Looping structure (also called iteration or repetition).

In the looping statements a group of statements are executed repeatedly until some condition has
been satisfied.

There are three types of looping structure statements or commands they are:

a. For loop statement.

b. While do loop statement.

c. Do while loop statement

a. For statement:

This is a conditional control structure statement which is used to execute a


statement or a group of statement s for a fixed number of times.

The format of for looping statement or command:

for( initial value; condition; increments / decrements)

{
Statement or statements;
}

Here the initial value is fixed first, this is the starting value. If the condition is satisfied then it
goes for increment or decrement .Then it performs the statement or statements. After performing the
statements it will go for condition again; then if the condition is satisfied then it goes increment or
decrement; then it performs the statement or statements & so no it repeats the process (loop) until the
condition is not satisfied then it exits the loop.

www.gollisuniversity.org Page 34
Fundamental of Programming Language (C++) Gollis University

A programme example:

This programme calculates the sum of 10 numbers by using the for loop statement.

#include <iostream>

void main()
{
float i;
float b;
float sum=0;

cout<<" ENTER ANY 10 NUMBERS TO CALCULATE THEIR SUM or TOTAL"<<endl;


for(i=1;i<=10;i++)
{
cout<<" ENTER THE NUMBER ";
cin>>b;
sum=sum+b;
}
cout<<" THE SUM = "<<sum<<endl;
cout<<"THE PROGRAMME IS FINISHED";
}

b. While Do statement:

The WHILE DO statement which is also called ENTRY CONTROL STATEMNT. The WHILE
DO statement is used to carry out the looping operation, in which a group of statements will be
executed repeatedly until some conditions has been satisfied.

The format of while do looping statement:

while (condition)
{
Statement or statements;
Increments or decrements
}

www.gollisuniversity.org Page 35
Fundamental of Programming Language (C++) Gollis University

A programme example:

A programme to find out the total of 10 numbers by using while do statement.

#include <iostream>

void main()
{
float i=1;
float b;
float sum=0;

cout<<" ENTER ANY 10 NUMBERS TO CALCULATE THEIR SUM or TOTAL"<<endl;


while(i<=10)
{
cout<<" ENTER THE NUMBER ";
cin>>b;
sum=sum+b;
i++;
}
cout<<" THE SUM = "<<sum<<endl;
cout<<"THE PROGRAMME IS FINISHED";
}

The while statement first checks the condition, If the condition is true this will execute a
statement or a group of statements. After executing the statements then it will increment or decrement the
counter element then it will go back to the condition if the condition is true then it will execute the
statements again and so on….. until the condition is not satisfied & then it exits the while loop structure.

c. do-while statement:

The DO-WHILE statement which is also called EXIT CONTROL STATEMNT. The DO-WHILE
statement is used to carry out the looping operation, in which a group of statements will be
executed repeatedly until some conditions has been satisfied.

The format of do-while looping statement:

do
{
Statement or statements;
Increments or decrements;
}
while (condition);

www.gollisuniversity.org Page 36
Fundamental of Programming Language (C++) Gollis University

A programme example:

A programme to find out the total of 10 numbers by using do while statement.

#include <iostream>

void main()
{
float i=1;
float b;
float sum=0;

cout<<" ENTER ANY 10 NUMBERS TO CALCULATE THEIR SUM or TOTAL"<<endl;


do
{
cout<<" ENTER THE NUMBER ";
cin>>b;
sum=sum+b;
i++;
}while(i<=10);
cout<<" THE SUM = "<<sum<<endl;
cout<<"THE PROGRAMME IS FINISHED";
}

The do-while statement first will execute the statement or a group of statements. Then it will
increment or decrement the counter element value then it will go to the condition if the condition is true
then it will execute the statement or a group of statements again then it will increment or decrement the
counter element value again then it will go to the condition; if the condition is true then it will execute the
statements & so on…….until the condition is not satisfied then it exits the do-while loop structure.

The difference between the WHILE-DO & DO-WHILE statements are:

 While-do statements:

 It checks the condition at the beginning of the loop (entry control statement).
 If the condition is false it will not execute any statement.

 do-while statements:

 It checks the condition at the end of the loop (exit control statement).
 If the condition is true or false it will execute the statement at least once.

www.gollisuniversity.org Page 37
Fundamental of Programming Language (C++) Gollis University

Nested Loops

DIFFINTION:

Nested loops mean a loop inside another loop. Here in same way we use any one of the looping
commands (for command, while command, do-while command).

A programme example:

A programme to display a given statement for six times by using two nested loops, here we cane use
any one of the looping commands.

#include<iostream.>

void main()
{
int i,j;
for(i=1;i<=3;i++)
{
for(j=1;j<=i;j++)
{
cout<<"HELLOW. "<<endl;
}
}
cout<<" the programme is finished ";
}

Note:

Here we can use any one of the looping commands to write such a programme, such as for, while, do-
while.

2.4 Statements

Definition:

C++ statements are the program elements that control how and in what order objects are
manipulated. This section includes:

****C++ statements are executed sequentially, except when an expression statement, a selection
statement, an iteration statement, or a jump statement specifically modifies that sequence*****

www.gollisuniversity.org Page 38
Fundamental of Programming Language (C++) Gollis University

Program No 1:

#include <iostream>
void main()
{
cout << "HELLO MY DEAR FRIEND!" << endl;
}

Programme No: 2

#include <iostream>
int main()
{
int a = 5;
int b = 10;
int x;
int z;
x = a + b;
z=a*b;
cout << "The current value of x is: " << x << endl;
cout << "The current value of z is: " << z << endl;
return 0;
}

Program No 3:

#include <iostream.h>
int main()
{
int a = 5;
int b = 10;
int x;
int z;
cout << " HELLO MY DEAR FRIEND!" << endl;
cout << " " << endl;
cout << "we are going to make a simple calculation below" << endl;
cout << "--------------------------------------------------------" << endl;
x = a + b;
z=a*b;
cout << "The current value of x after addition is = " << x << endl;
cout << "The current value of z after multiplication is = " << z << endl;
cout << " " << endl;
cout << "the programme is finished" << endl;
cout << " " << endl;
cout << "thank you" << endl;
return 0;
}

www.gollisuniversity.org Page 39
Fundamental of Programming Language (C++) Gollis University

Program No 4:

#include <iostream>
int main()
{
int a ;
int b ;
int x;
int z;

cout << " HELLO MY DEAR FRIEND!" << endl;


cout << " " << endl;
cout << "we are going to make a simple calculation below" << endl;
cout << "--------------------------------------------------------" << endl;
cout << "Enter the first number " ;
cin >> a;
cout << "Enter the second number " ;
cin >> b;

x = a + b;
z=a*b;

cout << "The current value of x after addition is = " << x << endl;
cout << "The current value of z after multiblication is = " << z << endl;
cout << " " << endl;
cout << "the programme is finished" << endl;
cout << " " << endl;
cout << "thank you" << endl;
return 0;
}

2.5 Break and continue Statements

In addition to the selection and repetition statements, C++ provides statements break and continue to
alter the flow of control. The preceding section showed how break can be used to terminate a switch
statement's execution. This section discusses how to use break in a repetition statement.

Break Statement

The break statement, when executed in a while, for, do...while or switch statement, causes immediate
exit from that statement. Program execution continues with the next statement. Common uses of the
break statement are to escape early from a loop or to skip the remainder of a switch statement.

www.gollisuniversity.org Page 40
Fundamental of Programming Language (C++) Gollis University

Example programme:

#include <iostream>
int main()
{
int count;
for ( count = 1; count <= 10; count++ )
{
if ( count == 5 )
break;
cout << count << " ";
}
cout << "\nBroke out of loop at count = " << count << endl;
return 0;
}

Continue Statement

The continue statement, when executed in a while, for or do...while statement, skips the remaining
statements in the body of that statement and proceeds with the next iteration of the loop. In while and
do...while statements, the loop-continuation test evaluates immediately after the continue statement
executes. In the for statement, the increment expression executes, then the loop-continuation test
evaluates.

Example programme:

#include <iostream>
int main()
{
int count;
for ( count = 1; count <= 10; count++ )
{
if ( count == 5 )
continue;
cout << count << " ";
}
cout << "\nBroke out of loop at count = " << count << endl;
return 0;
}

www.gollisuniversity.org Page 41
Fundamental of Programming Language (C++) Gollis University

3.1 Introduction

3.2 Declarations of functions

3.3 Defining function prototype

3.4 Scope of variables

3.5 Functions that return values

3.6 Math library functions

3.7 Recursion

3.8 Summary

www.gollisuniversity.org Page 42
Fundamental of Programming Language (C++) Gollis University

CHAPTER 3: FUNCTIONS and RECURSION

3.1 Introduction

C++ allows programmers to define their own functions. So Developers often need the ability to break
programs up into smaller chunks (parts) that are easier to develop & follow in the case of the large
programs. Functions help us to classify our programs to the necessary parts.

"Real world" programs can be many of thousands (or millions!) of lines long. Without this ability to
divide the program into parts, developing such large programs would quickly become impossible.

C++ allows programmers to divide their code up into chunks (parts) known as functions. A function
with a simple description and a well-defined interface to the outside world can be written and debugged
without worrying about the code that surrounds it.

A function:

which can also be referred to as subroutine, procedure, subprogram or even method, carries out
tasks defined by a sequence of statements called a statement block that need only be written once and
called by a program as many times as needed to carry out the same task.

Function:

is a another part of code written out side the main function thus creating a subprogram, the main
function will be the first to work then the functions will work next , the functions has t be called by the
main programme so then it can work.

Functions may depend on variables passed to them, called arguments or parameters, and may pass
results of a task on to the main function of the function, this is called the return value.

It is important to note that a function that exists in the global scope can also be called global function
and a function that is defined inside a class is called a member function. (The term method is commonly
used in other programming languages to refer to things like functions, but this can lead to dealing with
C++ which supports functions.)

3.2 Declarations of functions:

A function must be declared before being used, with a name to identify it, what type of value the
function returns and the types of any arguments or values that are to be passed to it. Parameters must be
named and declare what type of value it takes. Parameters should always be passed as constant if their
arguments are not modified. Usually functions perform actions, so the name should make clear what it
does. By using values in function names and following other naming conventions programs can be read
more naturally.

www.gollisuniversity.org Page 43
Fundamental of Programming Language (C++) Gollis University

The next example we defines a function named add that returns no value and takes no parameters or
value.

The content of the function is called the body of the function. The word void is a keyword. C++
keywords are reserved words, so cannot be used for any purpose other than what they are meant for. On
the other hand it means that the function will return no value or the main function will return no value.

3.3 Defining function prototypes (example):

A function may be defined anywhere in the module or source code or programme. (A module is
another name for a C++ source file.) However, something has to tell main() the full name of the
function before it can be called. Consider the following code example:

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

Function_type function-name (parameter-list)

{
local variables definitions;
………..
………..

function-implementation or function statements of code;


……….
………..
………..

Explanation:

1. If the function returns a value then the type of that value must be specified in function-type. For
the moment this could be int, float or char.
2. If the function does not return a value then the function-type must be void.
3. The function-name follows the same rules of composition as identifiers or variable.
4. The parameter-list lists the formal parameters of the function together with their types.
5. The local-definitions are definitions of variables that are used in the function-implementation.
These variables have no meaning outside the function.
6. The function-implementation consists of C++ executable statements that implement the effect of
the function.

www.gollisuniversity.org Page 44
Fundamental of Programming Language (C++) Gollis University

#include<iostream>
void fun1(); declaring the function(function name & type)
void main() the main function will work first
{
cout<<"THIS IS MAIN FUNCTION "<<endl;
cout<<"calling the function."<<endl;
fun1(); calling the function
cout<<"control is back to main function.";
}

void fun1() function code or function definition


{
cout<<"this is from the function one"<<endl;
} (returning the control back to main)

Programme No 1:

This programme is to find the addition of three numbers by using functions so the operations are
performed within function:

#include<iostream>
void add(); // function type & name this function returns no value
void main()
{
cout<<"THIS IS MAIN FUNCTION "<<endl;
cout<<"starting the addition now."<<endl;
add(); // calling the function or starting the function
cout<<"control is back to main function."<<endl;
cout<<"the programme is finished"<<endl;
}
void add() // the function code or function definition
{
int a,b,c,d;
cout<<"enter the number : ";
cin>>a;
cout<<"enter the number :";
cin>>b;
cout<<"enter the number :";
cin>>c;
d=a+b+c;
cout<<"the total is "<<d<<endl;
cout<<"this is from the function one"<<endl<<endl<<endl;
}

www.gollisuniversity.org Page 45
Fundamental of Programming Language (C++) Gollis University

Programme No 2:

This programme is to find the addition; subtraction & multiplication of three numbers by using
functions so every one of the operations are performed within different function:

#include<iostream>
void add(); // function type & name this function returns no value
void sub(); // function type & name this function returns no value
void mul(); // function type & name this function returns no value
void main()

{
cout<<"addttion"<<endl;
add(); // calling the function or starting the function
cout<<"subtraction."<<endl;
sub(); // calling the function or starting the function
cout<<"multiblication."<<endl;
mul(); // calling the function or starting the function
cout<<"the programme is finished."<<endl;
}
void add() // the function code or function definition
{
int a,b,c,add;
cout<<"enter the number : ";
cin>>a;
cout<<"enter the number : ";
cin>>b;
cout<<"enter the number : ";
cin>>c;
add=a+b+c;
cout<<" add = "<<add<<endl;
}
void sub() // the function code or function definition
{
int a,b,c,sub;
cout<<"enter the number : ";
cin>>a;
cout<<"enter the number : ";
cin>>b;
cout<<"enter the number : ";
cin>>c;
sub=a-b-c;
cout<<" sub = "<<sub<<endl;
}
void mul() // the function code or function definition
{
int a,b,c,mul;
cout<<"enter the number : ";
cin>>a;
cout<<"enter the number : ";

www.gollisuniversity.org Page 46
Fundamental of Programming Language (C++) Gollis University

cin>>b;
cout<<"enter the number : ";
cin>>c;
mul=a*b*c;
cout<<" mul = "<<mul<<endl;
}

Programme No 3:

This programme is to:

 Find the addition of 7 different numbers given by the user within separate function.
 Display & perform the following list:

 Addition.
 Multiplication.

By using functions so every one of the operations are performed within different function.

#include<iostream>
void list(); // function type & name
void loop(); // function type & name
void main()

{
cout<<"list"<<endl;
list(); // starting the function
cout<<"addtion of 7 numbers"<<endl;
cout<<endl;
loop(); // starting the function
cout<<"the programme is finished."<<endl;
}
void list() // the function code or function definition
{
int w,a,b,add,mul;
cout<<"1-addtion."<<endl;
cout<<"2-multiblication."<<endl;
cout<<"enter your choice : ";
cin>>w;
switch(w)
{
case 1:
cout<<"enter the number : ";
cin>>a;
cout<<"enter the number : ";
cin>>b;
add=a+b;

www.gollisuniversity.org Page 47
Fundamental of Programming Language (C++) Gollis University

cout<<" add= "<<add<<endl;


break;
case 2:
cout<<"enter the number : ";
cin>>a;
cout<<"enter the number : ";
cin>>b;
mul=a*b;
cout<<" mul = "<<mul<<endl;
break;
default:
cout<<"please enter any numbers between (1-2)"<<endl;
}
}
void loop() // the function code or function definition
{
int i,b,sum=0;
for(i=1;i<=7;i++)
{
cout<<"enter the number : ";
cin>>b;
sum=sum+b;
}
cout<<" sum= "<<sum<<endl;
}

3.4 Scope of Variables:

All the variables that we intend to use in a program must have been declared with its block.
A variable can be either of global or local scope. A global variable is a variable declared in the
main body of the source code, outside all functions, while a local variable is one declared within the
body of a function or a block like if, switch, loop, etc.

Global variables can be referred (used) from anywhere in the code, even inside functions,
whenever it is after its declaration.

The scope of local variables is limited to the block enclosed in braces { } where they are declared.
For example, if they are declared at the beginning of the body of a function (like in function main) their
scope is between its declaration point and the end of that function.

www.gollisuniversity.org Page 48
Fundamental of Programming Language (C++) Gollis University

In the example above, this means that if another function existed in addition to main, the local
variables declared in main could not be accessed from the other function and vice versa.

 Global Variables:

Definition:

The global variables are the variables that can be used any where through out the entire

programme & in any block.

 Local Variables:

Definition:

The local variables are the variables that can be used only within its own block & it can’t be

used elsewhere. So that it’s called a local variable. It’s local in that block & it’s known only in

that block.

A programme example:

A programme is shows an example of global & local variables.

#include<iostream>
void main()
{
float a,b; // global variables
cout<<"ENTER THE NUMBERS TO FIND OUT THE GREATES NUMBER AMONG
THEM"<<endl;

cout<<"enter the first number";


cin>>a;
cout<<"enter the second number";
cin>>b;
if (a>b)
{
Int w=100; // local variable with a block
cout<<a<<" the first number is the greatest number";
cout<<w<<endl;
}
else if (b>a)
{
cout<<b<<" the second number is the greatest number";
}
else
{

www.gollisuniversity.org Page 49
Fundamental of Programming Language (C++) Gollis University

cout<<c<<" both the numbers are equal.";


}
}

3.5 Functions that return values:

A function has a list of parameter declarations, a return type, and a block of statements.
Execution must end with a return statement returning an expression that can be converted to the return
type, unless void, in which case there is an implied return; at the end. Arguments passed to a function
must match the parameters or allow implicit conversion (such as int to double). Functions must be
defined before use, or have a matching declaration that replaces the block with a semicolon and may
optionally omit parameter names. Functions are always global (not defined in other functions).

Program example:

#include<iostream>

Int add(int a, int b)

Int r;

r= a+b;

return r;

Void main()

Int z;

Z=add(5,7);

cout<<”the result is =”<<z<<endl;

www.gollisuniversity.org Page 50
Fundamental of Programming Language (C++) Gollis University

Function Body

In order to use a function in your program, you have to let the compiler know what the function
does. To let the compiler know what the function is meant to do, you have to “define” it; which also
means describing its behavior.

The formula to define a function is:

void FunctionName (parameter-list)

Body

You define a function using the rule we applied with the main() function. Define it starting with its
return value (if none, use void), followed by the function name, its argument (if any) between
parentheses, and the body of the function. Once you have defined a function, other functions can use it.
A function has a body. The body of the function describes what the function is supposed to do. The body
starts with an opening curly bracket {and ends with a closing curly bracket }. Everything between these
two symbols belongs to the function. From what we have learned so far, here is an example:
void Message() {};

In the body of the function, you describe the assignment the function is supposed to perform. As simple
as it looks, a function can be used to display a message. Here is an example:
void Message()

cout << "HELLOW.";

A function can also implement a complete behaviour. For example, on a program used to perform
geometric shape calculations, you can use different functions to handle specific tasks. Imagine you want
to calculate the area of a square. You can define a particular function that would request the side of the
square.Calling Functions:

3.6 Math Library Functions

Sometimes functions are not members of a class. Such functions are called global functions. Like a
class's member functions, the function prototypes for global functions are placed in header files, so that
the global functions can be reused in any program that includes the header file and that can link to the

www.gollisuniversity.org Page 51
Fundamental of Programming Language (C++) Gollis University

function's object code. For example, recall that we used function pow of the <cmath> header file to raise
a value to a power in the following figure. We introduce various functions from the <cmath> header file
here to present the concept of global functions that do not belong to a particular class. In this chapter and
in subsequent chapters, we use a combination of global functions (such as main) and classes with
member functions to implement our example programs.

The <cmath> header file provides a collection of functions that enable you to perform common
mathematical calculations. For example, you can calculate the square root of 900.0 with the function call

sqrt( 900.0 )

The preceding expression evaluates to 30.0. Function sqrt takes an argument of type double and returns
a double result. Note that there is no need to create any objects before calling function sqrt. Also note
that all functions in the <cmath> header file are global functions therefore, each is called simply by
specifying the name of the function followed by parentheses containing the function's arguments.

Function arguments may be constants, variables or more complex expressions.

If c = 13.0, d = 3.0 and f = 4.0, then the statement

cout << sqrt( c + d * f ) << endl;

calculates and prints the square root of 13.0 + 3.0 * 4.0 = 25.0 namely, 5.0. Some math library functions
are summarized in. In the figure, the variables x and y are of type double.

Figure 6.2. Math library functions.

Function Description Example


ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0

ceil( -9.8 ) is -9.0


cos( x ) trigonometric cosine of x (x in radians) cos( 0.0 ) is 1.0
exp( x ) exponential function ex exp( 1.0 ) is 2.71828

exp( 2.0 ) is 7.38906


fabs( x ) absolute value of x fabs( 5.1 ) is 5.1

fabs( 0.0 ) is 0.0

fabs( -8.76 ) is 8.76


floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0

www.gollisuniversity.org Page 52
Fundamental of Programming Language (C++) Gollis University

Figure 6.2. Math library functions.

Function Description Example


floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating-point number fmod( 2.6, 1.2 ) is 0.2
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0

log( 7.389056 ) is 2.0


log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0

log10( 100.0 ) is 2.0


pow( x, y ) x raised to power y ( xy ) pow( 2, 7 ) is 128

pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0
sqrt( x ) square root of x (where x is a nonnegative value) sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x (x in radians) tan( 0.0 ) is 0

3.7 Recursion

The programs we have discussed are generally structured as functions that call one another in a
disciplined, hierarchical manner. For some problems, it is useful to have functions call themselves. A
recursive function is a function that calls itself, either directly or indirectly (through another function).

Recursion is an important topic discussed at length in upper-level computer science courses; this
section and the next present simple examples of recursion. This book contains an extensive treatment of
recursion.

We first consider recursion conceptually, then examine two programs containing recursive functions.
Recursive problem-solving approaches have a number of elements in common. A recursive function is
called to solve a problem. The function actually knows how to solve only the simplest case(s), or so-
called base case(s). If the function is called with a base case, the function simply returns a result. If the
function is called with a more complex problem, it typically divides the problem into two conceptual
piecesa piece that the function knows how to do and a piece that it does not know how to do. To make
recursion feasible, the latter piece must resemble the original problem, but be a slightly simpler or
slightly smaller version. This new problem looks like the original problem, so the function launches
(calls) a fresh copy of itself to work on the smaller problem this is referred to as a recursive call and is
also called the recursion step. The recursion step often includes the keyword return, because its result
will be combined with the portion of the problem the function knew how to solve to form a result that
will be passed back to the original caller, possibly main.

www.gollisuniversity.org Page 53
Fundamental of Programming Language (C++) Gollis University

The recursion step executes while the original call to the function is still open, i.e., it has not yet
finished executing. The recursion step can result in many more such recursive calls, as the function
keeps dividing each new sub problem with which the function is called into two conceptual pieces. In
order for the recursion to eventually terminate, each time the function calls itself with a slightly simpler
version of the original problem, this sequence of smaller and smaller problems must eventually
converge on the base case. At that point, the function recognizes the base case and returns a result to the
previous copy of the function, and a sequence of returns ensues all the way up the line until the original
function call eventually returns the final result to main. All of this sounds quite exotic compared to the
kind of "conventional" problem solving we have been using to this point. As an example of these
concepts at work, let us write a recursive program to perform a popular mathematical calculation.

The factorial of a nonnegative integer n, written n! (and pronounced "n factorial"), is the product

n · ( n 1) · ( n 2) · ... · 1

with 1! equal to 1, and 0! defined to be 1. For example, 5! is the product 5 · 4 · 3 · 2 · 1, which is equal
to 120.

The factorial of an integer, number, greater than or equal to 0, can be calculated iteratively (non
recursively) by using a for statement as follows:

factorial = 1;

for ( int counter = number; counter >= 1; counter-- )

factorial *= counter;

A recursive definition of the factorial function is arrived at by observing the following relationship:

n! = n · ( n 1)!

For example, 5! is clearly equal to 5 * 4! as is shown by the following:

5! = 5 · 4 · 3 · 2 · 1

5! = 5 · (4 · 3 · 2 · 1)

5! = 5 · (4!)

The evaluation of 5! would proceed as shown in the following example shows how the succession of
recursive calls proceeds until 1! is evaluated to be 1, which terminates the recursion and also shows the
values returned from each recursive call to its caller until the final value is calculated and returned.

The program uses recursion to calculate and print the factorials of the integers 010. (The choice of the
data type unsigned long is explained momentarily.) The recursive function factorial first determines
whether the terminating condition number <= 1 is true. If number is indeed less than or equal to 1,
function factorial returns 1, no further recursion is necessary and the function terminates. If number is
greater than 1, line 28 expresses the problem as the product of number and a recursive call to factorial
evaluating the factorial of number - 1. Note that factorial ( number - 1 ) is a slightly simpler problem
than the original calculation factorial ( number ).

www.gollisuniversity.org Page 54
Fundamental of Programming Language (C++) Gollis University

A programme example:

#include <iostream>

#include <iomanip>

using std::setw;

unsigned long factorial( unsigned long );

int main()

for ( int counter = 0; counter <= 10; counter++ )

cout << setw( 2 ) << counter << "! = " << factorial( counter )

<< endl;

return 0;

unsigned long factorial( unsigned long number )

if ( number <= 1 )

return 1;

else

return number * factorial( number - 1 );

3.8 Summary

1. A C++ function can return a value. The function must be declared to have the same type as this
value. If the function does not return a value then it must be given the type void.
2. Information is passed into a function via the parameter-list. Each parameter must be given a
type. If not declared to be otherwise then parameters are treated as value parameters
3. If a parameter is a value parameter then the function operates on a copy of the value of the
actual parameter hence the value of the actual parameter cannot be changed by the function.

www.gollisuniversity.org Page 55
Fundamental of Programming Language (C++) Gollis University

4. A function prototype provides information to the compiler about the return type of a function
and the types of its parameters. The function prototype must appear in the program before the
function is used.
5. Any variable declared inside a function is local to that function and has existence and meaning
only inside the function. Hence it can use an identifier already used in the main program or in
any other function without any confusion with that identifier.

www.gollisuniversity.org Page 56
Fundamental of Programming Language (C++) Gollis University

4.1 Definition

4.2 Single dimensional array

4.3 Two dimensional array

www.gollisuniversity.org Page 57
Fundamental of Programming Language (C++) Gollis University

CHAPTER 4: ARRAYS

4.1 Definition:
Arrays are collection of same type of data items which shares the common name.

There are two types of arrays they are:

 Single dimensional arrays.


 Two dimensional arrays.

4.2 Single dimensional array:

Single dimensional array is collection of same type of data items which shares the common name. It
contains array name & single index value.

Format:

Array name [index value];

Programme 1:

A programme to display an ARRAY (single dimensional array) of the size 7, a [7] .

#include <iostream>
void main()
{
int a[ ]={1,2,3,40,50,60,70};
int i;
for(i=0;i<7;i++)
{
cout<<a[i]<<endl;
}}

www.gollisuniversity.org Page 58
Fundamental of Programming Language (C++) Gollis University

Programme 2:

A programme to get an ARRAY (single dimensional array) of the size 10, a [10] . Here the user
enters all the values by him self.

#include <iostream>
void main()
{
int A[10];
int x;
for(x=0;x<10;x++)
{
cout << "Enter the number : " ;
cin>>A[x];
}
cout << "Array in ascending order is : ";
for (x=0;x<10;x++)
{
cout <<endl<<A[x];
}
}

Programme 3:

A programme to get an ARRAY (single dimensional array) of the size 10, a [10] . Here the user
enters all the values by him self & then it adds all the elements together.

#include <iostream>
void main()
{
int sum=0;
int A[10]; // declaring the array
int x;
for(x=0;x<10;x++)
{
cout << "Enter the numbers : ";
cin>>A[x]; // filling the array
}
cout << "Array in ascending order is : ";
cout<<"A = { ";
for (x=0;x<10;x++)
{
cout <<A[x]<<","; // displaying the array
sum=sum+A[x];
}
cout<<"} ";
cout<<" the sume = "<<sum<<endl;
}

www.gollisuniversity.org Page 59
Fundamental of Programming Language (C++) Gollis University

4.3 Two dimensional arrays:

Two dimensional arrays is collection of same type of data items which shares the common name. It
contains array name & two index values.

Format:

Array name [index 1] [index2];

A multidimensional array can be initialized in its declaration much like a one-dimensional array. For
example, a two-dimensional array b with values 1 and 2 in its row 0 elements and values 3 and 4 in its row
1 elements could be declared and initialized with

int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };

The values are grouped by row in braces. So, 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ], respectfully, and
3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ], respectfully. If there are not enough initializers for a given row,
the remaining elements of that row are initialized to 0. Thus, the declaration

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };

initializes b[ 0 ][ 0 ] to 1, b[ 0 ][ 1 ] to 0, b[ 1 ][ 0 ] to 3 and b[ 1 ][ 1 ] to 4.

The following program demonstrates initializing two-dimensional arrays in declarations. declare three
arrays, each with two rows and three columns.

www.gollisuniversity.org Page 60
Fundamental of Programming Language (C++) Gollis University

Initializing multidimensional arrays:


#include <iostream>
void printArray( const int [][ 3 ] ); // prototype
int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };

cout << "Values in array1 by row are:" << endl;


printArray( array1 );

cout << "\nValues in array2 by row are:" << endl;


printArray( array2 );

cout << "\nValues in array3 by row are:" << endl;


printArray( array3 );
return 0;
}

void printArray( const int a[][ 3 ] )


{
for ( int i = 0; i < 2; i++ )
{
for ( int j = 0; j < 3; j++ )
cout << a[ i ][ j ] << ' ';
cout << endl; // start new line of output
}
}

www.gollisuniversity.org Page 61
Fundamental of Programming Language (C++) Gollis University

5.1 Introduction

5.2 Source file

5.3 Object file

5.4 Application file

www.gollisuniversity.org Page 62
Fundamental of Programming Language (C++) Gollis University

CHAPTER 5: FILES IN C++

5.1 Introduction:

In any C++ programming language there are three types of files that can be associated written by the
user so these files are:

 Source file.
 Compile file or object file.
 Application file.

5.2 Source file:

What is source file?

DEFINITION: Is any collection of c++ statements & commands written in some human-
readable computer programming language.

DEFINITION: Source code is the mechanism most often used by programmers to specify the
actions to be performed by a computer.

Source code refers to the programming language one uses to write a program. There
are hundreds, if not thousands, of forms of source code. Some computer languages include C++, Java, and
Unix. Often people refer to source code of websites, which means programming conducted in HTML and
possibly Java.

5.3 Compile file (object file):

What is compile file?

DEFINITION:

It’s the file that has been compiled by the c++ compiler & converted from high level to low level
language.

What is compiler?

DEFINITION:

A compiler turns the program that you write in high level language into an executable low level
language (binary format) that your computer can actually understand and run.

A compiler is a special type of computer program that translates a human readable text file into a
form that the computer can more easily understand. At its most basic level, a computer can only
understand two things, a 1 and a 0. At this level, a human will operate very slowly and find the
information contained in the long string of 1s and 0s incomprehensible. A compiler is a computer
program that bridges this gap.

www.gollisuniversity.org Page 63
Fundamental of Programming Language (C++) Gollis University

5.4 Application file:

What is Application file?

DEFINITION:

It’s the file that has been activated & runed by the c++ compiler. It’s the file that implements the
commands & statements of the c++ programme to solve the required problems & operations required by
the users.

The practical steps to create the c++ files are as follows:

1-save ,compile & run the c++ programme:

www.gollisuniversity.org Page 64
Fundamental of Programming Language (C++) Gollis University

www.gollisuniversity.org Page 65
Fundamental of Programming Language (C++) Gollis University

2-Save your programme in a separate folder here it’s on the desktop:

www.gollisuniversity.org Page 66
Fundamental of Programming Language (C++) Gollis University

www.gollisuniversity.org Page 67
Fundamental of Programming Language (C++) Gollis University

www.gollisuniversity.org Page 68
Fundamental of Programming Language (C++) Gollis University

www.gollisuniversity.org Page 69
Fundamental of Programming Language (C++) Gollis University

6.1 Definition

6.2 Reference operator (&)

6.3 Dereference operator (*)

6.4 Declaring variables of pointer types

www.gollisuniversity.org Page 70
Fundamental of Programming Language (C++) Gollis University

CHAPTER 6: POINTERS

6.1 Definition:

We have already seen how variables are seen as memory cells that can be accessed using their
identifiers. This way we did not have to care about the physical location of our data within memory, we
simply used its identifier whenever we wanted to refer to our variable.

The memory of your computer can be imagined as a succession of memory cells, each one of the
minimal size that computers manage (one byte). These single-byte memory cells are numbered in a
consecutive way, so as, within any block of memory, every cell has the same number as the previous
one plus one.

This way, each cell can be easily located in the memory because it has a unique address and all the
memory cells follow a successive pattern. For example, if we are looking for cell 1776 we know that it
is going to be right between cells 1775 and 1777, exactly one thousand cells after 776 and exactly one
thousand cells before cell 2776.

6.2 Reference operator (&)

As soon as we declare a variable, the amount of memory needed is assigned for it at a specific
location in memory (its memory address). We generally do not actively decide the exact location of the
variable within the panel of cells that we have imagined the memory to be - Fortunately, that is a task
automatically performed by the operating system during runtime. However, in some cases we may be
interested in knowing the address where our variable is being stored during runtime in order to operate
with relative positions to it.

The address that locates a variable within memory is what we call a reference to that variable. This
reference to a variable can be obtained by preceding the identifier of a variable with an ampersand sign
(&), known as reference operator, and which can be literally translated as "address of". For example:

ted = &andy;

This would assign to ted the address of variable andy, since when preceding the name of the variable
andy with the reference operator (&) we are no longer talking about the content of the variable itself,
but about its reference (i.e., its address in memory).

From now on we are going to assume that andy is placed during runtime in the memory address 1776.
This number (1776) is just an arbitrary assumption we are inventing right now in order to help clarify
some concepts in this tutorial, but in reality, we cannot know before runtime the real value the address
of a variable will have in memory.

Consider the following code fragment:

andy = 25;

fred = andy;

ted = &andy;

www.gollisuniversity.org Page 71
Fundamental of Programming Language (C++) Gollis University

The values contained in each variable after the execution of this, are shown in the following diagram:

First, we have assigned the value 25 to andy (a variable whose address in memory we have assumed to
be 1776).

The second statement copied to fred the content of variable andy (which is 25). This is a standard
assignment operation, as we have done so many times before.

Finally, the third statement copies to ted not the value contained in andy but a reference to it (i.e., its
address, which we have assumed to be 1776). The reason is that in this third assignment operation we
have preceded the identifier andy with the reference operator (&), so we were no longer referring to the
value of andy but to its reference (its address in memory).

The variable that stores the reference to another variable (like ted in the previous example) is what we
call a pointer. Pointers are a very powerful feature of the C++ language that has many uses in advanced
programming. Farther ahead, we will see how this type of variable is used and declared.

6.3 Dereference operator (*)

We have just seen that a variable which stores a reference to another variable is called a pointer.
Pointers are said to "point to" the variable whose reference they store.

Using a pointer we can directly access the value stored in the variable which it points to. To do this, we
simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator
and that can be literally translated to "value pointed by".

Therefore, following with the values of the previous example, if we write:

beth = *ted;

(that we could read as: "beth equal to value pointed by ted") beth would take the value 25, since ted is
1776, and the value pointed by 1776 is 25.

www.gollisuniversity.org Page 72
Fundamental of Programming Language (C++) Gollis University

You must clearly differentiate that the expression ted refers to the value 1776, while *ted (with an
asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25.
Notice the difference of including or not including the dereference operator (I have included an
explanatory commentary of how each of these two expressions could be read):

beth = ted; // beth equal to ted ( 1776 )

beth = *ted; // beth equal to value pointed by ted ( 25 )

Notice the difference between the reference and dereference operators:

• & is the reference operator and can be read as "address of"


• * is the dereference operator and can be read as "value pointed by"

Thus, they have complementary (or opposite) meanings. A variable referenced with & can be
dereferenced with *.

Earlier we performed the following two assignment operations:

andy= 25;

ted = &andy;

Right after these two statements, all of the following expressions would give true as result:

andy == 25

&andy == 1776

ted == 1776

*ted == 25

The first expression is quite clear considering that the assignment operation performed on andy was
andy=25. The second one uses the reference operator (&), which returns the address of variable andy,
which we assumed it to have a value of 1776. The third one is somewhat obvious since the second
expression was true and the assignment operation performed on ted was ted=&andy. The fourth
expression uses the dereference operator (*) that, as we have just seen, can be read as "value pointed
by", and the value pointed by ted is indeed 25.

So, after all that, you may also infer that for as long as the address pointed by ted remains unchanged
the following expression will also be true:

*ted == andy

www.gollisuniversity.org Page 73
Fundamental of Programming Language (C++) Gollis University

6.4 Declaring variables of pointer types

Due to the ability of a pointer to directly refer to the value that it points to, it becomes necessary to
specify in its declaration which data type a pointer is going to point to. It is not the same thing to point
to a char as to point to an int or a float.

The declaration of pointers follows this format:

type * name;

where type is the data type of the value that the pointer is intended to point to. This type is not the type
of the pointer itself! but the type of the data the pointer points to. For example:

int * number;

char * character;

float * greatnumber;

These are three declarations of pointers. Each one is intended to point to a different data type, but in
fact all of them are pointers and all of them will occupy the same amount of space in memory (the size
in memory of a pointer depends on the platform where the code is going to run). Nevertheless, the data
to which they point to do not occupy the same amount of space nor are of the same type: the first one
points to an int, the second one to a char and the last one to a float. Therefore, although these three
example variables are all of them pointers which occupy the same size in memory, they are said to have
different types: int*, char* and float* respectively, depending on the type they point to.

I want to emphasize that the asterisk sign (*) that we use when declaring a pointer only means that it is
a pointer (it is part of its type compound specifier), and should not be confused with the dereference
operator that we have seen a bit earlier, but which is also written with an

asterisk (*). They are simply two different things represented with the same sign.

Now have a look at this code:

#include<iostream>

using namespace std;

int main()

int firstvalue, secondvalue;

int * mypointer;

www.gollisuniversity.org Page 74
Fundamental of Programming Language (C++) Gollis University

mypointer = &firstvalue;

*mypointer = 10;

mypointer = &secondvalue;

*mypointer = 20 ;

cout<<”firstvalue is “<<firstvalue<<endl;

cout<<”secondvalue is”<<secondvalue<<endl;

return 0;

Firstvalue is 10

Secondvalue is 20

Notice that even though we have never directly set a value to either firstvalue or secondvalue, both end
up with a value set indirectly through the use of mypointer. This is the procedure:

First, we have assigned as value of mypointer a reference to firstvalue using the reference operator (&).
And then we have assigned the value 10 to the memory location pointed by mypointer, that because at
this moment is pointing to the memory location of firstvalue, this in fact modifies the value of
firstvalue.

In order to demonstrate that a pointer may take several different values during the same program I have
repeated the process with secondvalue and that same pointer, mypointer.

Here is an example a little bit more elaborated:

#include<iostream>

using namespace std;

int main()

Int firstvalue 5 , secondvalue 15;

Int *p1, *p2;

www.gollisuniversity.org Page 75
Fundamental of Programming Language (C++) Gollis University

P1 = &firstvalue; // p1 = address of firstvalue

P2 = &secondvalue; // p2 = address of secondvalue

*p1 = 10; // value pointed by p1 = 10

*p2 = *p1; // value pointed by p2 = value pointed by p1

P1 = p2; // p1 = p2 (value of pointer is copied)

*p1 = 20; // value pointed by p1 = 20

cout << "firstvalue is " << firstvalue << endl;

cout << "secondvalue is " << secondvalue << endl;

return 0;

I have included as a comment on each line how the code can be read: ampersand (&) as "address of"
and asterisk (*) as "value pointed by".

Notice that there are expressions with pointers p1 and p2, both with and without dereference operator
(*). The meaning of an expression using the dereference operator (*) is very different from one that
does not: When this operator precedes the pointer name, the expression refers to the value being
pointed, while when a pointer name appears without this operator, it refers to the value of the pointer
itself (i.e. the address of what the pointer is pointing to).

Another thing that may call your attention is the line:

nt * p1, * p2;

This declares the two pointers used in the previous example. But notice that there is an asterisk (*) for
each pointer, in order for both to have type int* (pointer to int).

Otherwise, the type for the second variable declared in that line would have been int (and not int*)
because of precedence relationships. If we had written:

int * p1, p2;

p1 would indeed have int* type, but p2 would have type int (spaces do not matter at all for this
purpose). This is due to operator precedence rules. But anyway, simply remembering that you have to
put one asterisk per pointer is enough for most pointer users.

www.gollisuniversity.org Page 76

You might also like