0% found this document useful (0 votes)
1 views

COMPUTER PROGRAMMING I NOTES

The document covers various programming paradigms, including Procedure Oriented Programming (POP), Object Oriented Programming (OOP), Structured Programming, and Event-Driven Programming, highlighting their characteristics and differences. It emphasizes the importance of OOP, detailing its features such as encapsulation, inheritance, and polymorphism, and provides an overview of C++ fundamentals, including operators, keywords, identifiers, and constants. The document serves as a foundational guide for understanding programming concepts and the C++ language.

Uploaded by

leotunji91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

COMPUTER PROGRAMMING I NOTES

The document covers various programming paradigms, including Procedure Oriented Programming (POP), Object Oriented Programming (OOP), Structured Programming, and Event-Driven Programming, highlighting their characteristics and differences. It emphasizes the importance of OOP, detailing its features such as encapsulation, inheritance, and polymorphism, and provides an overview of C++ fundamentals, including operators, keywords, identifiers, and constants. The document serves as a foundational guide for understanding programming concepts and the C++ language.

Uploaded by

leotunji91
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

CSC 211: COMPUTER PROGRAMMING I

(C ++ PROGRAMMING)

0
PROGRAMMING PARADIGMS

Programming paradigms refer to the different programming approaches that can be used to
write computer programs. Comparison will be made between procedure oriented, structure
oriented, event driven and object oriented paradigms.

Procedure Oriented Programming (POP)

POP follows a step-by-step approach to break down a task into a collection of variables and
routines (or subroutines) through a sequence of instructions. Each step is carried out in a
systematic manner so that a computer can understand what to do. The program is divided into
small parts called functions and then it follows a series of computational steps to be carried
out in order.

It follows a top-down approach to actually solve a problem, hence the name. Procedures
correspond to functions and each function has its own purpose. Dividing the program into
functions is the key to procedural programming. So a number of different functions are written
in order to accomplish the tasks. POP focuses on procedural abstractions. Commonly used
POP languages are Pascal and FORTRAN.

OOP and POP are such high-level programming paradigms that use different approaches to
create a program to solve a particular problem in the less time possible. While an object-
oriented program depends mainly upon data rather than the algorithm, a procedure-oriented
program follows a step-by-step approach to solve a problem. OOP, of course, has a little edge
over POP in areas such as data security, ease of use, accessibility, operator overloading, and
more.

OOP POP
OOP takes a bottom-up approach in POP follows a top-down approach.
designing a program.
Program is divided into objects depending Program is divided into small chunks based
on the problem. on the functions.
Each object controls its own data. Each function contains different data.
1
Focuses on security of the data irrespective Follows a systematic approach to solve the
of the algorithm. problem.
The main priority is data rather than Functions are more important than data in a
functions in a program. program.
The functions of the objects are linked via Different parts of a program are
message passing. interconnected via parameter passing.
Data hiding is possible in OOP No easy way for data hiding.
Inheritance is allowed in OOP. No such concept of inheritance in POP.
Operator overloading is allowed. Operator overloading is not allowed.
C++, java. Pascal, Fortran.

Structured Programming

Structured programming is a programming paradigm aimed at improving the clarity, quality,


and development time of a computer program by making extensive use of the structured
control flow constructs of selection (if/then/else) and repetition (while and for), block
structures, and subroutines. Commonly used structured programming languages are C, C+,
PHP, Java, PERL, Ruby etc.

Event-Driven Programming

Event-driven programming is a programming paradigm in which the flow of the program is


determined by events such as user actions (mouse clicks, key presses), sensor outputs, or
messages from other programs or threads. Event- driven programming is the dominant
paradigm used in graphical user interfaces (GUI) and other applications (e.g. JavaScript web
applications) that are centered on performing certain actions in response to user input. This is
also the case of programming for device drivers. (E.g. USB device driver stacks).

2
Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm based on the concept of


"objects", which can contain data, in the form of fields (often known
as attributes or properties), and code, in the form of procedures (often known as methods). A
feature of objects is an object's procedures that can access and often modify the data fields of
the object with which they are associated (objects have a notion of "this" or "self"). In OOP,
computer programs are designed by making them out of objects that interact with one
another. OOP languages are diverse, but the most popular ones are class-based, meaning that
objects are instances of classes, which also determine their types.

Many of the most widely used programming languages (such as C++, Java, Python, etc.)
are multi-paradigm and they support object-oriented programming to a greater or lesser degree.

Object-oriented programming shifts the focus of attention to the objects, that is, to the aspects
on which the problem is centered. A program designed to maintain bank accounts would work
with data such as balances, credit limits, transfers, interest calculations, and so on. An object
representing an account in a program will have properties and capacities that are important for
account management. OOP objects combine data (properties) and functions (capacities). A
class defines a certain object type by defining both the properties and the capacities of the
objects of that type. Objects communicate by sending each other “messages,” which in turn
activate another object’s capacities.

Advantages of OOP Object-oriented programming offers several major advantages to


software development:
■ reduced susceptibility to errors: an object controls access to its own data. More specifically,
an object can reject erroneous access attempts

■ easy re-use: objects maintain themselves and can therefore be used as building blocks for
other programs

■ low maintenance requirement: an object type can modify its own internal data representation
without requiring changes to the application.

3
Fundamentals of Object Oriented Programming

Object-oriented programming is 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.

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 us to decompose a
problem into a number of entities called objects and then builds data and functions around
these entities. The combination of data and methods make up an object.

Features
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data is hidden and cannot be accessed by external functions.
4. Objects may communicate with each other though functions.
5. New data and functions can be easily added whenever necessary.
6. Follows bottom-up approach in program design.

Basic Concepts of Object-Oriented Programming

1. Objects
2. Classes
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message communication

4
1. Objects

Objects are the basic run-time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program must handle.
Programming problem is analyzed in terms of objects. When a program is executed, the objects
interact by sending messages to one another. For example if customer and account are two
objects in a program, then the customer object may send message to the account object
requesting for the bank balance. Each object contains data and code to manipulate the data.

---------------------------------------------------
Object: STUDENT
---------------------------------------------------
DATA
Name
Date-of-birth
Marks
------------------------------------------------------------
FUNCTIONS
Total
Average
Display

Objects serve two purposes: They promote understanding of the real world and provide a
practical basis for computer implementation. All Objects have identity and
are distinguishable.

2. Classes

An Object class describes a group of objects with similar properties (attributes), common
behavior (operations) and common relationships to other objects. Objects in a class have the
same attributes and behavior patterns. The entire set of data and code of an object can be made
a user defined data type with the help of a class.
E.g. Mango, Apple, Orange are the members of the class fruit. If fruit has been defined as a
class then the statement fruit mango; will create an object mango belonging to the class fruit.

A class serves as a blue print or a plan or a template. It specifies what data and what
functions will be included in objects of that class. Class with attributes, objects with values.

5
An attribute is a data value held by the objects in a class.

3. Data Abstraction

It consists of focusing on the essential inherent aspects of an entity. Most modern languages
provide data abstraction, but the ability to use inheritance and polymorphism provides
additional power. Classes use the concept of abstraction, they are known as Abstract Data
Types.

4. Encapsulation

It is also termed as information hiding. The wrapping up of data and functions into single unit
is known as encapsulation. It is the most essential feature of a class. The data is not accessible
to the outside and only those functions in the class can access it.

5. Inheritance

Inheritance is the sharing of attributes and operations among classes based on a


hierarchical relationship. (or)Inheritance is the process by which objects of one class acquire
the properties of objects of another class. Using a concept of inheritance new classes can be
built from the old ones. The new class referred to as a derived class, can inherit the data
structures and functions of the original or the base class. The new class can add data elements
and functions to those it inherits from its base class.

E.g. 1. Scrolling window and Fixed window are subclasses of window.

E.g.2. BIRD Attributes:


--------------------
FLYING BIRD NON FLYING BIRD
Attributes Attributes
---------------------------------- ----------------------------
ROBIN SWALLOW PENGUIN KIWI
Attributes Attributes Attributes Attributes
---------- ---------- ---------- ------------

The bird ROBIN is a part of the class FLYING BIRD that is again a part of the class BIRD. In
Object Oriented Programming, the concept of inheritance provides the idea of reusability. This
means that we can add additional features to an existing class without modifying it.

6
6. Polymorphism

Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
ability to take more than on form. An operation may exhibit different behavior is different
instances. The behavior depends upon the types of data used in the operation. For example,
consider the operation of addition. For two numbers, the operation will generate a sum. If the
operands are strings, then the operation would produce a third string by concatenation. The
process of making an operator to exhibit different behaviors in different instances is known as
operator overloading.

7. Dynamic binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic 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 polymorphism and inheritance. A
function call associated with a polymorphic reference depends on the dynamic type of that
reference.

8. Message communication
An object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language, involves the following basic steps:

1. Creating classes that define object and their behavior,


2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another. The concept of message passing makes it easier
to talk about building systems that directly model or simulate their real-world counterparts. A
Message for an object is a request for execution of a procedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired results. Message passing
involves specifying the name of object, the name of the function (message) and the information
to be sent.

7
C ++ Fundamentals

A program is a set of instructions in proper sequence that causes a computer to perform a


particular task.

When learning to program in any programming language, it’s best just to learn the “rules of
the game.”

Modern programs are projects composed of many of individual program modules that have to
be linked together in order to be run. In fact most developer systems have their own integrated
development environment (IDE) and programs are developed in phases within the IDE.

Every programming language has facilities to: In C++

Read data from some input device cin >>

Write output information onto an output device cout <<

Perform arithmetic operations + - * /

Perform relational operations < == >

Perform logical operations ! && ||

Branch to a non-sequential instruction (w/wo structure) while

Store (and retrieve) data values to (and from) memory =

C++ Character Set

Character set is a set of valid characters that a language can recognize.

Letters A-Z, a-z


Digits 0-9

8
Special Characters Space + - * / ^ \ () [] {} = != <> ‘ “ $ , ; : % ! & ?
_ # <= >= @
Formatting characters backspace, horizontal tab, vertical tab, form feed, and carriage
return

Punctuators

The following characters are used as punctuators in C++.

Brackets [ ] Opening and closing brackets indicate single and


multidimensional array subscript.

Parentheses ( ) Opening and closing brackets indicate functions calls, function


parameters for grouping expressions etc.

Braces { } Opening and closing braces indicate the start and end of a
compound statement.

Comma , It is used as a separator in a function argument list.

Semicolon ; It is used as a statement terminator.

Colon : It indicates a labeled statement or conditional operator symbol.

Asterisk * It is used in pointer declaration or as multiplication operator.

Equal sign = It is used as an assignment operator.

Pound sign # It is used as pre-processor directive.

Operators

Operators are special symbols used for specific purposes. C++ provides six types of operators.
Arithmetical operators, Relational operators, Logical operators, Unary operators, Assignment
operators, Conditional operators, Comma operator etc.

9
1. Arithmetical operators
Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric)
operation. You can use the operators +, -, *, and / with both integral and floating-point data
types.

2. Relational operators
The relational operators are used to test the relation between two values. All relational
operators are binary operators and therefore require two operands. A relational expression
returns zero when the relation is false and a non-zero when it is true. The following table
shows the relational operators.

Relational Operators Meaning


< Less than
<= Less than or equal to
== Equal to
> Greater than
>= Greater than or equal to
!= Not equal to

3. Logical operators
The logical operators are used to combine one or more relational expression. The logical
operators are:

Operators Meaning
|| OR
&& AND
! NOT

10
4. Unary operators
C++ provides two unary operators for which only one variable is required. For Example a = -
50; a = + 50; Here, plus sign (+) and minus sign (-) are unary because they are not used
between two variables.

5. Assignment operator
The assignment operator '=' is used for assigning a value to a variable. This operator takes
the expression on its right-hand-side and places it into the variable on its left-hand-side.

For example: m = 5;

The operator takes the expression on the right, 5, and stores it in the variable on the left, m.
x = y = z = 32;

This code stores the value 32 in each of the three variables x, y, and z.

6. The comma operator


The comma operator gives left to right evaluation of expressions. When the set of
expressions has to be evaluated for a value, only the rightmost expression is considered.

int a = 1, b = 2, c = 3, i; // comma acts as separator, not as an operator


i = (a, b); // stores b into i

This program would first assign the value of a to i, and then assign value of b to variable i.
So, at the end, variable i would contain the value 2.

Keywords

There are some reserved words in C++ which have predefined meaning to compiler called
keywords. These words may not be used as identifiers. Some commonly used Keywords are
given below:

11
Identifiers

Symbolic names can be used in C++ for various data items used by a programmer in his
program. A symbolic name is generally known as an identifier. The identifier is a sequence of
characters taken from C++ character set. In previous program x, y and z are identifiers of
variables. The rule for the formation of an identifier are:

An identifier can consist of alphabets, digits and/or underscores. It must not start with a digit
C++ is case sensitive that is upper case and lower case letters are considered different from
each other. It should not be a reserved word.

Constants

Constants (often referred to as literals) are data items that never change their value during the
execution of the program. The following types of literals are available in C++.

1. Integer Constants

12
Integer constants are whole number without any fractional part. C++ allows three types of
integer constants. Decimal integer constants: It consists of sequence of digits and should not
begin with 0 (zero). For example 124, - 179, +108. Octal integer constants: It consists of
sequence of digits starting with 0 (zero). For example. 014, 012. Hexadecimal integer
constant: It consists of sequence of digits preceded by ox or OX.

2. Character constants

A character constant in C++ must contain one or more characters and must be enclosed in
single quotation marks. For example 'A', '9', etc. C++ allows nongraphic characters which
cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These
characters can be represented by using an escape sequence. An escape sequence represents a
single character.

3. Floating constants

They are also called real constants. They are numbers having fractional parts. They may be
written in fractional form or exponent form. A real constant in fractional form consists of
signed or unsigned digits including a decimal point between digits. For example 3.0, -17.0, -
0.627 etc.

4. String Literals

A sequence of character enclosed within double quotes is called a string literal. String literal
is by default (automatically) added with a special character ‘\0' which denotes the end of the
string. Therefore the size of the string is increased by one character. For example
"COMPUTER" will be represented as "COMPUTER\0" in the memory and its size is 9
characters.

Basic Data Types

C++ supports a large number of data types. The built in or basic data types supported by C++
are integer, floating point and character. C++ also provides the data type bool for variables that
can hold only the values True and False.
13
Some commonly used data types are summarized in table along with description.

Type Description
int Small integer number
long int Large integer number
float Small real number
double Double precision real number
long double Long double precision real number
char A Single Character

Our First C++ Program

A C++ program is made up of objects with their accompanying member functions and global
functions, which do not belong to any single particular class. Each function fulfills its own
particular task and can also call other functions

No programming course is complete without the “Hello world” program:

Line 1 // My First program in C++.


Line 2 // Hello world.cpp
Line 3 #include <iostream.>
Line 4 using namespace std;
Line 5 int main(){
Line 6 cout << "Hello world." <<end1;
Line 7 return 0;
Line 8 }

Line 1 and 2 begin with // which are to indicate comments.


Line 3 begins with the symbol, #, which indicates that the line is intended for the preprocessor.
#include is a C pre-processor directive to “include” the file “iostream”. This tells the pre-
processor to include in the program the contents of the I/O stream header file called iostream.h.
This allows us to use standard stream input and output objects like cout (displays to the screen).

14
Line 4 The “using” directive allows direct access to the names of the std namespace. Predefined
names in C++ are to be found in the std (standard) namespace.
Line 5 All C++ programs must have a main. “main” is a function of type “int”. The body of
“main” is contained within {}.
Line 6 begins with “cout” which is a predefined instance of the stream “ostream”. The name
cout (console output) designates an object responsible for output. The two less-than symbols,
<< is an insertion operator, that inserts what follows into the stream “cout. endl (end of line)
causes a line feed
Line 7 The statement “return 0”; terminates the function main() and also the program, returning
a value of 0 as an exit code to the calling program. It is standard practice to use the exit code
0 to indicate that a program has terminated correctly.
Line 8 } (curly bracket) marks the end of the code.
Note that every statement must end with a semi-colon (;).

Variables
A variable is a temporary storage that is created to hold certain amount of data in a program.
A variable must be declared before it is defined and a variable must be defined before you can
use it in a program. This declaration may appear anywhere in the program, as long as it appears
before the variable is first used. The declaration creates the object.

When you define a variable the type is specified and an appropriate amount of memory
reserved. This memory space is addressed by reference to the name of the variable. A simple
definition has the following syntax:
SYNTAX: type name1 [name2 ... ];
This defines the names of the variables in the list name1 [, name2 ...] as variables of the type
type. E.g : char c; int i, ;double x, y, size;float a; etc.
For the following declaration:
int n;
The name of the object is n, the type (or class) is int. The object does not yet have a value.
n = 66; //now it has a value
15
or
int n=66; //This declaration also gives a value to n

There are 3 ways to give a variable a value:


• Give it an initial value at the declaration: int n=66;
• Assign it a value using the assignment (=) operator: n=66;
• Read the value in from an input device such as the keyboard: cin >> n;
Example 1.
STEP 1: Following statements declare three variables of type integer to store whole numbers.
int x; int y; int z;
You can declare more than one variable of same type in a single statement like: int x, y, z;
STEP 2: Following statement stores value in first variable
x = 25;
STEP 3: Following statement stores value in second variable y = 10;
STEP 4: Now, add these two numbers together and store the result of the addition in third
variable z = x + y;
STEP 5: Print the result cout << "The sum is ";
cout << z;
You can combine above two statements in one statement cout << "The sum is " << sum;
Here, is the complete program:
#include <iostream>
using namespace std;
int main() {
int x; int y; int z; //declare variables of integer type
x = 25; y = 10; //storing value in variables
z = x + y; //adding numbers and store the result in sum
cout << "The sum is ";
cout << z; //print the result
return 0;
}

16
Output: The sum is 35

Program 2:
//mean2.cpp
// this program calculates the mean of three numbers.
// and helps learns about variables.

#include <iostream>
using namespace std;
int main()
{
float mean;
cout << "My Second C++ Program.\n\n";
mean = (12+5+10)/3;
cout << mean;
return 0;
} //end main
Output: 9

STATEMENTS

Statements are the instructions given to the computer to perform any kind of action. Action
may be in the form of data movement, decision making etc. Statements form the smallest
executable unit within a C++ program. Statements are always terminated by semicolon.
Compound Statement
A compound statement is a grouping of statements in which each individual statement ends
with a semi-colon. The group of statements is called block. Compound statements are enclosed

17
between the pair of braces ({}.). The opening brace ({) signifies the beginning and closing
brace (}) signifies the end of the block.

Null Statement
Writing only a semicolon indicates a null statement. Thus ';' is a null or empty statement. This
is quite useful when the syntax of the language needs to specify a statement but the logic of
the program does not need any statement. This statement is generally used in for and while
looping statements.

Conditional Statements
Sometimes the program needs to be executed depending upon a particular condition. C++
provides the following statements for implementing the selection control structure.
 if statement
 if else statement
 nested if statement

If statement
Syntax of the if statement
if (condition) {
statement(s);
}

If else statement
syntax of the if - else statement
if (condition) {
statement1;
else
statement2;
}

18
From the above flowchart; for the if statement: it is clear that the given condition is evaluated
first, then if the condition is true, statement is executed; otherwise it is skipped.
For the if-else statement, if the condition is true, statement1 is executed. If the condition is
false, statement2 is executed. It should be kept in mind that statement1 and statement2 can be
single or compound statements.

if example if else example


if (x == 100) if (x == 100)
cout << "x is 100"; cout << "x is 100";
else
cout << "x is not 100";

Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else block.
syntax of the nested if statement :

if (condition 1)
{
If (condition 2)
{
statement(s);
}
}
if (condition 1)
statement 1;
else
if (condition 2)
statement2;
19
else
statement3;

if-else-if example
if (percentage>=60)
cout<<"1st division";
else
if (percentage>=50)
cout<<"2nd division";
else
if(percentage>=40)
cout<<"3rd division";
else
cout<<"Fail" ;

LOOPING
Looping is also called a repetitive control structure. Sometimes we require a set of statements
to be executed a number of times by changing the value of one or more variables each time to
obtain a different result. This type of program execution is called looping. C++ provides the
following construct:
 while loop
 do-while loop
 for loop

While loop
Syntax of while loop:
while (condition)
{
statement(s);
}

20
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop
body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly
as long as the condition remains true. As soon as the condition becomes false, it comes out of
the loop and goes to the statement next to the ‘while’ loop.

do-while loop
Syntax of do-while loop:
do
{ statements;
}
while (condition);

21
Note: That the loop body is always executed at least once. One important difference between
the while loop and the do-while loop is the relative ordering of the conditional test and loop
body execution. In the while loop, the loop repetition test is performed before each execution
of the loop body; the loop body is not executed at all if the initial test fail. In the do-while loop,
the loop termination test is performed after each execution of the loop body. Hence, the loop
body is always executed least once.

for loop
It is a count controlled loop in the sense that the program knows in advance how many times
the loop is to be executed.
syntax of for loop:
for (initialization; decision; increment/decrement)
{
statement(s);
}

The flow diagram indicates that in for loop three operations take place:
1. Initialization of loop control variable
2. Testing of loop control variable
3. Update the loop control variable either by incrementing or decrementing.

22
Operation (1) is used to initialize the value. On the other hand, operation (2) is used to test
whether the condition is true or false. If the condition is true, the program executes the body
of the loop and then the value of loop control variable is updated. Again it checks the condition
and so on. If the condition is false, it gets out of the loop.

Jump Statements
The jump statements unconditionally transfer program control within a function.
 goto statement
 break statement
 continue statement

The goto statement


goto allows to make a jump to another point in the program.
E.g.
goto pqr;
pqr: pqr is known as label. It is a user defined identifier. After the execution of goto statement,
the control transfers to the line after label pqr.

The break statement


The break statement, when executed in a loop, provides an immediate exit from the loop
structure.

The continue statement


The continue statement is used in loops and causes a program to skip the rest of the body of
the loop.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
The continue statement skips rest of the loop body and starts a new iteration.

The exit ( ) function


The execution of a program can be stopped at any point with exit ( ) and a status code can be
informed to the calling program. The general format is exit (code); where code is an integer
value. The code has a value 0 for correct execution. The value of the code varies depending
upon the operating system.

23
ARRAYS
An array is a collection of data elements of same data type. It is described by a single name
and each element of an array is referenced by using array name and its subscript number.

ONE DIMENSIONAL ARRAY

Declaration of Array
Type arrayName[numberOfElements];
For example:
int Age[5] ;
float cost[30];

Initialization of One Dimensional Array


An array can be initialized along with declaration. For array initialization it is required to place
the elements separated by commas enclosed within braces.
int A[5] = {11,2,23,4,15};
It is possible to leave the array size open. The compiler will count the array size.
int B[ ] = {6,7,8,9,15,12};

Referring to Array Elements


In any point of a program in which an array is visible, we can access the value of any of its
elements individually as if it was a normal variable, thus being able to both read and modify
its value.

The format is: name[index]

Examples:
cout << age[4]; //print an array element
age[4] = 55; // assign value to an array element
cin >> age[4]; //input element 4

Using Loop to input an Array from user


int age [10], i ;
for (i = 0 ; i < 10; i++)
24
{
cin >> age[i];
}

Basic Operation on One Dimensional Array

Function to traverse the array A

void display(int A[ ], int n)


{
cout << "The elements of the array are:\n";
for (int i = 0; i < n; i++)
cout << A[i];
}

Function to Read elements of the array A

void Input(int A[ ], int n)


{
cout << "Enter the elements:";
for (int i = 0; i < n; i++)
cin >> A[i];
}

Function to Search for an element from A by Linear Search

void lsearch(int A[ ], int n, int data)


{
for (int i = 0; i < n; i++)
{
if(A[i] = = data)
{
cout << "Data Found at : " << i;
return;
}
}
cout << "Data Not Found in the array" << endl;
}

25
TWO DIMENSIONAL ARRAY

It is a collection of data elements of same data type arranged in rows and columns (that is, in
two dimensions).

Declaration of Two-Dimensional Array

Type arrayName[numberOfRows][numberOfColumn];
For example,
int Sales[3][5];

Initialization of Two-Dimensional Array

A two-dimensional array can be initialized along with declaration. For two dimensional array
initialization, elements of each row are enclosed within curly braces and separated by commas.
All rows are enclosed within curly braces.

int A[4][3] = {{22, 23, 10},


{15, 25, 13},
{20, 74, 67},
{11, 18, 14}};

Referring to Array Elements

To access the elements of a two-dimensional array, we need a pair of indices: one for the row
position and one for the column position.
The format is:
name[rowIndex][columnIndex].

Examples:
cout << A[1][2]; //print an array element
A[1][2] = 13; // assign value to an array element
cin >> A[1][2]; //input element

26
Using Loop to input a Two-Dimensional Array from user

int mat[3][5], row, col ;


for (row = 0; row < 3; row++)
for (col = 0; col < 5; col++)
cin >> mat[row][col];

Arrays as Parameters

Two-dimensional arrays can be passed as parameters to a function, and they are passed by
reference. When declaring a two-dimensional array as a formal parameter, we can omit the
size of the first dimension, but not the second; that is, we must specify the number of columns.
For example:
void print(int A[ ][3], int N, int M)
In order to pass to this function an array declared as:
int arr[4][3];
the call is written like this:
print(arr);

Example:

#include <iostream> using namespace std;


void print(int A[ ][3], int N, int M)
{
for (R = 0; R < N; R++)
for (C = 0; C < M; C++)
cout << A[R][C];
}
int main ()
{
int arr[4][3] ={{12, 29, 11},
{25, 25, 13},
{24, 64, 67},
{11, 18, 14}};
print(arr,4,3);
return 0;
}

27
POINTER

In C++, a pointer refers to a variable that holds the address of another variable. Like regular
variables, pointers have a data type. For example, a pointer of type integer can hold the address
of a variable of type integer. A pointer of character type can hold the address of a variable of
character type.
A pointer is a symbolic representation of a memory address. With pointers, programs can
simulate call-by-reference. They can also create and manipulate dynamic data structures. In
C++, a pointer variable refers to a variable pointing to a specific address in a memory pointed
by another variable.

Addresses in C++
To understand C++ pointers, you must understand how computers store data.
When you create a variable in your C++ program, it is assigned some space the computer
memory. The value of this variable is stored in the assigned location.
To know the location in the computer memory where the data is stored, C++ provides
the & (reference) operator. The operator returns the address that a variable occupies.
For example, if x is a variable, &x returns the address of the variable.

Pointer Declaration Syntax


The declaration of C++ takes the following syntax:
datatype *variable_name;
 The datatype is the base type of the pointer which must be a valid C++ data type.
 The variable_name is should be the name of the pointer variable.
 Asterisk used above for pointer declaration is similar to asterisk used to perform
multiplication operation. It is the asterisk that marks the variable as a pointer.
Here is an example of valid pointer declarations in C++:
int *x; // a pointer to integer
double *x; // a pointer to double
float *x; // a pointer to float
char *ch // a pointer to a character

Reference operator (&) and Deference operator (*)


The reference operator (&) returns the variable's address.
The deference operator (*) helps us get the value that has been stored in a memory address.
For example:
If we have a variable given the name num, stored in the address 0x234 and storing the value
28.
The reference operator (&) will return 0x234.
The dereference operator (*) will return 28.
28
Example :
#include <iostream>
using namespace std;
int main() {
int x = 27;
int *ip;
ip = &x;
cout << "Value of x is : ";
cout << x << endl;
cout << "Value of ip is : ";
cout << ip<< endl;
cout << "Value of *ip is : ";
cout << *ip << endl;
return 0;
}
Output:

Code Explanation:
1. Import the iostream header file. This will allow us to use the functions defined in the
header file without getting errors.
2. Include the std namespace to use its classes without calling it.
3. Call the main() function. The program logic should be added within the body of this
function. The { marks the beginning of the function's body.
4. Declare an integer variable x and assigning it a value of 27.
5. Declare a pointer variable *ip.
6. Store the address of variable x in the pointer variable.
7. Print some text on the console.
8. Print the value of variable x on the screen.
9. Print some text on the console.
10. Print the address of variable x. The value of the address was stored in the variable ip.
11. Print some text on the console.
12. Print value of stored at the address of the pointer.
13. The program should return value upon successful execution.
14. End of the body of the main() function.

29
NULL Pointer
If there is no exact address that is to be assigned, then the pointer variable can be assigned a
NULL. It should be done during the declaration. Such a pointer is known as a null pointer. Its
value is zero and is defined in many standard libraries like iostream.
Example :
#include <iostream>
using namespace std;
int main() {
int *ip = NULL;
cout << "Value of ip is: " << ip;
return 0;
}
Output:

Code Explanation:
1. Declare a pointer variable ip and assigning it a value of NULL.
2. Print value of pointer variable ip alongside some text on the console.
3. The program must return value upon successful completion.
4. End of the body of the main() function.

Pointers of Variables
With C++, you can manipulate data directly from the computer's memory.
The memory space can be assigned or re-assigned as one wishes. This is made possible by
Pointer variables.
Pointer variables point to a specific address in the computer's memory pointed to by another
variable.
It can be declared as follows:
int *p;
Or,
int* p;
Example
#include <iostream>

using namespace std;


int main() {
int *p, x = 30;
p = &x;
cout << "Value of x is: " << *p;

30
return 0;
}
Output:

Code Explanation:
1. Declare a pointer variable p and a variable x with a value of 30.
2. Assign the address of variable x to p.
3. Print the value of pointer variable p alongside some text on the console.
4. The program must return value upon successful completion.
5. End of the body of the main() function.

Application of Pointers
Functions in C++ can return only one value. Further, all the variables declared in a function
are allocated on the function call stack. As soon as the function returns, all the stack variables
are destroyed.
Arguments to function are passed by value, and any modification done on the variables doesn't
change the value of the actual variables that are passed. Following example helps illustrate this
concept:-
Example 5:
#include <iostream>

using namespace std;


void test(int*, int*);
int main() {
int a = 5, b = 5;
cout << "Before changing:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

test(&a, &b);

cout << "\nAfter changing" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void test(int* n1, int* n2) {

31
*n1 = 10;
*n2 = 11;
}
Output:

Code Explanation:
1. Create a prototype of a function named test that will take two integer parameters.
2. Call the main() function. We will add the program logic inside its body.
3. Declare two integer variables a and b, each with a value of 5.
4. Print some text on the console. The endl (end line) will move the cursor to begin
printing in the next line.
5. Print the value of variable a on the console alongside other text. The endl (end line) will
move the cursor to begin printing in the next line.
6. Print the value of variable b on the console alongside other text. The endl (end line)
will move the cursor to begin printing in the next line.
7. Create a function named test() that takes in the addresses of variable a and b as the
parameters.
8. Print some text on the console. The \n will create a new blank line before the text is
printed. The endl (end line) will move the cursor to begin printing in the next line after
the text is printed.
9. Print the value of variable a on the console alongside other text. The endl (end line) will
move the cursor to begin printing in the next line.
10. Print the value of variable b on the console alongside other text. The endl (end line)
will move the cursor to begin printing in the next line.
11. The program must return value upon successful completion.
12. End of the body of the main() function.
13. Defining the function test(). The function should take two integer pointer variables *n1
and *n2.
14. Assigning the pointer variable *n1 a value of 10.
15. Assigning the pointer variable *n2 a value of 11.
16. End of the body of the function test().

Even Though, new values are assigned to variable a and b inside the function test, once the
function call completes, the same is not reflected in the outer function main.

32
Using pointers as function arguments helps to pass the variable's actual address in the function,
and all the changes performed on the variable will be reflected in the outer function.
In the above case, the function 'test' has the address of variables 'a' and 'b.' These two variables
are directly accessible from the function 'test', and hence any change done to these variables
are reflected in the caller function 'main.'

Advantages of using Pointers


Here, are pros/benefits of using Pointers
 Pointers are variables which store the address of other variables in C++.
 More than one variable can be modified and returned by function using pointers.
 Memory can be dynamically allocated and de-allocated using pointers.
 Pointers help in simplifying the complexity of the program.
 The execution speed of a program improves by using pointers.

Summary:
 A pointer refers to a variable holding address of another variable.
 Each pointer has a valid data type.
 A pointer is a symbolic representation of a memory address.
 Pointers allow programs to simulate call-by-reference and create and manipulate
dynamic data structures.
 Arrays and pointers use a related concept.
 The array name denotes the array's base.
 If you want to assign the address of an array to a pointer, don't use an ampersand (&).
 If there is no specific address to assign a pointer variable, assign it a NULL.

33
OBJECT ORIENTED PROGRAMMING CONCEPTS
There are two common programming methods: procedural programming and object-oriented
programming (OOP).
In a procedural program data is typically stored in a collection of variables and there is a set
of functions that perform operations on the data. The data and the functions are separate
entities. Usually the variables are passed to the functions that perform the desired operations.
The focus of procedural programming is on creating the functions, or procedures, that operate
on the program’s data. Procedural programming works well. However, as programs become
larger and more complex, the separation of a program’s data and the code that operates on the
data can lead to problems.
The object oriented programming design models the real world well and overcomes the
shortcomings of procedural paradigm. It views a problem in terms of objects and thus
emphasizes on both procedures as well as data.

An object is an entity that combines both data and procedures in a single unit. An object’s data
items, also referred to as its attributes, are stored in member variables. The procedures that an
object performs are called its member functions. This wrapping of an object’s data and
procedures together is called encapsulation.
Not only objects encapsulate associated data and procedures, they also permit data hiding.
Data hiding refers to an object’s ability to hide its data from code outside the object. Only the
object’s member functions can directly access and make changes to the object’s data.

Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object orientation
contributes to the solution of many problems associated with the development and quality of
software products. The new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost. The principal advantages are:

• Through inheritance, we can eliminate redundant code by the use of existing classes.

34
• Build programs from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch. This leads to saving of development
time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that cannot be
invaded by code in other parts of a programs.
• It is possible to have multiple instances 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 programmers to capture more detail of a model
and its implemental form.
• Object-oriented system can be easily upgraded from small to large system.
• Software complexity can be easily managed.

Application of OOP
OOP has become one of the programming buzzwords today. Applications of OOP are
beginning to gain importance in many areas. The most popular application of object-oriented
programming, up to now, has been in the area of user interface design such as window.
Hundreds of windowing systems have been developed, using the OOP techniques. Real-
business system are often much more complex and contain many more objects with
complicated attributes and method. OOP is useful in these types of application because it can
simplify a complex problem. The promising areas of application of OOP include:
• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and Expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems

35
Class & Objects
One of the major features of C++ is classes. They provide a method of binding together data
and functions which operate on them. Like structures in C, classes are user-defined data types.

The mechanism that allows you to combine data and the function in a single unit is called a
class. Once a class is defined, you can declare variables of that type. A class variable is called
object or instance. In other words, a class would be the data type, and an object would be the
variable.
A class in C++ is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A C++ class is like a blueprint for an
object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are
their properties.

 A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
defines the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can be apply brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated.

Keywords
Inline Functions: - An inline function is expanded in the line where it is invoked.
Member Function:- Private means that they can be accessed only by the functions
within the class.
Classes:- When you create the definition of a class you are defining the attributes and
behavior of a new type.

36
Objects:- Declaring a variable of a class type creates an object. You can have many
variables of the same type (class).

Classes are generally declared using the keyword class, with the following format:

class class_name {
private:
members1;
protected:
members2;
public:
members3;
};

Where class_name is a valid identifier for the class. The body of the declaration can contain
members that can be either data or function declarations. The members of a class are classified
into three categories: private, public, and protected. Private, protected, and public are reserved
words and are called member access specifiers. These specifiers modify the access rights that
the members following them acquire.
 Private members of a class are accessible only from within other members of the same
class. You cannot access it outside of the class.
 Protected members are accessible from members of their same class and also from
members of their derived classes.
 Public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all
its members. Therefore, any member that is declared before one other class specifier
automatically has private access.
Example:

/* C++ program to create a simple class and object.*/


#include <iostream>
using namespace std;
class Hello
{
public:
void sayHello()
{
cout << "Hello World" << endl;
37
}
};
int main()
{
Hello h;
h.sayHello();
return 0;
}

class Circle
{
private:
double radius;
public:
void setRadius(double r)
{
radius = r;
}
double getArea()
{
return 3.14 * radius * radius;
}
};

Object Declaration
Once a class is defined, you can declare objects of that type. The syntax for declaring an object
is the same as that for declaring any other variable. The following statements declare two
objects of type circle: Circle c1, c2;

Accessing Class Members


Once an object of a class is declared, it can access the public members of the class.
c1.setRadius(2.5);

Defining Member function of class


You can define Functions inside the class as shown in above example. Member functions
defined inside a class this way are created as inline functions by default. It is also possible to
declare a function within a class but define it elsewhere. Functions defined outside the class
are not normally inline. When a function is defined outside the class, it cannot be referenced
directly outside of the class. In order to reference these, we use the scope resolution operator,
:: (double colon).
Example, defining function setRadius outside the class:

38
void Circle :: setRadius(double r)
{
radius = r;
}

The following program demonstrates the general feature of classes. Member functions
setRadius() and getArea() defined outside the class.

#include <iostream>
using namespace std;
class Circle //specify a class
{
private :
double radius; //class data members
public:
void setRadius(double r);
double getArea(); //member function to return area
};
void Circle :: setRadius(double r)
{
radius = r;
}
double Circle :: getArea()
{
return 3.14 * radius * radius;
}
int main() {
Circle c1; //define object of class circle
c1.setRadius(2.5); //call member function to initialize radius
cout << c1.getArea(); //display area of circle object
return 0;
}

REFERENCE
1. Kyle Loudon. (2003). C++ Pocket Reference. O'Reilly Media; 1st edition, ISBN-
13 : 978-0596004965.
2. Stanley Lippman, Josée Lajoie, Barbara Moo. (2012). C++ Primer. Addison-Wesley
Professional; 5th edition, ISBN-13: 978-0321714114
3. Scott Meyers. (2014). Effective Modern C++: 42 Specific Ways to Improve Your Use of
C++11 and C++14. O'Reilly Media, Incorporated; 1st edition, ISBN-13 : 978-
1491903995
4. Dale, N. et al (2002). Programming and Problem Solving with C++ (3rd ed). Jones and
Bartlett Publishers. ISBN: 0763721034
39

You might also like