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

Oops - UNIT-1

Oops

Uploaded by

shaikasif7543
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views24 pages

Oops - UNIT-1

Oops

Uploaded by

shaikasif7543
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Unit 1- Introduction to C++

UNIT – 1
Introduction to C++: Difference between C and C++, Evolution of C++, The Object Oriented
Technology, Disadvantage of Conventional Programming-, Key Concepts of Object Oriented
Programming, Advantage of OOP, Object Oriented Language.
--------------------------------------------------------------------------------------------------------------------------- ---
1.1 Difference between C and C++
Some difference between C and C++ are as follows:
1) C is a procedure/function-oriented programming language and C++ language is driven by a
procedure/object.
2) Data is not protected in C, whereas data is secured in C++. Data hiding concept is absent in C
3) C uses a top-down approach while C++ uses a bottom-up approach. The program is prepared
by step by step in C, while C++ base elements as prepared first.
4) In C, we can’t give the same name to two functions in a program, whereas due to the function
overloading feature, the above concept is possible in C++. One can initialize a number of
functions with the same name, but with different arguments. The polymorphism feature is built
in C++, which supports this concept.
5) C uses printf() and scanf() functions to write and read the data respectively, while C+++ uses
cout and cin objects for output and input operations, respectively. Further cout uses
<<(insertion operator) and cin uses >>(extraction operator).
6) C uses stdio.h file for input and output functions, whereas C++ uses iostream.h for these
functions.
7) Constructor and destructors are absent in C and the same are provided in C++.
8) Inline functions are supported by C++, and the same are absent in C. Inline functions can be
used as macros. They are stated by a word ‘inline’
9) The C language provides calloc() and malloc() for dynamic allocation of memory and free()
for deallocation of memory. And the C++ language provides a new operator for the allocation
of memory and a delete operator for the deallocation of memory.
10) The C language does not support virtual and friend functions. And the C++ language supports
virtual and friend functions.
11) The namespace feature groups various entities like objects, classes, and functions under a
specific name. No namespace features are present in the C language. The C++ language uses
the namespace features to help avoid name collisions.
12) It does not provide any direct support for exceptional handling. It provides direct support for
exceptional handling. The C++ language uses a try-catch block.

--------------------------------------X--------------------------------------

1.2 Evolution of C++

Page 1
Unit 1- Introduction to C++
 C++ is an object oriented programming language and also considered as an extension of C.
 Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey (USA) developed
this language in the year 1980.
 He combined the features of both the languages C and SIMULA67 and developed a powerful
language that supports object oriented programming with features of C. The new language is
named as C WITH CLASSES.
 Later, various features from ALGOL 68 were added to C WITH CLASSES and the name
changed to C++ in 1983 by Rick Mascitti.
 The thought of C++ came from the C increment operator ++. Therefore, C++ is an extension of
C. C++ is a superset of C. All the concepts of C are applicable to C++ also.

--------------------------------------X--------------------------------------

1.3 The Object Oriented Technology


 Nature is composed of various objects. Living beings can be categorized into different objects.
For example, animals, people, fruits, flowers, vehicles, students, books, etc considered as
objects in the real world.
 Let us consider another example of a Teaching Institute with two working sections -
teaching and non-teaching. Sub-grouping of teaching and non-teaching is made for the co-
ordination of management. In the same way, the various department of any organization can
be thought of as objects working for certain goals and objectives.
 Usually an institute has faculty of different departments. The Principal is compulsory for the
overall management of the institute. There is an Academic dean who is responsible for the
academics of the institute. The Dean for planning should have the future plans of the institute
and he/she must see how the infrastructure is utilized effectively. The dean R&D should see
research activities run in the institute forever. Besides the teaching staff there must be
technical staff for the labs to assist practical sessions during lab hours. There must an account
department for handling monetary transactions and salaries of the employees. There must a
sports wing to conduct sports activities for students as well as staff. The Registrar for
administration and staff for dealing with administrative matters of the institute are also
requires. Each department has in-charge who carries responsibilities. Every department has its
own work as stated above.
 When an institute’s work is distributed into departments as shown in Fig.below, it is
comfortable to accomplish goals and objectives.
 The staff in the department is controlled properly and act according to the instructions laid
down by the management. The faculty performs activities related to teaching. If the higher
authority needs to know the details regarding the theory, practical, seminar and project loads
of individuals of the department, then a person from the department furnishes the same to the
higher authority. This way some responsible person from the department accesses the data and
provides the higher authority with the requisite information. It is also good to think that no
unconnected person from another department reads the data or attempts to make any alteration
that might corrupt the data.

Page 2
Unit 1- Introduction to C++

Fig. Relationship between different sections

 As shown in the above figure, an institute is divided into different departments such as library,
class room, computer laboratory, etc. each department performs its own activities in
association with the other departments. Each department may be considered as a module and
it contains class and object in C++ language. This theory of class and object can be extended
to every walk of life and can be implemented with software. In general, objects are in terms of
entities. In object oriented programming, objects of a program interact by sending messages to
each other.

--------------------------------------X--------------------------------------

1.4 Disadvantage of Conventional Programming


 Traditional programming languages like COBOL, FORTRAN etc are known as procedural
languages. In these languages the program is written as a set of statements which contains the
logic and control that instructs the compiler or interpreter how to perform a certain task. It
becomes difficult to manage the code when the program is quite large.

 To reduce complexity, functions or modules were introduced which divides a large program
into a set of cohesive units. Each unit is called a function and each function can call other
functions as shown below:

 Even though functions reduces complexity, with a lot of functions sharing a common set of global
data may lead to logical errors.

Page 3
Unit 1- Introduction to C++

Following are the disadvantages of procedural or structured languages:

1. Programs are divided into a set of functions which can share data. Hence, no data security.
2. Focus is on the code to perform the task but not on the data needed.
3. Data is shared globally by several functions which might lead to logical errors.
4. No restrictions on which functions can share the global data.

--------------------------------------X--------------------------------------

1.5 Programming Paradigms


1. Monolithic Programming

The Monolithic programming paradigm is the oldest. It has the following characteristics. It is also
known as the imperative programming paradigm.

 In this programming paradigm, the whole program is written in a single block/function. A


program is not divided into parts; hence it is named as monolithic programming. It is also called
single thread execution
 When program size increases it leads to difficulty.
 It uses all data variables are global which leads to data insecurity .
 We use the goto statement to jump from one statement to another statement.
 There are no flow control statements like if, switch, for, and while statements in this paradigm.
 There is no concept of data types.

An example of a Monolithic programming paradigm is Assembly language.


2. Structural Programming

The Structure-oriented programming paradigm is the advanced paradigm of the monolithic


paradigm. It has the following characteristics.

 This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
 It provides the concept of code reusability.
 It is introduced with the concept of data types.
 It also provides flow control statements that provide more control to the user.
 In this paradigm, all the data is used as global data which leads to data insecurity.

Examples of a structured-oriented programming paradigm is ALGOL, Pascal, PL/I and Ada.


3. Procedural programming

Page 4
Unit 1- Introduction to C++
The procedure-oriented programming paradigm is the advanced paradigm of a structure-oriented
paradigm. It has the following characteristics.

 This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
 It provides the concept of code reusability.
 It is introduced with the concept of data types.
 It also provides flow control statements that provide more control to the user.
 It follows all the concepts of structure-oriented programming paradigm but the data is defined
as global data, and also local data to the individual modules.
 In this paradigm, functions may transform data from one form to another.

Examples of procedure-oriented programming paradigm is C, visual basic, FORTRAN, etc.


4. Object oriented programming

The object-oriented programming paradigm is the most popular. It has the following
characteristics.

 In this paradigm, the whole program is created on the concept of objects.


 In this paradigm, objects may communicate with each other through function.
 This paradigm mainly focuses on data rather than functionality.
 In this paradigm, programs are divided into what are known as objects.
 It follows the bottom-up flow of execution.
 It introduces concepts like data abstraction, inheritance, and overloading of functions and
operators overloading.
 In this paradigm, data is hidden and cannot be accessed by an external function.
 It has the concept of friend functions and virtual functions.
 In this paradigm, everything belongs to objects.

Examples of procedure-oriented programming paradigm is C++, Java, C#, Python, etc.

--------------------------------------X--------------------------------------

Page 5
Unit 1- Introduction to C++

1.6 Key Concepts of Object Oriented Programming

Fig: Concepts/elements of object oriented paradigm


Following are the key concepts in object-oriented programming:
1) Objects
 Object is a real world entity or a prime run-time entity in object-oriented programming.
 Object occupies space in memory. Every object has its own properties and behavior.
 An object is an instance or specimen of a class.
 Every object is unique. Each object contains state, which is the collection of data values
associated with the properties of an object.
 Objects communicate with each other by sending messages.

Some of the real world examples for objects are shown below:

Object: City
Data:
Name_of_city
Popukation
Area
Functions:
Average age
Literacy_rate
Display
Representation of an Object

2) Classes
 A class is a collection of similar objects that have similar properties and exhibit similar
behavior. A class is a template or blueprint for creating objects. After a class is created, we can
create any number of objects. A class does not occupy any memory like an object.
 Real world examples of classes are shown below:

Page 6
Unit 1- Introduction to C++

Classes and their members:


Class home Class vehicle Class entertainment
{ { {
Telephone Bicycle Books
Book Bus Radio
Computer Car Tv
Watch Motorcycle Computer
lock } }
}

3) Methods
 An operation represents the behavior of an object. When an operation is coded in a class, it is
called a method. All objects in a class perform certain common actions or operations.
 Following figure shows a class, its data members, and methods written in different styles:

4) Data Abstraction
 Abstraction refers to the process of presenting essential features without including any complex
background details. A class uses this abstraction to represent only essential properties and
behavior.
 A powerful way to achieve abstraction is by manipulating hierarchical classifications. This
allows us to divide the system into several logical layers which can be maintained separately.
 Real world example for abstraction is a computer which is a single unit made up of several units
(parts) as shown below:
Page 7
Unit 1- Introduction to C++

5) Encapsulation
 The packing of data and functions together into a single unit is known as encapsulation.
Encapsulation is implemented by classes. A class contains data which is generally private and is
accessible to the outside world only through public methods.
 A side effect of encapsulation is data hiding which allows the users to use an object without
knowing its internal details. Following figure represents different sections of encapsulation :

6) Inheritance
 Deriving properties of an object from one class to object of another class is known as
inheritance. Inheritance promotes the feature of object-oriented programming, reusability.
 Using inheritance a new class can be created without affecting the existing class. We can use
already available functionality of the existing class and add new functionality in the new class
based on the requirements.
 Consider a group of vehicles. We need to create classes for Bus, Car and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If we create
these classes avoiding inheritance then we have to write all of these functions in each of the
three classes as shown in below figure:

 We can clearly see that above process results in duplication of same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation, inheritance
is used. If we create a class Vehicle and write these three functions in it and inherit the rest of
the classes from the vehicle class, then we can simply avoid the duplication of data and increase
re-usability. Look at the below diagram in which the three classes are inherited from vehicle
class:

Page 8
Unit 1- Introduction to C++

 Using inheritance, we have to write the functions only one time instead of three times as we
have inherited rest of the three classes from base class(Vehicle).

7) Polymorphism
 Single method exhibiting different behaviors in the same class or different classes is known as
polymorphism. We can code a generic interface (set of methods) to a set of associated actions.
 As a real world example for polymorphism consider a generic Line class which contains a
method Display(). Now consider three specific classes: DottedObject,
SingleObject, and DashObject which in turn also contains the same Display() method as
shown below:

8) Dynamic Binding
 The process of associating an action to a message at run-time is known as dynamic binding
which is also known as late binding. The action to be associated is recognized when the object
is created which is done at run-time.
 As an example, consider the above hierarchy in which a Line object can call
the Display() method in any of the three child classes: DottedObject,
SingleObject, or DashObject.
9) Message Passing
 Objects communicate through messages. A message is a request for an action. Object sending
the message can also pass data (parameters). Object which receives the message invokes a
corresponding member function (action).
 Consider the following example which represents message passing:

Page 9
Unit 1- Introduction to C++

10) Reusability
 Using the code available in an existing class to create new classes is known as reusability which
is an important feature of object-orientation. In the below example, class A is an already
existing class from which class B is created and from class B, class C is created:

11) Delegation
 In object-oriented programming, two classes can be joined either by inheritance or delegation.
Both of them promote reusability of code.
 As shown in the below figure (a), class Y is derived from class X. Here class Y is a kind of X.
This kind of relationship between Y and X classes is known as inheritance. Inheritance is also
known as is a relationship.
 Also as shown in figure (b) below, objects of classes A and B are members of class C. This kind
of relationship is known as has a relationship and is also called as delegation or composition.

Fig (a) Fig(b)

12) Genericity
 The software components (like classes) can have more than one implementation based on the
data type of arguments. Programmer can create a generic class or function which can work with
different types of arguments. The template feature in C++ allows generic programming.
 For example, a list data structure can operate on integers, characters, strings, floats or any other
types of objects. So, a programmer can create a generic List class which can accept any kind of
data.
--------------------------------------X--------------------------------------

Page 10
Unit 1- Introduction to C++
1.7 Advantage of OOP
Object-oriented programming offers many advantages to the programmers and users. This technology
allows programmers to create high quality software at an affordable price. Following are the advantages
of OOP:

1. Object-oriented programs can be upgraded easily.


2. Using inheritance, code redundancy can be eliminated.
3. Data hiding allows the programmers to develop safe programs that do not disturb code in other
parts of the program.
4. Encapsulation allows programmers to create classes with several features and only few public
methods to be exposed.
5. All object-oriented languages can create, extend and reuse existing programs.
6. Object-oriented programming enhances the thought process of a programmer leading to rapid
development of software.

--------------------------------------X--------------------------------------

1.8 Object Oriented Languages

There are many languages which support object oriented programming.


Table: Properties of pure OOP and object based languages.
Pure object Oriented Languages Object
Based
Languages
Properties Java Simula Smalltalk Eiffel Java Ada
Encapsulation
Inheritance No
Multiple X X X No
Inheritance
Polymorphism
Binding(Early Both Both Late binding Early Both Early
& Late)
Genericity X X X x
Class Few
Libraries
Garbage X
Collection
Persistence X Promised Less Same as
3GL
Concurrency Less Promised Hard

Table: Properties of extended traditional languages


Pure object Oriented Languages
Properties Objective C C++ Charm++ Objective Turbo
Pascal Pascal
Encapsulation
Inheritance
Multiple --- ---
Inheritance

Page 11
Unit 1- Introduction to C++
Polymorphism
Binding(Early & Both Both Late Early Both
Late)
Genericity X X X
Class Libraries
Garbage
Collection
Persistence X X X X X
Concurrency Poor Poor X X
The following are the object-oriented languages, which are widely accepted by the programmer.
 C++
 Smalltalk
 Charm ++
 Java

--------------------------------------X--------------------------------------

1.9 Difference Between Procedure-Oriented And Object-Oriented Programming


Both object-oriented and procedure-oriented paradigms are very popular and most commonly used
programming paradigms. The following table gives the differences between those.
Procedure-oriented Object-oriented
Procedural programming is based on the concept Object-oriented programming is based on the
of calling procedures. Procedures are also real world i.e objects.
known as functions or subroutines
Larger programs have divided into smaller The larger program has divided into objects.
modules called as functions.
It follows the top-bottom flow of execution. It follows the bottom-top flow of execution.
Example: C Example: C++
Top-down Approach start from main() function Bottom-up approach start from object and
and go to the respective function down the go to the function and then go to the main()
order.So, basically all C program execution start function for displaying the result. So, in c++
from top the order i.e; from main() function and program execution start from object to data
go to down the order, i.e; it is said as top-down to function then to main() function for
approach. Here is the pictorial view:- displaying result. Here is the pictorial view:-

Procedural programming is used for designing Object-oriented programming is used for

Page 12
Unit 1- Introduction to C++
medium-sized programs. designing large and complex programs.
In POP, Data can move freely from function to In OOP, objects can move and communicate
function in the system with each other through member functions.
To add new data and function in POP is not so OOP provides an easy way to add new data
easy and function.
The main focus is on solving the problem. The main focus is on data security.
It doesn’t support data abstraction. It supports data abstraction using access
specifiers that are public, protected, and
private.
It doesn’t support inheritance. It supports the inheritance of four types.
Overloading is not supported. It supports the overloading of function and
also the operator.
There is no concept of friend function and It has the concept of friend function and
virtual functions. virtual functions.
Examples - C, FORTRAN Examples - C++ , Java , VB.net, C#.net,
Python, R Programming, etc.

-----------------------------X-----------------------
1.10 Advantages and disadvantages of procedural programming
Advantages:

1. Procedural Programming is excellent for general-purpose programming


2. The coded simplicity along with ease of implementation of compilers and interpreters
3. A large variety of books and online course material available on tested algorithms, making it easier
to learn along the way
4. The source code is portable, therefore, it can be used to target a different CPU as well
5. The code can be reused in different parts of the program, without the need to copy it
6. Through Procedural Programming technique, the memory requirement also slashes
7. The program flow can be tracked easily

Disadvantages:

1. The program code is harder to write when Procedural Programming is employed


2. The Procedural code is often not reusable, which may pose the need to recreate the code if is
needed to use in another application
3. Difficult to relate with real-world objects
4. The importance is given to the operation rather than the data, which might pose issues in some data-
sensitive cases
5. The data is exposed to the whole program, making it not so much security friendly
--------------------------------------------X----------------------------------------------
1.11 Structure/Parts of a C++ Program

C++ program consists of classes, functions, variables, and other statements. The fig. shows four different
parts of a C++ program

Page 13
Unit 1- Introduction to C++

Preprocessor directives include header files


Class declaration or definitions
Class function definitions
The main() function and program
Fig: Parts of C++ Program
a) Preprocessor directives (Include header files section):
The preprocessor directives are to be includes at the beginning of the program before the main(). It
begins with pound or hash symbol# (hash). No white space should appear before the #, and semi
colon is NOT required at the end.
Many things that can be done during preprocessing phase include:

 Definition of symbolic constants and macros through #define directive


 Inclusion of other files through #include directive
Through some preprocessor directives we can also conditionally compile or execute some
preprocessor directives.

i) The #define directive


 The #define preprocessor allows us to define symbolic names and constants.
Example:
#define PI 3.14159
This statement will translate every occurrence of PI in the program to 3.14159.
 #define allows you to make text substitutions before compiling the program.
Example:
#define MAX 70
Before compilation, if the C++ preprocessor finds MAX as one word, in the source
code, it replaces it with the number 70.
 We can define strings as well.
Example: #define NAME "Computer Science C++"
Every time the preprocessor sees NAME it will replace it with "Computer Science C++"
Example:
/* C++ #define - Example Program of #define */

#include<iostream.h>
#define PI 3.14159

int main()
{
int r = 10;
float cir;
cir = PI * (r * r);
cout<<"Area of Circle: "<<cir<<endl;
return 0;
}

ii) Include header files section

Page 14
Unit 1- Introduction to C++
#include directive is used to read the content of file that is included at the beginning of the
program. Another file can be included at the start of the program with
#include name_of_the_file.cpp. The #include directive inserts a copy of the header file directly
into the .cpp file prior to compilation.
Example:
#include<iostream.h> or #include ”iostream”
It contains the contents of iostream header file in the program before compilation. This header
file is required for input output statements such as cin and cout.
It contains the contents of iostream header file in the program before compilation. This header
file is required for input output statements.
b) Class declaration or definition:
Declaration of class is done in this section. In class definition, prototype or definitions of function
are also declared.
c) Class function definitions:
This part contains definitions of functions. The definition of function can also be written outside
the class but before main(). The outside definitions of function should need class name and scope
access operator (::) before the function name.
d) The main() function:

Example : /* First C++ Program */

#include <iostream>
using namespace std;
int main()
{
cout<<"Welcome to TutorialRide";
return 0;
}
Output:
Welcome to TutorialRide

Following are the steps/ parts of the above C++ program:

/* First C++ /*...*/ comments are used for the documentation to understand the code to others.
Program */ These comments are ignored by the compiler.
#include<iostream> It is a preprocessor directive. It contains the contents of iostream header file in
the program before compilation. This header file is required for input output
statements.
int/void Integer (int) returns a value. In the above program it returns value 0. Void does
not return a value so there is no need to write return keyword.
main() It is an entry point of all the function where program execution begins.
Curly Braces {...} It is used to group all statements together.
std::cout It is requried when we use #include . Std::cout defines that we are using a
name (cout) which belongs to namespace std. Namespace is a new concept
introduced by ANSI where C++ standard libraries are defined.

Page 15
Unit 1- Introduction to C++

If using namespace std is placed into the program then it does not required
to write std:: throughout the code. Namespace std contains all the classes,
objects and functions of the standard C++ library.
"Welcome to The words in inverted commas are called a String. Each letter is called a
TutorialRide" character and series of characters that is grouped together is called a String.
String always be put between inverted commas.
<< It is the insertion stream operator. This operator sends the content of variables
on its right to the object on its left.

In the above program, right operand is the string "Welcome to


TutorialRide" and left operand is cout object. So it sends the string to
the cout object and then cout object displays the string as a output on the screen.
------------------------------------------------------------------X----------------------------------------------------------------------

1.12 Difference between structures and classes


Both a structure and a class provide a way to create a user defined data type which can be used
further to create instances. C++ expands the role of structure to create a class. The Structure and
class, are almost similar in all respect except the significant one difference that, structure by
default have all its member as “public”, and class by default have all its member “private”.
Furthermore, polymorphism and inheritance are not supported by the structure, but classes support
polymorphism and inheritance.

STRUCTURE CLASS
Structure is a collection of variables of differentA Class is defined as a collection of related
data types under a single name. variables and functions encapsulated in a single
structure.
Example: Example:
We want to store some information about a Apart from the name, citiNo and salary we have
person: his/her name, citizenship number and relationships such as getdata and putdata to
salary. We can easily create different variables work on variables under single name person
name, citiNo, and salary to store these
information separately under single name
person.
Structure is a value type and its object is crated Class is a reference type and its object is created
on the stack memory on the heap memory
Syntax for structure declaration: Syntax for class declaration:

struct structure_name{ class class_name{


datatype element 1; data member;
datatype element 2; member function;
datatype element 3; };
….
};

Example: Example:
struct Person class Person
{ {
char name[50]; char name[50];
Page 16
Unit 1- Introduction to C++
int age; int age;
float salary; float salary;
}; public:
void getdata();
void putdata();
};
Members of a class are public by default. Members of a class are private by default
Declaring the instance of structure: Declaring the instance of class:
int main(){ int main(){
person p1, p2; person p1, p2;
} }
The instances of the structure are called The instances of classes are called “objects”
“structure variable”.
Accessing structure members: Accessing class members:
Through structure variable and dot (.) operator Only public members can be accessed through
object and dot (.) operator
#include <iostream> #include <iostream>

struct Test { class Test {


int x; // x is public int x; // x is private
}; };
int main() int main()
{ {
Test t; Test t;
t.x = 20; // works fine because x is public t.x = 20; // compiler error because x is private
return 0; return 0;
} }
Structure can not be inherited. Class can be inherited
Structure should be used when you want to use Class is better choice for complex data
a small data structure structure.
The structure can initialize its members In order to initialize the member of a class, the
automatically. constructors and destructors are used.
There is no data hiding features comes with Data hiding is possible with classes.
structures.

----------------------------------------------------------X-----------------------------------------------------
Applications of OOPS
The promising areas for application of OOP includes:
1. Real-time systems
2. Simulation and modeling
3. Object-oriented databases
4. Hypertext, hypermedia and experttext
5. AI and expertsystems
6. Neural networks and parallel programming
7. Decision support and Automation system
8. CIM/CAM/CAD systems

Page 17
Unit 1- Introduction to C++
1.13 Sample CPP Programs

Write a C++ program to calculate area of a circle


A = π r2
Method1:
//Calculating area of a circle
#include<iostream>
using namespace std;
int main()
{
int r;
float pi, a;
cout<<"\nEnter radius";
cin>>r;
pi = 3.14;
a = pi * r *r;
cout<<"\nArea of a circle = "<<a;
return 0;
}
Output:

Enter radius 2

Area of a circle = 12.56

Method 2:
//Calculating area of a circle with function
#include<iostream>
using namespace std;
float area(); //function declaration
float area( ) //function definition
{
int r;
float pi, a;
cout<<"\nEnter radius";
cin>>r;
pi = 3.14;
a = pi * r *r;
return a;
}
int main()
{
cout<<"\nArea of a circle = "<<area(); //function call
return 0;
}
Output:

Enter radius 4

Area of a circle = 50.24

Method 3:
Page 18
Unit 1- Introduction to C++
//Calculating area of a circle with member function
#include<iostream>
using namespace std;
class A{
private:
int r;
public:
float area(); //member function declaration
};
float A::area( ) //member function definition
{
float pi, a;
cout<<"\nEnter radius";
cin>>r;
pi = 3.14;
a = pi * r *r;
return a;
}
int main()
{
A obj;
cout<<"\nArea of a circle = "<<obj.area(); //member function call
return 0;
}
Output:

Enter radius 3

Area of a circle = 28.26

Write a C++ program to calculate simple interest and compound interest


#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int p;
float r;
int t;
cout<<"Enter principal amount: ";
cin>>p;
cout<<"Enter rate of interest: ";
cin>>r;
cout<<"Enter time period (in years): ";
cin>>t;
float si = p*r*t;
cout<<"Simple interest to be paid is: Rs."<<si<<endl;
float total = p * pow((1+r/12), (12*t));
float ci = total - p;
cout<<"Compound interest to be paid is: Rs. "<<ci<<endl;
return 0;
Page 19
Unit 1- Introduction to C++
}
Output:
Enter principal amount: 10000
Enter rate of interest: 0.1
Enter time period (in years): 5
Simple interest to be paid is: Rs.5000
Compound interest to be paid is: Rs. 6453.08

Write a C++ program to swap two numbers.


//swapping two variables using temporary variable
#include<iostream>
using namespace std;
int main()
{
int a, b, t;
cout<<"\nEnter two integer values: ";
cin>>a>>b;
cout<<"\n Before swapping….\n";
cout<<"\na = "<<a<<"\tb = "<<b<<endl;
t = a;
a = b;
b = t;
cout<<"\nAfter sapping….\n";
cout<<"\na = "<<a<<"\tb = "<<b<<endl;
return 0;
}
Output:

Enter two integer values: 12 34

Before swapping….

a = 12 b = 34

After sapping….

a = 34 b = 12

Write a C++ program to swap two numbers without using temporary variable.
//swapping two variables using + and -
#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"\nEnter two integer values: ";
cin>>a>>b;
cout<<"\n Before swapping….\n";
cout<<"\na = "<<a<<"\tb = "<<b<<endl;
Page 20
Unit 1- Introduction to C++
a = a+b;
b = a-b;
a = a-b;
cout<<"\nAfter sapping….\n";
cout<<"\na = "<<a<<"\tb = "<<b<<endl;
return 0;
}
Output:

Enter two integer values: 23 45

Before swapping….

a = 23 b = 45

After sapping….

a = 45 b = 23

Write a cpp program to find Size of a Variable


// C++ program to find the size of int, char,
// float and double data types
#include <iostream>
using namespace std;

int main()
{
int i;
char c;
float f;
double d;

// Calculate and Print the size of integer type


cout << "Size of int is: " << sizeof(i) <<"\n";

// Calculate and Print the size of character type


cout << "Size of char is: " <<sizeof(c) <<"\n";

// Calculate and Print the size of float type


cout << "Size of float is: " <<sizeof(f) <<"\n";

// Calculate and Print the size of double type


cout << "Size of double is: " <<sizeof(d) <<"\n";

return 0;
}

Output:
Size of int is: 4
Size of char is: 1
Page 21
Unit 1- Introduction to C++
Size of float is: 4
Size of double is: 8

Write a C++ Program to Check Whether Number is Even or Odd


//C++ Program to Check Whether Number is Even or Odd
#include <iostream>
using namespace std;

int main()
{
int n;

cout << "Enter an integer: ";


cin >> n;

if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";

return 0;
}

Output:
Enter an integer: 23
23 is odd.

Write a C++ program to Check Whether Number is Even or Odd using ternary operators
//Check Whether Number is Even or Odd using ternary operators
#include <iostream>
using namespace std;

int main()
{
int n;

cout << "Enter an integer: ";


cin >> n;

(n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";

return 0;
}

Output:
Enter an integer: 48
48 is even.

Page 22
Unit 1- Introduction to C++
Write a C++ Program to find Factorial Program using Loop
//c++ program to find factorial of a given number
#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
return 0;
}
Output:
Enter any Number: 5
Factorial of 5 is: 120

Write a program in C++ to find the factorial of a given number using recursion.
// Factorial of a given number using recursion
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Output:
Enter any number: 6
Factorial of a number is: 720

Page 23
Unit 1- Introduction to C++
Sample Questions:

1. Differentiate between Object Oriented Programming and Procedural Oriented Programming.


2. What are the advantages and disadvantages of procedural programming?
3. Explain the limitations of conventional procedural programming
4. Explain Advantages of Object Oriented Programming.
5. What are the drawbacks of procedural languages? Explain the need of Object Oriented
programming with a suitable example
6. Differentiate between C and C++.
7. Describe the characteristics of Object-Oriented Programming
8. Explain in detail the four major principles of Object-Oriented Programming paradigm with
suitable examples.
Answer: Encapsulation, Abstraction, Inheritance, and Polymorphism
9. Explain the key concepts of Object Oriented Programming
10. What is Data Abstraction and Encapsulation in C++? Explain with a real time example.
11. Mention the promising application areas of Object-Oriented Programming in real time
environment.
12. How data and functions are organized in Object Oriented Program? Explain with an example.
13. Give the structure of a C++ Program.

Page 24

You might also like