COM 313-C-Plus-Plus HND - Last
COM 313-C-Plus-Plus HND - Last
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
Valueless void
3
COM 313 C++ Programming Language
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.
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
This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output
stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.
2 <iomanip>
This file declares services useful for performing formatted I/O
with so-called parameterized stream manipulators, such
as setw and setprecision.
3 <fstream>
This file declares services for user-controlled file processing. We
will discuss about it in detail in File and Stream related unit.
11
COM 313 C++ Programming Language
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
UNDERSTAND FUNCTIONS AND LIBRARIES IN C++
Functions
A function is a group of statements that together perform a task. Every C++
program has at least one function, which is main(), and all the most trivial
programs can define additional functions.
12
COM 313 C++ Programming Language
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.
Defining a Function
The general form of a C++ function definition is as follows −
return_typefunction_name( parameter list ) {
body of the function
}
A C++ function definition consists of a function header and a function body.
Here are all the parts of a function −
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
is the keyword void.
Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements
that define what the function does.
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_typefunction_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);
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.
13
COM 313 C++ Programming Language
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.
UNIT 5
CONTROL STURCTURES IN C++
The If_Statement; syntax:
14
COM 313 C++ Programming Language
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”;
}
}}
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.
15
COM 313 C++ Programming Language
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;
switch (p){ OUTPUT:
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;}
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’
16
COM 313 C++ Programming Language
- 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
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.
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.
18
COM 313 C++ Programming Language
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;
15. }
EXAMPLE 2
1. #include <iostream>
2. using namespace std;
3. class Student {
19
COM 313 C++ Programming Language
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. }
20