C++ Guide
C++ Guide
C++ Guide
CODE: CTE313
Unit: 2.0
Prerequisites:
In this Module, we are going to work you through from absolute Basics to Advance Concept
of programming Language Before you start practicing with various types of examples given in
C++ Language and building projects. So Average knowledge of programming language will
be helpful and a device that will ensure frequent practice.
1
“A computer is an electronic device capable of performing commands. The basic
commands that a computer performs are input (get data), output (display result),
storage, and performance of arithmetic and logical operations.”
What is Programming:
“A computer program is a series of instructions given to a computer to perform a specific task”.
It can be further explained as breaking apart more complex idea into a smallest instruction and
using a programming language to write those instructions. A computer will do exactly what
you tell them, so the instructions you give should better make sense.
In programming language, we write these instructions using syntax. Syntax are like sentences
in English Language they use words numbers and punctuations to express a single thought.
Most programming syntax are short just a few words. The words and punctuation you use
depends on the programming language. Some language requires your syntax to end with semi
colons while others don’t, some uses full uppercase for naming convention some lowercase
and others don’t care at all it all depends on your preference.
Programming Methodologies:
Two popular approaches to programming design are the structured approach and the object-
oriented approach, which are outlined below
Object-Oriented Programming:
Object-oriented design (OOD) is a widely used programming methodology. In OOD, the first
step in the problem-solving process is to identify the components called objects, which form
the basis of the solution, and to determine how these objects interact with one another. For
example, suppose you want to write a program that automates the video rental process for a
local video store. The two main objects in this problem are the video and the customer. After
identifying the objects, the next step is to specify for each object the relevant data and possible
operations to be performed on that data. For example, for a video object, the data might include
• Movie name
• The actors
• Producer
• Production company
• Number of copies in stock etc.
2
Some of the operations on a video object might include:
Figure i.0
3
Writing source code:
To write a source code you need a text editor that comes with the operating system like Notepad
on windows or TextEdit on Mac. It works smoothly to write any programming language. All
you are required is to save with the appropriate file extension for each.
Figure ii
Why C++:
The most important thing while learning C++ is to focus on concepts.
The purpose of learning a programming language is to become a better programmer; that is, to
become more effective at designing and implementing new systems and at maintaining old
ones.
C++ supports a variety of programming styles. You can write in the style of Fortran, C,
Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining
runtime and space efficiency C++ is being highly used to write device drivers and other
software that rely on direct manipulation of hardware under real-time constraints.
4
First Program
Above is a code snippet on basic simple program in C++ that will output a “Hello world”
Message on the console. If you are able to build and run this program successfully it means
you thoroughly follow the installation procedure given in class, else you might have a problem
with the compiler. Kindly read all error messages carefully apply the suggested solution or
even google it online you will definitely come across a reliable solution. Just be more patient
errors are part of the growth.
Lexical Elements:
Programming languages can be regarded in much the same way as linguistic languages such
as English French Spanish Portuguese etc. The lexical elements of a programming Language
consist of the syntax (words), punctuations and scope (semantics).
Syntax:
Syntax can be said as the rules for writing a language. For each language it has a specific syntax
to follow. Putting together the words and punctuations of a program in a legal and correct
manner.
Semantics:
Basically, semantics is a methodology in which you put together your syntax to be logically
correct. To learn the semantics of programming language it is to learn how to articulate an
algorithm using the language. Semantics of computer programming are generally harder to
learn than syntax but more easily transferred to other language.
Punctuations
These are the special characters such as { , : ; ‘’ () } and much more. They are used to satisfy
the rules of the syntax. Some programming language are not strict with certain punctuations
which means you can omit semi colon and the program will run smoothly.
Operators
Binary arithmetic operators include, ( +,-,/,*,% ), unary arithmetic operators are ( ++, -- ) and
the assignment operators (=, +=, -=, *= )
5
In a nut shell, we have multiple programming languages and does not mean we should learn
all. For each language has a purpose so the ball is in your court to make the choice. Luckily,
almost all the language has one thing in common, which is the semantics. If you learn a
particular language perfectly it will be a piece of cake switching to other languages because
you already have an idea on how the logic will be implemented so you just need to learn the
syntax of the new language.
Identifiers/Variable Name
Identifiers are names given to variables and functions. In identifying your variables, there are
key rules that must be followed if not the identifier will be invalid. The rules are as follows:
VARIABLES
Variable is a placeholder that stores in values of different data types. To declare a variable in C++, you
first specify what type of value you intend to store which will determine the data type. We have
numerous data type examples include
a. Integers (int)
b. Boolean (bool)
c. Float
d. String (str)
e. Character (char)
Each data type has a function. Integers store in positive and negative numbers without decimal
points, Floats hold integers with decimal points only, Boolean holds in truth (1) and false (0)
values, character stores a single character such as (*, #, $, %) and string stores in sequence of
characters as shown below
6
Basic Keywords in C++
These are words that are explicitly reserved and have strict meaning to the complier. It cannot
be redefined or redeclared. Example of C++ keywords include string, int, cout, if, for, while,
function class, return, struct, end etc.
7
CONTROL STRUCTURES:
A computer can process a program in one of the following ways: in sequence; selectively, by
making a choice, which is also called a branch; repetitively, by executing a statement over and
over, using a structure called a loop; or by calling a function. The diagram below illustrates the
three types of program flow
Before you can learn about selection and repetition, you must understand the nature of
conditional statements and how to use them. Consider the following three statements:
These statements are examples of conditional statements. You can see that certain statements
are to be executed only if certain conditions are met. A condition is met if it evaluates to true.
For example,
statement 1: score is greater than or equal to 90 is true if the value of score is greater than or
equal to 90; it is false otherwise. For example, if the value of score is 95, the statement evaluates
to true. Similarly, if the value of score is 86, the statement evaluates to false. It would be useful
if the computer could recognize these types of statements to be true for appropriate values.
Furthermore, in certain situations, the truth or falsity of a statement could depend on more than
one condition. For example, in statement 3, both temperature is greater than 70 degrees and it
is not raining must be true to recommend golfing.
8
RELATIONAL OPERATORS:
To write a condition for a compiler to understand you need to know relational operators
available in C++ programming language
In C++, a condition is represented by a logical (Boolean) expression. An expression that has a
value of either true or false is called a logical (Boolean) expression.
Consider the expression:
i > j;
If this expression is a logical expression, it will have the value true if the value of i is greater
than the value of j; otherwise, it will have the value false. The symbol > is called a relational
operator. A relational operator allows you to make comparisons in a program. C++ includes
six relational operators that allow you to state conditions and make comparisons. Table below
list the relational operators.
Operator Description
== Equals to
!= Not Equals to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
CONDITIONAL OPERATOR:
IF statements:
The most common type of decision structure is the if statements. This exist in all
programming languages but are implemented slightly different. The conditions are usually
written with relational and conditional operators.
9
The syntax of if statement as follows: IF (condition){
Code goes here…
}
Example:
Create a c++ program that determine the largest number between two integers collected from
the user.
Source code:
#include <iostream>
using namespace std;
int main()
{
int num1,num2;
cout<<"Enter the integer Values: "<<endl;
cin >>num1>>num2;
if(num1 > num2){
cout<<"The largest Number is:"<<num1;
}
else{
cout<<"The largest Number is:"<<num2;
}
return 0;
}
NB:
In a situation where by you have more than one condition then you create a new block called
the Else-if block. The syntax as follows:
If(condition 1){
//Codes…
}
Else if(condition 2){
//Codes…
}
Else{
//if all conditions are false this block of code will
//execute
}
you can create as much else-if block you wish but it’s not preferable rather if you have multiple
condition you use the SWITCH statements.
10
Case Study 1:
1. Computer Engineering Exams office need a grading system application that will
automatically grade the student’s performance base on the total score given. Assuming
the exams office requirements are as follows:
Scores from:
0-49: Repeat session(F)
50-69: pass with probation(C)
70-79: fairly good (B)
80 above: distinction (A)
Note: the output of your code should print the students Name, total score, grade and
short remark telling if the student is distinction or otherwise
I. Explain the procedures and steps to follow in solving the problem above
II. Write a constructive C++ code to justify your explanations in (I).
III. How can we solve a situation where by the user is having a Negative score (-
10) as the total score?
2. Write a program that mimics a calculator. The program should take as input two
integers and the operation to be performed. It should then output the numbers, the
operator, and the result.
SWITCH STATEMENTS:
An if else statement is great if you have one or two choices. But what happens when you have
several choices? You can still use it but switch statements are more preferable cause it makes
the code clean and easy to read.
A switch statements allow a variable to be tested for equality against a list of values. Each value
is called a case and the variable being switched on is checked for each case.
Case expression2:
Statements…
Break;
Case expression3:
11
Statements…
Break;
.
.
.
Default:
Statements…
In C++, switch, case, break, and default are reserved words. In a switch structure, first the
expression is evaluated. The value of the expression is then used to perform the actions
specified in the statements that follow the reserved word case. The break keyword helps in
breaking the expression after it has been evaluated to true or false.
Case Study 2:
1. Write C++ statements that output Male if the gender is 'M', Female if the gender is 'F',
and invalid gender otherwise.
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter an integer between 0 and 7: "; //Line 1
cin >> num; //Line 2
cout << endl; //Line 3
cout << "The number you entered is "<<num<< endl; //Line 4
switch(num) //Line 5
{
case 0: //Line 6
12
case 1: //Line 7
cout << "Learning to use "; //Line 8
case 2: //Line 9
cout << "C++'s "; //Line 10
case 3: //Line 11
cout << "switch structure." << endl; //Line 12
break; //Line 13
case 4: //Line 14
break; //Line 15
case 5: //Line 16
cout << "This program shows the effect "; //Line 17
case 6: //Line 18
case 7: //Line 19
cout << "of the break statement." << endl; //Line 20
break; //Line 21
default: //Line 22
cout << "The number is out of range." << endl; //Line 23
}
LOOPING (Repetition):
The concept of looping is to allow a programmer to execute a block of code several Number
of times. In general, statements are executed sequentially: line 1 will run before line 2
continuously. Programming languages provided various control structures that allow for more
complicated execution paths.
A loop statements allows us to execute a statement or group of statements multiple times. The
following are type of loops found in C++ programming.
a. While loop
b. For loop
c. Do while loop
d. Nested loops
13
WHILE LOOP:
This executes a target statement(s) as long as a given condition is true. The syntax of a while
loop as follows:
While (condition){
Staments….
Increment or Decrement
}
Example:
Using while loop write a C++ program that prints the HOD’s name twenty (20) times.
FOR LOOP:
This is a shorthand of while loop, it allows a programmer to efficiently write a loop that
needs to execute a specific number of times. The syntax as follows:
for(initialization; condition; increment/){
staements…
}
Example:
Using for loops write a c++ program that prints the HOD’s name twenty (20) times.
DO-WHILE LOOPS:
Unlike for and while loops which test the loop condition at the top of the loop, the do-while
loop checks its condition at the bottom of the loop. A do-while loop is more similar to a while
loop except that a do-while loop is guaranteed to execute at least one time. The syntax as
follows:
do{
Statement(s)
Increment/Decrement
}
while (condition);
14
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested. If the condition is true, the flow of control
jumps back to execute the do statements until the condition is false.
Example:
Using a do-while loop write a C++ program that prints the HOD’s name twenty (20) times.
NB: We can create infinite loop knowingly or unknowingly. Infinite loop is loop that
has no ending. This occurs when a condition is always true so the statements will
keep executing till told otherwise.
ARRAYS:
Before formally defining an array, let us consider the following problem. We want to write a
C++ program that reads five numbers, finds their sum, and prints the numbers in reverse order.
previously, you learned how to read numbers, print them, and find the sum. The difference here
is that we want to print the numbers in reverse order. This means we cannot print the first four
numbers until we have printed the fifth, and so on. To do this, we need to store all of the
numbers before we start printing them in reverse order.
From what we have learned so far, the following program accomplishes this task:
#include <iostream>
using namespace std;
int main()
{
int item0, item1, item2, item3, item4;
int sum;
cout << "Enter five integers: ";
cin >> item0 >> item1 >> item2 >> item3 >> item4;
cout << endl;
return 0;
15
This program works fine. However, if you need to read 100 (or more) numbers and print them
in reverse order, you would have to declare 100 variables and write many cin and cout
statements. Thus, for large amounts of data, this type of program is not desirable
Statement 1 tells you that you have to declare five variables. Statement 3 tells you that it would
be convenient if you could somehow put the last character, which is a number, into a counter
variable and use one of the loops to count from 0 to 4 for reading and another for loop to count
from 4 to 0 for printing. Finally, because all variables are of the same type, you should be able
to specify how many variables must be declared and their data type with a simpler statement
than the one we used earlier. The data structure that lets you do all of these things in C++ is
called an array.
“An array is a collection of a fixed number of components all of the same data type. A one-
dimensional array is an array in which the components are arranged in a list form.”
Where elements are the total number of components in the Array and must be a constant
expression that evaluates to a positive integer.
Example
The statement
int num[5];
An array num of five components was declared. Each component is of type integer. The
components are num[0], num[1], num[2], num[3], and num[4]. Illustrate the
array num
16
ACCESSING ARRAY COMPONENTS:
The general syntax used in accessing array arrayName[indexNumber]
components is
in which indeNumber, called the index, is any expression whose value is a nonnegative integer.
The index value specifies the position of the component in the array.
In C++, [ ] is an operator called the array subscripting operator. Moreover, in C++, the array
index starts from 0
Example
1. Explain The diagram below in respect to C++ programming language and write the
source code
A. If int i = 4,
then the assignment statement: list[2 * i - 3] = 58; what will be the output
and why?
Case study 3:
Now that we know how to declare and process arrays, let us rewrite the program that we
discussed in the beginning of this chapter using Array concept. Recall that this program reads
five numbers, finds the sum, and prints the numbers in reverse order.
Review Questions:
1. Consider the following declaration: double salary[10]; In this declaration,
identify the following:
a. The array name.
b. The array size.
c. The data type of each array component.
d. The range of values for the index of the array.
2. What would be a valid range for the index of an array of size 50?
3. Write C++ statements to do the following:
a. Declare an array alpha of 15 components of type int.
b. Output the value of the tenth component of the array alpha.
17
c. Set the value of the fifth component of the array alpha to 35.
d. Set the value of the ninth component of the array alpha to the sum of the sixth
and thirteenth components of the array alpha.
e. Set the value of the fourth component of the array alpha to three times the value
of the eighth component minus 57.
f. Output alpha so that five components per line are printed.
int main()
{
int temp[5];
for (int i = 0; i < 5; i++)
temp[i] = 2 * i - 3;
temp[0] = temp[4];
temp[4] = temp[1];
temp[2] = temp[3] + temp[0];
return 0;
18
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is such that each function
performs a particular assignment.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can call.
For example, function strcat() to concatenate two strings, function memcpy() to copy
one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.
DEFINING FUNCTIONS
To define a function in C++ you use the following syntax
return_type function_name (parameter list) {
body of the function…
}
I. Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type of that function is void.
II. Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
III. Parameters: A parameter is like a variable. When a function is invoked / called, you
key in a value to the parameter. This value is referred to as argument. The parameter
list refers to the type, order, and number of the parameters of a function. Parameters
are optional; that is, a function might not have any parameters and it is still valid
function.
IV. Function Body: The function body contains a collection of statements that define what
the function does.
EXAMPLE OF A FUNCTION:
Following is the source code for a function called max(). This function takes two parameters
num1 and num2 and return the biggest of both
int result;
return result;
}
FUNCTION ARGUMENTS
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
STRUCTURES (RECORDS):
Suppose that you want to write a program to process student data. A student record consists of,
among other things, the student’s name, student ID, GPA, courses taken, and course grades.
Thus, various components are associated with a student. However, these components are all of
different types. For example, the student’s name is a string, and the GPA is a floating-point
number. Because these components are of different types, you cannot use an array to group all
of the items associated with a student. C++ provides a structured data type called struct to group
items of different types. Grouping components that are related but of different types offers
several advantages.
“struct: A collection of a fixed number of components in which the components are
accessed by name. The components may be of different types”
Question:
20
Like any type definition, a struct is a definition, not a declaration. That is, it defines only a data
type; no memory is allocated. Once a data type is defined, you can declare variables of that
type. Let us first define a struct type, studentType, and then declare variables of that type.
struct studentType
{
string firstName;
string lastName;
char courseGrade;
int testScore;
int programmingScore;
double GPA;
};
structVariableName.memberName
newStudent.firstName = "Muhammad";
newStudent.lastName = "Sani";
The statement:
cin >> newStudent.firstName;
21
reads the next string from the standard input device and stores it in:
newStudent.firstName
The statement:
cin >> newStudent.testScore >> newStudent.programmingScore;
reads two integer values from the keyboard and stores them in newStudent.testScore and
newStudent.programmingScore, respectively. Suppose that score is a variable of type int.
The statement:
ARRAYS IN STRUCTS:
Suppose a company has 50 full-time employees. We need to print their monthly paychecks and
keep track of how much money has been paid to each employee in the year-to-date.
First you need to define an employee’s record as follows:
struct employeeType
{
string firstName;
string lastName;
int personID;
string deptID;
double yearlySalary;
double monthlySalary;
double yearToDatePaid;
double monthlyBonus;
};
Each employee has the following members(properties): first name, last name, personal ID,
department ID, yearly salary, monthly salary, year-to-date paid, and monthly bonus. Because
we have 50 employees and the data type of each employee is the same, we can use an array of
50 components to process the employees’ data. Which is illustrated as follows:
employeeType employees[50];
NB: with the syntax above we avoided having 50 different instantiations and we can
proceed to manipulate the variables as we wish
In a nutshell structures are called derived data types because the user gets to create a datatype
of his wish and assign values, they are use in representing complex object with multiple
attributes.
22
Review Questions:
1. Define a struct, checkingAccount, to store the following data about a checking
account: account holder’s name, account number, balance, and the interest rate.
i. Using the structure definition above, declare a checkingAccount variable and
write C++ statements to store the following information: account holder’s
name—Fatima bukar, account number: 17328910, balance: 24476.38, interest
rate:2.5%.
ii. Define a struct, movieType, to store the following data about a movie: movie
name (string), movie director (string), producer (string), the year movie was
released (int), and number of copies in stock.
2. Create lecturer’s management system for computer engineering where all the following
information will be stored and manipulated
• First Name
• Last Name
• DOB
• fileID
• Rank
Note: A system Administrator should be able to key in and print out all the details from
a dedicated desktop. Make all the codes to be dynamic
CLASSES:
C++ provides another structured data type, called a class, which is specifically designed to
group data and functions. This chapter first introduces classes and explains how to use them
and then discusses the similarities and differences between a struct and a class.
In OOD (Object Oriented Design), the first step is to identify the components, called objects.
An object combines data and the operations on that data in a single unit. In C++, the mechanism
that allows you to combine data and the operations on that data in a single unit is called a
class. Now that you know how to store and manipulate data in computer memory and how
to construct your own functions, you are ready to learn how objects are constructed.
“A class is a collection of a fixed number of components. The components of a class are
called the members of the class”
23
in which classMembersList consists of variable declarations and/or functions. That is, a
member of a class can be either a variable (to store data) or a function.
• If a member of a class is a variable, you declare it just like any other variable. Also, in
the definition of the class, you cannot initialize a variable when you declare it.
• If a member of a class is a function, you typically use the function prototype to declare
that member.
• If a member of a class is a function, it can (directly) access any member of the
classmember variables and member functions. That is, when you write the definition of
a member function, you can directly access any member variable of the class without
passing it as a parameter. The only obvious condition is that you must declare an
identifier before you can use it.
The members of a class are classified into three categories: private, public, and protected.
This chapter mainly discusses the first two types, private and public. In C++, private, protected,
and public are reserved words and are called member access specifiers. Following are some
facts about public and private members of a class:
24
To implement these seven operations, we will write seven functions: setTime(),
getTime(), printTime(), incrementSeconds(), incrementMinutes(),
incrementHours(), and equalTime(). From this discussion, it is clear that the class
clockType has 10 members: three member variables and seven member functions.
Some members of the class clockType will be private; others will be public. Deciding which
member to make public and which to make private depends on the nature of the member. The
general rule is that any member that needs to be accessed outside of the class is declared public;
any member that should not be accessed directly by the user should be declared private.
For example, the user should be able to set the time and print the time. Therefore, the members
that set the time and print the time should be declared public. Similarly, the members to
increment the time and compare the time for equality should be declared public. On the other
hand, to prevent the direct manipulation of the member variables hr, min, and sec, we will
declare them private.
CREATING OBJECT:
Once a class is defined, you can declare variables of that type. In C++ terminology, a class
variable is called a class object or class instance.
The syntax for declaring a class object is the same as that for declaring any other variable. The
following statements declare two objects of type clockType:
clockType myClock;
clockType yourClock;
Constructors:
To guarantee that the member variables of a class are initialized, you use constructors. There
are two types of constructors: with parameters and without parameters. The constructor without
parameters is called the default constructor. Constructors have the following properties:
25
• A class can have more than one constructor. However, all constructors of a class have
the same name.
• If a class has more than one constructor, the constructors must have different formal
parameter lists.
• Constructors execute automatically when a class object enters its scope. Because they
have no types, they cannot be invoked like other functions.
• The number of arguments and their type should match the formal parameters (in the
order given) of one of the constructors.
• If the type of the arguments does not match the formal parameters of any constructor
(in the order given), C++ uses type conversion and looks for the best match. Any
ambiguity will result in a compile-time error.
NB: a default constructor invoke itself without passing any arguments when the object of
class is created.
Destructors
Like constructors, destructors are also functions. Moreover, like constructors, a destructor does
not have a type. That is, it is neither a value-returning function nor a void function. However,
a class can have only one destructor, and the destructor has no parameters. The name of a
destructor is the tilde character (~), followed by the name of the class. For example, the name
of the destructor for the class clockType is: ~clockType();
A destructor automatically executes when the class object goes out of scope.
A Struct vs a Class:
A struct is a fixed collection of components, wherein the components can be of different types.
This definition of components in a struct included only member variables.
However, a C++ struct is very similar to a C++ class. As with a class, members of a struct can
also be functions, including constructors and a destructor. The only difference between a struct
and a class is that, by default, all members of a struct are public, and all members of a class are
private. You can use the member access specifier private in a struct to make a member private.
26
NB: Struct and classes are identically similar but not the same. Which means any
program you create using struct methodology can be mimic with class mechanism.
Review Question:
1. Study The codes and answer the questions below
class die
{
public:
die();
int roll();
private
int num;
};
void BB();
}
3. Strictly using the concept of classes, create lecturer’s management system for computer
engineering where all the following information will be stored and manipulated
• First Name
• Last Name
• DOB
• fileID
• Rank
Note: A system Administrator should be able to key in and print out all the details from
a dedicated desktop. Make all the codes to be dynamic
27