0% found this document useful (0 votes)
11 views42 pages

C++ Notes

C++ is an object-oriented programming language developed by Bjarne Stroustrup in 1980 as an extension of C, adding features like classes and objects. It is popular for its portability, efficiency, and ability to structure programs clearly, allowing for code reuse. The document also covers data types, operators, identifiers, variables, and the basic structure of a C++ program.

Uploaded by

ileler69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views42 pages

C++ Notes

C++ is an object-oriented programming language developed by Bjarne Stroustrup in 1980 as an extension of C, adding features like classes and objects. It is popular for its portability, efficiency, and ability to structure programs clearly, allowing for code reuse. The document also covers data types, operators, identifiers, variables, and the basic structure of a C++ program.

Uploaded by

ileler69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Programming in C++

Lecture Notes

1
1 History of C++

C++ programming language was developed in 1980 by Bjarne Stroustrup at Bell


laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A. Bjarne
Stroustrup is known as the founder of the C++ language. It was developed to add
a feature of OOP (Object Oriented Programming) in C without significantly
changing the C component. Therefore, C++ was created as an extension of C, and both
languages have almost the same syntax. The main difference between C and C++ is
that C++ supports classes and objects, while C does not.

2 Why Use C++

1. C++ is one of the world's most popular programming languages.


2. C++ can be found in today's operating systems, Graphical User Interfaces, and
embedded systems.
3. C++ is an object-oriented programming language that gives a clear structure to
programs and allows code to be reused, lowering development costs.
4. C++ is portable and can be used to develop applications that can be adapted to
multiple platforms.
5. C++ is fun and easy to learn!

The following are the differences between C and 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.

- E.g String s=”anova”;


C does not support reference variables.
String s1=&s

7 C++ mainly uses stream cin and cout


In C, scanf() and printf() are mainly
to perform input and output
used for input/output.
operations.
8 Operator overloading is not possible in Operator overloading is possible in

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.

3 C++ Data Types

A data type specifies the type of data that a variable can store, such as integer,
floating, character, etc

Types Data Types


Basic Data Type (Built-in/Primitive Data types) int, char, float, double, void etc
Derived Data Type array, pointer, reference etc
Enumeration Data Type enum
User Defined Data Type Structure, Class, Union, Typedef

4 Basic Data Types

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

Note: Other data types will be discussed in the coming sections

5 Operands and Operators


5.1 Operands

Operands are variables or values that operators can manipulate

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.

Operator Description Example


Multiplies values on either It is evaluated
* (Multiplication) A * B will give 200
side of the Operator. first. If there
Divides left-hand operand are several
/ (Division) B / A will give 2
by right-hand operand. operators of
this type,
Divides left-hand operand they're
% (Modulus) by right-hand operand and B % A will give 0 evaluated
returns remainder. from left to
right.
Adds values on either side It is evaluated
+ (Addition) A + B will give 30
of the Operator. next. If there
are several
operators of
Subtracts right-hand
this type, they
- (Subtraction) operand from the left-hand A - B will give -10
are evaluated
operand.
from left to
right.
Its is
= Assign a value to a
evaluated
(Equal/Assignment) variable
last.

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.

Operator Description Example


Checks if the values of two operands are
(A == B) is not
== (equal to) equal or not, if yes then condition
true.
becomes true.
Checks if the values of two operands are
!= (not equal to) equal or not, if values are not equal then (A != B) is true.
condition becomes true.
Checks if the value of left operand is
> (greater than) greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.
Checks if the value of left operand is less
< (less than) than the value of right operand, if yes (A < B) is true.
then condition becomes true.
Checks if the value of left operand is
>= (greater than or greater than or equal to the value of (A >= B) is not
equal to) right operand, if yes then condition true.
becomes true.
Checks if the value of left operand is less
<= (less than or than or equal to the value of right
(A <= B) is true.
equal to) operand, if yes then condition becomes
true.

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

The following table lists the bitwise operators;

Assume integer variable A holds 60 and variable B holds 13 then;

Operator Description Example


Binary AND Operator copies a
(A & B) will give 12,
& (bitwise and) bit to the result if it exists in
which is 0000 1100
both operands.
Binary OR Operator copies a
(A | B) will give 61, which
| (bitwise or) bit if it exists in either
is 0011 1101
operand.
Binary XOR Operator copies
(A ^ B) will give 49,
^ (bitwise XOR) the bit if it is set in one
which is 0011 0001
operand but not both.
Binary Ones Complement (~A ) will give -61, which
~ (bitwise compliment) Operator is unary and has the is 1100 0011 in 2's
effect of 'flipping' bits. complement form due to

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.

iv. Logical Operators

The following table lists the logical operators.

Assume Boolean variables A holds true and variable B holds false, then.

Operator Description Example


Called Logical AND Operator.
If both the operands are non-
&& (logical and) (A && B) is false
zero, then the condition
becomes true.
|| (logical or) Called Logical OR Operator. If (A || B) is true

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

Following are the assignment operators supported by the C++ language

Operator Description Example


Simple assignment operator.
Assigns values from right-side C = A + B will assign the
=
operands to left-side value of A + B to C
operands.
Add AND assignment
operator. It adds the right
C += A is equivalent to C
+= operand to the left operand
=C+A
and assigns the result to the
left operand.
Subtract AND assignment
operator. It subtracts the
C -= A is equivalent to C
-= right operand from the left
=C–A
operand and assigns the
result to the left operand.

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:

❖ Only alphabetic characters, digits, and underscores are allowed.


❖ The identifier name cannot start with a digit, i.e., the first letter should be
alphabetical. After the first letter, we can use letters, digits, or underscores.
❖ In C++, uppercase and lowercase letters are distinct. Therefore, we can say that
C++ identifiers are case-sensitive.
❖ A declared keyword cannot be used as a variable name.

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.

6.2 Valid Identifiers

The following are examples of valid identifiers are:

Result

Test2

_sum

power

6.3 Invalid Identifiers

Sum-1 // containing the special character '-'.


2data // The first letter is a digit.
break // use of a keyword.

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.

The following is the syntax for declaring a variable.

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:

1. int x=5,b=10; //declaring 2 variable of integer type


2. float f=30.8;
3. char c='A';

13
8 Basic Structure of a C++ Program

A C++ program is structured in a specific manner. In C++, a program is divided into


the following three sections:

1. Standard Libraries Section


2. Main Function Section
3. Function Body Section

For example, let's look at the implementation of We are BIT 1 program:

Program

01 #include<iostream>
02 using namespace std;
03 int main()
04 {
05 cout<<" We are BIT 1";
06 }
07

Output

Question: Write a C++ Program to add two number

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):

A constant is declared using the constant keyword

The syntax for declaring a constant

constant data_type constant_name;

e.g., constant float PI=3.14

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

10 C++ Control Statements | Control Flow in C++


C++ compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, C++ provides
statements that can be used to control the flow of C++ code. Such statements are
called control flow statements. It is one of the fundamental features of C++, which
provides a smooth program flow.

C++ provides three types of control flow statements.

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

10.1 Decision-Making Statements

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)

Statement 1; //executes when the condition is true.

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.

Table 2: Average Scores vs Grades


Average score Grade
80-100 A
70-79 B+
60-69 B
50-59 C
0-49 F

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

10.2 Switch Case Statement

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).

Table 4: Module code against the department

Module code Department


7313 Data Structure and Algorithm
7312 Programming in Java
7212 Programming in C++

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

10.3 Looping statements

Looping statements allow certain instructions to be executed repeatedly until a


condition has become false. Consider a circumstance where you must print numbers
ranging from 1 to 1000. How would you react? Will you type cout thousands of times
or try to copy/paste it? Hopefully, it will be a tedious job. By using looping statements,
this process can be completed efficiently.

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

for(init; condition, incr/decr)


{
//Statements to be executed or body
}

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.

Note that: The “init, condition and incr/decr” parts are enclosed inside the brackets in
the for loop syntax

Question: Write a C++ program to display 1 to 10 using for loop

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

Question: Write a Java program to display 2, 4, 6, 8, 10 using a for loop

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.

Question: Write a Java program to display 1 to 10 using a while loop

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

Question: Write a Java program to display 1 to 10 using a do-while loop

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

An array is a collection of elements with the same data type

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:

The syntax for declaring an array:

Data_type Array_name[Array_size];

Example

int A[10];

From the above declaration

int: Indicates the data type

35
A: Is an array name

10: Array size

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;

The elements 10,20,30,40,50,60,70,80,90,100 of an Array “A” can be stored as follows


in the computer memory.

Values 10 20 30 40 50 60 70 80 90 100
Index 0 1 2 3 4 5 6 7 8 9

Actions that can be performed to an Array “A” above

1) Storing Elements 10,20,30,40,50,60,70,80,90,100 to the array “A”

Sample of storing elements to an Array “A”

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;

2) Storing 100 into index 1 of an array “A”


A[1]=100;
3) Retrieving 40 from Array “A”
cout<<A[3];

Question:

a) Define an array (Refer to the definition array on the previous page)


b) Write a C++ program to perform the following to an array named “A”.
i. Storing elements 10,20,30,40,50,60,70,80,90,100 into an array “A “ as
integers
ii. Retrieving the element 30 from an array “A”
iii. Retrieving the 3rd element from an array “A”
iv. Updating the element 50 to 100 from an array “A”
v. Retrieving all Elements using a for loop

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

A C++ method/Function is a collection of statements grouped to perform a certain


operation when being called in a program. For example, a section of a bank information
system dealing with customers' deposit may contain several lines of code that
communicate with the database, which transfer and store the desired amount in the

38
customer's account. All program statements that perform deposits can be grouped into
a function.

The syntax for creating a function

return_type method name (list of arguments)


{
//Function Body
}

Note that: The list of arguments part is optional.

Example: A C++ program implementing a function that enables a banker to open a


bank account for a particular customer and display account details on the screen.
Case 1: A program without parameters
01 #include<iostream>
02 using namespace std;
03 void openbankaccout()
04 {
05 string accountname;
06 string accountnumber;
07 float balance;
08 cout<<" Enter Account Name\n";
09 cin>>accountname;
10 cout<<" Enter Account Number\n";
11 cin>>accountnumber;
12 cout<<" Enter Balance\n";
13 cin>>balance;
14
15 cout<<"\n********** You have Opened the Following Account\n";
16 cout<<" Enter Account Name: "<<accountname<<"\n";
17 cout<<" Enter Account Number: "<<accountnumber<<"\n";
18 cout<<" Enter Balance: "<< balance<<"\n";
19 }
20 int main()

39
21 {
22 openbankaccout();
23 }

Output

Case 2: A program with parameters/Using message passing concept


01 #include<iostream>
02 using namespace std;
03 void openbankaccout (string a,string b, float c)
04 {
05 cout<<"\n********** You have Opened the Following Account\n";
06 cout<<" Enter Account Name: "<<a<<"\n";
07 cout<<" Enter Account Number: "<<b<<"\n";
08 cout<<" Enter Balance: "<< c <<"\n";
09 }
10 int main()
11 {
12 string accountname;
13 string accountnumber;
14 float balance;
15 cout<<" Enter Account Name\n";
16 cin>>accountname;
17 cout<<" Enter Account Number\n";
18 cin>>accountnumber;
19 cout<<" Enter Balance\n";

40
20 cin>>balance;
21
22 openbankaccout (accountname, accountnumber, balance);
23 }

Output

13 C++ Classes and Objects

What is a class in C++?

A Class is an object constructor or a "blueprint" for creating objects. Or Class is a


group of variables and methods of different data types.

What is an object in C++?

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

An object is an instance of a class

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

Imagine our object is a bank account


State: current balance, opening date, account number
Behaviour: withdraw, deposit, transfer, and check the balance
Identity: Account Name
The syntax for declaring a class
To create a class, use the class keyword
class class_name {
Access specifier:
Data_type variable 1;
Data_type variable 2;
……………………………
……………………………

Data_type variable n;
Data_type function1();
Data_type function2();
……………………………
……………………………
Data_type function n();
}

42

You might also like