Procedural and Object-Oriented Programming

2.1 Concept of procedural programming

It is focused on process not on the objects itself. It does not have properties such as abstraction, encapsulation, inheritance and polymorphism. It follows on top-down approach.

2.3 Keywords: In C programming, there are certain words which has specific meaning. Keywords such as define, int, float, char, return, if, else, switch. Keywords are case-sensitive. They are used to create parse tree and recognized by compiler.

Identifiers: Identifiers are the name given to variables, functions, arrays. Generally, in C they are created using a-Z, 0-9, start with _ . Identifiers are case-sensitive.

Keywords and Identifiers can’t be the same words.

2.4 Data types: According to the machine or according to the microprocessor, the length in memory taken by data are of different length. In C, int has 4 bytes length, char has 1 byte length, float has 4 bytes with single precision, double has 64 bits with double precision. Int can take +,- and 0 value.

2.5 Statements and operators: The instruction with data is called statement. In C, the each single instruction has ; to end the instruction scope. On the other hand, control structures may contain lengthy statements. Operators act upon operands. Operator such as +, -, &&, ||, <, >, =, ++, -- are few examples available in C. Some operands are un-ary like ++, -- and some are binary which needs two operands for operation like +, - , &&, ||

2.6 Preprocessor Directives: Generally, we call preprocessor directives to pull all the available functions, keywords, definition before writing our program. It is required to make the program valid and syntactically accepted. They are loaded before compilation. In C, # is used to include preprocessor directives.

2.7 Input/Output: It is required to take data from/to outside environment.

Control statements and Loops:

Programs must be written in such a way that they do not enter into infinite loop. There must be always exit step after certain condition is achieved.

                             In C, we have if () {} ,, for(){} , while {}, do{}while(), switch{}

All these statements must be executed till they satisfy certain condition.

if (control checking) {

              Statements;

}

else {

          statements;

}

for(initialization; checking; update){

         statements;

}

while(check){

         statements;

}

do {

      statements;

}while(checking);  #do-while loop executes at least one time.

2.8 Procedure/functions:

Functions is a section of code which executes once it is called from main body. It helps us to organize the code reducing the code length.

In C,

Data type functionname (datatype, datatype);   #function declaration

Datatype functionname (data type parameter1, data type parameter2) {

         statements;

}

int maxvalue(int x, int y){

return (x>y)?x:y;

}

Int main(){

         Int x=5;

         Int y=6;

         Int z;

         Z=maxvalue(x,y);

         Return 0;

}

In memory, function code resides in code segment. The variables used in functions are stored in stack section in memory.

 

In overall, function helps increase code readability and reusability.

 

2.9 Array, String and Pointer

Array is a data structure. It stores a similar type of data in linear fashion. In other words, we say it takes contiguous memory location. During execution, we can’t increase the size of an array. It is a limitation of this data structure. So, we must know the size of the problem beforehand or use other of data structure such as linked list. Secondly, we can use dynamic memory allocation using malloc.

During program compilation, memory is assigned for it.

In c, array is constructed as: datatype arrayname[size] for example, int x[5]. Its index is started from 0,1,….. For x[5] it is x[0],x[1],…..upto x[4].

String is not a separate data type in C programming. However, they are char arrays. So, In C, string is an array of character ending with a null character \0. For example, char x[]=”ram”;

#’r’,’a’,’m’,’\0’

Pointer is a powerful feature provided in C programming language. It points to the address of the variable it is assigned to.

For example

int x;

x=5;

int * ptr;

ptr = &x;

printf(“output is :%d”,*ptr);

 

#output is: 5;

So, we can say ptr has now value of x.

 

Now Lets say

X=10;

printf(“output is :%d”,*ptr);

#output is: 10

 

If we write printf(“output is:%d”, ptr); #output is: address of ptr

 

2.10 Structure and Union

 

Using array, we can store multiple values with only same data type. Sometimes, we need to store data in various data types under single name. For example, for students we store student name, roll number and weight. For this case, we use syntax of structure and take value of those data members.

In C,

struct student {

         int roll;

         char name[50];

         float weight;

};

int main(){

         struct student ram;

         ram.roll=10;

         strcpy(ram.name,”Ram”;

         ram.weight=49.5;

return 0;

}

 

Union:

It is similar to structure. But, only one variable can take a value in memory.

 

Structure vs Union

In structure, each member has its own memory. Total size used in memory is sum of all members and all members can hold values at once.

In union, all members share memory. Size of the largest member is allocated space in memory. Only one member is used at a time.

Syntax is:

In C,

union student {

         int roll;

         char name[50];

         float weight;

};

int main(){

         union student ram;

         ram.roll=10;

         strcpy(ram.name,”Ram”);

         ram.weight=49.5;

return 0;

}

Here, the final value of weight will replace above values.

 

2.11 Files

In C, we use files to feed data to program and also output data to files for storing it permanently. We generally use files for managing data and sometimes for storing the result for future use.

 

2.12 Object oriented programming and features

Significant difference between procedural and OOP is former is top-down and later is bottom-up approach. OOP emphasize on object and data not on the functions/procedures. OOP has important features such as abstraction, encapsulation, inheritance and polymorphism.

Data values and methods can be bind together.

Reusability of code is limited in C whereas reuse in OOP is high from features of inheritance.

Function and operator overloading

Using polymorphism feature of OOP we can use same function in varieties of way according to the data parameter.

 

 

class add{

public:

void sum(int a, int b){

cout<<”add int”;

}

void sum(float a, float b){

cout<<”add float”;

}

void sum(char a, char b){

cout<<”add char”;

}

}

int main(){

         add a1;

         a1.sum(2,3);

         a1.sum(2.3,3.2);

         a1.sum(‘a’,’b’);

return 0;

}

        

 

Function overloading is compile-time polymorphism. It means during compilation of program we know which function is to execute for same a1.sum() #based upon the parameter

 

2.14 Operator overloading: Besides few operator such as scope resolution operator (::), dot operator(.), sizeof() operator , other operator like + , -, / can be overloaded.

For example to add two complex numbers:

 

 

class complex{

         private:

                  int real;

                  int imag;

         public:

                  complex(int r=0, int i=0){real=r;imag=i;}

                  complex operator + (complex & obj ){

                           complex result;

                           result.real=real+obj.real;

                           result.imag=imag+obj.imag;

                           return result;

                  }

                  void show(){

                           cout<<”real is:”<<real<<”+i”<<imag;

                  }

};     

int main(){

         complex c1(1,2),c2(2,4),c3;

         c3=c1+c2;

         c3.show();

return 0;

}

 

2.15 Abstraction, Encapsulation, Inheritance, Polymorphism, Template

These are the features of OOP.

Abstraction: Objects can be accessed through just interfaces. The implementation details is hide to outer environment.

Encapsulation: Data members and method of an object are binded up together.

Inheritance: We can create objects which follows parent-child relationship. Multilevel and multiple inheritance are the varieties of inheritance. This increase code reusability.

Multilevel inheritance:

class classA{

}

class classB: public classA{

}

 

class classC: public classB{

 

}

 

Multiple inheritance:

 

class classA{

}

class classB{

}

 

class classC: public classB, public class A{

 

}

 

# Important : In Multiple inheritance, order of inheritance is important. In above cases, first classB is called, then classA and finally classC is called. If class classC: public classA, public classB is written then first classA, classB and finally classC is called.

 

Polymorphism:

We already talk about function overloading, which is an example of polymorphism. In addition to that, now we are going to give example of run-time polymorphism using virtual keyword.

 

 

class ClassA{

         private:

                  int x;

         public:

                  virtual void area()=0;

}

 

 

class classB: public classA{

         private:

                  float radius;

         public:

                  classB(float r){radius=r;}

                  void area() override{

         cout<<”Area of circle is:<<3.14*radius*radius;

}

};

 

Class classC: public classA{

private:

         float length;

         float breadth;

public:

         classC(float x,float y){length=x;breadth=y;}

         void area() override{

                  cout<<”Area of rectangle is:<<length*breadth;

}

};

 

int main(){  

         classA* s1;

         classB c(2.5);

         classC r(2.5,3.5);

         s1=&c;

         s1->area();

         s1=&r;

         s1->area();

return 0;

}

 

 

For template:

Sometime our variable can be int, char, float i.e object can have any one of data type. So, we want our class have generic data type such that it can support any data type in future scenario.

The syntax for it is:

template <typename T>

class Box {

private:

         T value;

public:

         Box(T v){value=v;}

         void show(){

cout<<”Value is:”<<value;

}

};

int main (){

         Box<int> s1(5);

         s1.show();

         Box<float> s2(5.05);

         s2.show();

         return 0;

}

 

2.16 Exception Handling:

Concept of exit from program if any error is found during execution. It means if valid data entry is not made then program will gracefully exit.

 

int main() {

    int a = 10, b;

 

    cout << "Enter divisor: ";

    cin >> b;

 

    try {

        if (b == 0)

            throw "Division by zero not allowed!";

        cout << "Result: " << a / b << endl;

    }

    catch (const char* msg) {

        cout << "Error: " << msg << endl;

    }

 

    return 0;

}

 

We have “throw” inside our program. If  any issue is found then throw will be executed and “catch” body will execute.

 

Difference between structured and object oriented programming:

Aspect

Structured programming

Object Oriented Programming

Approach

Programming in top-down. It breaks problem into small function

Programming in bottom-up. Builds program using objects

Features

Iteration (Control Structures)

Supports abstraction, encapsulation, inheritance, polymorphism

Data share

Data is often shared between functions

Data is encapsulated

Focus

Functions and procedures

Objects and data

Example of language

C

C++

 

 

Write difference between compile time and run time polymorphism.

Aspect

Compile time polymorphism

Run time polymorphism

Compiler

It generates different functions signatures during compilation

It generates same function signature. However, it is decided during execution.

Methods to achieve

Function overloading, operator overloading are example of compile time polymorphism.

Virtual method support run time polymorphism