COM 313-C-Plus-Plus HND
COM 313-C-Plus-Plus HND
4. Case-Sensitive
C++ is case-sensitive, which means that it treats uppercase and lowercase characters
differently.
5. Mid-level programming language
Having the features of both a low-level (machine-level) language and a high-level language
(user-oriented language that is easily understandable and close to human language), C++ is
termed a mid-level or intermediate programming language. C++ is used to develop low-level
system applications, such as kernels, drivers, etc., and high-level applications, such as GUIs,
desktop applications, etc.
6. Structured Programming Language
C++ is a structured programming language. Programming in C++ is modular i.e. we are able to
break the complex code into smaller pieces (subdividing a computer program into separate
sub-programs) and combine them using functions, classes, and objects. This results in cleaner
code and makes maintenance much easier.
7. Rich Library
C++ provides developers with many built-in functions or libraries that save developers time
and make development faster. Some of the header files include:
<iostream>: Include C++ standard input and output functions
<cmath>: Include math library functions
<cstdlib>: Includes functions that convert numbers to text and vice versa, allocate
memory, create random numbers, and perform various other functions.
<fstream>: Include functions to create files, write information to files, and read
information from files.
<iterator>: Include classes for accessing data in the C++ Standard Library containers
8. Compiler-Based
It is not possible to run C++ code without compilation, since it is a compiler based
programming language. To execute our program, we must first compile it using a compiler that
translate the program into machine language which can be understood directly by the system.
The resulting program is therefore highly efficient and faster than most interpreter-based
languages, such as Python and Java.
C++ is a highly portable language and is often the language of selection for multi-device,
multi-platform app development.
2
COM 313 C++ Programming Language
UNIT 2
While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer,
floating point, double floating point, boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory.
Primitive Built-in Types
C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types −
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
3
COM 313 C++ Programming Language
Valueless void
Wide character wchar_t
Several of the basic types can be modified using one or more of these type modifiers:
signed
unsigned
short
long
Assignment 1:
Make a list consisting of the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.
4
COM 313 C++ Programming Language
Here, blue will have a value of 6 because each name will be one greater than
the one that precedes it.
OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical
or logical manipulations. C++ is rich in built-in operators and provide the
following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
For convenience, we will examine the arithmetic, relational, logical, bitwise,
assignment and other operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then;
Operato Description Example
r
+ Adds two operands A + B will give 30
- Subtracts second operand A - B will give -10
from the first
5
COM 313 C++ Programming Language
Relational Operators
There are following relational operators supported by C++ language
Assuming the same applies to variable A and B as before, then
Operato Description Example
r
== Checks if the values of two operands (A == B) is not true.
are equal or not, if yes then condition
becomes true.
!= Checks if the values of two operands (A != B) is true.
are equal or not, if values are not
equal then condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right
operand, if yes then condition
becomes true.
< Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if
yes then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of
right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is (A <= B) is true.
less than or equal to the value of right
operand, if yes then condition
becomes true.
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then;
Operato Description Example
r
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition
becomes true.
|| Called Logical OR Operator. If any of the (A || B) is true.
6
COM 313 C++ Programming Language
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following
table. Assume variable A holds 60 and variable B holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the (A & B) will give 12
result if it exists in both operands. which is 0000 1100
| Binary OR Operator copies a bit if it (A | B) will give 61
exists in either operand. which is 0011 1101
^ Binary XOR Operator copies the bit if it (A ^ B) will give 49
is set in one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is (~A ) will give -61
unary and has the effect of 'flipping' which is 1100 0011 in
bits. 2's complement form
due to a signed binary
number.
<< Binary Left Shift Operator. The left A << 2 will give 240
operands value is moved left by the which is 1111 0000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left A >> 2 will give 15
operands value is moved right by the which is 0000 1111
number of bits specified by the right
7
COM 313 C++ Programming Language
operand.
Assignment Operators
There are following assignment operators supported by C++ language −
Operator Description Example
= Simple assignment operator, Assigns C = A + B will assign
values from right side operands to value of A + B into C
left side operand.
+= Add AND assignment operator, It C += A is equivalent to C
adds right operand to the left =C+A
operand and assign the result to left
operand.
-= Subtract AND assignment operator, It C -= A is equivalent to C
subtracts right operand from the left =C-A
operand and assign the result to left
operand.
*= Multiply AND assignment operator, It C *= A is equivalent to C
multiplies right operand with the left =C*A
operand and assign the result to left
operand.
/= Divide AND assignment operator, It C /= A is equivalent to C
divides left operand with the right =C/A
operand and assign the result to left
operand.
%= Modulus AND assignment operator, It C %= A is equivalent to C
takes modulus using two operands =C%A
and assign the result to left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C =
C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C =
C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C
&2
^= Bitwise exclusive OR and assignment C ^= 2 is same as C = C
operator. ^2
|= Bitwise inclusive OR and assignment C |= 2 is same as C = C |
operator. 2
Misc Operators
The following table lists some other operators that C++ supports.
S/No Operator & Description
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a),
where ‘a’ is integer, and will return 4.
2 Condition ? X : Y
8
COM 313 C++ Programming Language
Escape Sequence
Escape sequences are special characters used in control strings to modify the
format of the output. These specific characters are translated into another
character or a sequence of characters that may be difficult to represent directly.
For example, if you want to put a line break in the output of a C++ statement
then you will use the “\n” character which is an escape sequence itself.
An escape sequence consists of two or more characters. For all sequences, the
first character will be ”\” i.e. backslash. The other characters determine the
interpretation of the escape sequence. For example, “n” of “\n” tells the cursor
to move to the next line.
Tab (\T):
A TAB is equal to eight spaces. Whenever the TAB button is pressed from the
keyboard, then 8 spaces are left blank. This escape sequence performs the
functionality of the TAB key in the output stream. The code given below will
insert a TAB between two words.
cout<<”COMPUTER\tSCIENCE”;
9
COM 313 C++ Programming Language
As you can see after printing “COMPUTER”, 8 spaces are left blank, and then
“SCIENCE” is printed on the screen.
cout<<”COMPUTER\aSCIENCE”;
First of all, “COMPUTER” is printed then a beep is played and after that
“SCIENCE” is printed.
Backspace (\B):
Whenever we want to delete a single character, we press the button
“backspace” from our keyboard. The same functionality can be achieved in C++
output with this escape sequence. For example:
cout<<”COMPUTER\bSCIENCE”;
Assignment 2.
a) Tabulate the operator precedence chart in C++ language
b) Find out and explain many more escape sequence used by C++
UNIT 3
OBJECTIVE: UNDERSTAND INPUT AND OUTPUT OPERATIONS IN C++
10
COM 313 C++ Programming Language
11
COM 313 C++ Programming Language
cause its output to be held in a buffer until the buffer is filled or until the buffer
is flushed.
The clog is also used in conjunction with the stream insertion operator.
You would not be able to see any difference in cout, cerr and clog with these
small examples, but while writing and executing big programs the difference
becomes obvious. So it is good practice to display error messages using cerr
stream and while displaying other log messages then clog should be used.
The above class contains the details of a student, namely its roll number, name
and marks.
Object Definitions
When a class is defined, it is only a specification. There is no memory or
storage allocated at that time. So the object is created from the class to access
the data and functions defined in the class. A class can also be called the
blueprint for an object.
The declaration of an object of class student is given as follows.
Student stu1;
A program that demonstrates classes and objects in C++ is obviously given.
See appendixes.
UNIT 4
12
COM 313 C++ Programming Language
Function Declarations
A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For example, the following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is
required, so following is also valid declaration −
int max(int, int);
13
COM 313 C++ Programming Language
Function declaration is required when you define a function in one source file
and you call that function in another file. In such case, you should declare the
function at the top of the file calling the function.
Calling a Function
Function calling is the process of actually implementing or using the function so
declared in a program. To use a function, you will have to call or invoke that
function.
To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned
value.
While calling a function, there are two ways that arguments can be passed to a
function
Sr.N Call Type & Description
o
1 Call by Value
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the
argument.
2 Call by Pointer
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made
to the parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access
the actual argument used in the call. This means that changes
made to the parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means
that code within a function cannot alter the arguments used to call the function.
C++ Libraries
The C++ Standard Library is a reference for C++ programmer to help them at
every steps of their projects related to system programming. All the C++
functions have been explained in easy to understand way and they can be used
easily in your C++ projects.
Assignment 3
List 20 library classes or functions found in the C++ standard library.
14
COM 313 C++ Programming Language
UNIT 5
CONTROL STURCTURES IN C++
The If_Statement; syntax:
if (condition)
{
//body (codes)
}
1. If the condition inside the parenthesis is evaluated to be true, then its body is executed otherwise
it doesn’t execute.
In the case of if in the place of condition always zero and non-zero value is checked in which zero
means condition is false and non-zero means condition is true.
If_Else Statement in C++ Language
Syntax:
if (conditional stmt)
{
//if condition is true: execute code
}
else
{
//if condition is evaluated to false, execute here
}
Nested If_Statement in C++ Language
Syntax:
if (condition)
{
if(another condition){
//statements…
}
}
a) Nested means one inside another; so one if inside another if is called nested if.
b) In the case of if in the place of condition always zero and non-zero value is checked in
which zero means condition is false and non-zero means condition is true
Sample Code:
#include<iostream>
int main() {
int x = 10;
if(x>5) //checking the condition_1
{
if(x<15)//checking the condition_2
{
cout<”x is greater than 5 and less than 15”;
}
}
}
15
COM 313 C++ Programming Language
In the above program, the outer if condition is true, so its body will execute and the condition of
inner if is also true so the output is: “x is greater than 5 and less than 15”
Assignment:
Change the above sample code but ensure it produces the same results. Hint: make use of the logical
operators: AND, OR, or NOT.
The Switch Statement in C++ Language
The switch statement allows us the opportunity to execute one statement from many statements and
those statements are called case. Actually, in switch statement, inside the body of switch a number of
cases are used and a parameter is passed and from which case this parameter is matched, executed.
Syntax:
switch(parameter){
case 1:
statement_1;
break;
case 2:
statement_2;
break;
…
…
case n:
statement_n;
break;
default;
default_statement;
}
1. In the switch statement, a value/number is passed in the place of parameter and that
case will execute; which is equal to that value/number.
2. If no case matched with the parameter(s) then the default case will execute.
Sample Code:
#include<iostream>
int main() {
//assigning parameter’s value
intp=2;
OUTPUT:
switch (p){
case 1: it is case 2
cout<< “it is case1”;
break;
case 2:
cout<< “it is case 2”; Note: this is because P=2, so case
break; 2 will execute
case 3:
cout<< “it is case 3”;
break;
default:
cout<< “No case matched!”;
}
return 0;
}
16
COM 313 C++ Programming Language
Assignment:
Re-write the sample program above to compute students’ grade using the following parameters:
- 75 and above = ‘A’
- 65 – 74 = ‘B’
- 55 – 64 = ‘C’
- 45 – 54 = ‘D’
- 40 – 44 = ‘E’
- 0-39 = default = ‘F’
Compile your source code and print the output.
Sample:
#include<iostream>
int main()
{
for(inti=1; i<=10; i++)
{
cout<<i<<”\n”;
}
}//the output will generate numbers from 1-10
17
COM 313 C++ Programming Language
do {
// body of the loop
}
while(condition);
This type of loop will execute until when a certain condition (given) is true.
Exercises:
1. Re-write the sample program above using the do…while loop as shown in the syntax
above.
2. Establish the distinction between the do...while and the while loops.
UNIT 6
OBJECT ORIENTED PROGRAMMING CONCEPTS
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts: Object; Class; Inheritance;
Polymorphism; Abstraction; and Encapsulation.
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
A Class in C++ is the foundational element that leads to Object-Oriented programming. A class
instance must be created in order to access and use the user-defined data type's data members and
member functions. An object's class acts as its blueprint.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism. Reusability -
As a result, when we wish to create a new class, but an existing class already contains some of the
code we need, we can generate our new class from the old class thanks to inheritance. This allows us
to utilize the fields and methods of the pre-existing class.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. Data abstraction is the
process of exposing to the outside world only the information that is absolutely necessary while
concealing implementation or background information. For example: phone call, we don't know the
internal processing.
18
COM 313 C++ Programming Language
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
Encapsulation is typically understood as the grouping of related pieces of information and data into a
single entity. Encapsulation is the process of tying together data and the functions that work with it in
object-oriented programming.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It can have
fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonen Sewuese";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
19
COM 313 C++ Programming Language
15. }
EXAMPLE 2
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(01, "Sonnen");
21. s2.insert(02, "Ojieh");
22. s1.display();
23. s2.display();
24. return 0;
25. }
EXAMPLE 3
Let's see another example of C++ class where we are storing and displaying employee information
using method.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
20
COM 313 C++ Programming Language
EXAMPLE 4
#include<iostream>
using namespace std;
class calculator {
int number1;
int number2;
char symbol;
public :
void add() {
cout<<"The sum is "<<number1 + number2 ;
}
void subtract() {
cout<<"The subtraction is "<<number1 - number2 ;
}
void multiply() {
cout<<"The multiplication is "<<number1 * number2 ;
}
void divide() {
cout<<"The division is "<<number1 / number2 ;
}
calculator (int a , int b , char sym) {
number1 = a;
number2 = b;
symbol = sym;
switch(symbol){
case '+' : add();
break;
case '-' : add();
break;
case '*' : add();
break;
case '/' : add();
break;
default : cout<<"Wrong operator";
}
}
};
int main() {
calculator c1(12 , 34 , '+');
}
UNIT SEVEN
CONTROL STURCTURES IN C++
The If_Statement; syntax:
21
COM 313 C++ Programming Language
if (condition)
{
//body (codes)
}
2. If the condition inside the parenthesis is evaluated to be true, then its body is executed otherwise
it doesn’t execute.
3. In the case of if in the place of condition always zero and non-zero value is checked in which
zero means condition is false and non-zero means condition is true.
22
COM 313 C++ Programming Language
…
case n:
st
atement_n;
break;
default;
default_statement;
}
1. In the switch statement, a value/number is passed in the place of parameter and that
casewill execute; which is equal to that value/number.
2. If no case matched with the parameter(s) then the default case will execute.
23
COM 313 C++ Programming Language
Definition: A loop inside another loop is called nested loop; so one for loop inside another for loop is
called nested for-loop and so on.
Syntax:
for(..; …; …)
{
for(..; …; …)
{//statements
}
//statements
}
Sample:
#include<iostream.h>
void main() {
int a=10; //normal variable initialized
int *p; //pointer variable declared
p=&a; //address of variable a is assigned to p
cout<<”value of a=”<<a;
cout<<”address of a=”<<&a;
cout<<”value of p=”<<p;
cout<<”address of p=”<<&p;
cout<<”value of *p=”<<*p;
}
### Output ###
Value of a=10
Address of a=8284
Value of p=8284
Address of p=8288
Value of *p=10
24
COM 313 C++ Programming Language
4. The indexing of array always start with 0; and must always be an integer number.
5. Array may be of any data type like int, char, float, etc.
Syntax (Array Declaration):
int arr[10];
25
COM 313 C++ Programming Language
What is Structure?
1) It is a collection of data of different data types
2) It is a user defined data type
3) Data can be int, char, float, double, etc. data types
4) We can access the members of structure by making a variable of structure
5) Struct is the keyword used to create a structure.
Syntax:
Structstructure_name
{//body of structopens(begins)
Data_type var1;
Data_type var2;
……………….
Data_typevar n;
};//body of struct closes and must end with (;)
What is Union?
a) It is a collection of data of different data type
b) It is user defined data type
c) We can access the member of union by making the variable of union.
d) Union is the keyword used to create a union.
e) Union doesn’t support multiple values simultaneously, but can store one value at a time.
Syntax:
unionstructure_name Example:
{ union student {
data_type var1; char name [200];
data_type var2;
introllNo;
………………………..
float marks;
data_typevar n;
};
};
26
COM 313 C++ Programming Language
4. fstream: This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files and even read
information from files.
The Various Operations on a File
File Opening: modes
In C++, file can be opened in different mode to perform read and write operations on a file. open()
function is used to open a file, open function takes two arguments…
open (const char *filename,ios::openmode mode);
Different file opening modes are given below:
27
COM 313 C++ Programming Language
EXCEPTION HANDLING
Exception
To understand the exception firstly we should know about the error in prgram.Errors in
program can be categorized into two types.
Compile Time Errors:- Errors caught during compiled time is called Compile time errors.
Compile time errors include library reference, syntax error or incorrect class import.
Run Time Errors:- The error that occours during the run time of program is called run time
error.
They are also known as exceptions. Hence we can say that exception is a runtime error that
occours because of user's mistake.
Reasons of Exception
28
COM 313 C++ Programming Language
Mismatched Input :Suppose that we are entering our name in place of age,causing
exception because age is of data type int and name will be string.
File does not exist :Suppose that we are reading a text file easy.txt and that file does not
exist in the system,causing exception.
Exception related to array :Suppose that the array size is 5 and we are inserting more than
5 elements,causing exception.
Divide by zero exception :When a number is divided by zero then the output will be
undefined(infinity).
Exception Handling
The process of handling the exception is called exception handling. There are three main
keywords are used to solve the problem of exception.
try block: It is the place where actual code is written and exception occurs. When the code
will lead to any error, that error/exception will get caught inside the catch block.
catch block: catch block is intended to catch the error and handle the exception condition.
We can have multiple catch blocks to handle different types of exception and perform
different actions when the exceptions occur.
throw statement: It is used to show the user defined message about the exception.
Syntax of try-catch
try{
// protected code
}catch(ExceptionNamee1){
// catch block
}catch(ExceptionNamee2){
// catch block
}catch(ExceptionNameeN){
// catch block
}
29