0% found this document useful (0 votes)
9 views24 pages

Introduction to Object-Oriented Programming

Chapter 1 introduces Object-Oriented Programming (OOP) and its principles, highlighting the evolution of C++ from C and the key features of OOP such as encapsulation, inheritance, and polymorphism. It contrasts procedure-oriented programming with OOP, emphasizing the benefits of OOP including modularity, data hiding, and reusability. The chapter also covers basic concepts, data types, and the structure of C++ programming.

Uploaded by

rakibpathan381
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)
9 views24 pages

Introduction to Object-Oriented Programming

Chapter 1 introduces Object-Oriented Programming (OOP) and its principles, highlighting the evolution of C++ from C and the key features of OOP such as encapsulation, inheritance, and polymorphism. It contrasts procedure-oriented programming with OOP, emphasizing the benefits of OOP including modularity, data hiding, and reusability. The chapter also covers basic concepts, data types, and the structure of C++ programming.

Uploaded by

rakibpathan381
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

Chapter 1

Introduction to OOP’s

- Introduction to oop’s
- Object oriented programming
- Basic concept of oop’s
- Benefits of oop’s

INTRODUCTION TO OOP’S
C++ is an object oriented programming language. It was developed by Bjarne
Stroustrup at AT & T Bell Laboratories in the early 1980’s. stroustrup, an admirer of
Simula67 and a strong supporter of C, wanted to combine the best of both the languages
and create a more powerful language that could support object oriented programming
features and still retain the power and elegance of C. the result was C++. However, later
in 1983, the name was changed to C++. The idea of C++ comes from the C increment
operator ++, thereby suggesting that C++ is an augmented (incremented) version of C.
C++ is a superset of C. Most of what we already know about C applies to C++ also.
Therefore, almost all C programs are also C++ programs.
The most important facilities that C++ adds on to C are classes, inheritance, function
overloading, and operator overloading. These features enable creating of abstract data
types, inherit properties from existing data types and support polymorphism, thereby
making C++ a truly object oriented language. C and C++ both are middle level
languages.

1
Procedure oriented programming

- Conventional programming, using high level language such as COBOL,


FORTRAN and C, is commonly known as procedure oriented programming
(POP).
- In the procedure oriented approach, the problem is viewed as a sequence of
things to be done such as reading, calculating and printing. A number of
functions are written to accomplish these tasks.
- Procedure oriented programming basically consists of writing a list of
instructions or actions for the computer to follow, and organizing these
instructions into groups known as functions.

Features / Characteristics of procedure oriented programming are:


a. Emphasis is on procedure or we can say function. (algorithms)
b. Large programs are divided into smaller programs known as functions.
c. Most of the functions share global data
d. Data move openly around the system from function to function.
e. Functions transform data from one form to another.
f. Employs top-down approach in program design.

Procedure – oriented programs

2
OBJECT ORIENTED PROGRAMMING (OOP)
Definition:
“Object- oriented programming as an approach that provides a way of
modularizing programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on
demand”
Object oriented programming (OOP) is an approach to program organization and
development that attempts to eliminate some of the pitfalls of conventional programming
methods by incorporating the best of structured programming features with several
powerful new concepts. It is a new way of organizing and developing programs and has
nothing to do with any particular language.

- OOP treats data as a critical element in the program development and does not
allow it to flow freely around the system.
- It ties data more closely to the functions that operate on it, and protects it from
accidental modification from outside functions.
- OOP allows decomposition of a problem into a number of entities called objects
and then builds data and functions around these objects.
- An object is considered to be a partitioned area of computer memory that
stores data and set of operations that can access that data.

Features / characteristics of object- oriented programming are:


a. Emphasis is on data rather than procedure.
b. Programs are divided into what are known as objects.
c. Data structures are designed such that they characterize the objects.
d. Data is hidden and cannot be accessed by external functions.
e. Objects may communicate with each other through functions.
f. New data and functions can be easily added whenever necessary.
g. Follows bottom- up approach in program design.

3
Organization of data and functions in OOP
.

BASIC CONCEPT OF OOPS

Some concept of object oriented programming


a. Objects
b. Classes
c. Data abstraction and encapsulation
d. Polymorphism
e. Dynamic binding
f. Message passing

OBJECT
- Objects are basic run time entities in an object oriented system. (e.g. person, a
place, a bank account, etc)
- Objects are variables of the type class
- They may also represent user defined data such as vectors, time and lists.
- Objects take up space in the memory and have an associated address like a record
in a structure in C.
- When a program is executed, the objects interact by sending messages to one
another.
- Objects can interact without having to know details of each others data or code.
- Objects contain data and code to manipulate the data.

4
Object: student

DATA
Name
Date of birth
Marks

FUNTIONS
Total
Average
Display

CLASSES
- The entire set of data and code of an object can be made a user-defined data type
with the help of a class.
- A class is thus a collection of objects of similar type.
- Classes are user defined data types and behave like the built in types of a
programming language.
- The syntax used to create an object is no different than the syntax used to create
an integer object in C.
E.g.: if ‘student’ has been defined as class, then the statement

Syntax:

<Class name> <Object name>;


Student obj1;

Will create an object ‘obj1’ belonging to the class ‘student’

ENCAPSULATION and DATA ABSTRACTION

ENCAPSULATION (sum up, summarize)


- The wrapping(binding) up of data and functions into a single unit ( called class)
is known as encapsulation
- The data is not accessible to the outsider, and only those functions which are
wrapped in the class can access it.
- This insulation (to isolate, to separate) of the data from direct access by the
program is called data hiding or information hiding.

5
ABSTRACTION (construct)
- Abstraction refers to the act of representing essential features without including
the background details or explanations.
- Attributes are sometimes called data members because they hold information.
- The functions that operate on these data are sometimes called methods or
member functions.
- Class use the concept of data abstraction, they known as Abstract Data
Types(ADT)

INHERITANCE
- Inheritance is the process by which objects of one class acquire the properties of
object of another class.
- In OOP, the concept of inheritance provides the idea of reusability. This means
that we can add additional features to an existing class without modifying it. This
is possible by deriving a new class from the existing one.
- The new class will have the combined features of both the classes (‘old’ as well
as ‘new’)
- Note that each sub – class defines only those features that are unique to it.

POLYMORPHISM
- Polymorphism, a Greek term, means the ability to take more than one form.
- Polymorphism means one name, multiple forms. It allows us to have more than
one function with the same name in a program.
- The process of making an operator to exhibit different behaviours in different
instances is known as operator overloading.
- Using a single function name to perform different types of tasks is known as
function overloading.

DYNAMIC BUINDING
- Dynamic binding means that the code associated with a given procedure is not
known until the time of the call at run-time.
- Dynamic binding (also known as late binding) means that the code associated
with a given procedure call is not known until the time of the call at run – time.
- It is associated with a polymorphism and inheritance.

MESSAGE PASSING
- Message passing involves specifying the name of the object, the name of the
function (message) and the information to be sent.
- Object communicate with one another by sending and receiving information
much the same way as people pass messages to one another.
- Objects have a life cycle. They can be created and destroyed.

6
.

BENEFITS OF OOPS

OOP offers several benefits to both the program designer and the user.
- The new technology promises greater programmer productivity, better quality of
software and lesser maintenance cost.
- Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
- We can build programs from the standard working modules, this leads to saving
of development time and higher productivity.
- The principle of data hiding helps the programmers to build secure programs.
- It is possible to have multiple instance of an object to co-exist without any
interference.
- It is easy to partition the work in a project based on objects.
- The data-centered design approach enables us to capture more details of a model
in implemental form.
- Object oriented systems can be easily upgraded from small to large system.
- Software complexity can be easily managed.

--------------------------Luck require Hard Work -------------------------------

7
Chapter 1 Introduction to C++

Tokens
As we know, the smallest individual units in a program are known as tokens. C++
has following tokens
 Keywords
 Identifiers
 Constants
 Strings
 Operators
- A C++ program is written using these tokens, white spaces, and the syntax
of the language.
- Most of the C++ tokens are basically similar to the C tokens with the
exception of some additions and minor modifications.

Keywords
- There are 48 keywords in C++. (There are 32 keywords in C language).
- These keywords have specific meaning associated (related/connected) with
them.
- The keyword can not be used as variable name (user define data type).
C++ keywords
asm auto break case catch
char class const continue default
delete do double else enum
extern float for friend goto
if inline int long new
operator private protected public register
return short signed sizeof static
struct switch template this throw
try typedef union unsigned virtual
void volatile while

- Many of them are common to both C and C++.

IDENTIFIERS AND CONSTANTS


- Identifiers refer to the names of variables, functions, array, classes etc.
created by the programmer
Rules:
1. Only alphabetic characters, digits and underscores are permitted.
2. The variable name cannot start with a digit.
3. Uppercase and lowercase letters are distinct (different).
4. A keyword cannot be used as a variable name.

- C++ does not have limit on the length of identifiers.


- Some operating systems impose a restriction on the length of such a
variable name.
- Constants refer to fixed values that do not change during the execution of
a program.

1
Chapter 1 Introduction to C++

BASIC DATA TYPES


Data types in C++ can be classified under various categories as follow:

C++ Data Types

.User – defined type Derived type

- class - array
- enumeration Built in type - function
- structure - pointer
- union - reference

Integral type void Floating point

int char float double

- Both C and C++ compilers support all the built-in (also known as basic
or fundamental) data types.
- ‘void’ data type is not having modifiers.
- Basic data type Character, integer are having modifiers like signed,
unsigned, long and short.

Declaration of variable:
- All variable must be declared before they are used in executable
statements.
- They can be declared any where in the program.
Syntax:
<data type > <variable name>
Example:
-int rollno; // “rollno” is the variable of type integer.
-char name[10]; // “name” is the variable of type character(string).

Dynamic initialization of variables:


- C++ permits initialization of the variable at runtime known as dynamic
initialization.
Example:
float area = 3.14 * r * r ;

- From above example, observe that declaration and initialization of variable


can be done simultaneously.

2
Chapter 1 Introduction to C++

Reference variable:
- A reference variable provides an alternative name (alias) for previously
defined variable.
Syntax:
data type &reference variable = variable - name

Example:
int total = 100;
int &sum = total;

Void data type:


Two normal uses of void are
1. To specify the return type of a function when it is not returning any value
2. To indicate an empty argument list to a function.

Example:
void funct1(void);

A. User-defined data types:


i. Structure and Classes
- ‘struct’ and ‘union’ used as user-defined data type in C and C++.
- ‘class’ is one new data type introduced by C++.
- The class variables are known as objects.

ii. Enumerated data type


- The enum keyword (from C) automatically enumerates a list of words by
assigning them values 0,1,2 and so on.
- This facility provides an alternative means for creating symbolic
constants.
- The syntax of an enum statement is similar to that of the struct
statement
- By default, the enumerators are assigned integer values starting with 0
for the first enumerator, 1 for the second, and so on.
- In C++, an enum defined within a class( or structure) is local to that class(
or structure) only.
Example:
enum shape{circle, square, triangle};
enum color{red, blue, green, yellow};
enum position{off, on};
enum class{BCA,BSc_cs,BSc_cm,BSc_se, BSc_it};

we can declare new variable


Example:
shape ellipse_type // ellipse is of type shape.
color background // background is of type color.
class code // code is of type class
//Program to demonstrate ‘enum’ keyword.

3
Chapter 1 Introduction to C++

#include<iostream.h> [ In this given program


#include<conio.h>
enum batch{BCA,BSc_cs,BSc_cm,BSc_se,BSc_it}; programmer define
enum datatype that is
void main() ‘batch’ under that more
{ than one option is
clrscr();
int code=0;
available. After
do execution of this
{ program, if user
cout<<"\nEnter student class [0-4]: "; chooses ‘2’ then it will
cin>>code; display the answer
switch(code)
{ ‘Select BSc CM’. it
case BCA: means that by default,
cout<<"\nSelect BCA "; the enumerators are
break; assigned integer values
case BSc_cs:
cout<<"\nSelect BSc CS ";
starting with 0 for the
break; first enumerator, 1 for
case BSc_cm: second and so on. It
cout<<"\nSelect BSc CM "; means in given
break; example: 0 for BCA, 1
case BSc_se:
cout<<"\nSelect BSC SE "; for BSc_cs, 2 for
break; BSc_cm and so on.]
case BSc_it:
cout<<"\nSelect BSc IT ";
break;
default:
cout<<"\nInvalid input";
break;
}
}while(code >= 0 && code <= 4);
getch();
}

Output:
Enter student class [0-4]: 2
Select BSc CS

B. Derived data types:


Arrays
- A collection of data elements arranged to be indexed in one or more
dimensions. In C++, arrays are stored in contiguous memory.
- A collection of data elements acquiring different data but same data type
- The application of array in C++ is similar to that in C, but only one
exception is character array initialization.
Example:
char string[3]= ”XYZ” // character type initialization is valid in C.

- But in C++, the size should be one larger than the number of character in
the string. For instance,

Char string[4] = “xyz” // character type initialization is valid in C++

4
Chapter 1 Introduction to C++

Functions:
- We can say function is to do a given specific task.
- A function is a mechanism that enables us to use modular programming
and facilitates software reuse.
- A statement block in a program is a set of statements within curly braces.
- Function can use local and global variables and even other functions, in
their implementation.
Syntax:
Data-type function-name(argument-list); .

Pointers:
- A pointer is a variable that to holds a memory address of another
variable.
- Pointers are generally used in C++ for memory management and achieving
polymorphism.

Pointers are declared and initialization:


int *ip,x //declare integer pointer variable “ip” and simple variable ‘x’.
ip = &x; // address of ‘x’ assigned to ip.
*ip = x; // 10 assigned to ‘x’ through indirection

Symbolic constant
There are two ways of creating symbolic constant in C++.
i. Using the qualifier “const”, and
ii. Defining a set of integer constant using “enum” keyword.

- Value declared as const cannot be able to modify in whole program.


- In C++, we can use const in a constant expression, such as
Example:
const int size = 10;
char name[size];

- C++ requires a const to be initialized.

Structure of C ++ Program
- Typical C++ program would contain four sections.
- These sections may be placed in separate code files and then compiled
independently or jointly.

Structure of C++ program:

Include files Section 1

Class declaration Section 2

Member functions definitions Section 3

Main function program Section 4

5
Chapter 1 Introduction to C++

- It is a common practice to organize a program into three separate files.


- The class declaration is placed in a header file.
- The definitions of member functions go into another file.
- The main program that uses the class is placed in a third file which
“includes” the previous two files as well as any other files required.
- This approach is based on the concept of client server model.
- The class definition including the member functions constitute the
server that provides services to the main program known as client.
- The client uses the server through the public interface of the class.

The client server model

Member Functions
server

Class definition

client
Main function program

I/O statements
Let us begin with a simple example
Output statement
// program to demonstrate simple output statement
- First include header files. That
#include<iostream.h> would be helpful to us during
the program.
void main() // start main() function - After that execution begin with
{ main() function. Every C or
cout << “ Welcome in OOP language”; C++ program must have main()
} function.
- With the help of cout (console
Output output and insertion operator)
Welcome in OOP language displays the message on
console.
C++ introduce new comment
symbol that is “//”(double slash).
Before that we are used “/* */”
in ANSI C as comment line.

6
Chapter 1 Introduction to C++

Input statement
// program to demonstrate simple input statement
#include<iostream.h> - With the help of cout (console
void main() // start main() function output and insertion operator)
{ displays the message on
char name[10]; console.
cout << “ Welcome in OOP language”; - With the help of cin(console
cout<< “Input good name please : ”; input and extraction operator)
cin >> name; take input from user.
cout<< “Your good name is :” << name;
}

Output:
Welcome in OOP language
Input good name please : anil
Your good name is : anil

Operators in C++
- All C operators are valid in C++ also.
In addition, C++ introduces some new operators.
Operator Name
<< Insertion operator
>> Extraction operator
:: Scope resolution operator
::* Pointer to member
->* Pointer to member operator
.* Pointer to member operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator

<< Insertion operator:


- “<<” is insertion or put to operator.
- It insert (or sends) the contents of the variable on its right to the object on
its left.
- This is similar to printf() operation in C language.
Example:
cout << name;
- Above statement will display the contents of variable “name”.
- Here, “cout” is predefined object that represents standard output stream in
C++.

>> Extraction operator:


- “>>” operator is extraction operator or get from operator.
- If extracts (or takes) the value from the keyboard and assign it to the
variable on its right. --This is similar to scanf() operation in C language.
Example:

7
Chapter 1 Introduction to C++

cin >> number1;


- This statement causes the programmer to wait for the user to type in a
number.
- “cin” is predefined object in C++ that corresponds to standard input
stream.

Scope resolution operator


- C++ is also a block structured language
- Blocks and scopes can be used in constructing programs.
- The same variable name can be used to have different meanings in
different blocks.
- A variable declared inside a block is said to be local to that block

Example:
….
{
int x = 10;
}
….
{
int x =1;
}

- In above example, the two declarations of x refer to two different memory


locations containing different values.
- Block in C++ is often nested.
- In C, global version of a variable cannot be accessed from within the
inner block. C++ resolves this problem by introducing new operator “::”
called the scope resolution operator.
Syntax:
:: variable name

// Program to demonstrate scope resolution operator


# include< iostream.h> [ In above program, the
#include<conio.h> variable m is declared at
int m = 10; // global variable m three places, namely,
outside the main
void main() function, inside the
{ main(), and inside the
int m =20 ; // local in main function inner block]
clrscr();
{
int k =m;
int m = 30; // m declare in inner block

cout << “\n We are in inner block”;


cout << “\n k =” <<k ;
cout << “\n m=” << m ;
cout << “\n ::m=” << ::m;

8
Chapter 1 Introduction to C++

cout << “\n We are in outer block”;


cout << “\n m=” << m ;
cout << “\n ::m=” << ::m;
getch();
}

Output:
We are in inner block
k= 20
m= 30
::m= 10

We are in outer block


m = 20
::m= 10

Manipulators:

- Manipulators are operators that are used to format the data display.
- The most commonly used manipulators are endl and setw.
- The endl operator is similar to that of ‘\n’.

Example:
cout << “m = ” << endl;
cout << “n =” <<endl;
This would cause two lines of output.
Output: m = n =
Control structures
- A function is a set up to perform a task. When the task is complex, many
different algorithms can be designed to achieve the same goal.
- The format should be such that it is easy to trace the flow of execution of
statements.
Following are the control structures:
1. Selection structure (branching statement)

Action 1 Action 2

Action 3

9
Chapter 1 Introduction to C++

C++ supports two types of selection statements:


if and switch.
If statement
The if statement is implemented in three forms:
i. if statement
ii. if .. else statement
iii. if.. else.. if ladder statements
The general form of the if statement is
if(expression or condition)
{
Statement;
}
else
{
Statement;
}

- A statement may consist of a single statement, a block of statements, or


nothing.
- If expression/conditions is to true, then first block is executed. If
expression/condition is false then else statement or second block is
executed.

Nested if else

if(expression or condition)
{
Statement;
}
else
{
if (condition)
{
Statement;
}
else
{
Statement;
}
}

Switch statement:
switch (expression)
{
case (condition 1):
{
Statement 1;
}
case (condition 2):

10
Chapter 1 Introduction to C++

{
Statement 2;
}
default:
{
Statement 3;
}
}
- This is a multiple branching statement where, based on a condition, the
control is transferred to one of the many possible points.
- In a switch there can be either variable or expression
- If it is a variable it must be either integer or character
- If it is an expression it must be an arithmetic expression.
- There can be any number of cases.
- Every case should have unique value.
- These cases can be written in any sequence.
- In a case there can be any number of statements.
- It is possible to have the nested switch.
- After every case break statement is compulsory.
- Default is a case which gets selected when none of the case value
matches with the result of expression.
- Default case is optional.

2. Loop structure ( Iteration or Repetition )


We are using following as a looping statements

i. do ..While
- Until the condition is false, all the statements within do while loop will be
execute.
- At least one time this loop will be executed, whether condition is true or
false.

Syntax:
do
{
Action1;
}while(condition is true);
Action2;

ii. While

- Under while loop, firstly condition is check. Whether condition is true


then we can able to enter under loop.
- Until the condition is false, all the statements within do while loop will be
execute. Syntax:
while( condition )
{
Action 1;
Action 2;
}

11
Chapter 1 Introduction to C++

Difference between ‘while’ and ‘ do while’


Sr. While Do—while
no.
1) Condition is at the top Condition is at the bottom.
2) No necessity of brackets if Brackets are compulsory even if
there is single statement in there is a single statement.
body.
03) There is no semicolon at the The semicolon is compulsory at
end of while. the end of do-while.
04) Computer executes the body Computer executes the body at
if and only if condition is least once even if condition is
true. false
05) This should be used when This should be used when the
condition is more important. process is important.
06) This loop is also referred as This loop is also referred as exit
entry controlled loop. controlled loop.
07) while(n<=10) do
{ {
cout<<n; cout<<n;
n++; n++;
} }while(n<=100);

iii. for :
- This is also a loop structure.
- Under the for loop divide into three parts as follows:

1. Initial value
Under this first give a value to memory variable.
2. Condition
In this statement, there is condition.
This loop will execute until this given condition is satisfied or true.
3. Increment / Decrement
With the help of these we can able to increment / decrement the
value of given variable.
Syntax:
for(initial value; condition ; increment / decrement operator)
{
Action / statement 1;
}
Jump Statements in C++
Jump statements are implemented to change the flow of the program when particular
conditions are satisfied. It is used within a program to end or continue a loop or to pause
the execution of a function. C++ has four jump statements: continue, break, return, and
goto.

12
Chapter 1 Introduction to C++

Continue:

Instead of terminating the loop, it performs the next iteration of the same loop but
ignoring the parts specified by the condition. Within the loop, it must be used in
conjunction with a decision-making statement. This statement can be used within a for,
while, or do-while loop.

1st Program:

Consider a situation in which all of the numbers between 1 and 15 except 7 are present.
So, after the value of j is 7, the goal is to use the continue statement. The program for the
same is as follows:

C++ Program:

1. // C++ code that shows how to use the continue statement


2. #include <iostream>
3. int main ()
4. {
5. for (int j = 1; j < 15; j++) {
6.
7. if (j == 7)
8. continue;
9. cout << j << " ";
10. }
11. return 0;
12. }
Output:

1 2 3 4 5 6 8 9 10 11 12 13 14

Break:

If the condition is met, the loop is terminated with the break command. When the
condition is met, the loop is broken and the remainder of the loop is skipped, unlike the
continue statement. Break statements are used in conjunction with decision-making
statements such as if, if-else, or switch statements in a for loop, which can be a for loop,
while loop, or do-while loop. It causes the loop to stop executing future iterations.

Consider the case when a number series is to be displayed but not after a specified value
p. In this scenario, the break statement is used once the value of j is p. The program or the
same is as follows:

C++ Program:

1. // C++ code that shows how to use the break statement


2. #include <iostream>
3. int main ()
4. {
5. for (int j = 1; j < 15; j++) {
6.
7. // using break Condition
8. if (j == 7)

13
Chapter 1 Introduction to C++

9. break;
10. cout << j << " ";
11. }
12. return 0;
13. }
Output:

123456

Return:

It removes control from the function. It is more powerful than a break. It is used to end
the entire function after the function has completed or after a condition has been met.
Except for the void() function, every function contains a return statement that returns
some value. Although the void() function can also have a return statement to conclude the
function's execution.

The following software demonstrates the return statement:

C++ Program:

1. // C++ code that shows how to use the return statement


2. #include <iostream>
3. int main()
4. {
5. cout << "Start with ";
6. for (int j = 0; j < 15; j++)
7. {
8. if (j == 7)
9. return 0;
10. cout << j << " ";
11. }
12. cout << "end";
13.
14. return 0;
15. }
Output:

Start with 0 1 2 3 4 5 6

Arrays
Like other programming languages, array in C++ is a group of similar types of elements
that have contiguous memory location.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.

A collection of related data items stored in adjacent memory places is referred to as an


array in the C/C++ programming language or any other programming language for that
matter. Elements of an array can be accessed arbitrarily using its indices. They can be
used to store a collection of any type of primitive data type, including int, float, double,
char, etc. An array in C/C++ can also store derived data types like structures, pointers,

14
Chapter 1 Introduction to C++

and other data types, which is an addition. The array representation in a picture is
provided below.

Advantages of C++ Array

o Code Optimization (less code)


o Random Access
o Easy to traverse data
o Easy to manipulate data
o Easy to sort data etc.

Disadvantages of C++ Array

o Fixed size

C++ Array Types

There are 2 types of arrays in C++ programming:

1. Single Dimensional Array


2. Multidimensional Array

C++ Single Dimensional Array

Let's see a simple example of C++ array, where we are going to create, initialize and
traverse array.

1. #include <iostream>
2. int main()
3. {
4. int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
5. //traversing array
6. for (int i = 0; i < 5; i++)
7. {
8. cout<<arr[i]<<"\n";
9. }
10. }
Output:

10
0
20
0
30

15
Chapter 1 Introduction to C++

Two-Dimensional Array
A two-dimensional array in C++ is the simplest form of a multi-dimensional array. It
can be visualized as an array of arrays. The image below depicts a two-dimensional array.

2D Array Representation
A two-dimensional array is also called a matrix. It can be of any type like integer,
character, float, etc. depending on the initialization. In the next section, we are going to
discuss how we can initialize 2D arrays.
Initializing a 2D array in C++

So, how do we initialize a two-dimensional array in C++? As simple as this:

int arr[4][2] = {
{1234, 56},
{1212, 33},
{1434, 80},
{1312, 78}
};

So, as you can see, we initialize a 2D array arr, with 4 rows and 2 columns as an array of
arrays. Each element of the array is yet again an array of integers.
We can also initialize a 2D array in the following way.
int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78};
Copy
In this case too, arr is a 2D array with 4 rows and 2 columns.
Printing a 2D Array in C++

We are done initializing a 2D array, now without actually printing the same, we cannot
confirm that it was done correctly.

Also, in many cases, we may need to print a resultant 2D array after performing some
operations on it. So how do we do that?

The code below shows us how we can do that.

#include<iostream>
main( )
{
int arr[4][2] = {
{ 10, 11 },
{ 20, 21 },
{ 30, 31 },
{ 40, 41 }
};

int i,j;

16
Chapter 1 Introduction to C++

cout<<"Printing a 2D Array:\n";
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
}

Output:

Printing A 2D Array

In the above code,

 We firstly initialize a 2D array, arr[4][2] with certain values,


 After that, we try to print the respective array using two for loops,
 the outer for loop iterates over the rows, while the inner one iterates over the
columns of the 2D array,
 So, for each iteration of the outer loop, i increases and takes us to the next 1D
array. Also, the inner loop traverses over the whole 1D array at a time,
 And accordingly, we print the individual element arr[ i ][ j ].

17

You might also like