C++ Notes
C++ Notes
Lecture Notes
1
1 History of C++
Sno C C++
1 C++ is a multi-paradigm. It supports
C follows the procedural style of
both procedural and object-
programming.
oriented.
2 Data is less secure in C. In C++, you can use modifiers for class
members to make them inaccessible to
outside users.
3 C follows the top-down approach. C++ follows the bottom-up
2
- Top-Down Model is a system approach
design approach where the - Bottom-Up Model is a system
design starts from the system as design approach where a
a whole. The complete system is system's parts are defined in
then divided into smaller sub- detail. Once these parts are
applications with more details. designed and developed, then
Each part again goes through the these parts or components are
top-down approach till the linked together to prepare a
complete system is designed with bigger component. This
all the minute detail. approach is repeated until the
complete system is built.
4 C++ supports function overloading.
C does not support function overloading.
- Two functions can have the
same name with different
numbers of parameters
e.g. calculate () and
calculate (int x) are two
different functions
5 In C, you can't use functions in In C++, you can use functions in
Structure. Structure.
6 C++ supports reference variables.
3
C. C++.
9 C programs are divided into C++ programs are divided into
procedures and modules functions and classes.
10 C does not provide the feature of the C++ supports the feature of the
namespace. namespace.
11 Exception handling is not easy in C. It C++ provides exception handling using
has to perform using other functions. Try and Catch block.
12 C does not support inheritance. C++ supports inheritance.
A data type specifies the type of data that a variable can store, such as integer,
floating, character, etc
The basic data types are integer-based and floating-point based. C++ language
supports both signed and unsigned literals.
The memory size of basic data types may change according to 32 or 64-bit operating
systems.
4
Data Types Memory Size Range
char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 32,767
short int 2 byte -32,768 to 32,767
signed short int 2 byte -32,768 to 32,767
unsigned short int 2 byte 0 to 32,767
long int 4 byte
signed long int 4 byte
unsigned long int 4 byte
float 4 byte
double 8 byte
long double 10 byte
5.2 Operators
Operators are symbols that perform operations on variables and values. C++ provides a
rich set of operators to manipulate variables. We can divide all the C++ operators into
the following groups.
5
i. Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra. The following table lists the arithmetic operators. Assume integer
variable A holds 10 and variable B holds 20, then.
6
ii. Relational Operators
There are the following relational operators supported by C++ language. Assume
variable A holds 10 and variable B holds 20, then.
7
iii. Bitwise Operators
C++ defines several bitwise operators, which can be applied to the integer types long,
int, short, char, and byte.
Bitwise Operator works on bits and performs the bit-by-bit operation. Assume if a = 60
and b = 13; now in the 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
8
a signed binary number.
Binary Left Shift Operator.
The left operand value is
A << 2 will give 240,
<< (left shift) moved left by the number of
which is 1111 0000
bits specified by the right
operand.
Binary Right Shift Operator.
The left operand value is
A >> 2 will give 15,
>> (right shift) moved right by the number
which is 1111
of bits specified by the right
operand.
Shift right zero fill operator.
The left operands value is
moved right by the number A >>>2 will give 15
>>> (zero fill right shift)
of bits specified by the right which is 0000 1111
operand and shifted values
are filled up with zeros.
Assume Boolean variables A holds true and variable B holds false, then.
9
any of the two operands are
non-zero, then the condition
becomes true.
Called Logical NOT Operator.
Use to reverse the logical
state of its operand. If a
! (logical not) !(A && B) is true
condition is true, then the
Logical NOT operator will
make false.
v. Assignment Operators
10
Multiply AND assignment
operator. It multiplies the
C *= A is equivalent to C
*= right operand with the left
=C*A
operand and assigns the
result to the left operand.
Divide AND assignment
operator. It divides the left
C /= A is equivalent to C
/= operand with the right
=C/A
operand and assigns the
result to the left operand.
Modulus AND assignment
operator. It takes modulus
C %= A is equivalent to
%= using two operands and
C=C%A
assigns the result to the left
operand.
6 C++ Identifiers
C++ identifiers in a program refer to the name of the variables, functions, arrays, or
other user-defined data types created by the programmer. They are the basic
requirement of any language. Every language has its own rules for naming the
identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a
program which are given below:
❖ Variables
❖ Constants
❖ Functions
❖ Labels
11
❖ Defined data types
6.1 Some naming rules are common in both C and C++. They are as follows:
For example, suppose we have two identifiers named 'FirstName', and 'Firstname'.
Both identifiers will be different as the letter 'N' in the first case is in uppercase while
lowercase is in the second. Therefore, it proves that identifiers are case-sensitive.
Result
Test2
_sum
power
12
7 C++ Variables
A variable is the name of a memory location whose value(data) can change during
program execution. The value stored in the variable can be changed when it is reused
many times. We name the memory location before storing data so that it will be easy to
restore them when needed by referring to the memory location name.
Data_type variable_name;
e.g.
int x;
float y;
char z;
Here, x, y, and z are variables, and int, float, and char are data types.
We can also provide values while declaring the variables as given below:
13
8 Basic Structure of a C++ Program
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 cout<<" We are BIT 1";
06 }
07
Output
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 float a=10,b=100,sum;
06 sum=a+b;
07
14
08 cout<<" The Sum is "<<sum;
09 }
10
Output
9 C++ Constants
A constant is the name of a memory location whose value(data) can not change during
program execution.
When you do not want others (or yourself) to change existing variable values, use the
const keyword (this will declare the variable as "constant", which means
unchangeable and read-only):
Question: Write a C++ program to calculate the area of a circle with a radius of 22cm.
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int r=22;
06 float PI=3.14,Area;
15
07 Area=PI*r*r;
08 cout<<" Area is: "<<Area <<" Cm";
09 }
10
Output
1. Decision-Making statements
• if statements
• switch statement
2. Looping statements
• for loop
• do while loop
• while loop
• for loop
3. Jump statements
• break statement
16
• continue statement
Simple if statement:
It is the most basic statement among all control flow statements in C++. It evaluates a
Boolean expression and enables the program to enter a code block if the expression is
true.
Syntax
if(condition)
Question: Given two numbers, a=10 and b=20. Write a C++ Program to determine
which number is greater and display the output on the screen.
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int a=10, b=20;
06 if(a>b)
07 {
08 cout<<" First Number is Greater";
09 }
10 if(b>a)
11 {
12 cout<<" Second Number is Greater";
13 }
14 if(a==b)
15 {
16 cout<<" The given numbers are equal";
17 }
18 }
Output
17
if-else- statement
It is an extension to the if-statement, which uses another block of code, i.e., the else
block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax
if(condition)
{
Statement 1; //executes when the condition is true.
}
else
{
Statement 2; //executes when the condition is false
}
Question: Write a C++ program to find the largest between two input numbers. Note
that a program should receive numbers as input from the user.
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int a, b;
06 cout<<"Enter the First Number\n";
07 cin>>a;
08 cout<<"Enter the Second Number\n";
09 cin>>b;
10 if(a>b)
11 {
12 cout<<" First Number is Greater";
13 }
14 if(b>a)
15 {
16 cout<<" Second Number is Greater";
18
17 }
18 else
19 {
20 cout<<" The given numbers are equal";
21 }
22 }
Output
if-else-if statement
The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that the chain of if-else statements creates a
decision tree where the program may enter the block of code where the condition is
true. We can also define an else statement at the end of the chain.
Syntax
if (condition 1)
{
Statement 1; //executes when condition 1 is true
}
else if (condition 2)
{
Statement 2; //executes when condition 2 is true
}
else
{
Statement 3; //executes when all the conditions are false
}
Question: Assume that CBE always assigns Diploma students' to different Bachelor's
Degree Courses based on their GPA qualification, as shown in Table 1. CBE
implemented a simple program to automate this task to avoid paperwork and save
19
time. Assume that you are working as a programmer at CBE. Write a simple C++
program that can perform this task.
Table 1:
GPA Range Department
4.5 - 5.0 ICT
4.5 - 5.0 Legal Metrology
3.5 - 4.4 Accounts
2.1 - 3.4 Procurement
2.1 - 3.4 Marketing
Program
01 #include<iostream>
02 using namespace std;
03
04
05 int main()
06 {
07 float GPA;
08 cout<<"Enter Student GPA\n";
09 cin>>GPA;
10 if(GPA>=4.5 && GPA <=5.0)
11 {
12 cout<<"Student can be Allocated to the ICT or Legal Metrology Department";
13 }
14 else if(GPA>=3.5 && GPA<=4.4)
15 {
16 cout<<"Student is Allocated to the Accounts Department";
17 }
18 else if(GPA>=2.1 && GPA<=3.4)
19 {
20 cout<<"Student can be Allocated to the Procurement or Marketing Department";
21 }
22 else
23 {
24 cout<<"Student doe not qualify for any department";
25 }
26 }
27
20
Output
Question: Write a C++ program to display the student's examination results. Your
program should perform the following: Accept the Student name, English Marks,
Geography Marks and Biology Marks as inputs from the user; also calculate the average
and grade based on the given average marks range as shown in Table 2. Finally, the
program should display student names, marks obtained from each subject, average
marks, and grades obtained.
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 string studentName;
06 float englmarks,geogmarks,biolmarks,averagegmarks;
07 cout<<"Enter Student Name\n";
08 cin>>studentName;
09 cout<<"Enter English Marks\n";
10 cin>>englmarks;
11 cout<<"Enter Geography Marks\n";
12 cin>>geogmarks;
21
13 cout<<"Enter Biology Marks\n";
14 cin>>biolmarks;
15 averagegmarks =(englmarks+englmarks+geogmarks)/3;
16
17 cout<<" ******* The following are Student Results *******\n";
18 cout<<"\n Student Name is "<<studentName;
19 cout<<"\n English Marks is "<<englmarks;
20 cout<<"\n Geography Marks is "<<geogmarks;
21 cout<<"\n Biology Marks is "<<biolmarks;
22 cout<<"\n Average Marks is "<<averagegmarks ;
23
24 if(averagegmarks>=80 && averagegmarks<=100)
25 {
26 cout<<"\n Grade is A";
27 }
28 else if(averagegmarks>=70 && averagegmarks<=79)
29 {
30 cout<<"\n Grade is B+";
31 }
32 else if(averagegmarks>=60 && averagegmarks<=69)
33 {
34 cout<<"\n Grade is B";
35 }
36 else if(averagegmarks>=50 && averagegmarks<=59)
37 {
38 cout<<"\n Grade is C";
39 }
40 else
41 {
42 cout<<"\n Grade is F";
43 }
44 }
22
Output
The Java switch statement executes one statement from multiple conditions. It is like
the if-else-if ladder statement; it tests the expression value against each case value. It
executes the case value body if the expression value matches the case value. However,
it executes the default body if no match is found. Each case statement can have an
optional break statement. When control reaches the break statement, it exits the switch
statement. If a break statement is not found, it executes the next case.
Syntax
Switch (expression)
{
case value 1:
//code to be executed;
break; //optional
case value 2:
//code to be executed;
break; //optional
......
23
…..
case value n:
default:
Code to be executed if all cases are not matched;
}
Question: Using a switch case statement, write a Java program to display the module
name based on the given module code considering Table 3. Note that your program
should accept module code as input from the user (Also observe the output without
using the break statements).
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int modulecode;
06 cout<<" Enter Module code\n";
07 cin>>modulecode;
08 switch(modulecode)
09 {
10 case 7313:
11 cout<<"Data Structure and Algorithm";
12 break;
13 case 7312:
24
14 cout<<"Programming in Java";
15 break;
16 case 7212:
17 cout<<"Programming in C++";
18 break;
19 default:
20 cout<<"Please Select the Correct Code";
21 }
22 }
Output
for loop
Like a while loop, the for loop executes its internal part only if the condition is valid in
each execution. Therefore, before performing any iteration, the for loop tests the
condition to see if it is true.
25
Syntax
❖ init: The init expression is used for initializing a variable and is executed only
once.
❖ Condition: It executes the condition statement for every iteration. It executes the
loop's body if it evaluates the condition as true. The loop will continue to run
until the condition becomes false.
❖ incr/decr: The increment or decrement statement is applied to the variable to
update the initial expression.
Note that: The “init, condition and incr/decr” parts are enclosed inside the brackets in
the for loop syntax
Program
01 #include<iostream>
02 using namespace std;
03 int main ()
04 {
05 int i;
06 for (i=1;i<=10;i++)
07 {
08 cout<< i <<"\n";
09 }
10 }
26
Output
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int i,n;
06 for(i=1;i<=5;i++)
07 {
08 n=i*2;
09 cout<<n<<" ";
10 }
11 }
Output
27
Question: Write a Java program to display the following shape using for loop
*
**
***
****
*****
******
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 for(int i=1; i<=6; i++)
06 {
07 for(int j=1;j<=i;j++)
08 {
09 cout<<"*";
10 }
11 cout<<"\n";
12 }
13 }
Output
28
Question: Write a Java program to display the following shape using for loop
*******
******
*****
****
***
**
*
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 for(int i=1; i<=6; i++)
06 {
07 for(int j=1;j<=7-i;j++)
08 {
09 cout<<"*";
10 }
11 cout<<"\n";
12 }
13 }
Output
29
Question: Write a Java program to display the following shape using for loop
2
24
246
2468
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 for(int i=1; i<=4; i++)
06 {
07 for(int j=1;j<=i;j++)
08 {
09 int n=2*j;
10 cout<<n;
11 }
12 cout<<"\n";
13 }
14 }
Question: Write a Java program to display the following shape using a for loop
1 2345
1 234
1 23
1 2
1
30
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 for(int i=0; i<=6; i++)
06 {
07 for(int j=1;j<=6-i;j++)
08 {
09 cout<<j;
10 }
11 cout<<"\n";
12 }
13 }
14
Output
while loop
Like a for loop, the while loop executes its internal part only if the condition is valid in
each execution. Therefore, before performing any iteration, the while looptests the
condition to see if it is true. The while loop is similar to for loop; however, the init,
condition and the incr/decr part are separate (not enclosed inside the bracket)
31
Syntax
init;
while (condition)
{
//Statements to be executed or body
incr/decr;
}
In the above syntax:
❖ init: The init expression is used for initializing a variable and is executed only
once.
❖ condition: It executes the condition statement for every iteration. It executes the
loop's body if it evaluates the condition as true. The loop will continue to run
until the condition becomes false.
❖ incr/decr: The increment or decrement statement is applied to the variable to
update the initial expression.
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int i=1;
06 while(i<=10)
07 {
08 cout<<i<<"\n";
09 i=i+1;
10 }
11
12 }
32
Output
Question: Attempt all programs completed using for loop statement above using a
while loop
do-while loop
Unlike Like a for loop and while loop,the do-while executes its internal part only if
the condition is valid in each execution proceeding the first one. It means the first
execution is a must for the do-while loop. Like while loop, the init, condition and
the incr/decr part are separate (not enclosed inside the bracket)
Syntax
init;
do
{
//Statements to be executed or body
incr/decr;
}
while(condition);
33
In the above syntax:
❖ init: The init expression is used for initializing a variable andis executed only
once.
❖ condition: It executes the condition statement for every iteration. It executes the
loop's body if it evaluates the condition as true. The loop will continue to run
until the condition becomes false.
❖ incr/decr: The increment or decrement statement is applied to the variable to
update the initial expression
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int i=1;
06 do
07 {
08 cout<<i<<"\n";
09 i=i+1;
10 }
11 while(i<=10);
12 }
34
Output
Question: Attempt all programs completed using for loop statement above using a do-
while loop
11 Arrays
An array is a variable that stores a collection of data with the same data type or
Arrays are used to store multiple values in a single variable instead of declaring
separate variables for each value.
To declare an array, define the variable type, specify the name of the array followed by
square brackets, and specify the number of elements it should store:
Data_type Array_name[Array_size];
Example
int A[10];
35
A: Is an array name
The elements of an array are stored in a contiguous memory location. We can store
only a fixed set of elements in an array. Array in C++ is index-based; the first element
of the array is stored at the 0th index, 2nd element is stored on the 1st index, and so
on. Consider a description of an array
A[10] below;
Values 10 20 30 40 50 60 70 80 90 100
Index 0 1 2 3 4 5 6 7 8 9
int A[10]={10,20,30,40,50,60,70,80,90,100}
36
or
A[0]=10;
A[1]=20;
A[2]=30;
A[3]=40;
A[4]=50;
A[5]=60;
A[6]=70;
A[7]=80;
A[8]=90;
A[9]=100;
Question:
37
Program for part(b)
Program
01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 int A[10]={10,20,30,40,50,60,70,80,90,100}; //Storing of Elements
06 cout<<A[2]<<"\n"; // Retrieving Element 30
07 cout<<A[2]<<"\n"; // Retrieving Element 30
08 A[4]=100; //Updating 50 to 100
09
10 //Displaying All Elements Using for Loop
11 for(int i=0;i<=9;i++)
12 {
13 cout<< A[i]<<" ";
14 }
15 }
Output
12 Functions/Methods
38
customer's account. All program statements that perform deposits can be grouped into
a function.
39
21 {
22 openbankaccout();
23 }
Output
40
20 cin>>balance;
21
22 openbankaccout (accountname, accountnumber, balance);
23 }
Output
An object is any real-world entity that can be converted into a computer program. The
object can be physical or logical (tangible and intangible). An example of an intangible
object is the banking system. Examples of tangible objects include a chair, bike,
marker, pen, table, and car.
Or
41
An object has three characteristics (Imagine our object is a bus)
State: These are properties of an object. For example, a bus as an object state will be
colour, current speed, number of wheels, etc. In programming, object states are
represented by variables.
Behaviour: These are all actions that an object can perform. For example, for a bus,
object behaviour will be slow down, speed up and turn around. In programming,
objects' behaviours are represented by functions.
Identity: It is a unique name for an object which differentiates an object from the rest
Data_type variable n;
Data_type function1();
Data_type function2();
……………………………
……………………………
Data_type function n();
}
42