c_Cpp5

  Paper DSC 203:PROGRAMMING WITH C & C++

UNIT-IINTRODUCTION TO C LANGUAGE, VARIABLES, DATA TYPES AND OPERATORS INTRODUCTION: TYPES OF LANGUAGES- HISTORY OF C LANGUAGE – BASIC  TRUCTURE –PROGRAMMING RULES – FLOW CHARTS-ALGORITHMS–COMMONLY USED LIBRARY FUNCTIONS - EXECUTING THE C PROGRAM - PRE-PROCESSORS IN “C”- KEYWORDS & IDENTIFIERS – CONSTANTS – VARIABLES: RULES FOR DEFINING VARIABLES - SCOPE AND LIFE OF A VARIABLE–- DATA TYPES - TYPE CONVERSION - FORMATTED INPUT AND OUTPUT OPERATIONS. OPERATORS: INTRODUCTION – ARITHMETIC – RELATIONAL – LOGICAL – ASSIGNMENT - CONDITIONAL - SPECIAL - BITWISE - INCREMENT / DECREMENT OPERATOR.

UNIT-II: WORKING WITH CONTROL STATEMENTS, LOOPS CONDITIONAL STATEMENTS: INTRODUCTION - IF STATEMENTS - IF-ELSE STATEMENTS – NESTED IF-ELSE – BREAKSTATEMENT-CONTINUE STATEMENT-GO TO STATEMENT-SWITCH STATEMENTS. LOOPING STATEMENTS: INTRODUCTION-WHILE STATEMENTS – DO-WHILE STATEMENTS - FOR STATEMENTS-NESTED LOOP STATEMENTS.

UNIT-III: FUNCTIONS, ARRAYS AND STRINGS FUNCTIONS: DEFINITION AND DECLARATION OF FUNCTIONS- FUNCTION PROTO TYPE-RETURN STATEMENT- TYPES OF FUNCTIONS-FORMATTED AND UNFORMATTED FUNCTIONS. BUILT IN FUNCTIONS: MATHEMATICAL FUNCTIONS - STRING FUNCTIONS - CHARACTER FUNCTIONS - DATE FUNCTIONS.USER DEFINED FUNCTIONS: INTRODUCTION - NEED FOR USER DEFINED FUNCTIONS - ELEMENTS OF FUNCTIONS – FUNCTION CALL – CALL BY VALUE AND CALL BY REFERENCE - RECURSIVE FUNCTIONS.ARRAYS: INTRODUCTION - DEFINING AN ARRAY - INITIALIZING AN ARRAY –CHARACTERISTICS OF AN ARRAY- ONE DIMENSIONAL ARRAY – TWO DIMENSIONAL ARRAY – MULTI DIMENSIONAL ARRAY. STRINGS: INTRODUCTION - DECLARING AND INITIALIZING STRING - READING AND WRITING STRINGS - STRING STANDARD FUNCTIONS.

UNIT-IV: POINTERS, STRUCTURES AND UNIONS POINTERS: FEATURES OF POINTERS- DECLARATION OF POINTERS-ARITHMETIC OPERATIONS WITH POINTERS STRUCTURES: FEATURES OF STRUCTURES - DECLARING AND INITIALIZATION OF STRUCTURES –STRUCTURE WITHIN STRUCTURE- ARRAY OF STRUCTURES- ENUMERATED DATA TYPE-UNIONS-DEFINITION AND ADVANTAGES OF UNIONS COMPARISON BETWEEN STRUCTURE & UNIONS.

UNIT-V: OBJECT ORIENTED CONCEPTS USING C++ OBJECT ORIENTED PROGRAMMING: INTRODUCTION TO OBJECT ORIENTED PROGRAMMING - STRUCTURE OF C++ – SIMPLE PROGRAMOF C++– STORAGE CLASSES-SIMILARITIES AND DIFFERENCES BETWEEN C & C++ - DATA MEMBERS-MEMBER FUNCTIONS - OBJECT ORIENTED CONCEPTS-CLASS-OBJECT-INHERITANCE- OLYMORPHISM- ENCAPSULATION-ABSTRACTION. 

UNIT-V:

OBJECT ORIENTED CONCEPTS USING C++

Introduction to Object Oriented Programming:

Object-oriented programming (OOP) is a style of programming that focuses on using objects to design and build applications. The object-oriented programming deals with objects. Data and associated operations are combined into objects. OOP enables the reuse of code and design. These languages gives importance to both the data and functions.

The most important object-oriented programming features are:

Abstraction, Encapsulation and data hiding, Inheritance, Polymorphism and reusable code.

Those features are useful to produce reliable and reusable software in reduced cost and time.

C++, JAVA, C#, PYTHON, SMALLTALK,etc. are examples of object-oriented programming languages.

Similarities and Differences between C & C++

No.CC++
1)C follows the procedural style programming.C++ is multi-paradigm. It supports both procedural and object oriented.
2)Data is less secured in C.In C++, you can use modifiers for class members to make it inaccessible for outside users.
3)C follows the top-down approach.C++ follows the bottom-up approach.
4)C does not support function overloading.C++ supports function overloading.
5)In C, you can't use functions in structure.In C++, you can use functions in structure.
6)C does not support reference variables.C++ supports reference variables.
7)In C, scanf() and printf() are mainly used for input/output.C++ mainly uses stream cin and cout to perform input and output operations.
8)Operator overloading is not possible in C.Operator overloading is possible in C++.
9)C programs are divided into procedures and modulesC++ programs are divided into functions and classes.
10)C does not provide the feature of namespace.C++ supports the feature of namespace.
11)Exception handling is not easy in C. It has to perform using other functions.C++ provides exception handling using Try and Catch block.
12)C does not support the inheritance.C++ supports inheritance.

Introduction to C++

C++ is an Object Oriented Programming Language. It was designed by Bjarne Stroustrup at AT & T Bell Labs of USA in  1980.

  1.   The incremental operator ++ was added in 1983 to C to indicate that C++ is an incremental version of C.
  2.   In 1997, the American National Standards Institute (ANSI)/International Organization for
  3. Standardization (ISO), standardization committee provided an ANSI/ISO C++ standard.
  4.   C++ is an extension of C language. It is a proper superset of C language. This means that a C++ compiler can compile programs written in C language.
  5.   It was initially called ‘C with classes’.
  6.   The following differences can be noticed between Date structure in C and C++:
  7.   The keyword class has been used instead of struct.
  8.   Two new keywords—private and public—appear in the code.
  9.   Apart from data members, the class constructor also has member functions.
  10.   A function that has the same name as the class itself is also present in the class
  11.   C++ implement the features of OOPS, such as data hiding, data encapsulation, data abstraction, and a guaranteed initialization of data.
  12.   C++ programs have the extension ‘.cpp’.
  13.   The latest version of C++ is known as C++14 and was released in the year 2014.

Structure of a program

A typical C++ program may contain four sections. Those are:

1. Include Files

2. Class Declarations

3. Member Functions

4. Main Function Program

It is common to organize a c++ program components into three separate files in the following fashion:

1. Class Declarations are stored in their own header files. A header file that contains a class declaration is called a class specification file.

The name of this specification file is the same as the name of the class, with a .h extension. For example, the Rectangle class would be declared in the file Rectangle.h

2. The Member Function definitions for a class are stored in a separate .cpp file called the class implementation file. The file usually has the same name as the class, with the .cpp extension. For example, the Rectangle class’s member functions would be defined in the file Rectangle.cpp.

3. Any Main Function program that uses the class should #include the class’s header file. The class’s .cpp file (that which contains the member function definitions) should be compiled and linked with the main program.

This approach is based on the concept of Client-Server Model

 The class definitions and Member functions jointly acts as a server and provides their services to the Main function program known as client.

This process can be automated with Integrated Development Environments (IDEs) such as CodeBlocks, Visual Studio to create the multi-file projects.

Simple program of C++

#include<iostream>

using namespace std;

int main()

{

int x,y,sum;                           //variable declaration.

cout<<” Enter a Number:”; //C++ Output statement

cin>>x;                                   //Input statement in C++

cout<<” Enter another Number:”;

cin>>y;

sum=x+y;                              // addition

cout<<”\nSum=”<<sum;

return 0;                                 // returning a value to the calling process

}

                                                                        --O--

Introduction:

  1.  The most important feature of C++ is the "class”.
  2.  Its significance is highlighted by the fact that Stroustrup initially gave the name " C with classes " to his new language.
  3. A class is an extension of the idea of structure used in C.

Specifying a Class

A class is a way to bind the data and its associated functions together. When defining a class, we are creating a new abstract data type that can be treated like any other built-in data type.

Generally, a class specification has two parts:

l. Class declaration

2. Class function definitions

The class declaration describes the type and scope of its members.

The class function definitions describe how the class  functions are implemented

The general form of a class declaration is:

class class_name

{

private:

variable declarations;

function declarations;

public:

variable declarations;

function declaration;

};

The keyword class specifies, that what follows is an abstract data of type class_name.

  1.  The body of a class is enclosed within braces and terminated by a semicolon.
  2. The class body contains the declaration of  variables and functions.
  3. These functions and variables are collectively called class members. They are grouped in two sections, private and public. The keywords known as visibility labels or access specifiers. These keywords are followed by a colon(:).
  4. The private members can be accessed only from within the class.
  5. Public members can be accessed from outside the class also.
  6. By default, the members of a class are private.
  7.  The variables declared inside the class are known as data members and the functions are known as member functions.
  8. The binding of data and functions together into a single class type variable is referred to as encapsulation.

A typical class declaration would look like:

class item

{

int number;                                       // variables declaration

float cost;                                            // private by default

public:

void getdata(int a, float b);                                     // functions declaration

void putdata(void);                                     // using prototype

} ;                                                         // ends with semicolon

The Class name item becomes a new type identifier that can be used to declare instances of that class type. The class item contains two data members and two function members.

Public Member Functions

To allow access to a class’s private member variables, you create public member functions that work with the private member variables.

The function getdata() can be used to assign values to the member variables number and cost, and putdata() for displaying their values.

The data members can be accessed by member of the class item.

Defining Member Functions

Member functions can be defined in two places:

• Outside the class definition.


• Inside the class definition.

Outside the Class Definition

Member functions that are declared inside a class have to be defined separately outside the class. They should have a function header and a function body.

The membership label class-name:: tells the compiler that the function function-name belongs to the class class-name. That is, the scope of the function is restricted to the class-name specified in the header line. The symbol :: is called the scope resolution operator.

For instance, consider the member functions getdata() and putdata() as discussed below.

void item :: getdata(int a, float b)

{

number = a;

cost = b;

}

void item :: putdata(void)

{

cout<< “Number: “ << number << "\n" ;

cout<< “cost :” << cost << "\n";

}

Since these functions do not return any value, their return-type is void.

The member functions characteristics are:

• Several different classes can use the same function name. The 'membership label' will resolve their scope.

• Member functions can access the private data of the class. A non-member function can not do so.

• A member function can call another member function directly, without using the dot operator.

Inside the Class Definition

class item

{

int number;

float cost;

public:

void getdata(int a, float b); //declaration  inline function

void putdata(void)   //definition inside the class

{

cout<< number << "\n";

cout<< cost << "\n";

}

};

Defining an Instance of a Class

Once a class has been declared, we can create variables of that type by using the class name. Defining a class object is called the instantiation of a class.

Syntax:

Class_Name   object_Name;

In the general format, Class_Name is the name of a class, and object_Name is the name we are giving the object.

item x;             // memory for x is created

·      creates a variable x of type item.

·      In C++, the class variables are known as objects.

·      Therefore, x is called an object of type item.

·      We may also declare more than one object in one statement.

Example: item   x,y,z;

The declaration of an object is similar to that of a variable of any basic type. The necessary memory space is allocated to an object at this stage.

Objects can also be created when a class is defined by placing their names immediately after the closing brace as below.

c1ass item

{

………

}x,y, z;

would create the objects x, y and z of type item.

Accessing an Object’s Members

object-name.function-name(actual-arguments);


The following is the format for calling a member function.

For example the function call statement

x.getdata(l00,75.5);

is valid and assigns the value 100 to number and 75.5 to cost of  the object x by implementing the getdata() function. The assignments occur in the actual function Similarly, the statement

x.putdata() ;

would display the values of data members. Remember, a member function can be invoked only by using an object .


Program1.cpp A Class Demonstration Program

# include< iostream. h>

class item

{

int number;

float cost;

public:

void getdata ( int a , float b);

void putdala ( void)

{

cout<<“number:”<<number<<endl; cout<<”cost :”<<cost<<endl;

}

};

void item :: getdata (int a , float b)

{

number=a;

cost=b;

}

main ( )

{

item x;

cout<<”\nobjectx”<<endl;

x. getdata( 100,299.95);

x .putdata();

item y;

cout<<”\n object y”<<endl;

y. getdata(200,175.5);

y. putdata();

}

output:                  Object x

number: 100 

cost:299.95

Object y

number :200

cost : 175.5

1.Explain OOPS Concepts in C++ with example ?

Ans:

Basic Concepts of Object Oriented Programing:

The following are the basic concepts of Object Oriented Programming:

1) Objects                     5) Inheritance

2) Class                        6) Polymorphism

3) Data Abstraction 7) Dynamic binding

4) Encapsulation     8) Message passing.

1). Objects:

An object is a combination of code and data that can be treated as a unit. It has a state and behavior. Objects are the basic runtime entities.

For example, a 'car' object might have some data (i.e. 'speed,' 'direction,' 'lights,' 'current fuel,' etc.) and some actions it can take ('turn right,' 'turn lights on,' 'accelerate,' etc.).

2). Classes:

A class is a set of objects that share common properties and behavior. It is a logical construct.

It defines a new data type. It can be used to create objects. Thus, a class is a template for an object, and an object is an instance of a class. A class can be defined with the keyword ‘class.

A class can be defined with the keyword ‘class.

It has the following syntax:

class classname {

private:

variable_declarations;

Function Declarations;

public:

variable_declarations;

Function Declarations;

};

The methods and variables defined within a class are called members of the class.

The members of a class are classified into three categories: private, public, and protected. In C++, private, protected, and public are reserved words and are called member access specifiers.

3). Abstraction:

Abstraction refers to the mechanism of representing the main features without showing the inner details. There are two types of Abstraction:

* Procedural Abstraction: Using a function without having to know the inner steps in the function known as Procedural Abstraction.

* Data Abstraction: Data Abstraction refers to knowing only the name of that object without knowing its inner details.

4.) Encapsulation:

The wrapping up of data and functions into a single unit is known as Encapsulation. It is useful to hide an object’s data and functions from other objects.

The objects from outside of a class cannot access the data. Only the functions within the class can access the data. This type of protection of data is called as Encapsulation or Data Hiding.

5.) Inheritance :

Deriving a new class from an existing class is known as Inheritance. The new class will have the combined features of both the classes. The different types of inheritance are: Single, Multi-level, Multiple, Hierarchical and Hybrid inheritance.

There are many advantages of inheritance:

* We can develop reusable components

* No need of testing the inherited code.

* This will save the time as well as cost for the developers

6.) Polymorphism:

Polymorphism means “one name multiple forms”. By using the polymorphism concept, the methods will contain the same names but the operations performed by those methods will be different.

There are two types of Polymorphism:

Compile time Polymorphism: The member functions are selected for invoking at compile time by matching the type and number of arguments. So this is called as Early binding or Static binding or Compile time polymorphism.

Run Time Polymorphism :

The appropriate member function is selected while the program is running. This is called as late binding or dynamic binding or Run time polymorphism.

7.) Message Communication:

Objects communicate with each another by sending and receiving information. For example ‘customer’ and ‘account’ are two objects in a class. when the ‘customer’ ask for the balance , the ‘account’ object will receive the message and then get the balance and again send it back to the ‘customer’ object. Thus communication is a very important part of OOP.

Storage Classes in C++

2.Explain Various Storage class  in C language?

Ans:

Storage Classes are used to specify the scope, visibility and life-time of a varible which help us to trace the existence of a particular variable during the runtime of a program. To specify the storage class for a variable, the following syntax is to be followed:

Syntax:

storage_class var_data_type var_name;

C++ uses 5 storage classes, namely:

  1. auto
  2. register
  3. extern
  4. static
  5. mutable

autoThe auto storage class is the default class of all the variables declared inside a block. The auto stands for automatic and all the local variables that are declared in a block automatically belong to this class.

Properties of auto Storage Class Objects

  • Scope: Local
  • Default Value: Garbage Value
  • Memory Location: RAM
  • Lifetime: Till the end of its scope

Example:

#include <iostream>

using namespace std;

void autoStorageClass()

{

 cout << "Demonstrating auto class\n";

            auto int a = 32;

            auto float b = 3.2;

            auto string c = "Kranthi";

            auto char d = 'G';

            cout << a << " \n";

            cout << b << " \n";

            cout << c << " \n";

            cout << d << " \n";

}

int main()

{

            autoStorageClass();

            return 0;

}

Output:

Demonstrating auto class

32

3.2

Kranthi 

G

extern

The extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used (i.e. external linkage). Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. An extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere.

A normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program.

Properties of extern Storage Class Objects

  • Scope: Global
  • Default Value: Zero
  • Memory Location: RAM
  • Lifetime: Till the end of the program

Example:

#include <iostream>

using namespace std;

int x;

void externStorageClass()

{

cout << "Demonstrating extern class\n";

extern int x;

cout << "Value of the variable 'x'"

<< "declared, as extern: " << x << "\n"; 

            x = 2;

cout<< "Modified value of the variable 'x'" << " declared as extern: \n"       << x;

}

 int main()

{

externStorageClass();

return 0;

}

 Output:

Demonstrating extern class

Value of the variable 'x'declared, as extern: 0

Modified value of the variable 'x' declared as extern:

2

 

staticThe static storage class is used to declare static variables which are popularly used while writing programs in C++ language. Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope.

We can say that they are initialized only once and exist until the termination of the program. Thus, no new memory is allocated because they are not re-declared. Global static variables can be accessed anywhere in the program.

0 seconds of 15 secondsVolume 0%
 

Properties of static Storage Class

  • Scope: Local
  • Default Value: Zero
  • Memory Location: RAM
  • Lifetime: Till the end of the program

#include <iostream>

using namespace std;

int staticFun()

{

cout << "For static variables: ";

static int count = 0;

count++;

return count;

}

 int nonStaticFun()

{

cout << "For Non-Static variables: ";

int count = 0;

count++;

return count;

}

int main()

{

cout << staticFun() << "\n";

cout << staticFun() << "\n";

cout << nonStaticFun() << "\n";

cout << nonStaticFun() << "\n";

return 0;

}

 Output:

For static variables: 1

For static variables: 2

For Non-Static variables: 1

For Non-Static variables: 1

 

registerThe register storage class declares register variables using the ‘register’ keyword which has the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free register is not available, these are then stored in the memory only. 

An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.

Properties of register Storage Class Objects

  • Scope: Local
  • Default Value: Garbage Value
  • Memory Location: Register in CPU or RAM
  • Lifetime: Till the end of its scope

Example:

#include <iostream>

using namespace std;

 void registerStorageClass()

{

cout << "Demonstrating register class\n";

register char b = 'G';

cout << "Value of the variable 'b'"<< " declared as register: " << b;

}

int main()

{

            registerStorageClass();

            return 0;

}

 

Output:

Demonstrating register class

Value of the variable 'b' declared as register: G

 mutable: Sometimes there is a requirement to modify one or more data members of class/struct through const function even though you don’t want the function to update other members of class/struct. This task can be easily performed by using the mutable keyword. The keyword mutable is mainly used to allow a particular data member of const object to be modified. When we declare a function as const, this pointer passed to function becomes const. Adding mutable to a variable allows a const pointer to change members.

Example:

#include <iostream>

using std::cout;

class Test {

public:

int x;

mutable int y; // defining mutable variable y   now this can be modified

Test()

{

x = 4;

y = 10;

}

};

int main()

{

const Test t1;                         // t1 is set to constant

t1.y = 20;                                // trying to change the value

cout << t1.y;                          // Uncommenting below lines   will throw error

// t1.x = 8;

// cout << t1.x;

return 0;

}

Output: 20    

Inheritance

3.Explain Inheritance with examples?

The technique of deriving a new class from an old one is called inheritance. The old class is referred to as base class or Super Class and the new class is referred to as derived class or subclass.

A class can get derived from one or more classes, which means it can inherit data and functions from multiple base classes.

Advantage of inheritance

  1.  Application development time is less.
  2. Application take less memory.
  3.  Application execution time is less.
  4. Application performance is enhance (improved).
  5.  Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and less storage cost.

Syntax:

class subclass_name :access_modebase_class_name

{

  //body of subclass

};

Here, subclass_name is the name of the sub class,access_mode is the mode in which you want to inherit this sub class for example: public, private etc. and base_class_name is the name of the base class from which you want to inherit the sub class.

A derived class doesn’t inherit access to private data members.

Modes of Inheritance

Public mode: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class.

-Protected mode: If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class.

-Private mode: If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class.

Types of Inheritance

Single inheritance:  In single inheritance, there is only one base class and one derived class. The Derived class gets inherited from its base class. This is the simplest form of inheritance.

class A
{ 
//Body of Class A
};
class B: public A
{
//Body of Class B
};

#include<iostream>

using namespace std;

class Student

{

public:

int rno,m1,m2;

void get()

{

cout<<"Enter the Roll no :";

cin>>rno;

cout<<"Enter the marks in two subjects :";

cin>>m1>>m2;

}

};

class Results:public Student

{

int tot,avg;

public:

void display()

{

tot=(m1+m2);

avg=tot/2;

cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;

cout<<"\n\tAverage : "<<avg;

}

};

int main()

{

Results obj;

obj.get();

obj.display();

return 0;

}

Multiple Inheritance:

In this type of inheritance, a single derived class may inherit from two or more base classes.

class B
{ 
//Body of class B
};
class C
{
//Body of Class C
};
class A: public B, public C
{
//Body of Class A
};

Hierarchical inheritance:

In this type of inheritance, multiple derived classes get inherited from a single base class.

class A  
{  
    // body of the class A.  
}    
class B : public A   
{  
    // body of class B.  
}  
class C : public A  
{  
    // body of class C.  
}   
class D : public A  
{  
    // body of class D.  
}   

Multilevel Inheritance:

The classes can also be derived from the classes that are already derived. This type of inheritance is called multilevel inheritance.

class C
{ 
//Body of class C
};
class B:public C
{
//Body of class B
};
class A: public B
{
//Body of class A
};

Hybrid inheritance:

Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.


No comments:

Post a Comment