Need for object-oriented paradigm - KMIT

33
Need for object-oriented paradigm it produces reusable code/objects because of encapsulation and inheritance. the data is protected because it can be altered only by the encapsulated methods. it is more efficient to write programs which use pre-defined objects. the storage structure and/or procedures within an object type could be altered if required without affecting programs that make use of that object type. new functions can easily be added to objects by using inheritance the code produced is likely to contain fewer errors because pretested objects are being used. less maintenance effort will be required by the developer because objects can be reused. Differences between OOP and Procedure oriented programming Basis For comparison POP OOP Basic Procedure/Structure oriented . Object oriented. Approach Top-down. Bottom-up. Basis Main focus is on "how to get the task done" i.e. on the procedure or structure of a program . Main focus is on 'data security'. Hence, only objects are permitted to access the entities of a class. Division Large program is divided into units called functions. Entire program is divided into objects. Entity accessing mode No access specifier observed. Access specifier are "public", "private", "protected". Overloading/Polymorphism Neither it overload functions nor operators. It overloads functions, constructors, and operators. Inheritance Their is no provision of inheritance. Inheritance achieved in three modes public private and protected. Data hiding & security There is no proper way of hiding the data, so data is insecure Data is hidden in three modes public, private, and protected. hence data security increases. Data sharing Global data is shared among the functions in the program. Data is shared among the objects through the member functions. Friend functions/classes No concept of friend function. Classes or function can become a friend of another class with the keyword "friend". Note: "friend" keyword is used only in c++ Virtual classes/ function No concept of virtual classes . Concept of virtual function appear during inheritance. Example C, VB, FORTRAN, Pascal C++, JAVA, VB.NET, C#.NET. Overview of OOP concepts- Object Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical. Class

Transcript of Need for object-oriented paradigm - KMIT

Page 1: Need for object-oriented paradigm - KMIT

Need for object-oriented paradigm

it produces reusable code/objects because of encapsulation and inheritance.

the data is protected because it can be altered only by the encapsulated methods.

it is more efficient to write programs which use pre-defined objects.

the storage structure and/or procedures within an object type could be altered if required without affecting

programs that make use of that object type.

new functions can easily be added to objects by using inheritance

the code produced is likely to contain fewer errors because pretested objects are being used.

less maintenance effort will be required by the developer because objects can be reused.

Differences between OOP and Procedure oriented programming

Basis For comparison POP OOP

Basic Procedure/Structure oriented . Object oriented.

Approach Top-down. Bottom-up.

Basis

Main focus is on "how to get the task done"

i.e. on the procedure or structure of a

program .

Main focus is on 'data security'. Hence,

only objects are permitted to access the

entities of a class.

Division Large program is divided into units called

functions. Entire program is divided into objects.

Entity accessing mode No access specifier observed. Access specifier are "public", "private",

"protected".

Overloading/Polymorphism Neither it overload functions nor operators. It overloads functions, constructors, and

operators.

Inheritance Their is no provision of inheritance. Inheritance achieved in three modes

public private and protected.

Data hiding & security There is no proper way of hiding the data, so

data is insecure

Data is hidden in three modes public,

private, and protected. hence data security

increases.

Data sharing Global data is shared among the functions in

the program.

Data is shared among the objects through

the member functions.

Friend functions/classes No concept of friend function.

Classes or function can become a friend

of another class with the keyword

"friend".

Note: "friend" keyword is used only in

c++

Virtual classes/ function No concept of virtual classes . Concept of virtual function appear during

inheritance.

Example C, VB, FORTRAN, Pascal C++, JAVA, VB.NET, C#.NET.

Overview of OOP concepts-

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It

can be physical and logical.

Class

Page 2: Need for object-oriented paradigm - KMIT

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It

provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convince the

customer differently, to draw something e.g. shape or rectangle etc.

In C++, we use Function overloading and Function overriding to achieve polymorphism.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't

know the internal processing.

In C++, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example:

capsule, it is wrapped with different medicines.

Structure of a CPP program

Page 3: Need for object-oriented paradigm - KMIT

Data types in C++ are categorised in three groups: Built-in, user-defined and Derived.

What are Variables?

Variables are used in C++ where you will need to store any type of values within a program and

whose value can be changed during the program execution. These variables can be declared in

various ways each having different memory requirements and storing capability. Variables are

the name of memory locations that are allocated by compilers, and the allocation is done based

on the data type used for declaring the variable.

Variable Definition in C++

A variable definition means that the programmer writes some instructions to tell the compiler to

create the storage in a memory location. The syntax for defining variables is:

Syntax:

data_type variable_name;

Page 4: Need for object-oriented paradigm - KMIT

data_type variable_name, variable_name, variable_name;

/* variable definition */int width, height, age;

char letter;

float area;

double d;

Variable Initialization in C++

Variables are declared in the above example, but none of them has been assigned any value.

Variables can be initialized, and the initial value can be assigned along with their declaration.

Syntax:

data_type variable_name = value;

Example:

/* variable definition and initialization */int width, height=5, age=32;

char letter='A';

float area;

double d;

/* actual initialization */width = 10;

area = 26.5;

Rules of Declaring variables in C++

A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and

the underscore character.

The first character must be a letter or underscore.

Blank spaces cannot be used in variable names.

Special characters like #, $ are not allowed.

C++ keywords cannot be used as variable names.

Variable names are case-sensitive.

A variable name can be consisting of 31 characters only if we declare a variable more

than one characters compiler will ignore after 31 characters.

Variable type can be bool, char, int, float, double, void or wchar_t.

Here's a Program to Show the Usage of Variables in C++

Example:

#include <iostream>

using namespace std;

int main()

{

int x = 5;

int y = 2;

int Result;

Page 5: Need for object-oriented paradigm - KMIT

Result = x * y;

cout << Result;

}

Another program showing how Global variables are declared and used within a program:

#include <iostream>

using namespace std;

// Global Variable declaration:

int x, y;

float f;

int main()

{

// Local variable

int tot;

float f;

x = 10;

y = 20;

tot = x + y;

cout << tot;

cout << endl;

f = 70.0 / 3.0;

cout << f;

cout << endl;

}

Expressions

A combination of variables, constants and operators that represents a computation forms an

expression. Depending upon the type of operands involved in an expression or the result

obtained after evaluating expression, there are different categories of an expression. These

categories of an expression are discussed here. Constant expressions: The expressions that

comprise only constant values are called constant expressions. Some examples of constant

expressions are 20, ‘ a‘ and 2/5+30 .

• Integral expressions: The expressions that produce an integer value as output after performing

all types of conversions are called integral expressions. For example, x, 6*x-y and 10 +int (5.0)

are integral expressions. Here, x and yare variables of type into

Float expressions: The expressions that produce floating-point value as output after performing

all types of conversions are called float expressions. For example, 9.25, x-y and 9+ float (7) are

float expressions. Here, x 'and yare variables of type float.

Page 6: Need for object-oriented paradigm - KMIT

• Relational or Boolean expressions: The expressions that produce a bool type value, that is,

either true or false are called relational or Boolean expressions. For example, x + y<100, m +

n==a-b and a>=b + c .are relational expressions.

• Logical expressions: The expressions that produce a bool type value after combining two or

more relational expressions are called logical expressions. For example, x==5 &&m==5 and

y>x I I m<=n are logical expressions.

• Bitwise expressions: The expressions which manipulate data at bit level are called bitwise

expressions. For example, a >> 4 and b<< 2 are bitwise expressions.

Operators in C / C++

We can define operators as symbols that helps us to perform specific mathematical and logical

computations on operands. In other words we can say that an operator operates the operands.

For example, consider the below statement:

c = a + b;

Page 7: Need for object-oriented paradigm - KMIT

Arithmetic Operators: These are the operators used to perform arithmetic/mathematical

operations on operands. Examples: (+, -, *, /, %,++,–).

Arithmetic operator are of two types:

1. Unary Operators: Operators that operates or works with a single operand are unary

operators.

For example: (++ , –)

2. Binary Operators: Operators that operates or works with two operands are binary

operators.For example: (+ , – , * , /)

To learn Arithmetic Operators in details visit this link.

Relational Operators: Relational operators are used for comparison of the values of two

operands. For example: checking if one operand is equal to the other operand or not, an operand

is greater than the other operand or not etc. Some of the relational operators are (==, >= , <= ).

To learn about each of these operators in details go to this link.

Logical Operators: Logical Operators are used to combine two or more

conditions/constraints or to complement the evaluation of the original condition in consideration.

The result of the operation of a logical operator is a boolean value either true or false. To learn

about different logical operators in details please visit this link.

Bitwise Operators: The Bitwise operators is used to perform bit-level operations on the

operands. The operators are first converted to bit-level and then calculation is performed on the

operands. The mathematical operations such as addition , subtraction , multiplication etc. can be

performed at bit-level for faster processing. To learn bitwise operators in details, visit this link.

Assignment Operators: Assignment operators are used to assign value to a variable. The left

side operand of the assignment operator is a variable and right side operand of the assignment

operator is a value. The value on the right side must be of the same data-type of variable on the

left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

“=”: This is the simplest assignment operator. This operator is used to assign the value on

the right to the variable on the left.

For example:

a = 10;

b = 20;

ch = 'y';

“+=”:This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the

current value of the variable on left to the value on right and then assigns the result to the

variable on the left.

Example:

(a += b) can be written as (a = a + b)

If initially value stored in a is 5. Then (a += 6) = 11.

“-=”:This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts

the value on right from the current value of the variable on left and then assigns the result

Page 8: Need for object-oriented paradigm - KMIT

to the variable on the left.

Example:

(a -= b) can be written as (a = a - b)

If initially value stored in a is 8. Then (a -= 6) = 2.

“*=”:This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies

the current value of the variable on left to the value on right and then assigns the result to

the variable on the left.

Example:

(a *= b) can be written as (a = a * b)

If initially value stored in a is 5. Then (a *= 6) = 30.

“/=”:This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the

current value of the variable on left by the value on right and then assigns the result to the

variable on the left.

Example:

(a /= b) can be written as (a = a / b)

If initially value stored in a is 6. Then (a /= 2) = 3.

Other Operators: Apart from the above operators there are some other operators available in

C or C++ used to perform some specific task. Some of them are discussed here:

sizeof operator: sizeof is a much used in the C/C++ programming language. It is a

compile time unary operator which can be used to compute the size of its operand. The

result of sizeof is of unsigned integral type which is usually denoted by size_t. Basically,

sizeof operator is used to compute the size of the variable. To learn about sizeof operator

in details you may visit this link.

Comma Operator: The comma operator (represented by the token ,) is a binary operator

that evaluates its first operand and discards the result, it then evaluates the second

operand and returns this value (and type). The comma operator has the lowest precedence

of any C operator. Comma acts as both operator and separator. To learn about comma in

details visit this link.

Conditional Operator: Conditional operator is of the form Expression1 ? Expression2 :

Expression3 . Here, Expression1 is the condition to be evaluated. If the

condition(Expression1) is True then we will execute and return the result of Expression2

otherwise if the condition(Expression1) is false then we will execute and return the result

of Expression3. We may replace the use of if..else statements by conditional operators.

To learn about conditional operators in details, visit this link.

Operator precedence chart The below table describes the precedence order and associativity of operators in C / C++

. Precedence of operator decreases from top to bottom.

Page 9: Need for object-oriented paradigm - KMIT

Expression evaluation in CPP

Priority: this represents evaluation of expression starts from what operator.

Associativity:

It represents which operator should be evaluated first if an expression is containing more than

one operator with same priority.

Operator Priority Associativity

{}, (), [] 1 Left to right

++, --, ! 2 Right to left

*, /, % 3 Left to right

+, - 4 Left to right

<, <=, >, >=, ==, != 5 Left to right

&& 6 Left to right

|| 7 Left to right

?: 8 Right to left

=, +=, -=, *=, /=, %= 9 Right to left

Example 1:

Example 2

Page 10: Need for object-oriented paradigm - KMIT

Type Conversion in C++

A type cast is basically a conversion from one type to another. There are two types of type

conversion:

Implicit Type Conversion Also known as ‘automatic type conversion’.

Done by the compiler on its own, without any external trigger from the user.

Generally takes place when in an expression more than one data type is present. In such

condition type conversion (type promotion) takes place to avoid lose of data.

All the data types of the variables are upgraded to the data type of the variable with

largest data type.

It is possible for implicit conversions to lose information, signs can be lost (when signed

is implicitly converted to unsigned), and overflow can occur (when long long is implicitly

converted to float).

#include <iostream>

using namespace std;

int main()

{

int x = 10; // integer x

char y = 'a'; // character c

// y implicitly converted to int. ASCII

// value of 'a' is 97

x = x + y;

// x is implicitly converted to float

float z = x + 1.0;

cout << "x = " << x << endl

Page 11: Need for object-oriented paradigm - KMIT

<< "y = " << y << endl

<< "z = " << z << endl;

return 0;

}

Explicit Type Conversion: This process is also called type casting and it is user-defined. Here

the user can typecast the result to make it of a particular data type.

Converting by assignment: This is done by explicitly defining the required type in front of the

expression in parenthesis. This can be also considered as forceful casting.

(type) expression

#include <iostream>

using namespace std;

int main()

{

double x = 1.2;

// Explicit conversion from double to int

int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;

}

What are Pointers?

A pointer is a variable whose value is the address of another variable. Like any variable or

constant, you must declare a pointer before you can work with it. The general form of a pointer

variable declaration is −

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of

the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use

for multiplication. However, in this statement the asterisk is being used to designate a variable as

a pointer. Following are the valid pointer declaration –

int *ip; // pointer to an integer

double *dp; // pointer to a double

float *fp; // pointer to a float

char *ch // pointer to character

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is

the same, a long hexadecimal number that represents a memory address. The only difference

between pointers of different data types is the data type of the variable or constant that the

pointer points to.

Page 12: Need for object-oriented paradigm - KMIT

Using Pointers in C++

There are few important operations, which we will do with the pointers very frequently. (a) We

define a pointer variable. (b) Assign the address of a variable to a pointer. (c) Finally access the

value at the address available in the pointer variable. This is done by using unary operator * that

returns the value of the variable located at the address specified by its operand. Following

example makes use of these operations −

#include <iostream>

using namespace std;

int main () {

int var = 20; // actual variable declaration.

int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";

cout << var << endl;

// print the address stored in ip pointer variable

cout << "Address stored in ip variable: ";

cout << ip << endl;

// access the value at the address available in pointer

cout << "Value of *ip variable: ";

cout << *ip << endl;

return 0;

}

Output of the above program:

Value of var variable: 20

Address stored in ip variable: 0xbfc601ac

Value of *ip variable: 20

Pointers have many but easy concepts and they are very important to C++ programming. There

are following few important pointer concepts which should be clear to a C++ programmer –

Sr.No Concept & Description

1

Null Pointers

C++ supports null pointer, which is a constant with a value of zero defined in several

standard libraries.

2 Pointer Arithmetic

Page 13: Need for object-oriented paradigm - KMIT

There are four arithmetic operators that can be used on pointers: ++, --, +, -

3 Pointers vs Arrays

There is a close relationship between pointers and arrays.

4 Array of Pointers

You can define arrays to hold a number of pointers.

5 Pointer to Pointer

C++ allows you to have pointer to a pointer and so on.

6

Passing Pointers to Functions

Passing an argument by reference or by address both enable the passed argument to be

changed in the calling function by the called function.

7

Return Pointer from Functions

C++ allows a function to return a pointer to local variable, static variable and dynamically

allocated memory as well.

C++ References

A reference variable is an alias, that is, another name for an already existing variable. Once a

reference is initialized with a variable, either the variable name or the reference name may be

used to refer to the variable.

Creating References in C++

Think of a variable name as a label attached to the variable's location in memory. You can then

think of a reference as a second label attached to that memory location. Therefore, you can

access the contents of the variable through either the original variable name or the reference. For

example, suppose we have the following example −

int i = 17;

We can declare reference variables for i as follows.

int& r = i;

#include <iostream>

using namespace std;

int main () {

// declare simple variables

int i;

Page 14: Need for object-oriented paradigm - KMIT

double d;

// declare reference variables

int& r = i;

double& s = d;

i = 5;

cout << "Value of i : " << i << endl;

cout << "Value of i reference : " << r << endl;

d = 11.7;

cout << "Value of d : " << d << endl;

cout << "Value of d reference : " << s << endl;

return 0;

}

Output of the program:

Value of i : 5

Value of i reference : 5

Value of d : 11.7

Value of d reference : 11.7

References are usually used for function argument lists and function return values. So following

are two important subjects related to C++ references which should be clear to a C++ programmer

Sr.No Concept & Description

1 References as Parameters

C++ supports passing references as function parameter more safely than parameters.

2 Reference as Return Value

You can return reference from a C++ function like any other data type.

Arrays

An array is a collection of elements of the same type placed in contiguous memory locations that

can be individually referenced by using an index to a unique identifier.

Five values of type int can be declared as an array without having to declare five different

variables (each with its own identifier).

For example, a five element integer array foo may be logically represented as;

Page 15: Need for object-oriented paradigm - KMIT

where each blank panel represents an element of the array. In this case, these are values of type

int. These elements are numbered from 0 to 4, with 0 being the first while 4 being the last; In

C++, the index of the first array element is always zero. As expected, an n array must be declared

prior its use. A typical declaration for an array in C++ is:

type name [elements];

Initializing arrays

By default, are left uninitialized. This means that none of its elements are set to anyparticular

value; their contents are undetermined at the point the array is declared.

The initializer can even have no values, just the braces:

int baz [5] = { };

This creates an array of five int values, each initialized with a value of zero:

But, the elements in an array can be explicitly initialized to specific values when it is declared,

by enclosing those initial values in braces {}. For example:

int foo [5] = { 16, 2, 77, 40, 12071 };

This statement declares an array that can be represented like this:

The number of values between braces {} shall not be greater than the number of elements in the

array. For example, in the example above, foo was declared having 5 elements (as specified by

the number enclosed in square brackets, []), and the braces {} contained exactly 5 values, one for

each element. If declared with less, the remaining elements are set to their default values (which

for fundamental types, means they are filled with zeroes). For example:

int bar [5] = { 10, 20, 30 };

Will create an array like this:

Page 16: Need for object-oriented paradigm - KMIT

When an initialization of values is provided for an array, C++ allows the possibility of leaving

the square brackets empty[]. In this case, the compiler will assume automatically a size for the

array that matches the number of values included between the braces {}:

int foo [] = { 16, 2, 77, 40, 12071 };

After this declaration, array foo would be five int long, since we have provided five initialization

values.

Both these statements are equivalent:

int foo[] = { 10, 20, 30 };

int foo[] { 10, 20, 30 };

Pointers and Arrays: Pointers are the variables that hold address. Not only can pointers store

address of a single variable, it can also store address of cells of an array.

int* ptr;

int a[5];

ptr = &a[2]; // &a[2] is the address of third element of a[5].

Suppose, pointer needs to point to the fourth element of an array, that is, hold address of fourth

array element in above case.

Since ptr points to the third element in the above example, ptr + 1 will point to the fourth

element.

You may think, ptr + 1 gives you the address of next byte to the ptr. But it's not correct.

This is because pointer ptr is a pointer to an int and size of int is fixed for a operating system

(size of int is 4 byte of 64-bit operating system). Hence, the address between ptr and ptr + 1

differs by 4 bytes.

Page 17: Need for object-oriented paradigm - KMIT

If pointer ptr was pointer to char then, the address between ptr and ptr + 1

would have differed by 1 byte since size of a character is 1 byte.

#include <iostream>

using namespace std;

int main()

{

float arr[5];

float *ptr;

cout << "Displaying address using arrays: " << endl;

for (int i = 0; i < 5; ++i)

{

cout << "&arr[" << i << "] = " << &arr[i] << endl;

}

// ptr = &arr[0]

ptr = arr;

cout<<"\nDisplaying address using pointers: "<< endl;

for (int i = 0; i < 5; ++i)

{

cout << "ptr + " << i << " = "<< ptr + i << endl;

}

return 0;

}

C++ Program to display address of array elements using pointer notation.

#include <iostream>

using namespace std;

int main() {

float arr[5];

cout<<"Displaying address using pointers notation: "<< endl;

for (int i = 0; i < 5; ++i) {

cout << arr + i <<endl;

}

return 0;

}

Displaying address using pointers notation:

0x7fff5fbff8a0

0x7fff5fbff8a4

0x7fff5fbff8a8

0x7fff5fbff8ac

0x7fff5fbff8b0

C++ Program to insert and display data entered by using pointer notation.

#include <iostream>

using namespace std;

int main() {

Page 18: Need for object-oriented paradigm - KMIT

float arr[5];

// Inserting data using pointer notation

cout << "Enter 5 numbers: ";

for (int i = 0; i < 5; ++i) {

cin >> *(arr + i) ;

}

// Displaying data using pointer notation

cout << "Displaying data: " << endl;

for (int i = 0; i < 5; ++i) {

cout << *(arr + i) << endl ;

}

return 0;

}

Enter 5 numbers: 2.5

3.5

4.5

5

2

Displaying data:

2.5

3.5

4.5

5

2

Strings in CPP

String is a collection of characters. There are two types of strings commonly

used in C++ programming language:

C++ program to display a string entered by user.

#include <iostream>

using namespace std;

int main()

{

char str[100];

cout << "Enter a string: ";

cin >> str;

cout << "You entered: " << str << endl;

cout << "\nEnter another string: ";

cin >> str;

cout << "You entered: "<<str<<endl;

return 0;

}

Enter a string: C++

You entered: C++

Enter another string: Programming is fun.

You entered: Programming

C++ program to read and display an entire line entered by user.

Page 19: Need for object-oriented paradigm - KMIT

#include <iostream>

using namespace std;

int main()

{

char str[100];

cout << "Enter a string: ";

cin.get(str, 100);

cout << "You entered: " << str << endl;

return 0;

}

Enter a string: Programming is fun.

You entered: Programming is fun.

string Object

In C++, you can also create a string object for holding strings.

Unlike using char arrays, string objects has no fixed length, and can be extended as per your

requirement.

#include <iostream>

using namespace std;

int main()

{

// Declaring a string object

string str;

cout << "Enter a string: ";

getline(cin, str);

cout << "You entered: " << str << endl;

return 0;

}

Enter a string: Programming is fun.

You entered: Programming is fun.

Passing String to a Function

Strings are passed to a function in a similar way arrays are passed to a function.

#include <iostream>

using namespace std;

void display(char *);

void display(string);

int main()

{

string str1;

char str[100];

Page 20: Need for object-oriented paradigm - KMIT

cout << "Enter a string: ";

getline(cin, str1);

cout << "Enter another string: ";

cin.get(str, 100, '\n');

display(str1);

display(str);

return 0;

}

void display(char s[])

{

cout << "Entered char array is: " << s << endl;

}

void display(string s)

{

cout << "Entered string is: " << s << endl;

}

Enter a string: Programming is fun.

Enter another string: Really?

Entered string is: Programming is fun.

Entered char array is: Really?

In the above program, two strings are asked to enter. These are stored in str and str1 respectively,

where str is a char array and str1 is a string object. Then, we have two functions display()

that outputs the string onto the string. The only difference between the two functions is the

parameter. The first display() function takes char array as a parameter, while the second takes

string as a parameter.

Find Frequency of Characters of a String Object #include <iostream>

using namespace std;

int main()

{

string str = "C++ Programming is awesome";

char checkCharacter = 'a';

int count = 0;

for (int i = 0; i < str.size(); i++)

{

if (str[i] == checkCharacter)

{

++ count;

}

}

cout << "Number of " << checkCharacter << " = " << count;

return 0;

}

Page 21: Need for object-oriented paradigm - KMIT

Length of String Object

You can get the length of a string object by using a size() function or a length() function.

The size() and length() functions are just synonyms and they both do exactly same thing.

#include <iostream>

using namespace std;

int main()

{

string str = "C++ Programming";

// you can also use str.length()

cout << "String Length = " << str.size();

return 0;

}

Output

String Length = 15

To get the length of a C-string string, strlen() function is used.

#include <iostream>

#include <cstring>

using namespace std;

int main()

{

char str[] = "C++ Programming is awesome";

// you can also use str.length()

cout << "String Length = " << strlen(str);

return 0;

}

Output

String Length = 26

C++ Structures Structure is a collection of variables of different data types under a single

name. It is similar to a class in that, both holds a collecion of data of

different data types.

Page 22: Need for object-oriented paradigm - KMIT

For example: You want to store some information about a person: his/her name,

citizenship number and salary. You can easily create different variables

name, citNo, salary to store these information separately.

However, in the future, you would want to store information about multiple persons. Now, you'd

need to create different variables for each information per person: name1, citNo1, salary1,

name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also, since no relation

between the variables (information) would exist, it's going to be a daunting task.

A better approach will be to have a collection of all related information under a single name

Person, and use it for every person. Now, the code looks much cleaner, readable and efficient as

well.

This collection of all related information under a single name Person is a structure.

How to declare a structure in C++ programming? struct Person

{

char name[50];

int age;

float salary;

};

When a structure is created, no memory is allocated.

How to access members of a structure?

The members of structure variable is accessed using a dot (.) operator.

Suppose, you want to access age of structure variable bill and assign it 50 to it. You can perform

this task by using following code below:

bill.age = 50;

C++ Program to assign data to members of a structure variable and display it.

#include <iostream>

using namespace std;

struct Person

{

char name[50];

int age;

float salary;

};

int main()

{

Person p1;

cout << "Enter Full name: ";

Page 23: Need for object-oriented paradigm - KMIT

cin.get(p1.name, 50);

cout << "Enter age: ";

cin >> p1.age;

cout << "Enter salary: ";

cin >> p1.salary;

cout << "\nDisplaying Information." << endl;

cout << "Name: " << p1.name << endl;

cout <<"Age: " << p1.age << endl;

cout << "Salary: " << p1.salary;

return 0;

}

Output:

Enter Full name: Magdalena Dankova

Enter age: 27

Enter salary: 1024.4

Displaying Information.

Name: Magdalena Dankova

Age: 27

Salary: 1024.4

Store and Display Information Using Structure #include <iostream>

using namespace std;

struct student

{

char name[50];

int roll;

float marks;

};

int main()

{

student s;

cout << "Enter information," << endl;

cout << "Enter name: ";

cin >> s.name;

cout << "Enter roll number: ";

cin >> s.roll;

cout << "Enter marks: ";

cin >> s.marks;

cout << "\nDisplaying Information," << endl;

cout << "Name: " << s.name << endl;

cout << "Roll: " << s.roll << endl;

cout << "Marks: " << s.marks << endl;

return 0;

}

Enter information,

Enter name: Bill

Enter roll number: 4

Enter marks: 55.6

Displaying Information,

Name: Bill

Page 24: Need for object-oriented paradigm - KMIT

Roll: 4

Marks: 55.6

Control Statements in C++

Control statements are elements in the source code that control the flow of

program execution. They include blocks using { and } brackets, loops using

for, while and do while, and decision-making using if and switch. There's

also goto. There are two types of control statements: conditional and

unconditional.

Conditional Statements in C++

At times, a program needs to execute depending on a particular condition. Conditional

statements are executed when one or more conditions are satisfied. The most common of these

conditional statements is the if statement, which takes the form:

if (condition)

{

statement(s);

}

This statement executes whenever the condition is true.

C++ uses many other conditional statements including:

if-else: An if-else statement operates on an either/or basis. One statement is executed if

the condition is true; another is executed if the condition is false.

if-else if-else: This statement chooses one of the statements available depending on the

condition. If no conditions are true, the else statement at the end is executed.

while: While repeats a statement as long as a given statement is true.

do while: A do while statement is similar to a while statement with the addition that the

condition is checked at the end.

for: A for statement repeats a statement as long as the condition is satisfied.

Unconditional Control Statements

Unconditional control statements do not need to satisfy any condition. They immediately move

control from one part of the program to another part. Unconditional statements in C++ include:

goto: A goto statement directs control to another part of the program.

break: A break statement terminates a loop (a repeated structure)

continue: A continue statement is used in loops to repeat the loop for the next value by

transferring control back to the beginning of the loop and ignoring the statements that

come after it.

Page 25: Need for object-oriented paradigm - KMIT

These statements are executed when one or more conditions is/are satisfied. C++ supports

many such statements. These statements are listed below with a brief description.

if:- The statement following the if statement is executed when the condition given is true.

if(condition)

s1;

s2;

When the condition is true statement s1 and then s2 is executed. If the

condition is false only s2 is executed. If we want to execute more than 1 statements

whencondition is true then we should write all those statements within braces {} after if

if(condition)

{

s1;

s2;

}

s3;

when the condition is true statement s1, s2 and then s3 is executed. If the condition isfalse

only s3 is executed

if-else:- Also known as either or. This statement is used to select one statement and

ignore the other statements.

if(condition)

s1;

else

s2;

when the condition is true statement s1 is executed. If the condition is false s2is

executed. Thus one of the statements, either s1 or s2 is always executed

if-else if-else:- It is a branching statement which can choose and execute on of

thestatements available depending upon the condition.

if(condition1)

s1;

else if(condition2)

s2;

else

s3;

when the condition1 is true statement s1 is executed and rest are ignored.

Whencondition1 is false condition2 is verified. If condition2 is true statement s2 is

exected and other statements are ignored and so on. Thus only one statement is executed

fro the top, depending upon the condition. The statement following else is executed when

allthe conditions are false. However else clause is optional.

while:- It is a repeated structure statement which repeats a statement given as long as

thecondition is true.

Page 26: Need for object-oriented paradigm - KMIT

while(condition)

statement1;

statement1 is executed till the condition is true.

do while:- Like while statement it repeats a statement given as long as the condition

issatisfied unlike in while statement the condition is checked at the end of the structure.

do

{

statement1;

}

while(condition);

statement1 is executed till the condition is true.

for:- It is a repeated structure which can repeat a statement as long as the given

conditionis satisfied.

for(statement1; condition; statement2)

statement3;

where statement1 initialises control variable, condition is used to check

whetherstatement written after loop can be repeated or not , statement2 is used to modify

the conrol variable. Statement3 is a simple statement (having only one statement) or

compund statement (a set of statements written within braces {} ) which can be repeated

as log as condition is true or satisfied.

gotoxy(x,y):- This function moves the cursor to the xth

column of the yth

row i.e. it

fixesthe displaying position at xth

column of yth

row. Its header file is <conio.h>

switch:- It is a multi branch statement which can be used to select and execute one of

theavailable statements.

switch(value)

{

case 1: statement 1; break;

case 2: statement 2; break;

case n: statement n; break;

default: statement d;

}

Where value can be a variable of type numeric or character. The case label 1 to n can

alsobe written with constant identifiers.

When the value assigned matches with case label 1 statement 1 is executed. The

break statement written after statement 1 transfers the control out of the switch statement.

When the value doesn’t match with case label 1 then it checks with case label 2 and so

on. When the value assigned doesn’t match with any of the case labels (1 to n) then the

default clause is considered and the statement d is executed.

Page 27: Need for object-oriented paradigm - KMIT

Default clause is optional like else clause in if-else-if-else statement.

C++ Functions

In programming, function refers to a segment that groups code to perform a specific task.

Depending on whether a function is predefined or created by programmer; there are two types of

function:

1. Library Function

2. User-defined Function

Library Function

Library functions are the built-in function in C++ programming.

Programmer can use library function by invoking function directly; they don't need to write it

themselves.

Example program on usage of library functions

#include <iostream>

#include <cmath>

using namespace std;

int main()

{

double number, squareRoot;

cout << "Enter a number: ";

cin >> number;

// sqrt() is a library function to calculate square root

squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;

}

Enter a number: 26

Square root of 26 = 5.09902

User-defined Function

C++ allows programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is given a

name(identifier).

When the function is invoked from any part of program, it all executes the codes defined in the

body of function.

Page 28: Need for object-oriented paradigm - KMIT

How user-defined function works in C Programming?

User Defined Function Example Program

#include <iostream>

using namespace std;

// Function prototype (declaration)

int add(int, int);

int main()

{

int num1, num2, sum;

cout<<"Enters two numbers to add: ";

cin >> num1 >> num2;

// Function call

sum = add(num1, num2);

cout << "Sum = " << sum;

return 0;

}

// Function definition

int add(int a, int b)

{

int add;

add = a + b;

// Return statement

return add;

}

Enters two integers: 8

-4

Sum = 4

Passing Arguments to Function

In programming, argument (parameter) refers to the data which is passed to a function (function

definition) while calling it.

Page 29: Need for object-oriented paradigm - KMIT

In the above example, two variables, num1 and num2 are passed to function during function call.

These arguments are known as actual arguments.

The value of num1 and num2 are initialized to variables a and b respectively. These arguments a

and b are called formal arguments.

This is demonstrated in figure below:

Notes on passing arguments

The numbers of actual arguments and formals argument should be the same. (Exception: Function Overloading)

The type of first actual argument should match the type of first formal argument. Similarly, type of second actual argument should match the type of second formal argument and so on.

You may call function a without passing any argument. The number(s) of argument passed to a function depends on how programmer want to solve the problem.

You may assign default values to the argument. These arguments are known as default arguments.

In the above program, both arguments are of int type. But it's not necessary to have both arguments of same type.

Return Statement A function can return a single value to the calling program using return statement.

In the above program, the value of add is returned from user-defined function to the

calling program using statement below: return add;

The figure below demonstrates the working of return statement.

Page 30: Need for object-oriented paradigm - KMIT

Prime Numbers Between two Intervals using functions #include <iostream>

using namespace std;

int checkPrimeNumber(int);

int main()

{

int n1, n2;

bool flag;

cout << "Enter two positive integers: ";

cin >> n1 >> n2;

cout << "Prime numbers between " << n1 << " and " << n2 << " are: ";

for(int i = n1+1; i < n2; ++i)

{

// If i is a prime number, flag will be equal to 1

flag = checkPrimeNumber(i);

if(flag)

cout << i << " ";

}

return 0;

}

// user-defined function to check prime number

int checkPrimeNumber(int n)

{

bool flag = true;

for(int j = 2; j <= n/2; ++j)

{

if (n%j == 0)

{

flag = false;

break;

Page 31: Need for object-oriented paradigm - KMIT

}

}

return flag;

}

Enter two positive integers: 12

55

Prime numbers between 12 and 55 are: 13 17 19 23 29 31 37 41 43 47 53

C++ inline function: How is it different from regular function and why is it

required?

Normally, a function call transfers the control from the calling program to the called function.

After the execution of the program, the called function returns the control to the calling program

with a return value.

This concept of function saves program space because instead of writing same code multiple

times the function stored in a place can be simply used by calling it at a desired place in

the program.

This might be handy to reduce the program size but it definitely increases the execution time of

the program as the function is invoked every time the control is passed to the function and

returns a value after execution.

In large functions, this is very helpful but in a small function in order to save execution time a

user may wish to put the code of function definition directly in the line of called location.

For this C++ provides inline function to reduce function call overhead. That is every time a

function is called the compiler generate a copy of the function’s code in place to avoid function

call.

This type of function whose code is copied to the called location is called inline function

inline data_type function_name(arguments_list);

Page 32: Need for object-oriented paradigm - KMIT

C++ Inline Function Example #include <iostream>

#using namespace std;

inline void square_me(int a) //inline function

{

a* = a;

}

int main()

{

int x;

cout << "enter number: ";

cin >> x;

square_me( x );

cout << x;

return 0;

}

enter number: 5

25

C++ Recursion with example

The process in which a function calls itself is known as recursion and the

corresponding function is called the recursive function. The popular example

to understand the recursion is factorial function.

C++ recursion example: Factorial #include <iostream>

using namespace std;

//Factorial function

int f(int n){

/* This is called the base condition, it is

* very important to specify the base condition

* in recursion, otherwise your program will throw

* stack overflow error.

*/

if (n <= 1)

return 1;

else

return n*f(n-1);

}

int main(){

int num;

Page 33: Need for object-oriented paradigm - KMIT

cout<<"Enter a number: ";

cin>>num;

cout<<"Factorial of entered number: "<<f(num);

return 0;

}

Enter a number: 5

Factorial of entered number: 120

Direct recursion: When function calls itself, it is called direct recursion, the example we have

seen above is a direct recursion example.

Indirect recursion: When function calls another function and that function calls the calling

function, then this is called indirect recursion. For example: function A calls function B and

Function B calls function A.

Indirect Recursion Example in C++

#include <iostream>

using namespace std;

int fa(int);

int fb(int);

int fa(int n){

if(n<=1)

return 1;

else

return n*fb(n-1);

}

int fb(int n){

if(n<=1)

return 1;

else

return n*fa(n-1);

}

int main(){

int num=5;

cout<<fa(num);

return 0;

}

Pointers to functions

A pointer to a function points to the address of the executable code of the function. You can use

pointers to call functions and to pass functions as arguments to other functions. You cannot

perform pointer arithmetic on pointers to functions.

The type of a pointer to a function is based on both the return type and parameter types of the

function.

A declaration of a pointer to a function must have the pointer name in parentheses.

int (*g)(int a); /* pointer g to a function returning an int