0% found this document useful (0 votes)
20 views

COSC301 Lecture Notes

Java lecture note for 300L computer Sciecne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

COSC301 Lecture Notes

Java lecture note for 300L computer Sciecne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

GOMBE STATE UNIVERSITY

DEPARTMENT OF COMPUTER SCIENCE

OBJECT ORIENTED PROGRAMMING FUNDAMENTALS


AND C++

(COSC301)

LECTURE NOTE 1

Course Lecturer: Muhammad Dawaki


COSC 301 OBJECT ORIENTED PROGRAMMING FUNDAMENTALS AND C++

Credit unit: 3

Lecture duration: 3 hours per week

Laboratory hours: 1 hour per week.

Assessment Breakdown

Number of assessments: 3 assessments equivalent to (40 marks)

1. Assessment 1: Written test which will engulf 20 marks.


2. Assessment 2: Practical test which involves writing and executing C++ program
(20 marks).
3. Assessment 3: Practical group work, were each group would solve a particular
problem using C++ programming language, write a report about their work and
then make a presentation to the class.

Recommended textbooks: see the student handbook for the syllabus and list of
recommended books.

Course Objectives

The learning objectives of this course are:

1. To learn the syntax and semantics of C++ programming language.


2. To understand how C++ improves C with object oriented features.
3. To learn how to design C++ classes for code reuse.
4. To learn how to debug errors in C++ codes.
5. To learn how to apply C++ programming language features in solving real life
problems.

Laboratory Instructions

1. Students are expected to attend all the lab sessions and ensure that they have
attempted all the lab exercises.
2. Students are expected to seek for help from the course lecturer whenever they
encountered any problem while attempting the lab exercises.

© Gombe State Unibversity,2024 email: [email protected] 2


INTRODUCTION TO OBJECT ORIENTED PROGRAMMING PARADIGM

A computer program is a precise sequence of steps to solve a particular computing


problem, hence programming a computer simply means telling the computer what to
do, the instructions are passed to the computer using a specific language which the
computer understands, it is called a programming language. These programming
languages are often classified into several patterns based on their features. Some of
the paradigms include:

1. Procedural or Imperative paradigm.


2. Object Oriented programming paradigm
3. Functional programming paradigm (Declarative)
4. Logical programming paradigm

OBJECT ORIENTED PROGRAMMING (OOP)

The objective of this course is to study the concept of object oriented programming
and how it is applied in C++ programming language, let us dive properly into defining
the concept of object oriented programming (OOP).

Definition of Object-oriented programming (OOP)

Object-oriented programming (OOP) refers to a type of computer programming


(software design) 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.

Object-oriented programming (OOP) can also be defined as a paradigm or pattern of


programming whereby the solution to a programming problem is modelled as a
collection of collaborating objects. The objects collaborate by sending
messages to each other. It is most suitable for managing large, complex
problems.

What is an object?

An object is an entity that possesses both state (properties or attributes) and


behaviour. In other words, we can safely say that an object encapsulates data and

© Gombe State Unibversity,2024 email: [email protected] 3


the functions that operate on that data. The data is usually hidden from other objects
so that the only way to affect the data is through the object’s functions (or methods).

Principles Of Object-Oriented Programming (OOP)

There are four basic principles or tenets of object oriented programming, they are:
inheritance, polymorphism, abstraction and encapsulation.

1- Inheritance can be defined as the process where one (parent/super) class


acquires the properties (methods and fields) of another (child/sub). With the
use of inheritance, the information is made manageable in a hierarchical order.
2- Polymorphism is the ability of an object to perform different actions (or, exhibit
different behaviours) based on the context.
3- Abstraction is a process of hiding the implementation details from the user,
only the functionality will be provided to the user. In other words, the user will
have the information on what the object does instead of how it does it.
4- Encapsulation is a mechanism for wrapping the data (variables) and code
acting on the data (methods) together as a single unit. In encapsulation, the
variables of a class will be hidden from other classes and can be
accessed only through the methods of their current class. Therefore, it is
also known as data hiding.

Benefits of Object-Oriented Programming (OOP)

Object oriented programming has many advantages which include:

1. It provides a clear modular structure for programs which makes it good for
defining abstract datatypes in which implementation details are hidden
2. The objects created can be reused within an across applications, hence OOP
lowers the cost of software development.
3. It makes the modification of existing code less tedious as new objects can be
created with small differences to existing ones.
4. It makes software easier to maintain, because the design is modular, hence,
locating and fixing problems becomes less tedious.

5. It provides a good framework for code libraries where the supplied software
components can be easily adapted and modified by the programmer.

© Gombe State Unibversity,2024 email: [email protected] 4


INTRODUCTION TO C++ PROGRAMMING LANGUAGE

Brief History of C++

Since C was a successful computer programming language, why was there a need for
something else? The answer is complexity. Throughout the history of programming,
the increasing complexity of programs has driven the need for better ways to manage
that complexity. C++ is a response to that need.

C++ is a high-level object-oriented programming language that helps programmers to


write fast, portable programs. It was built upon the foundation of C. Thus, C++ is a
superset of C. This programming language (C++) was invented by Bjarne Stroustrup
in 1979, at Bell Laboratories in Murray Hill, New Jersey. He initially called the new
language “C with Classes.” However, in 1983 the name was changed to C++.

Applications of C++ programming language

C++ is one of the most important programming languages, because almost all the
programs/systems that we use today have some part of the code base that is written
in C/C++. Be it Windows, be it the photo editing software, be it your favourite game,
be it your web browser, C++ plays an integral role in almost all applications that we
use, some of the interesting areas where C++ is popularly used are:

1. Operating Systems

Be it Microsoft Windows or Mac OSX or Linux – all of them are programmed in C++.
C/C++ is the backbone of all the well-known operating systems owing to the fact that
it is a strongly typed and a fast programming language which makes it an ideal choice
for developing an operating system. Moreover, C++ is quite close to the assembly
language which further helps in writing low-level operating system modules.

2. Browsers

The rendering engines of various web browsers are programmed in C++ simply
because of the speed that it offers. The rendering engines require faster execution to

© Gombe State Unibversity,2024 email: [email protected] 5


make sure that users don’t have to wait for the content to come up on the screen. As
a result, such low-latency systems employ C++ as the programming language.

3. Libraries

Many high-level libraries use C++ as the core programming language. For instance,
several Machine Learning libraries use C++ in the backend because of its speed.
Tensorflow, one of the most widely used Machine Learning libraries uses C++ as the
backend programming language. Such libraries required high-performance
computations, because they involve multiplications of huge matrices for the purpose
of training Machine Learning models. As a result, performance becomes critical. C++
comes to the rescue in such libraries.

4. Graphics

All graphics applications require fast rendering and just like the case of web browsers,
here also C++ helps in reducing the latency. Software that employ computer vision,
digital image processing, high-end graphical processing mostly use C++ as the
backend programming language. Even the popular games that are heavy on graphics
use C++ as the primary programming language. The speed that C++ offers in such
situations helps the developers in expanding the target audience, because an
optimized application can run even on low-end devices that do not have high
computation power available.

5. Cloud/Distributed Systems

Large organizations that develop cloud storage systems and other distributed systems
also use C++ because it connects very well with the hardware and is compatible with
a lot of machines. Cloud storage systems use scalable file-systems that work close to
the hardware. C++ becomes a preferred choice in such situations because it is close
to the hardware and also the multithreading libraries in C++ provide high concurrency
and load tolerance which is very much needed in such scenarios.

6. Databases

© Gombe State Unibversity,2024 email: [email protected] 6


Postgres and MySQL – two of the most widely used databases are written in C++ and
C, the precursor to C++. These databases are used in almost all of the well-known
applications that we all use in our day to day life, for example Quora, YouTube, etc.

7. Embedded Systems

Various embedded systems like medical machines, smartwatches, etc. use C++ as
the primary programming language because of the fact that C++ is closer to the
hardware level as compared to other high-level programming languages.

8. Compilers

The compilers of various programming languages use C and C++ as the backend
programming language. This is because of the fact that both C and C++ are relatively
lower level languages and are closer to the hardware and therefore are the ideal
choice for such compilation systems.

In summary, if we look at these areas where C++ is put into use, we can
observe that C++ is used in most advanced applications that play a vital role in
making the world a better place, thus, learning how to write C++ code is very important
and rewarding. C++ has so many advantages which include: Rich library support,
speed in terms of compilation and execution. It also has support for pointer.

STRUCTURE OF A C++ PROGRAM

Probably the best way to start learning a programming language is by writing a


program. Therefore, here is our first program:

// my first program in C++


#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}

// my first program in C++

© Gombe State Unibversity,2024 email: [email protected] 7


This is a comment line. All lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behaviour of the program. The
programmer can use them to include short explanations or observations within the
source code itself. In this case, the line is a brief description of what our program is.

#include <iostream>

Lines beginning with a hash sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor. In
this case the directive #include <iostream> tells the preprocessor to include the
iostream standard file. This specific file (iostream) includes the declarations of the
basic standard input-output library in C++, and it is included because its functionality
is going to be used later in the program.

using namespace std;

All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std. So in order to access its functionality
we declare with this expression that we will be using these entities. This line is very
frequent in C++ programs that use the standard library.

int main ()

This line corresponds to the definition of the main function. The main function is the
point where all C++ programs start their execution, independently of its location within
the source code. It does not matter whether there are other functions with other names
defined before or after it – the instructions contained within this function's definition will
always be the first ones to be executed in any C++ program. For that same reason, it
is essential that all C++ programs have a main function.

The word main is followed in the code by a pair of parentheses (()), because it is a
function declaration: In C++, what differentiates a function declaration from other types
of expressions are these parentheses that follow its name. Optionally, these
parentheses may enclose a list of parameters within them. Right after these
parentheses we can find the body of the main function enclosed in braces ({}). What
is contained within these braces is what the function does when it is executed.

cout << "Hello World!";

© Gombe State Unibversity,2024 email: [email protected] 8


This line is a C++ statement. A statement is a simple or compound expression that
can actually produce some effect. In fact, this statement performs the only action that
generates a visible effect in our first program. cout represents the standard output
stream in C++, and the meaning of the entire statement is to insert a sequence of
characters (in this case the Hello World sequence of characters) into the standard
output stream (which usually is the screen). cout is declared in the iostream standard
file within the std namespace, so that's why we needed to include that specific file and
to declare that we were going to use this specific namespace earlier in our code.

Notice that the statement ends with a semicolon character (;). This character is used
to mark the end of the statement and in fact it must be included at the end of all
expression statements in all C++ programs (one of the most common syntax errors is
indeed to forget to include some semicolon after a statement).

return 0;

The return statement causes the main function to finish, return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for
the main function is generally interpreted as the program worked as expected without
any errors during its execution. This is the most usual way to end a C++ console
program.

HOW C++ PROGRAM IS COMPILED

The compilation of a C++ program involves a series of actions which operates on the
C++ source file (source code). The source code written by the programmer is saved
with a .cpp file extension (e.g. firstCode.cpp) and passed to the C++ compiler. The
compiler now perform the following steps.

1- Preprocessing: the preprocessor works on one C++ source file at a time by


replacing #include directives with the content of the respective files (which is
usually just declarations). After all replacement, the preprocessor produces a
single output that contain a stream of tokens resulting from the transformations
described above. It also adds some special markers that tell the compiler where
each line came from so that it can use those to produce sensible error
messages.

© Gombe State Unibversity,2024 email: [email protected] 9


2- Compilation: the compiler takes the pre-processor's output and produces an
object file from it. This step does not create anything the user can actually run,
instead, the compiler merely produces the machine language instructions
(object code) that correspond to the source code file that was compiled. For
instance, if you compile (but don't link) three separate files, you will have three
object files created as output, each with the name .o or .obj (the extension
depends on the compiler used). It is at this stage that compiler errors, like
syntax errors or failed overload resolution errors are reported. Each object file
contains a translation of the source code file into a machine language file which
cannot be executed yet, they need to be converted into executables which the
users operating system can run.
3- Linking: The linker is what produces the final compilation output from the object
files the compiler produced. It links all the object files by replacing the
references to undefined symbols with the correct addresses. Each of these
symbols can be defined in other object files or in libraries. If they are defined in
libraries other than the standard library, you need to tell the linker about them.
At this stage the most common errors are missing definitions or duplicate
definitions. The former means that either the definitions don't exist (i.e. they are
not written), or that the object files or libraries where they reside were not given
to the linker. The latter is obvious: the same symbol was defined in two different
object files or libraries.

Fig 1.0 Compilation stages of a C++ program.

© Gombe State Unibversity,2024 email: [email protected] 10


TOKENS

A token is the smallest element of a C++ program that is meaningful to the compiler.
The C++ parser recognizes these kinds of tokens which may be identifiers, keywords,
literals, operators, punctuators, and other separators. A stream of these tokens
makes up a translation unit. Tokens are usually separated by white space. White
space can be one or more: blanks, horizontal / vertical tabs, new lines.

Tokens can be classified as follows:

• Keywords
• Identifiers
• Constants
• Special Symbols
• Operators

Keywords: keywords are pre-defined or reserved words in a programming language.


Each keyword is meant to perform a specific function in a program. Since keywords
are referred names for a compiler, they can’t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword which is not allowed.
You cannot redefine keywords. However, you can specify text to be substituted for
keywords before compilation by using C/C++ preprocessor directives.

Some of the C/C++ keywords are:

© Gombe State Unibversity,2024 email: [email protected] 11


Identifiers: Identifiers are used as the general terminology for naming of variables,
functions and arrays. These are user defined names consisting of randomly long
sequence of letters and digits with either a letter or the underscore (_) as a first
character. Identifier names must differ in spelling and case from any keywords. This
means that keywords cannot be used as identifiers; they are reserved for special use.
Once declared, you can use the identifier in later program statements to refer the
associated value.

Rules for Naming C++ Identifiers

There are certain rules which should be followed while naming C++ identifiers, all
identifiers

1. Must begin with a letter or underscore ( _ ).

2. Must consist of only letters, digits, or underscore. No other special character is

allowed.
3. Must not be a keyword.

4. Must not contain white space.

Example of valid and invalid C++ identifiers:

Identifier Remark
_cosc301 Valid
123SaveCost Invalid because it starts with numeric value
Age.Year Invalid because of special character (.)

© Gombe State Unibversity,2024 email: [email protected] 12


Note that the C++ language is a "case sensitive" language. That means that an
identifier written in capital letters is not equivalent to another one with the same name
but written in small letters. Thus, for example, the RESULT variable is not the same
as the result variable or the Result variable. These are three different variable.

Special Symbols: The following special symbols are used in C++ and they have
some special meaning, thus, cannot be used for some other purpose. These special
symbols include:

• Brackets [ ] - Opening and closing brackets are used as array element


reference. These indicate single and multidimensional subscripts.

• Parentheses ( ) - These special symbols are used to indicate function calls and
function parameters.

• Braces { } -These opening and ending curly braces marks the start and end of
a block of code containing more than one executable statement.

• Comma , - It is used to separate more than one statements, for example,


separating parameters in function calls.

• Asterisks * - It is used to create pointer variable.

• Preprocessor # - The preprocessor is a macro processor that is used


automatically by the compiler to transform the program before actual
compilation.

Constants: Constants are also like normal variables, however, the only difference is
that, their values cannot be modified by the program once they are defined. Constants
refer to fixed values, they are also called literals. The syntax for defining a constant
variable is:
const data_type variable_name;

Types of Constants:
1. Integer constants – Example: 0, 1, 1218, 12482
2. Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
3. String constants -Example: “helloworld”

© Gombe State Unibversity,2024 email: [email protected] 13


Operators: Operators are symbols that triggers an action when applied to C++
variables and other objects. The data items on which operators act upon are called
operands. Depending on the number of operands that an operator can act upon,
operators can be classified as follows:

• Unary Operators: Those operators that require only single operand to act upon
are known as unary operators. For example increment and decrement
operators. Example i++

• Binary Operators: Those operators that require two operands to act upon are
called binary operators, for example a+b. Binary operators are classified into:

1. Arithmetic operators e.g ( +, -, *, /, % )

2. Relational Operators e.g ( ==, !=, >, <, >=, <= )

3. Logical Operators e.g ( !, &&, || )

4. Assignment Operators e.g (+=, -=, *=, /=, %=)

5. Conditional Operators e.g (?:)

• Ternary Operators: These operators require three operands to act upon. For
Example Conditional operator (?:).

C++ DATA TYPES

All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data it
can store. Whenever a variable is defined in C++, the compiler allocates some memory
for that variable based on the data-type with which it is declared. Every data type
requires different amount of memory. The data type in C++ is mainly divided into two:

1. Primitive Data Types: These data types are built-in or predefined data types and
can be used directly by the user to declare variables. Some of the primitive data
types available in C++ are explained below:

• Integer: Keyword used for integer data types is int. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647.

© Gombe State Unibversity,2024 email: [email protected] 14


• Character: Character data type is used for storing characters. Keyword used for
character data type is char. Characters typically requires 1 byte of memory space
and ranges from -128 to 127 or 0 to 255.

• Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean data type
is bool.

• Floating Point: Floating Point data type is used for storing single precision floating
point values or decimal values. Keyword used for floating point data type is float.
Float variables typically requires 4 byte of memory space.

• Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating
point data type is double. Double variables typically requires 8 byte of memory
space.

• Void: Void means without any value. void datatype represents a valueless entity.
Void data type is used for those function which does not returns a value.

2. Abstract or User Defined Data Type: These data types are defined by user itself.
Like, defining a class in C++ or a structure (struct).

C++ DATATYPE MODIFIERS

Data type modifiers are used with the built-in data types to modify the length of data
that a particular data type can hold. Data type modifiers available in C++ are:

• Signed

• Unsigned

• Short

• Long

Below table summarizes the modified size and range of built-in datatypes when
combined with the type modifiers:

© Gombe State Unibversity,2024 email: [email protected] 15


VARIABLE DECLARATION IN C++

C++ is a strongly-typed language, and requires every variable to be declared with its
type before its first use. This informs the compiler the size to reserve in memory for
the variable and how to interpret its value. The syntax to declare a new variable in C++
is straightforward: we simply write the type followed by the variable name (i.e., its
identifier). For example:

int number;
float decimalNumber;

These are two valid declarations of variables. The first one declares a variable of
type int with the identifier number. The second one declares a variable of
type float with the identifier decimalNumber. Once declared, the
variables number and decimalNumber can be used within the rest of their scope in the
program. If declaring more than one variable of the same type, they can all be declared
in a single statement by separating their identifiers with commas. For example:

int a, b, c;

© Gombe State Unibversity,2024 email: [email protected] 16


This declares three variables (a, b and c), all of them of type int, and has exactly the
same meaning as:

int a;
int b;
int c;

VARIABLES INITIALIZATION IN C++

When the variables are declared, they have an undetermined value until they are
assigned a value for the first time. A variable is said to be initialized when a specific
value is assigned to it when it was initially declared. This is called the initialization of
the variable. In C++, there are three ways to initialize variables. They are all equivalent
and are reminiscent of the evolution of the language over the years.

The first one, known as c-like initialization (because it is inherited from the C
language), it is achieved by appending an equal sign ‘=’ followed by the value to which
the variable is initialized:

type identifier = initial_value;

For example, to declare a variable of type int called x and initialize it to a value of one
from the same moment it is declared, we can write:

int x = 1;

The second method, known as constructor initialization (introduced by the C++


language), encloses the initial value between parentheses ():

type identifier (initial_value);

For example:

int x (0);

© Gombe State Unibversity,2024 email: [email protected] 17


Finally, a third method, known as uniform initialization, similar to the above, but
using curly braces ({}) instead of parentheses (this was introduced by the revision of
the C++ standard, in 2011);

type identifier {initial_value};

For example:

int x {0};

CHARACTER AND STRING LITERALS

Character and string literals are enclosed in quotes:

'z'
'p'
"Hello world"
"How do you do?"

The first two expressions represent single-character literals, and the next two
represent string literals composed of several characters. Notice that to represent a
single character, we enclose it between single quotes ('), and to express a string
(which generally consists of more than one character), we enclose the characters
between double quotes (").

Both single-character and string literals require quotation marks surrounding them to
distinguish them from possible variable identifiers or reserved keywords. Notice the
difference between these two expressions x and ‘x’.

Here, x alone would refer to an identifier, such as the name of a variable or a


compound type, whereas 'x' (enclosed within single quotation marks) would refer to
the character literal 'x' (the character that represents a lowercase x letter). Character

© Gombe State Unibversity,2024 email: [email protected] 18


and string literals can also represent special characters that are difficult or impossible
to express otherwise in the source code of a program, like newline (\n) or tab (\t).
These special characters are all of them preceded by a backslash character (\). Here
you have a list of the single character escape codes:

Escape code Description


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

Several string literals can be concatenated to form a single string literal simply by
separating them by one or more blank spaces, including tabs, newlines, and other
valid blank characters. For example:

1 "this forms" "a single" " string "


2 "of characters"

The above is a string literal equivalent to:

"this forms a single string of characters"

Note how spaces within the quotes are part of the literal, while those outside them are
not. Some programmers also use a trick to include long string literals in multiple lines:
In C++, a backslash (\) at the end of line is considered a line-continuation character
that merges both that line and the next into a single line. Therefore the following code:

© Gombe State Unibversity,2024 email: [email protected] 19


x = "string expressed in \
two lines"

is equivalent to:

x = "string expressed in two lines"

TYPE CASTING

A value in any of the built-in types we have seen so far can be converted (type-cast)
to any of the other types. The syntax is:

(data type) expression

For example:

(int) 3.14 // converts 3.14 to an int to give 3

(double) 2 // converts 2 to a double to give 2.0

(char) 122 // converts 122 to a char whose code is 122

As shown by these examples, the built-in type identifiers can be used as type
operators. Type operators are unary (i.e., take one operand) and appear inside
brackets to the left of their operand. This is called explicit type conversion. When the
type name is just one word, an alternate notation may be used in which the brackets
appear around the operand:

int (3.14) // same as: (int) 3.14

In some cases, C++ also performs implicit type conversion. This happens when values
of different types are mixed in an expression. For example:

double d = 1; // d receives 1.0

int i = 10.5; // i receives 10

i = i + d; // means: i = int(double(i) + d)

© Gombe State Unibversity,2024 email: [email protected] 20


In the last example, i + d involves mismatching types, so i is first converted to double
(promoted) and then added to d. The result is a double which does not match the type
of i on the left side of the assignment, so it is converted to int (demoted) before being
assigned to i.

CONTROL STRUCTURES

A program is usually not limited to a linear sequence of instructions, during its


processes, it may split, repeat code or take decisions. For that purpose, C++ provides
control structures that serve to specify what has to be done by our program, when and
under which circumstances. Some example of control structures are explained below:

1- CONDITIONAL STRUCTURES

Conditional structures are statements used to control the flow of execution within a
C++ program. Some example of these statements include:

a. The ‘if’ and ‘else’ statement

The if keyword is used to execute a statement or block only if a condition is fulfilled.


Its form is:

if (condition) statement

Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the
program continues right after this conditional structure.

For example, the following code fragment prints x is 100 only if the value stored in the
x variable is indeed 100:

if (x == 100)

cout << "x is 100";

If we want more than a single statement to be executed in case that the condition is
true we can specify a block using braces { }:

if (x == 100){

cout << "x is ";

© Gombe State Unibversity,2024 email: [email protected] 21


cout << x;

We can additionally specify what we want to happen if the condition is not fulfilled by
using the keyword else. Conditional execution of code is implemented in C++ using
the if … else construct that looks like this:

if (conditional expression)

Do something when expression evaluates true;

else

Do something else when condition evaluates false;

b. The if else-if else statement

Another format of the if-else statement is the if else-if else statement. The conditional
expressions are evaluated from the top downward. As soon as a true condition is
found, the statement associated with it is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be
executed. The final else often acts as a default condition; that is, if all other conditional
tests fail, then the last else statement is performed. If there is no final else and all other
conditions are false, then no action will take place. The syntax is:

if (conditional expression)

Do something when expression evaluates true;

else if (conditional expression)

Do something when expression evaluates true;

else if (conditional expression)

Do something when expression evaluates true;

else

Do something else when condition evaluates false;

Nested if Statements

© Gombe State Unibversity,2024 email: [email protected] 22


A nested if is an if statement that act as a target of another if or else statement. Nested
ifs are very common in programming, the main thing to remember about nested ifs in
C++ is that an else statement always refers to the nearest if statement that is within
the same block as the else and not already associated with an else. Here is an
example:

As the comments indicate, the final else is not associated with if (j) (even though it is
the closest if without an else), because it is not in the same block. Rather, the final
else is associated with if (i). The inner else is associated with if (k) because that is the
nearest if.

c. Switch Statements

The syntax of the switch statement is a bit peculiar. Its objective is to check several
possible constant values for an expression. Something similar to what we did at the
beginning of this section with the concatenation of several if and else if instructions.
The syntax is as follows:

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

© Gombe State Unibversity,2024 email: [email protected] 23


default group of statements
}
It works in the following way: switch evaluates expression and checks if it is equivalent
to constant1, if it is, it executes group of statements 1 until it finds the break statement.
When it finds this break statement the program jumps to the end of the switch selective
structure.

If expression was not equal to constant1 it will be checked against constant2. If it is


equal to this, it will execute group of statements 2 until a break keyword is found, and
then it will jump to the end of the switch selective structure.

Finally, if the value of expression did not match any of the previously specified
constants (you can include as many case labels as values you want to check), the
program will execute the statements included after the default: label, if it exists (since
it is optional).

ITERATIVE STATEMENTS

They provide a way of repeating a statement while a condition holds. There are three
flavours of iteration in C++. We will pick each and every one of them for discussion.

a. While Loop

The while statement (also called while loop) provides a way of repeating an statement
while a condition holds. It is one of the three flavors of iteration in C++. The general
form of the while statement is:

while (expression) statement;

First expression (called the loop condition) is evaluated. If the outcome is nonzero then
statement (called the loop body) is executed and the whole process is repeated.
Otherwise, the loop is terminated.

For example, suppose we wish to print the range of numbers from 1-8 using while
loops.This can be expressed as:

© Gombe State Unibversity,2024 email: [email protected] 24


#include <iostream>

using namespace std;

int main(){

int i= 1;

while (i<=8){

cout << i;

The output of the above program is

12345678

b. Do while loop

The do statement (also called do loop) is similar to the while statement, except that its
body is executed first and then the loop condition is examined. The general form of
the do statement is:

do

statement;

while (expression);

First statement is executed and then expression is evaluated. If the outcome of the
latter is nonzero then the whole process is repeated. Otherwise, the loop is terminated.

The do loop is less frequently used than the while loop. It is useful for situations where
we need the loop body to be executed at least once, regardless of the loop condition.
For example, suppose we wish to repeatedly read a value and print its square, and
stop when the value is zero. This can be expressed as the following loop:

© Gombe State Unibversity,2024 email: [email protected] 25


do {

cin >> n;

cout << n * n << '\n';

} while (n != 0);

Unlike the while loop, the do loop is never used in situations where it would have a
null body. Although a do loop with a null body would be equivalent to a similar while
loop, the latter is always preferred for its superior readability.

c. For Loop

The for statement is a more sophisticated loop in that it allows for an initialization
statement executed once (typically used to initialize a counter), checking for an exit
condition (typically using this counter), and performing an action at the end of every
loop (typically incrementing or modifying this counter).

The syntax of the for loop is

for (initial expression executed only once; exit condition


executed at the beginning of every loop; loop expression
executed at the end of every loop){

DoSomeActivities;

The main function of the for loop is to repeat statement while condition remains true,
like the while loop. But in addition, the for loop provides specific locations to contain
an initialization statement and an increase statement. So this loop is specially
designed to perform a repetitive action with a counter which is initialized and increased
on each iteration.

It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a counter variable.

© Gombe State Unibversity,2024 email: [email protected] 26


This is executed only once.

2. Condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).

3. statement is executed. As usual, it can be either a single statement or a block


enclosed in braces { }.

4. finally, whatever is specified in the increase field is executed and the loop gets back
to step 2.

The for statement (also called for loop) is similar to the while statement, but has two
additional components: an expression which is evaluated only once before everything
else, and an expression which is evaluated once at the end of each iteration. The
general form of the for statement is:

The most common use of for loops is for situations where a variable is incremented or
decremented with every iteration of the loop. The following for loop, for example,
calculates the sum of all integers from 1 to 20.

#include <iostream>

using namespace std;

int main(){

int sum = 0;

for (int i = 1; i <= 20; i++) {

sum += i;

cout<< sum;

For loops with multiple loop variables are not unusual. In such cases, the comma
operator is used to separate their expressions:

© Gombe State Unibversity,2024 email: [email protected] 27


for (i = 0, j = 0; i + j < n; ++i, ++j) {

//do something

ARRAYS

An array is a collection of variables of the same type that are referred to by a common
name. Arrays may have from one to several dimensions (1-dimensional array or multi-
dimensional arrays), although the one-dimensional array is the most common. Arrays
offer a convenient means of creating lists of related variables.

Types of Array

There two types of an array, we have:

1. One-Dimensional Array
2. Multi-Dimensional Array.

One-Dimensional Arrays

A one-dimensional array (or a list, or a vector) is a group of related values with the
same data type that is stored using a group name. The group name is referred to as
the array name. The items in the list can be declared as a single unit and stored under
a common variable name called the array name.

The general form of a one-dimensional array declaration is

type array_name[size];

For example, suppose that we would like to store five exam grades in an array, named
grade, the declaration statement will be:

int grade[5];

Other examples:

char code[4]; //an array of four character values.

© Gombe State Unibversity,2024 email: [email protected] 28


Each element in an array is called an element or component of the array.The individual
elements stored in the array are stored sequentially, with the first array element stored
in the first reserved location, the second element stored in the second reserved
location, and so on.

Initializing the values of one dimensional array

Array elements can be initialized within their declaration statements, enclosing their
values within braces. For example:

int grade[5] = { 95, 87, 92, 100, 80 };

If the number of initializers is less than the declared number of elements listed in
square brackets, the initializers are applied starting with array element zero. For
example:

int grade[5] = { 98, 100, 80 };

will only initialize the first three elements.

A unique feature of initializers is that the size of an array may be omitted when the
initializing values are included in the declaration statement. For example:

int gallons [ ] = { 16, 12, 10, 15, 19 };

char code [4] ={ 'a', 'b', 'c', 'd' };

char code [ ] ={ 'a', 'b', 'c', 'd' };

Accessing the values of an array.

In any point of a program in which an array is visible, we can access the value of any
of its elements individually as if it was a normal variable, thus being able to both read
and modify its value. The format is as simple as:

data_type name[index]

For example:

int billy[5];

© Gombe State Unibversity,2024 email: [email protected] 29


Now the array billy would hold 5 values.

For example, to store the value 75 in the third element of billy, we could write the
following statement:

billy[2] = 75;

and, for example, to pass the value of the third element of billy to a variable called a,
we could write:

a = billy[2];

Therefore, the expression billy[2] is for all purposes like a variable of type int.

Notice that the third element of billy is specified billy[2], since the first one is billy[0],
the second one is billy[1], and therefore, the third one is billy[2]. By this same reason,
its last element is billy[4]. Therefore, if we write billy[5], we would be accessing the
sixth element of billy and therefore exceeding the size of the array.

It is important to be able to clearly distinguish between the two uses that brackets[
]have related to arrays. They perform two different tasks: one is to specify the size of
arrays when they are declared; and the second one is to specify indices for concrete
array elements.

int billy[5]; // declaration of a new array

billy[2] = 75; // access to an element of the array.

If you read carefully, you will see that a type specifier always precedes a variable or
array declaration, while it never precedes an access.

Example of Array usage

// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;

© Gombe State Unibversity,2024 email: [email protected] 30


int main () {

for ( n=0 ; n<5 ; n++ ){


result += billy[n];
}
cout << result;
return 0;

Multi-dimensional Array

C++ allows multidimensional arrays. The simplest form of the multidimensional array
is the two-dimensional array. A two-dimensional array is, in essence, a list of one-
dimensional arrays. To declare a two-dimensional integer array twoD of size 10 by 20,
you would write:

int twoD [10] [20];

Pay careful attention to the declaration. Unlike some other computer languages, which
use commas to separate the array dimensions, C++ places each dimension in its own
set of brackets. Similarly, to access an element, specify the indices within their own
set of brackets.

In the next example, a two-dimensional array is loaded with the numbers 1 through
12.

© Gombe State Unibversity,2024 email: [email protected] 31


In this example, nums[0] [0] will have the value 1, nums[0] [1] the value 2, nums[0] [2]
the value 3, and so on. The value of nums[2] [3] will be 12. Conceptually, the array will
look like that shown below:

Two-dimensional arrays are stored in a row-column matrix, where the first index
indicates the row and the second indicates the column. This means that when array
elements are accessed in the order in which they are actually stored in memory, the
right index changes faster than the left. You should remember that storage for all array
elements is determined at compile time. Also, the memory used to hold an array is
required the entire time that the array is in existence.

© Gombe State Unibversity,2024 email: [email protected] 32


© Gombe State Unibversity,2024 email: [email protected] 33

You might also like