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

OOP Couse File

Uploaded by

shivani.8023
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

OOP Couse File

Uploaded by

shivani.8023
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 195

B.Sc.

(Graphics and Web Designing/ Cyber Security)


COURSE FILE
SUBJECT: OOPs Using
C++ (UGCA1909)

B.Sc. (G&WD / CS)


2nd Semester

Session: Jan- July 2025


FACULTY: Ms. Shivani Rana

Chandigarh College of Technology


Landran, Mohali-140307(Punjab)
INDEX
Remarks
S No. Contents
1 Academic Calendar for Even/Odd Sem
2 POs and PSOs
3 Syllabus of subject along with course Outcomes(Cos)
4 Cos-POs Mapping
5 Curricular Gaps and their Delivery Details
6 Content Beyond syllabus
7 Lecture plan with CO Mapping
8 Time Table
9 List of Students
10 Structure of MST
11 MST Question Papers(CO Mapped)
12 MST Evaluation Scheme
13 Samples of checked MST sheets
14 List of academically weak students
15 Action Taken and outcome
16 Assignments with CO mapping
17 Samples of checked Assignment sheets
18 Evaluation scheme :Total Internal marks(Sessional marks + Assignments
marks + Attendance marks)
19 Student Wise Internal Assessment marks
20 List of Innovative Teaching Tools
21 Activities included for Experimential Learning
22 Last 2 years solved question papers
23 Question Bank based on PTU Paper Pattern(Unit wise and CO mapped)
24 Notes/Reference Material
25 Summary and Sample copy of PPT’s
26 CO Attainment of the course
27 Minutes of Meeting

28. Any Other


Academic Calendar
PROGRAMME OBJECTIVES (POS)
B.Sc. (Graphics and Web Designing )

Programme Educational Objectives:


PEO 1: To impart core theoretical and practical knowledge of Graphics and Web
Designing for leading successful career in industries, pursuing higher studies or
entrepreneurial endeavours.
PEO 2: To develop the ability to critically think, analyze, design and develop Graphics
and Web based solutions.
PEO 3: To imbibe the life-long learning and understanding of ethical values, their duties
toward environmental issues and sensitize them toward their social responsibility as
Graphics Designer and Web Developer.

Programme Outcomes:
PO1: Graphics knowledge: Apply the knowledge of mathematics, science and IT to the
complex graphics design.
PO2: Problem analysis: Identify, formulate, research literature, and analyze complex
problems reaching substantiated conclusions using principles of mathematics, natural
sciences, and IT.
PO3: Design/development of solutions: Develop solutions for complex graphics and web
designing problems that meet the specified needs with appropriate consideration for the
cultural, societal, and environmental considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and
methods including analysis and interpretation of data that can explore different
approaches in computer graphics and web development.
PO5: Modern tool usage: Create, select, and apply various aspects of interactive
websites, motion graphics, video and informational graphics with an understanding of
the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional practice.
PO7: Environment and sustainability: Understand the impact of the graphics andwebsite
development in societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the professional practice.
PO9: Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex graphics and web design
activities with the professional community and with society at large, such as, being able
to comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of
the development and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinaryenvironments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
PROGRAMME SPECIFIC OUTCOMES (PSOS)

Programme Specific Outcomes:

PSO 1: Able to acquire practical competency with emerging technologies and skills
needed for becoming an effective graphics and web designer.

PSO 2: Able to assess hardware and software aspects necessary to develop Graphics
and Web Designing.
SYLLABUS
I. K. Gujral Punjab Technical University
Bachelor of Graphics and Web Designing (B.Sc. G&WD)
Course Code: UGCA1909
Course Name: Object Oriented Programming using C++

Program: B.Sc L: 3 T: 1 P: 0
Branch: Graphics and Web Designing Credits: 4
Semester: 2nd Contact hours: 40
Theory/Practical: Theory Percentage of numerical/design problems: --
Internal max. marks: 40 Duration of end semester exam (ESE): --
External max. marks: 60 Elective status: Core/Elective
Total marks: 100

Prerequisite: Basic understanding of computer system.


Co requisite: -NA-
Additional material required in ESE: -NA-

CO# Course outcomes


CO1 To learn programming from real world examples.
CO2 To understand Object oriented approach for finding solutions to various problems with the
help of C++ language.
CO3 To create computer based solutions to various real-world problems using C++
CO4 To learn various concepts of object oriented approach towards problem solving
Detailed contents Contact hours
Unit-I

Principles of object oriented programming


Introduction to OOP and its basic features, Basic components of a C++,
Program and program structure, Compiling and Executing C++ Program.
Difference between Procedure Oriented Language(C) and Object Oriented
12 hours
Language

Unit-II

Classes & Objects and Concept of Constructors


Defining classes, Defining member functions, Declaration of objects to class,
Access to member variables from objects, Different forms of member 10 hours
Functions, Access specifies (Private, public, protected), Array of objects.
Introduction to constructors, Parameterized constructors, Copy Constructor,
Multiple constructors in class, Dynamic initialization of objects, Destructors.

Unit-III

Inheritance and Operator overloading


Introduction to Inheritance, Types of inheritance: - Single inheritance,
Multiple 12 hours
inheritance, Multilevel inheritance, Hierarchical inheritance, Hybrid
inheritance, Defining operator overloading, Overloading of Unary and Binary
operators, Rules for overloading operators

Unit-IV

Polymorphism and File Handling


Early Binding, Late Binding, Virtual Functions, pure virtual functions, 10 hours
Abstract Classes.
Opening and Closing File, Reading and Writing a file.

Text Books:
1. Object Oriented Programming with C++, E. Balagurusami, Fourth Edition,
TataMc-Graw Hill, 2009.

2. Object Oriented Programming in Turbo C++, Robert Lafore, Fourth


Edition Galgotia Publications, 2013.

3. The C++ Programming Language, BjarnaStroustrup, Third Edition,


Addison-Wesley Publishing Company,2015.

4. Object Oriented Programming Using C++, Salaria, R. S, Fourth


Edition, Khanna Book Publishing, 2017.

Reference Books:
1. Object Oriented Programming in Turbo C++, Robert Lafore,
Galgotia Publications.
2. The C++ Programming Language, Bjarna Stroustrup, Third
Edition, Addison- Wesley Publishing Company.
E Books/ Online learning material:

1. www.sakshat.ac.in
2. https://swayam.gov.in/course/4067-computer-fundamentals
Mapping of COs with PO(s) and PSO(s)
C++ (UGCA 1909)
CO P P PO P P P P P P PO PO PO
O O 3 O O O O O O 10 11 12
1 2 4 5 6 7 8 9
CO1
3 2 2 3 3 3 3 3 2 3
CO2
3 2 3 3
CO3
3 3 3 2 2 3 3 2 3
CO4
3 3 3 3 2 3 2 3
CONTENT BEYOND SYLLABUS

S. No. Name of the Topic/Subtopic

1. Linked Lists

2. Function Overloading

3. Storage Classes
COLLEGE OF ENGINEERING -CGC
Department of Sciences and Computing

Lecture Plan

B.Sc. (G&WD/AI&ML/Cyber Security)/ 2nd sem


Object Oriented Programming using C++/ UGCA1909

Lecture References
Topics/Contents Mapping with
Schedule Ref. / Chapter CO
No.

Introduction to R1/1/1.1-1.8 C
Object Oriented O
Lecture 1
Programming 1
(OOP) and its basic
features
Basic components of R1/2/2.1-2.7 C
Lecture 2 a C++, Program and O
program structure 1
Compiling R1/2/2.7,2.8 C
Lecture 3 and O
Executing 1
C++
Program.
Difference R1/1/1.5 C
between O
Lecture 4 Procedural 1
oriented
Language (C)
and Object
Oriented
Language.
defining classes R1/2/2.5 C
Lecture 5 O
2
Lecture 6 Defining member R1/5/5.4 CO2
functions
Lecture 7 Declaration of object R1/5/5.1,5.2,5.3 CO2
to class
Acess to member R1/5/5.5 CO2
Lecture 8 variables from object

Lecture 9 Different forms of R1/5/5.4 CO2


member functions
Data Types and R1/3 CO2
Lecture
10 Identifiers
Access specifiers R1/R4 CO2
Lecture (Private, public,
11 protected)
R1/R4 C
Lecture Array of objects. O
12 4
Lecture Introduction to R1/R4 C
13 constructors O
4
R1/R4 C
Lecture Parameterized O
14 constructors 4

Copy Constructor R1/R4 C


Lecture
15 O
4
Lecture Multiple constructors R1/R4 C
16 in class O
4
Dynamic R1/R4 C
Lecture initialization of O
17 objects 4
Destructors R1/R4 C
Lecture
18 O
4
Introduction R1/R4 C
Lecture to O
19 Inheritance 4
Types of R1/R4 C
Lecture
Inheritanc O
20
e: - Single 4
inheritanc
e
Lecture Multiple inheritance R1/R4 C
21 O
4
Lecture Multilevel inheritance R1/R4 C
22 O
4
Lecture Hierarchical R1/R4 CO4
23 inheritance
Lecture Hybrid inheritance R1/R4 CO4
24
Lecture Defining operator R1/R4 CO4
25 overloading
Lecture Overloading of Unary R1/R4 C
26 and Binary operators O
3
Lecture Rules for overloading R1/R4 CO3
27 operators
Lecture Polymorphism and R1/R4 CO3
28 Early Binding,
Lecture Late Binding R1/R4 CO3
29
Lecture Virtual Functions R1/R4 CO3
30
Lecture pure virtual functions R1/R4 CO3
31
Lecture Abstract Classes. R1/R4 CO3
32
Lecture Opening and Closing R1/R4 C
33 File O
2,
C
O
4
Lecture Reading and Writing R1/R4 C
34 a file. O
2,
C
O
4
Lecture Revision
35
Lecture Revision
36
Course Outcomes:

C Course
O outcomes
#
CO1 To learn programming from real world examples.

CO2 To understand Object oriented approach for finding


Solutions to various problems with the help of C++ language.
CO3 To create computer based solutions to various real-world problems using C++

CO4 To learn various concepts of object oriented approach towards problem solving

References:
Text Books:
R1.Object Oriented Programming with C++, E. Balaguruswami, Fourth Edition,
Tata Mc-Graw Hill
R2.Programming using C++, D. Ravichandran, Tata Mc-Graw Hill
R3.Object Oriented Programming Using C++, Salaria, R. S, Fourth Edition,
Khanna Book Publishing

Reference Books:
R4. Object Oriented Programming in Turbo C++, Robert Lafore, Galgotia
Publications.

R5. The C++ Programming Language, Bjarna Stroustrup, Third Edition, Addison-
Wesley Publishing Company.
E Books/ Online learning material:

R6.www.sakshat.ac.in
R7.https://swayam.gov.in/course/4067-computer-fundamentals

Signature of HOD Signature of Subject Coordinator

Signature of Course Coordinator


TIME TABLE
LIST OF STUDENTS

S.No Roll Name


. Number

1
2210238 AAKASH

2
2210239 AAYUSHI

3
2210240 ABHAY

4
2210241 ABHISHEK GAUR

5
2210242 ADITYA SHARMA

6
2210243 AJAY SINGH

7
2210244 AMANPREET KAUR

8
2210245 AMAR DIL RAJ SINGH

9
2210246 AMARJIT KAUR

10
2210247 AMIT JASWAL

11
2210248 AMRIT DHIMAN

12
2210249 ANIL KUMAR

13
2210250 ANJU

14
2210251 ANKIT GOYAL

15
2210252 ANKIT KUMAR

16
2210253 ANSHIKA

17
2210254 ANSHIKA THAKUR
18
2210255 ANUJ GAUR

19
2210256 ANUJ TANWAR

20
2210257 ARSHDEEP KAUR

21
2210258 ARSHDEEP KAUR

22
2210259 ARUSHI MAKKAR

23
2210260 AVNEET KAUR

24
2210261 AVTAR SINGH

25
2210262 CHAHAT

26
2210263 CHANDER SHEKHAR

27
2210264 DEVANSH SHARMA

28
2210265 DISHA SHARMA

29
2210266 EKTA

30
2210267 GOURAV SHARMA

31
2210268 GURJEET KAUR

32
2210269 GURPREET SINGH

33
2210270 HARMANJEET KAUR

34
2210271 HARPREET SINGH

35
2210272 HARSH KAPOOR

36
2210273 HARSHITA ARYAN

37
2210274 ISHITA ARORA

38
2210275 J JEBA JASMINE
39
2210276 JAPSIMAR SINGH GULATI

40
2210277 JASHANPREET KAUR

41
2210278 JASPREET KAUR

42
2210279 JASPREET SINGH

43
2210280 KAMALPREET KAUR

44
2210281 KANIKA CHOUDHARY

45
2210282 KANISH NARANG

46
2210283 KARANPREET SINGH CHAUHAN

47
2210284 KARANVEER SINGH

48
2210285 KIRAT SNEH

49
2210286 KOMAL

50
2210287 KUNAL KANWAR
51
2210288 LIZA SHARMA
52
2210289 MANDEEP SINGH
53
2210290 MANISHA
54
2210291 MANOJ KUMAR
55
2210292 MANPREET KAUR
56
2210293 MANPREET KAUR
57
2210294 MANVIR SINGH
58
2210295 MEHAK PATHAK
59
2210296 MNAKSHI
60
2210297 MONU SHARMA
61
2210298 MUSKAN
62
2210299 NAINA KHATOON
63
2210300 NAVDEEP KAUR
64
2210301 NAVJOT KAUR
65
2210302 NIDHI
66
2210303 NIKHIL RATHOUR
67
2210304 NISHA KADAM
68
2210305 NITIN KAMBOJ
69
2210306 NITISH GARG
70
2210307 PALAK KUMARI
71
2210308 PALAK MALHOTRA
72
2210309 PALLAVI
73
2210310 PARAMPREET SINGH
74
2210311 PARAS
75
2210312 PARAS
76
2210313 PIYUSH
77
2210314 PRASHANT
78
2210315 PRERNA DEVI
79
2210316 PRINCE PATEL
80
2210317 PRIYA
81
2210318 PRIYANSHU SAINI
82
2210319 RAHUL SEHDEV
83
2210320 RAJAN SINGLA
84
2210321 RAJAT KUMAR
85
2210322 RAJAT MALIK
86
2210323 RANJAN KUMAR
87
2210324 RAVDEEP SINGH
88
2210325 RITIK KUMAR SINGH
89
2210326 RITIKA
90
2210327 RIYANSHU
91
2210328 ROHAN SONI
92
2210329 ROHIT KUMAR
93
2210330 SAHIBA
94
2210331 SAHIL GILL
95
2210332 SAKSHAM GAUR
96
2210333 SANDEEP KUMAR
97
2210334 SANDEEP SINGH
98
2210335 SANTOSH MANDAL
99
2210336 SEJAL THAKUR
100
2210337 SHEFALI KHARBANDA
101
2210338 SHIVAM KAPOOR
102
2210339 SHIVAM KUMAR
103
2210340 SHIVANSH MALHOTRA
104
2210341 SHIVANSH NAGAR
105
2210342 SHRIKANT
106
2210343 SHRIYA SHARMA
107
2210344 SHUBHAM MISHRA
108
2210345 SIMRAN PATHANIA
109
2210346 SIMRANJIT KAUR
110
2210347 SONIA
111
2210348 SUHAIL MUSHTAQ
112
2210349 SUMIT PANDEY
113
2210350 SUNIL KUMAR
114
2210351 SUNIL KUMAR RANA
115
2210352 SURESH KUMAR
116
2210353 TANISHA GARG
117
2210354 TANISHA SHARMA
118
2210355 TANISHKA THAKUR
119
2210356 TARAN PREET KAUR
120
2210357 TWINKLE
121
2210358 UJJWAL GARG
122
2210359 VIJAY KUMAR
123
2210360 VISHAVJEET SINGH SAINI
124
2210361 VISHWA ARYA
125
2210362 YASH

LAST 2 YEARS SOLVED PTU


QUESTION PAPERS
B.Sc (2013 & Onward)/B.Sc. ( IT) (2015 & Onward)
(Sem.–2)
OOPS USING C++
Subject Code : BSBC/BSIT-203 Paper ID : [B1115]
Roll No.
Total No. of Questions : 07

Time : 3 Hrs. Max. Marks : 60

INSTRUCTION TO CANDIDATES :
● SECTION-A is COMPULSORY consisting of TEN questions carrying TWO marks each.
● SECTION-B contains SIX questions carrying TEN marks each and a student has to
attempt any FOUR questions.

SECTION-A

Q1 Answer briefly :

a) List various features of object oriented programming language.


● Inheritance is a concept that provide reusability of codes and recourse in object
oriented programming languages
● Polymorphism this is existing features of oop. It provide that concept of same
name or different behavior.
● Data abstraction. This features of oop languages focus on hiding of complexity
of program.
● Encapsulation is a feature of oop languages that provides the concept of
wrapping of data and member function in single unit.

b) What is early and late binding?

Early Binding (compile-time time polymorphism) As the name indicates, compiler (or linker)
directly associate an address to the function call. It replaces the call with a machine language
instruction that tells the mainframe to leap to the address of the function.
Late Binding : (Run time polymorphism) In this, the compiler adds code that identifies the kind of
object at runtime then matches the call with the right function definition (Refer this for details).
This can be achieved by declaring a virtual function.
c)Define structure and union.

Structure stores the different types of elements i.e heterogeneous elements. The struct keyword is
used to define structure.
Syntax
struct structure_name
{
data_type member1;

data_type memeberN;
};
Union also stores the different types of elements i.e heterogeneous elements. The union keyword is
used to define structure. Union takes the memory of largest member only so occupies less
memory than structures.
Syntax
union union_name
{
data_type member1;

data_type memeberN;
};

d)What is object and class?

A class is a blueprint for the object.


We can think of class as a sketch (prototype) of a house. It contains all the details about the floors,
doors, windows etc. Based on these descriptions we build the house. House is the object.
As, many houses can be made from the same description, we can create many objects from a class.
A class is defined in C++ using keyword class followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a semicolon at the end.
class className

// some data

// some functions

};

C++ Objects
When class is defined, only the specification for the object is defined; no memory or storage is
allocated.
To use the data and access functions defined in the class, you need to create objects.

Syntax to Define Object in C++

className objectVariableName;

e)What are various characteristics of a pointer variable?

1. Pointers provide direct access to memory


2. It provides a way to return more than one value to the function.
3. Reduces the storage space and complexity of the program.
4. Reduces the execution time of the program.
5. Provides an alternative way to access array elements.
6. It allows us to perform the dynamic memory allocation. And allows us to re-size it too.
7. Address of objects can be extracted using pointers.
8. Pointers help us to build complex data structures like linked lists, queues, stacks, trees,
graphs etc.

f)What is static member function?

static member variables we have static member functions that are used for a specific purpose. To
create a static member function we need to use the static keyword while declaring the function.
Since static member variables are class properties and not object properties, to access them we need
to use the class name instead of the object name.

Properties of static member functions:

1. A static function can only access other static variables or functions present in the same class
2. Static member functions are called using the class name.
Syntax- class_name::function_name( )

Let’s consider a classic example to understand the concept of static member functions in detail. In
this example, we will understand all the concepts related to static member functions.

g)Write a C++ program to swap two numbers without using third variable.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a=5, b=10;
6. cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
7. a=a*b; //a=50 (5*10)
8. b=a/b; //b=5 (50/10)
9. a=a/b; //a=10 (50/5)
10. cout<<"After swap a= "<<a<<" b= "<<b<<endl;
11. return 0;
12. }

Output:

Before swap a= 5 b= 10
After swap a= 10 b= 5

h)Differentiate union and class.


STRUCTURES UNION

Struct keyword is used to Union keyword is used to declare the

declare the structure Union

Structure variable will

allocate memory for all the Union variable will allocate common

structure members memory for all the union members.

separately.

Example:
Example:

union Employee{
struct Employee{

int age;
int age;

char name[50];
char name[50];

float salary;
float salary;

};
};

Structures will occupy more

memory

space.Memory_Size = Union will occupy less memory space

addition of all the structure compared to structures.Memory_Size =

members sizes. Size of the largest Union member. From


i)Define binary operator overloading.

The binary operators take two arguments and following are the examples of Binary operators. You
use binary operators very frequently like addition (+) operator, subtraction (-) operator and
division (/) operator.
Following example explains how addition (+) operator can be overloaded. Similar way, you can
overload subtraction (-) and division (/) operators.

J)What is pure virtual function?


● A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t
have implementation, we only declare it. A pure virtual function is declared by assigning 0
in declaration. See the following example.

// An abstract class
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;

/* Other members */
};
SECTION-B
Q2 What is data hiding and encapsulation? How it is implemented using C++? Explain with example.

Encapsulation
Encapsulation binds the data & functions together which keeps both safe from outside interference. Data encapsulation
led to data hiding.

Let’s look at an example of encapsulation. Here, we are specifying the getter & setter function to get & set the value of
variable num without accessing it directly.

Example:
1
2
3
4
5
6
7
8
9
1
0
1
1
1 #include<iostream>
2 using namespace std;
1
3 class Encapsulation
1 {
4 private:
1 // data hidden from outside world
5 int num;
1
6 public:
1 // function to set value of
7 // variable x
1 void set(int a)
8 {
1 num =a;
9 }
2
0 // function to return value of
2 // variable x
1 int get()
2 {
2 return num;
2 }
3 };
2
4 // main function
2 int main()
5 {
2 Encapsulation obj;
6
2 obj.set(5);
7
cout<<obj.get();
2
return 0;
8
}
2
9
3
0
Data Hiding in C++
Data hiding is a process of combining data and functions into a single unit. The ideology behind data hiding is to
conceal data within a class, to prevent its direct access from outside the class. It helps programmers to create classes
with unique data sets and functions, avoiding unnecessary penetration from other program classes.

Discussing data hiding & data encapsulation, data hiding only hides class data components, whereas data encapsulation
hides class data parts and private methods.

Now you also need to know access specifier for understanding data hiding.

private, public & protected are three types of protection/ access specifiers available within a class. Usually, the data
within a class is private & the functions are public. The data is hidden, so that it will be safe from accidental
manipulation.

● Private members/methods can only be accessed by methods defined as part of the class. Data is most often
defined as private to prevent direct outside access from other classes. Private members can be accessed by
members of the class.
● Public members/methods can be accessed from anywhere in the program. Class methods are usually public
which is used to manipulate the data present in the class. As a general rule, data should not be declared public.
Public members can be accessed by members and objects of the class.
● Protected member/methods are private within a class and are available for private access in the derived class.

Now let’s look at a data hiding example.

Example: Data Hiding in C++


1
2
3
4
5
6
7
8
9
1
0 #include<iostream>
1 using namespace std;
1 class Base{
1
2 int num; //by default private
1 public:
3
1 void read();
4 void print();
1
5 };
1
void Base :: read(){
6
cout<<"Enter any Integer value"<<endl;
1
cin>>num;
7
1 }
8
1 void Base :: print(){
9 cout<<"The value is "<<num<<endl;
2 }
0
2 int main(){
1 Base obj;
2
2 obj.read();
2 obj.print();
3
2 return 0;
4 }
2
5
2
6
2
7
2
8
2
9
Q3 Define Constructor. What are its different types? Explain with suitable example.

A special method of the class that is automatically invoked when an instance of the class is created is called a
constructor. The main use of constructors is to initialize the private fields of the class while creating an instance for the
class. When you have not created a constructor in the class, the compiler will automatically create a default constructor
of the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to
null.

Some of the key points regarding constructor are

● A class can have any number of constructors.


● A constructor doesn't have any return type, not even void.
● A static constructor can not be a parametrized constructor.
● Within a class, you can create one static constructor only.

In C#, constructors can be divided into 5 types

1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor

Now, let's see each constructor type with the example below.

Default Constructor in C#

A constructor without any parameters is called a default constructor; in other words, this type of constructor does not
take parameters. The drawback of a default constructor is that every instance of the class will be initialized to the same
values and it is not possible to initialize each instance of the class with different values. The default
constructor initializes:

1. All numeric fields in the class to zero.


2. All string and object fields to null.

Example

1. using System;
2. namespace DefaultConstractor
3. {
4. class addition
5. {
6. int a, b;
7. public addition() //default contructor
8. {
9. a = 100;
10. b = 175;
11. }
12.
13. public static void Main()
14. {
15. addition obj = new addition(); //an object is created , constructor is called
16. Console.WriteLine(obj.a);
17. Console.WriteLine(obj.b);
18. Console.Read();
19. }
20. }
21. }

Parameterized Constructor in C#

A constructor with at least one parameter is called a parameterized constructor. The advantage of a parameterized
constructor is that you can initialize each instance of the class with a different value.
Copy Constructor in C#

The constructor which creates an object by copying variables from another object is called a copy constructor. The
purpose of a copy constructor is to initialize a new instance to the values of an existing instance.

Syntax

1. public employee(employee emp)


2. {
3. name=emp.name;
4. age=emp.age;
5. }

The copy constructor is invoked by instantiating an object of type employee and bypassing it the object to be copied.

Q4 What is function and operator overloading? Write and explain a C++ program to demonstrate the
concept of unary operator overloading.

Function refers to a segment that groups code to perform a specific task.In C++ programming, two functions can have
same name if number and/or type of arguments passed are different.
The number and type of arguments passed to these two functions are same even though the return type is different.
Hence, the compiler will throw error.
Example 1: Function Overloading

#include <iostream>
using namespace std;

void display(int);
void display(float);
void display(int, float);

int main() {
int a = 5;
float b = 5.5;

display(a);
display(b);
display(a, b);

return 0;
}

void display(int var) {


cout << "Integer number: " << var << endl;
}

void display(float var) {


cout << "Float number: " << var << endl;
}

void display(int var1, float var2) {


cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 and float number: 5.5

he unary operators operate on a single operand and following are the examples of Unary operators

● The increment (++) and decrement (--) operators.


● The unary minus (-) operator.
● The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left
side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage.
Live Demo
#include <iostream>
using namespace std;

class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};

int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}

Q5Discuss the role of streams, buffers and files by taking suitable example in C++.
C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just like water and oil
flowing through a pipe). In input operations, data bytes flow from an input source (such as keyboard, file, network or
another program) into the program. In output operations, data bytes flow from the program to an output sink (such as
console, file, network or another program). Streams acts as an intermediaries between the programs and the actual IO
devices, in such the way that frees the programmers from handling the actual devices, so as to archive device
independent IO operations.

C++ provides both the formatted and unformatted IO functions. In formatted or high-level IO, bytes are grouped and
converted to types such as int, double, string or user-defined types. In unformatted or low-level IO, bytes are treated as
raw bytes and unconverted. Formatted IO operations are supported via overloading the stream insertion (<<) and stream
extraction (>>) operators, which presents a consistent public IO interface.
To perform input and output, a C++ program:
1. Construct a stream object.
2. Connect (Associate) the stream object to an actual IO device (e.g., keyboard, console, file, network, another
program).
3. Perform input/output operations on the stream, via the functions defined in the stream's pubic interface in a
device independent manner. Some functions convert the data between the external format and internal format
(formatted IO); while other does not (unformatted or binary IO).
4. Disconnect (Dissociate) the stream to the actual IO device (e.g., close the file).
5. Free the stream object.
A temporary storage area is called buffer. All standard input and output devices contain an input and

output buffer. In standard C/C++, streams are buffered, for example in the case of standard input, when we

press the key on keyboard, it isn’t sent to your program, rather it is buffered by operating system till the

time is allotted to that program.

Usually, when you open a file, a buffer is created. When you close the file, the buffer is flushed. When working in C++,
you can create a buffer by allocating memory in this manner:
char* buffer = new char[length];
When you want to free up the memory allocated to a buffer, you do so like this:
delete[ ] buffer;
files are mainly dealt by using three classes fstream, ifstream, ofstream.
● ofstream: This Stream class signifies the output file stream and is applied to create files for writing information
to files
● ifstream: This Stream class signifies the input file stream and is applied for reading information from files
● fstream: This Stream class can be used for both read and write from/to files.

All the above three classes are derived from fstreambase and from the corresponding iostream class and they are
designed specifically to manage disk files.
C++ provides us with the following operations in File Handling:

● Creating a file: open()


● Reading data: read()
● Writing new data: write()
● Closing a file: close()

Q6 Write notes on the following :

a) Array of structure

Structure is collection of different data type. An object of structure represents a single record in memory, if we want
more than one record of structure type, we have to create an array of structure or object. As we know, an array is a
collection of similar type, therefore an array can be of structure type.
Syntax for declaring structure array

struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};

struct-name obj [ size ];

Example for declaring structure array

#include<iostream.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

void main()
{
int i;
Employee Emp[ 3 ]; //Statement 1

for(i=0;i<3;i++)
{

cout << "\nEnter details of " << i+1 << " Employee";

cout << "\n\tEnter Employee Id : ";


cin >> Emp[i].Id;

cout << "\n\tEnter Employee Name : ";


cin >> Emp[i].Name;

cout << "\n\tEnter Employee Age : ";


cin >> Emp[i].Age;

cout << "\n\tEnter Employee Salary : ";


cin >> Emp[i].Salary;
}

cout << "\nDetails of Employees";


for(i=0;i<3;i++)
cout << "\n"<< Emp[i].Id <<"\t"<< Emp[i].Name <<"\t"
<< Emp[i].Age <<"\t"<< Emp[i].Salary;

b) Need and types of inheritance

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to
define a class in terms of another class, which makes it easier to create and maintain an application. This also provides
an opportunity to reuse the code functionality and fast implementation time.
● Single Inheritance
Single Inheritance
This type of inheritance in C++ happens when the parent class has only one child class. In other words, this is only one
derived class formed from a base class.

Syntax-
Class BAse
{
// BODY OF THE BASE CLASS
};
class Derived : acess_specifier Base
{
// BODY OF THE DERIVED CLASS
};

● Multiple Inheritance
v This type of inheritance happens when the child class inherits its properties from more than one base class. In other
others, the derived class inherits properties from multiple base classes.

Syntax
class A // Base class of B
{
// BODY OF THE CLASS A
};
class B // Derived class of A and Base class
{
// BODY OF THE CLASS B
};
class C : acess_specifier A, access_specifier A // Derived class of A and B
{
// BODY OF CLASS C
};
Multilevel Inheritance
This type of inheritance is the best way to represent the transitive nature of inheritance. In multilevel inheritance, a
derived class inherits all its properties from a class that itself inherits from another class.

Syntax
class A // Base class
{
// BODY OF CLASS A
};
class B : acess_specifier A // Derived class of A
{
// BODY OF CLASS B
};
class C : access_specifier B // Derived from derived class B
{
// BODY OF CLASS C
};

● Hierarchical Inheritance
● When multiple child classes inherit their properties from just a single base class.

● Syntax
● class A // Base class of B
{
// BODY OF THE PROGRAM
};
class B : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};
class C : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};
class D : access_specifier A // Derived class of A
{
// BODY OF THE PROGRAM
};

● Hybrid Inheritance
This type of inheritance essentially combines more than two forms of inheritance discussed above. For instance,
when a child class inherits from multiple base classes all of its parent classes and that child class itself serves as
a base class for 3 of its derived classes.

Q7 What are friend and inline functions? Explain with example.

If a function is inline, the compiler places a copy of the code of that function at each point where the function is called
at compile time.
Any change to an inline function could require all clients of the function to be recompiled because compiler would
need to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are
made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers
#include <iostream>

using namespace std;

inline int Max(int x, int y) {


return (x > y)? x : y;
}

// Main function for the program


int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;
}

If a function is defined as a friend function then, the private and protected data of a class can be accessed using
the function.The complier knows a given function is a friend function by the use of the keyword friend.
For accessing the data, the declaration of a friend function should be made inside the body of the class (can be
anywhere inside class either in private or public section) starting with keyword friend.

Declaration of friend function in C++

class class_name

... .. ...

friend return_type function_name(argument/s);


... .. ...

Now, you can define the friend function as a normal function to access the data of the class. No friend keyword is
used in the definition.
class className

... .. ...

friend return_type functionName(argument/s);

... .. ...

return_type functionName(argument/s)

... .. ...

// Private and protected data of className can be accessed from

// this function because it is a friend function of className.

... .. ...

Example 1: Working of friend Function

/* C++ program to demonstrate the working of friend function.*/


#include <iostream>
using namespace std;

class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};

// friend function definition


int addFive(Distance d)
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}

int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}
Total No. of Questions: 07
B.Sc (2011 & Onward)
B.Sc.(IT) (2015 & Onward) (Sem. – 2)
OOPS USING C++
M Code: 10052
Subject Code: BSBC-203/BSIT-203 Paper ID:
[B1115]
Time: 3 Hrs. Max. Marks: 60

INSTRUCTIONS TO CANDIDATES:
1. SECTION-A is COMPULSORY consisting of TEN questions carrying TWO marks each.
2. SECTION-B contains SIX questions carrying TEN marks each and students have to attempt any FOUR questions.

SECTION A

1. a) What do you mean by access specifiers in C++?

public - members are accessible from outside the class.


private - members cannot be accessed (or viewed) from outside the class.
protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.
b) How will you declare 2-Dimensional Array in C++?

Two – dimensional array is the simplest form of a multidimensional array. We can see a two – dimensional array as an
array of one – dimensional array for easier understanding.
● The basic form of declaring a two-dimensional array of size x, y:
Syntax:
● data_type array_name[x][y];
● data_type: Type of data to be stored. Valid C/C++ data type.
● We can declare a two dimensional integer array say ‘x’ of size 10,20 as:
int x[10][20];
c) What are various advantages/disadvantages of Friend function?
Merits of friend function

● Friend function act as bridge between two classes by operating on their private datas.
● Must have access to source code for the class to make a function into friend.
● Able to access members without need of inheriting the class.
● Allows a more abvious syntax for calling a function rather than member function.
For example num.square(); is less obvious than square(num);
● Can be declared either in the public or the private part of a class.
● Can be used to increase versatility of overloaded operator.

Demerits of friend function


● Friend function have access to private members of a class from outside the class which violates the law
of data hiding.
● Breach of data integrity
● Conceptually messy
● Lead to spaghetti-code situation if numerous friends muddy the boundary between classes.
● Maximum size of memory will be occupied by objects according to size of friend members.

d) What do you mean by Operator Overloading?


Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type. Operator overloading is used
to overload or redefines most of the operators available in C++. It is used to perform the operation
on the user-defined data type.
e) Define Scope Resolution Operator.
The scope resolution operator ( :: ) is used for several reasons. For example: If the global variable name is same as
local variable name, the scope resolution operator will be used to call the global variable. It is also used to define a
function outside the class and used to access the static variables of class.
Here an example of scope resolution operator in C++ language,
2. Example

3. #include <iostream>

4. using namespace std;

5. char a = 'm';

6. static int b = 50;

7.

8. int main() {

9. char a = 's';

10.

11. cout << "The static variable : "<< ::b;

12. cout << "\nThe local variable : " << a;

13. cout << "\nThe global variable : " << ::a;

14.

15. return 0;

16. }
17. Here is the output
18. The static variable : 50
19. The local variable : s
20. The global variable : m

f)What are Inline Functions?


To inline a function, place the keyword inline before the function name and define the function before any calls are
made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers
Live Demo
#include <iostream>

using namespace std;

inline int Max(int x, int y) {


return (x > y)? x : y;
}

// Main function for the program


int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;
}

g)Define Union in C++?


Union is a user-defined datatype. All the members of union share same memory location. Size of union is decided by
the size of largest member of union. If you want to use same memory location for two or more members, union is the
best for that.
Unions are similar to structures. Union variables are created in same manner as structure variables. The keyword
“union” is used to define unions in C language.
Here is the syntax of unions in C language,

union union_name {
member definition;
} union_variables;
Here,
● union_name Any name given to the union.
● member definition Set of member variables.
● union_variable This is the object of union.
h)What do you mean by Polymorphism?
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a
greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation,
and polymorphism.
1. class A // base class declaration.
2. {
3. int a;
4. public:
5. void display()
6. {
7. cout<< "Class A ";
8. }
9. };
10. class B : public A // derived class declaration.
11. {
12. int b;
13. public:
14. void display()
15. {
16. cout<<"Class B";
17. }
18. };

i)What are pure virtual functions?

A virtual function whose declaration ends with =0 is called a pure virtual function. For example,
class Weapon

public:

virtual void features() = 0;

};

Here, the pure virtual function is


virtual void features() = 0

j)Define late Binding.

Late Binding
This is run time polymorphism. In this type of binding the compiler adds code that identifies the object type at runtime
then matches the call with the right function definition. This is achieved by using virtual function.
Example

#include<iostream>

using namespace std;

class Base {

public:

virtual void display() {

cout<<"In Base class" << endl;

};

class Derived: public Base {

public:

void display() {

cout<<"In Derived class" <<endl;

};

int main() {

Base *base_pointer = new Derived;

base_pointer->display();

return 0;

ECTION B
2. What do you mean by structures in C++? Write a program covering “accessing structure members” and “arrays of
structure”.
Structures in C++ are user defined data types which are used to store group of items of non-similar data types.
structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of
possibly different types into a single type. The ‘struct’ keyword is used to create a structure. The general syntax to
create a structure is as shown below:
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
Structures in C++ can contain two types of members:
● Data Member: These members are normal C++ variables. We can create a structure with variables of different data
types in C++.
● Member Functions: These members are normal C++ functions. Along with variables, we can also include functions
inside a structure declaration.
Example:
filter_none
brightness_4
// Data Members
int roll;
int age;
int marks;

// Member Functions
void printDetails()
{
cout<<"Roll = "<<roll<<"\n";
cout<<"Age = "<<age<<"\n";
cout<<"Marks = "<<marks;
}

Accessing Structure Members

To access any member of a structure, we use themember access operator (.). The member access operator is coded as a peri

#include <iostream>
#include <cstring>

using namespace std;

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;
}
When the above code is compiled and executed, it produces the following result
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700

Array Of Structurres

The data members are three integer variables to store roll number, age and marks of any student and the member
function is printDetails() which is printing all of the above details of any student.
we can create an array of structures.
#include <iostream>
using namespace std;

struct Point {
int x, y;
};

int main()
{
// Create an array of structures
struct Point arr[10];

// Access array members


arr[0].x = 10;
arr[0].y = 20;

cout << arr[0].x << " " << arr[0].y;


return 0;
}
Output:
10 0

3.Define functions. Discuss the concepts of “Pass by value” and “Pass by reference” with help of program in C++.
A function is a group of statements that together perform a task. Every C++ program has at least one function,
which is main(), and all the most trivial programs can define additional functions. You can divide up your code
into separate functions. How you divide up your code among different functions is up to you, but logically the
division usually is such that each function performs a specific task.
Call by value and call by reference in C++
There are two ways to pass value or data to function in C language: call by value and call by reference. Original value
is not modified in call by value but it is modified in call by reference.
Call by value in C++
In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the function parameter in stack memory
location. If you change the value of function parameter, it is changed for the current function only. It will not change
the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in C++ language by the example given below:
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Output:
Value of the data is: 3

Call by reference in C++


In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, va
Note:To understand the call by reference, you must have the basic knowledge of pointers.
Let's try to understand the concept of call by reference in C++ language by the example given below:
1. #include<iostream>
2. usingnamespacestd;
3. voidswap(int*x,int*y)
4. {
5.
6.
7.
8.
9. }
10. intmain()
11. {
12.
13.
14.
15.
16.
17. }
Output:
Value of x is: 100
Value of y is: 500

Difference between call by value and call by reference in C++


No. Call by value Call by reference

1 A copy of value is passed to the function An address of value is passed to the


function
2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be created Actual and formal arguments will be
in different memory location created in same memory location

4.What do you mean by constructor and destructor? Write a program to demonstrate copy constructor and destructor.
A class constructor is a special member function of a class that is executed whenever we create new objects of that
class.A constructor will have exact same name as the class and it does not have any return type at all, not even
void. Constructors can be very useful for setting initial values for certain member variables.
class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};

Copy Constructor in C++


Copy Constructor is a type of constructor which is used to create a copy of an already existing object of a class type. It
is usually of the form X (X&), where X is the class name. The compiler provides a default Copy Constructor to all the
classes.

Syntax of Copy Constructor


Classname(const classname & objectname)
{
....
}
As it is used to create an object, hence it is called a constructor. And, it creates a new object, which is exact copy of the
existing copy, hence it is called copy constructor.

Below is a sample program on Copy Constructor:


#include<iostream>
using namespace std;
class Samplecopyconstructor
{
private:
int x, y; //data members

public:
Samplecopyconstructor(int x1, int y1)
{
x = x1;
y = y1;
}

/* Copy constructor */
Samplecopyconstructor (const Samplecopyconstructor &sam)
{
x = sam.x;
y = sam.y;
}

void display()
{
cout<<x<<" "<<y<<endl;
}
};
/* main function */
int main()
{
Samplecopyconstructor obj1(10, 15); // Normal constructor
Samplecopyconstructor obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
Normal constructor : 10 15
Copy constructor : 10 15

5.What is inheritance? What are different types of inheritance available in C++?


n C++, inheritance is a process in which one object acquires all the properties and behaviors of its parent object
automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other
class.
In C++, the class which inherits the members of another class is called derived class and the class whose members are
inherited is called base class. The derived class is the specialized class for the base class.
Advantage of C++ Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no need to define the member
again. So less code is required in the class.
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.

Where 'A' is the base class, and 'B' is the derived class
C++ Multilevel Inheritance
Multilevel inheritance is a process of deriving a class from another derived class.
C++ Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more classes.

Syntax of the Derived class:


1. class D : visibility B-1, visibility B-2, ?
2. {
3. // Body of the class;
4. }
C++ Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
6.What are various control and conditional statements available in C++? Explain the use of break and continue
statements.
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.
Conditional structure: if and else

The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:

if (condition) statement

Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is
false, statement is ignored (not executed)
if (condition) statement1 else statement2

For example:

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

prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100.

The if + else structures can be concatenated with the intention of verifying a range of values. The following example
shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):

1 if (x > 0)
cout << "x is
positive";
else if (x < 0)
cout << "x is
negative";
else
cout << "x is 0";

Iteration structures (loops)

Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.

The while loop


Its format is:

while (expression) statement

and its functionality is simply to repeat statement while the condition set in expression is true.
For example, we are going to make a program to countdown using a while-loop:

1 // custom countdown using Enter the starting number > 8


while 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
2
#include <iostream>
3 using namespace std;

4 int main ()
{
5 int n;
cout << "Enter the starting
6 number > ";
cin >> n;
7
while (n>0) {
8 cout << n << ", ";
--n;
9 }

1 cout << "FIRE!\n";


0 return 0;
}
1 E
1 dit
&
1 Ru
2 n

1
3

1
4

1
5

1
6

1
7

1
8

1
9
When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop
begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows
the condition will be executed and repeated while the condition (n>0) remains being true.
The do-while loop

Its format is:

do statement while (condition);

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the
execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled.
For example, the following example program echoes any number you enter until you enter 0.

1 // number echoer Enter number (0 to end): 12345


You entered: 12345
2 #include <iostream> Enter number (0 to end): 160277
using namespace std; You entered: 160277
3 Enter number (0 to end): 0
int main () You entered: 0
4 {
unsigned long n;
5 do {
cout << "Enter number (0 to end): ";
6 cin >> n;
cout << "You entered: " << n << "\
7 n";
} while (n != 0);
8 return 0;
} E
9 dit
&
1 Ru
0 n

1
1

1
2

1
3

1
4

1
5
The do-while loop is usually used when the condition that has to determine the end of the loop is
determined within the loop statement itself, like in the previous case, where the user input within the block is
what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you
can be prompted for more numbers forever.
The for loop

Its format is:

for (initialization; condition; increase) statement;

and its main function is to repeat statement while condition remains true, like the while loop. But in addition,
the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is
specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration.

It works in the following way:

1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only
once.
2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not
executed).
3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop:


1 // countdown using a for loop 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
#include <iostream> FIRE!
2 using namespace std;
int main ()
3 {
for (int n=10; n>0; n--) {
4 cout << n << ", ";
}
5 cout << "FIRE!\n";
return 0; E
6 } dit
&
7 Ru
n
8

1
0

1
1

Jump statements.

The break statement

Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop,
or to force it to end before its natural end. For example, we are going to stop the count down before its natural end
(maybe because of an engine check failure?):
1 // break loop example 10, 9, 8, 7, 6, 5, 4, 3,
countdown aborted!
2 #include <iostream>
using namespace std;
3
int main ()
4 {
int n;
5 for (n=10; n>0; n--)
{
6 cout << n << ", ";
if (n==3)
7 {
cout << "countdown
8 aborted!";
break;
9 }
}
1 return 0;
0 }

1 E
1 dit
&
1 Ru
2 n

1
3

1
4

1
5

1
6

1
7

1
8

1
9
The continue statement

The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the
statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going
to skip the number 5 in our countdown:

1 // continue loop example


2 #include <iostream>
3 using namespace std;
4
5 int main ()
6 {
7 for (int n=10; n>0; n--) {
8 if (n==5) continue;
9 cout << n << ", ";
10 }
11 cout << "FIRE!\n";
12 return 0;
13 }

7.What is File Handling? Write a program in C++ to copy contents of one file to another.
File Handling In C++
Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output
of a program in a file and to perform various operations on it. A stream is an abstraction that represents a device on
which operations of input and output are performed.
Problem:- C++ Program To Copy Contents Of One File Into Another
Explanation:- So in this problem, we have copied the one file into another file. The program first will ask you to enter
the first file name after that ask for entering the second file name than program copied the first file into the second file.
We have to enter both file name with extension cause file always have extension or folder not this is useful when you
want to merge two files or in other words, we can say that merge two file.

Solution:-

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
//Ghanendra Yadav
ifstream fs;
ofstream ft;
char ch, fname1[20], fname2[20];
cout<<"Enter Source File Name With Extension : ";
gets(fname1);
fs.open(fname1);
if(!fs)
{
cout<<"Error In Opening Source File..!!";
getch();
exit(1);
}
cout<<"Enter Destination File Name With Extension : ";
gets(fname2);
ft.open(fname2);
if(!ft)
{
cout<<"Error In Opening Target File..!!";
fs.close();
getch();
exit(2);
}
while(fs.eof()==0)
{
fs>>ch;
ft<<ch;
}
cout<<"File Copied Successfully..!!";
fs.close();
ft.close();
getch();
}

Output:-
Question Bank Based on PTU Paper Pattern(Unit Wise and CO Mapped))

Unit - 1(CO1,CO2)
Short Answer Ques(2 marks)

1) Give the evolution diagram of OOPS concept.


Machine language
Procedure language
Assembly language
OOPS

2) What is Procedure oriented language?


Conventional programming, using high-level language such as COBOL, FORTRAN and C are
commonly known as Procedure oriented language (POP). In POP number of functions are written
to accomplish the tasks such as reading, calculating and printing.

3) Give some characteristics of procedure-oriented language.


• Emphasis is on doing things (algorithms).
• Larger programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Employs top-down approach in program design.

4) Write any four features of OOPS.


• Emphasis is on data rather than on procedure.
• Programs are divided into objects.
• Data is hidden and cannot be accessed by external functions.
• Follows bottom -up approach in program design.

5) What are the basic concepts of OOS?


• Objects.
• Classes.
• Data abstraction and Encapsulation.
• Inheritance.
• Polymorphism.
• Dynamic binding.
• Message passing.
6) What are objects?
Objects are basic run-time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to handle. Each object has
the data and code to manipulate the data and theses objects interact with each other.

7) What is a class?
• The entire set of data and code of an object can be made a user-defined data type with the help of
a class.
• Once a class has been defined, we can create any number of objects belonging to the classes.
• Classes are user-defined data types and behave like built-in types of the programming language.

8) what is encapsulation?
Wrapping up of data and function within the structure is called as encapsulation.

9) What is data abstraction?


The insulation of data from direct access by the program is called as data hiding or information
binding.
The data is not accessible to the outside world and only those functions, which are wrapped in the
class, can access it.
10) What are data members and member functions?
Classes use the concept of abstraction and are defined as a list of abstract attributes such as size,
weight, and cost and uses functions to operate on these attributes.The attributes are sometimes
called as data members because they hold information. The functions that operate on these data are
called as methods or member functions.
Eg: int a,b; // a,b are data members
Void getdata ( ) ; // member function

11) What is dynamic binding or late binding?


Binding refers to the linking of a procedure to the code to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is not known until the
time of the call at the run-time.

12) Write the process of programming in an object-oriented language?


• Create classes that define objects and their behavior.
• Creating objects from class definition.
• Establishing communication among objects.

13) Give any four advantages of OOPS.


• The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code in other parts of the program.
• It is possible to have multiple instances of an object to co-exist without any interference.
• Object oriented programming can be easily upgraded from small to large systems.
• Software complexity can be easily managed.
14) What are the features required for object-based programming Language?
• Data encapsulation.
• Data hiding and access mechanisms.
• Automatic initialization and clear up of objects.
• Operator overloading.

15) What are the features required for object oriented language?
• Data encapsulation.
• Data hiding and access mechanisms.
• Automatic initialization and clear up of objects.
• Operator overloading.
• Inheritance.
• Dynamic binding.

16) Give any four applications of OOPS


• Real-time systems.
• Simulation and modeling.
• Object-oriented databases.
• AI and expert systems.

17) Give any four applications of c++?


• Since c++ allows us to create hierarchy-related objects, we can build special object-oriented
libraries, which can be used later by many programmers.
• C++ are easily maintainable and expandable.
• C part of C++ gives the language the ability to get close to the machine-level details.
• It is expected that C++ will replace C as a general-purpose language in the near future.

18) What are tokens?


The smallest individual units in a program are known as tokens. C++ has the following tokens,
• Keyword
• Identifiers
• Constants
• Strings
• Operator
19) What are keywords?
The keywords implement specific C++ language features. They are explicitly reserved identifiers
and cannot be used as names fro the program variables or other user defined program elements.
Eg: go to, If, struct , else ,union etc.

20) Rules for naming the identifiers in C++.


• Only alphabetic characters, digits and underscore are permitted.
• The name cannot start with a digit.
• The upper case and lower case letters are distinct.
• A declared keyword cannot be used as a variable name.

21) What are the operators available in C++?


All operators in C are also used in C++. In addition to insertion operator << and extraction operator
>> the other new operators in C++ are,
: : Scope resolution operator
: : * Pointer-to-member declarator
->* Pointer-to-member operator
.* Pointer-to-member operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator

22) What is a scope resolution operator?


Scope resolution operator is used to uncover the hidden variables. It also allows access to global
version of variables.
Eg:
#include<iostream. h>
int m=10; // global variable m
void main ( )
{
int m=20; // local variable m
cout<<”m=”<<m<<”\n”;
cout<<”: : m=”<<: : m<<”\n”;
}
output:
20
10 (: : m access global m)
Scope resolution operator is used to define the function outside the class.

Syntax:
Return type <class name> : : <function name>
Eg:
Void x : : getdata()

23) What are free store operators (or) Memory management operators?
New and Delete operators are called as free store operators since they allocate the memory
dynamically.
New operator can be used to create objects of any data type.
Pointer-variable = new data type;
Initialization of the memory using new operator can be done. This can be done as,
Pointer-variable = new data-type(value)
Delete operator is used to release the memory space for reuse. The general form of its use is
Delete pointer-variable;

24) What are manipulators?


Setw, endl are known as manipulators.
Manipulators are operators that are used to format the display. The endl manipulator when used in
an output statement causes a linefeed to be inserted and its effect is similar to that of the newline
character”\n”.
Eg:Cout<<setw(5)<<sum<<endl;
25) What do you mean by enumerated datatype?
An enumerated datatype is another user-defined datatype, which provides a way for attaching
names to numbers, thereby increasing comprehensibility of the code.The syntax of an enum
statement is similar to that of the struct statesmen.
Eg:
enum shape{ circle, square, triangle}
enum color{ red, blue, green, yellow}

26) What are symbolic constants?


There are two ways for creating symbolic constants in C++:
• Using the qualifier constant.
• Defining a set of integer constants using enum keyword.
The program in any way cannot modify the value declared as constant in c++.
Eg:
Const int size =10;
Char name [size];

27) What do you mean by dynamic initialization of variables?


C++ permits initialization of the variables at run-time. This is referred to as dynamic initialization
of variables.
In C++ ,a variable can be initialized at run-time using expressions at the place of declaration as,
……..
…......
int n =strlen(string);
……..
float area=3.14*rad*rad;
Thus declaration and initialization is done simultaneously at the place where the variable is used for
the first time.

28) What are reference variable?


A reference variable provides an alias(alternative name) for a previously defined variable.
sum total For example , if make the variable a reference to the variable , then sum and total can be
used interchancheably to represent that variable.
Syntax :
Data-type &reference-name = variable-name
Eg:
float total = 100;
float sum = total;

29) What is member-dereferencing operator?


C++ permits to access the class members through pointers. It provides three pointer-to-member
operators for this purpose,
: :* To declare a pointer to a member of a class.
* To access a member using object name and a pointer to the member
->* To access a member using a pointer to the object and a pointer to that member.

30) What is function prototype ?


The function prototype describes function interface to the compiler by giving details such as
number ,type of arguments and type of return values
Function prototype is a declaration statement in the calling program and is of the
following
Type function_name(argument list); Eg float volume(int x,float y);

31) what is an inline function ?


An inline function is a function that is expanded in line when it is invoked. That is compiler
replaces the function call with the corresponding function code.
The inline functions are defined as Inline function-header
{
function body
}
32) Write some situations where inline expansion may not work
• for functions returning values, if loop, a switch, or a goto exists
• for functions not returning values ,if a return statement exists
• if function contain static variables
• if inline functions are recursive

33) what is a default argument ?


Default arguments assign a default value to the parameter, which does not have matching argument
in the function call. Default values are specified when the f unction is declared.
Eg : float amount(float principle,int period,float rate=0. 15)
Function call is
Value=amount(5000,7);
Here it takes principle=5000& period=7
And default value for rate=0.15
Value=amount(5000,7,0.34)
Passes an explicit value 0f 0.34 to rate
We must add default value from right to left

34) What are constant arguments ?


keyword is const. The qualifier const tells the compiler that the function should not modify the
argument. The compiler will generate an error when this condition is violated. This type of
declaration is significant only when we pass arguments by reference or pointers
eg: int strlen( const char *p);

35) How the class is specified ?


Generally class specification has two parts
• class declaration
It describes the type and scope of its member
• class function definition
It describes how the class functions are implemented
The general form is
Class class_name
{
private:
variable declarations;
function declaration;
public:
variable declaration;
function declaration;
};

36) How to create an object ?


Once the class has been declared, we can create variables of that type by using the classname
Eg:classname x; //memory for x is created

37) How to access a class member ?


object-name. function-name(actual arguments)
eg:x.getdata(100,75.5);

38) How the member functions are defined ?


Member functions can be defined in two ways
• outside the class definition
Member function can be defined by using scope resolution operator::
General format is
Return type class_ name::function-name(argument declaration)
{
}
• Inside the class definition
This method of defining member function is to replace the function declaration by the actual
function definition inside the class. It is treated as inline function
Eg:class item
{
int a,b ;
void getdata(int x,int y)
{
a=x;
b=y;
};
39) What is static data member?
Static variable are normally used to maintain values common to the entire class.
Feature:
• It is initialized to zero when the first object is created. No other initialization is permitted
• only one copy of that member is created for the entire class and is shared by all the objects
• It is only visible within the class, but its life time is the entire class type and scope of each
static member variable must be defined outside the class
• It is stored separately rather than objects
Eg: static int count//count is initialized to zero when an object is created.
int classname::count;//definition of static data member

40) What is static member function?


A member function that is declared as static has the following properties
• A static function can have access to only other static member declared in the same class
• A static member function can be called using the classname as
follows classname ::function_name;
41) How the objects are used as function argument?
This can be done in two ways
• A copy of the entire object is passed to the argument
• Only address of the objects is transferred to the f unction

42) What is called pass by reference?


In this method address of an object is passed, the called function works directly on the actual
arguments.

43) Define const member


If a member function does not alter any data in the class, then we may declare it as const member
function as
Void mul(int ,int)const;

44) Define pointers to member


It is possible to take the address of a member of a class and assign it to a pointer. The address of a
member can be obtained by applying the operator &to a “fully qualified” class member name. A
class member pointer can be declared using the operator::*with the class name.
Eg: class A
{
int m;
public:
void show( );
};
pointer to member m is defined as
int A::*ip=&A::m;
A::*->pointer to member of A class
&A::m->address of the m member of A class

45) When the deferencing operator ->* is used?


It is used to access a member when we use pointer to both the object and the member.
47) When the deferencing operator .* is used?
It is used to access a member when the object itself is used as pointers.
48) Define local classes.
Classes can be defined and used inside a function or a block. such classes are called local classes. It
can use global variables and static variables declared inside the function but cannot use automatic
local variables.
Eg;
void test(int a)
{
…….
}
class student
{
………
};
student s1(a);
}

46) What are Friend functions? Write the syntax


A function that has access to the private member of the class but is not itself a member of the class
is called friend functions.
The general form is
friend data_type function_name( );
Friend function is preceded by the keyword ‘friend’.

47)Write some properties of friend functions.


• Friend function is not in the scope of the class to which it has been declared as friend. Hence it
cannot be called using the object of that class.
• Usually it has object as arguments.
• It can be declared either in the public or private part of a class.
• It cannot access member names directly. It has to use an object name and dot
membership operator with each member name. eg: ( A . x )

48) What is function overloading? Give an example.


Function overloading means we can use the same function name to create functions that perform a
variety of different tasks.
Eg: An overloaded add ( ) function handles different data types as shown below.
// Declarations
i. int add( int a, int b); //add function with 2 arguments of same type
ii. int add( int a, int b, int c); //add function with 3 arguments of same type
iii. double add( int p, double q); //add function with 2 arguments
of different type
//Function calls
add (3 , 4); //uses prototype ( i. )
add (3, 4, 5); //uses prototype ( ii. )
add (3 , 10.0); //uses prototype ( iii. )

48) Define local classes.


Classes can be defined and used inside a function or a block. such classes are called
local classes. It can use global variables and static variables declared inside the function
but cannot use automatic local variables.
Eg;
void test(int a)
{
…….
}
class student
{
………
};
student s1(a);}
49) Define constructor
A constructor is a special member function whose task is to initialize the objects of its class. It is
special because its name is same as class name. The constructor is invoked whenever an object of
its associated class is created. It is called constructor because it constructs the values of data
members of the class
Eg:
integer Class
{
……
public:
integer( );//constructo r
………
}

50) Define default constructor


The constructor with no arguments is called default constructor
Eg:
Class integer
{
int m,n;
Public:
Integer( );
…….
};
integer::integer( )//default constructor
{ m=0;n=
0;
}
the statement
integer a;
invokes the default constructor

51) Define parameterized constructor


constructor with arguments is called parameterized constructor
Eg;
Class integer
{ int m,n;
public:
integer(int x,int y)
{ m=x;n=y;
}
To invoke parameterized constructor we must pass the initial values as arguments to the constructor
function when an object is declared. This is done in two ways
1. By calling the constructor
explicitly eg: integer
int1=integer(10,10);
2. By calling the constructor
implicitly eg: Integer int1(10,10);

52) Define default argument constructor


The constructor with default arguments are called default argument constructor
Eg:
Complex(float real,float imag=0);
The default value of the argument imag is 0
The statement complex a(6.0)
assign real=6.0 and imag=0
the statement
complex a(2.3,9.0)
assign real=2.3 and imag=9.0

53) What is the ambiguity between default constructor and default


argument constructor ?
The default argument constructor can be called with either one argument or no arguments.
when called with no arguments ,it becomes a default constructor. When both these forms are
used in a class ,it cause ambiguity for a statement such as A a;
The ambiguity is whether to call A::A() or A::A(int i=0)

54) Define copy constructor


A copy constructor is used to declare and initialize an object from another object. It takes a
reference to an object of the same class as an argument
Eg: integer i2(i1);
would define the object i2 at the same time initialize it to the values of i1.
Another form of this statement is
Eg: integer i2=i1;
The process of initializing through a copy constructor is known as copy initialization .

55) Define dynamic constructor


Allocation of memory to objects at time of their construction is known as dynamic constructor. The
memory is allocated with the help of the NEW operator
Eg:
Class string
{
char *name;
int length;
public:
string( )
{
length=0;
name=new char[ length +1];
}
void main( )
{
string name1(“Louis”),name3(Lagrange);
}

56) Define const object


We can create constant object by using const keyword before object declaration.
Eg: Const matrix x(m,n);

57) Define destructor


It is used to destroy the objects that have been created by constructor. Destructor name is same as
class name preceded by tilde symbol(~)

Eg;
~integer()
{
}
A destructor never takes any arguments nor it does it return any value. The compiler upon exit from
the program will invoke it. new Whenever operator is used to allocate memory in the constructor,
we should
use delete to free that memory.

58) Define multiple constructors (constructor overloading).


The class that has different types of constructor is called multiple constructors
Eg:
#include<iostream. h>
#include<conio.h>
class integer
{
int m,n;
public:
integer( ) //default constructor
{ m=0;n=
0;
}
integer(int a,int b) //parameterized constructor
{
m=a; n=b;
}
integer(&i) //copy constructor
{
m=i. m;
n=i.n;
}
void main()
{
integer i1; //invokes default constructor
integer i2(45,67);//invokes parameterized constructor
integer i3(i2); //invokes copy constructor
}

59) Write some special characteristics of constructor


• T hey should be declared in the public section
• They are invoked automatically when the objects are created
• They do not have return types, not even void and therefore, and they cannot return values
• They cannot be inherited, though a derived class can call the base class
• They can have default arguments
• Constructors cannot be virtual f unction

60) How the objects are initialized dynamically?


To call parameterized constructor we should the pass values to the object ie,for the constructor
integer(int a,int b) it is invoked by integer a(10,18)
this value can be get during run time. i.e., f or above constructor
int p,q;
cin>>p>>q;
integer a(p,q);

61)Define Inline Function?


Inline function is defined as a function definition such that each call to the function is in effect,
replaced by the statements that define the function. It is expanded in line when it is invoked. The
general form is
inline function-header
{
function body
}

62)Explain return by reference with an example.


A function can also return a reference. Consider the following function
int &max( int &x , int &y)
{ if(x>y)
return x;
else
return y;
}
Since the return type of max ( ) is int & the function returns reference to x or y (and not the values).
Then a function call such as max ( a , b) will yield a reference to either a or b depending on their
values.
The statement
max ( a , b) = -1;
is legal and assigns –1 to a if it is larger, otherwise –1 to b.

63) What is operator overloading?


C++ has the ability to provide the operators with a special meaning for a data type. This mechanism
of giving such special meanings to an operator is known as Operator overloading. It provides a
flexible option for the creation of new definitions for C++ operators.

64) List out the operators that cannot be overloaded.


• Class member access operator (. , .*)
• Scope resolution operator (::)
• Size operator ( sizeof )
• Conditional operator (?:)

65) What is the purpose of using operator function? Write its syntax.
To define an additional task to an operator, we must specify what it means in relation to the class to
which the operator is applied. This is done by Operator function , which describes the task.
Operator functions are either member functions or friend functions. The general form is
return type classname :: operator (op-arglist )
{
function body
}
where return type is the type of value returned by specified operation.
Op- operator being overloaded. The op is preceded by a keyword operator. operator op is
the function name.

66) Write at least four rules for Operator overloading.


• Only the existing operators can be overloaded.
• The overloaded operator must have at least one operand that is of user defined data type.
• The basic meaning of the operator should not be changed.
• Overloaded operators follow the syntax rules of the original operators. They cannot be overridden.
67) How will you overload Unary & Binary operator using member functions?
When unary operators are overloaded using member functions it takes no explicit arguments and
return no explicit values. When binary operators are overloaded using member functions, it takes
one explicit argument. Also the left hand side operand must be an object of the relevant class.
68) How will you overload Unary and Binary operator using Friend functions?
When unary operators are overloaded using friend function, it takes one reference argument (object
of the relevant class) When binary operators are overloaded using friend function, it takes two
explicit
arguments.

69) How an overloaded operator can be invoked using member functions?


In case of Unary operators, overloaded operator can be invoked as op object_name or object_name
op
In case of binary operators, it would be invoked as Object .operator op(y)
where op is the overloaded operator and y is the argument.

70) How an overloaded operator can be invoked using Friend functions?


In case of unary operators, overloaded operator can be invoked as Operator op (x);
In case of binary operators, overloaded operator can be invoked as Operator op (x , y)

71) List out the operators that cannot be overloaded using Friend function.
• Assignment operator =
• Function call operator ( )
• Subscripting operator [ ]
• Class member access operator

72) Explain basic to class type conversion with an example.


Conversion from basic data type to class type can be done in destination class.
Using constructors does it. Constructor takes a single argument whose type is to be converted.
Eg: Converting int type to class type
class time
{
int hrs,mins;
public:
………….
Time ( int t) //constructor
{
hours= t/60 ; //t in minutes
mins =t % 60;
}
};
Constructor will be called automatically while creating objects so that this conversion is done
automatically.

73) Explain class to basic type conversion with an example.


Using Type Casting operator, conversion from class to basic type conversion can be done. It is done
in the source class itself.
Eg: vector : : operator double( )
{
double sum=0;
for(int I=0;I<size;I++)
sum=sum+v[ i ] *u[ i ] ;
return sqrt ( sum ) ;
}
This function converts a vector to the corresponding scalar magnitude.

74) Explain one class to another class conversion with an example.


Conversion from one class type to another is the combination of class to basic and basic to class
type conversion. Here constructor is used in destination class and casting operator function is used
in source class.

Eg: objX = objY

objX is the object of class X and objY is an object of class Y. The class Y type data is converted
into class X type data and the converted value is assigned to the obj X. Here class Y is the source
class and class X is the destination class.

75) What are Exceptions?


Exceptions which occur during the program execution, due to some fault in the input data

76) What are the two types of exceptions?


Exceptions are classifieds into
a)Synchronous exception
b) Asynchronous exception

77) What is a synchronous exception?


The technique that is not suitable to handle the current class of data, within the program are
known as synchronous exception

78) What is an Asynchronous exception?


The exceptions caused by events or faults unrelated to the program and beyond the control
of program are called asynchronous exceptions
79) What are the blocks used in the Exception Handling?
The exception-handling mechanism uses three blocks
1)try block
2)throw block
3)catch block
The try-block must be followed immediately by a handler,which is a catch-block.
If an exception is thrown in the try-block

80) Draw the Exception handling model?

Perform operation which may

Invoke function having throw block

except

exception

Catches all exceptions thrown


from within try block or by
function invoked within a try

81) Write the syntax of try construct


The try keyword defines a boundary within which an exception can occur.A block of code
in which an exception can occur must be prefixed by the keyword try.Following the try keyword is
a block of code enclosed by braces.This indicates that the program is prepared to test for the
existence of exceptions
try
{
//code raising exception or referring to a function raising exception
}
catch(type_id1)
{
//actions for handling an exception
}


catch(type_idn)
{
//actions for handling an exception
}

82) Write the syntax of catch construct


The exception handler is indicated by the catch keyword.It must be used immediately after
the statements marked by the try keyword.The catch handler can also occur immediately after
another catch.Each handler will only evaluate an exception that matches,or can be covered to the
type specified in its argument list.

K object name or
Catch(T) nameless object
{
// actions for handling an exception
}

83) Write the syntax of throw construct


The keyword throw is used to raise an exception when an error is generated in the
computation.The throw expression initializes a temporary object of the type T(to match the type of
argyment arg)used in throw(T arg)

Named object, nameless


K object
84) List out the tasks to be performed for error handling code
1)Detect the problem causing exception(Hit the
exception) 2)Inform that an error has occurred(Throw the
exception) 3)Receive the error information(Catch the
exception) 4)Take corrective actions(Handle the
exceptions)
85) Write the steps to be performed when an exception is raised
1) The program searches for a matching handler
2) If a handler is found, the stack is unwound to that
point 3)Program control is transferred to the handler
4)If no handler is found, the program will invoke the terminate()function. If no exceptions
are thrown, the program executes in the normal fashion

86) Write the syntax of catch all construct

Three dots:indicate catch allexceptions

Catch(…)
{
//actions for handling an exception
}

87) List out some of the error handling functions


a) eof()-Returns true if end-of-file is encountered
b) fail()-Returns true when an input or output operation has failed
c) bad()-Returns true if invalid operation is attempted by or any uncoverable error has
occurred
d) good()-Returns true if no error has occurred
88) What are the two types of errors or bugs?
a) Logical errors-errors occur due to poor understanding of the problem and
solution procedure
b) Syntatic errors-errors that arise due to poor understanding of the language itself.

89)What is class template?


Classes can also be declared to operate on different data types. Such classes are called class
templates. A class template specifies how individual classes can be constructed similar to normal
class specification
90)Write the syntax of class template

template<class T1,class T2,…>


class classname
{
T1 data1;
….
//functions of template arguments T1,T2,….
void func1(T1 a,T2 &b);

T func2(T2 *x,T2 *y);
};

91) What is meant by inheritance?


Inheritance is the process by which objects of one class acquire the properties of another class. It
supports the concept of hierarchical classification. It provides the idea of reusability. We can
add additional features to an existing class without modifying it by deriving a new class from it.

92)List the rules for inheritance


1) The default mode is private
2) Difficult to inherit the base class private members
3) The base class public and protected member functions are considered as public and
protected member functions in derived class,When those class is publicly inherited from base
class
4) The base class public and protected member functions are considered as private
member function in derived class,when those class is privately inherited from base class

93)List the class member’s visibility


There are three visibilities of class members.They are
i) Public visibility
ii)Private visibility
iii)Protected visibility

94) What is meant by single inheritance?


If a single class is derived from a single base class is called single inheritance.
Eg:
Base class
Derived class
Here class A is the base class from which the class D is derived. Class D is the public
derivation of class B hence it inherits all the public members of B. But D cannot access
private members of B.
95) What is multiple inheritance?
If a class is derived from more than one base class, it is called multiple inheritance.
Eg: Base classes
Derived class
Here class C is derived from two base classes A & B.

96) What is hierarchical inheritance?


If a number of classes are derived from a single base class then it is called
hierarchical inheritance.
Eg : Hierarchical classification of students in University
A
B
A
C
B

97) What is multilevel inheritance?


If a class is derived from a class, which in turn is derived from another class, is called multilevel
inheritance. This process can be extended to any number of levels.
Eg:
Base class Grand father
Intermediate
Base class Father
Derived class Child

98) What is hybrid inheritance?


It is the combination of one or more types of inheritance.
Multilevel
inheritance
Multiple
inheritance
The class result will have both the multilevel and multiple inheritances.

99) What is meant by Abstract base class?


A class that serves only as a base class from which derived classes are derived. No objects of an
abstract base class are created. A base class that contains pure virtual function is an abstract
base class.

100) Write short notes on virtual base class.


A base class that is qualified as virtual in the inheritance definition. In case of multiple inheritance,
if the base class is not virtual the derived class will inherit more than one copy of members of the
base class. For a virtual base class only one copy of members will be inherited regardless of number
of inheritance paths between base class and derived class.
Eg: Processing of students’ results. Assume that class sports derive the roll
number from class student. Class test is derived from class Student. Class result is
derived from class Test and sports. As a virtual base class

101)What are virtual functions?


A function qualified by the ‘virtual’ keyword is called virtual function. When a virtual function is
called through a pointer, class of the object pointed to determine which function definition will
be used.

102)Write some of the basic rules for virtual functions


• Virtual f unctions must be member of some class.
• They cannot be static members and they are accessed by using object pointers
• Virtual f unction in a base class must be defined.
• Prototypes of base class version of a virtual function and all the derived class versions must
be identical.
• If a virtual function is defined in the base class, it need not be redefined in the derived class.

103) What are pure virtual functions? Write the syntax.


A pure virtual function is a function declared in a base class that has no definition relative to the
base class. In such cases, the compiler requires each derived class to either define the function
or redeclare it as a pure virtual function. A class containing pure virtual functions cannot be
used to declare any object of its own. It is also known as “donothing” function.
The “do-nothing” function is defined as follows:
virtual void display ( ) =0;
104) What is polymorphism?
Polymorphism is the ability to take more than one form. An operation may exhibit
different behaviors in different. The behavior depends upon the type of data used.

105)What are the types of polymorphism?


Basic Types
i)Runtime polymorphism
ii)Compile time polymorphism

Major Types
a.Run-time polymorphism
b.Compile time polymorphism
c.ad-hoc polymorphism
d.Parametric polymorphism
e.Virtual functions
f.Function name overloading
g.Operator overloading
106)What is compile time polymorphism?
The overloaded member functions are selected for invoking by matching arguments both
type and number.This information is known to the compiler at the compile time and therefore
compiler is able to select the appropriate function for a particular call at the compile time itself.This
is called early binding or static binding or static linking.Also known as compile time polymorphism

107)What the types in compile time polymorphism?


a) Function overloading
b) Operator overloading
Upcasting means classes can easily converge to a general class

108) What are streams?


A Stream is a sequence of bytes. It can either as a source from which the input data can be
obtained or as a destination to which the output data can be sent
The stream source that provides data to the program is called the input stream and the
destination stream that receives output from the program is called output stream

109) What are the stream classes for console operations?


a)ios
b)istrean
c)ostream
d)iostream
e)streambuf

Throw
block
i
If(failure)
o
Throw object;
istream

Catch block
iostream
103) Draw the stream classes for hierarchy filebuf

ifstream fstream ofstream

streambuf ostream
fstreambas
e
104) What are the functions that the file stream class
provides? a)seekg()-Moves get pointer to a specified
location b)seekp()-Moves put pointer to a specified
location c)tellg()-Gives the current position of the get
pointer d)tellp()-Gives the current position of the put
pointer

105) What is a file?


A file is a collection of related information defined by its creator. Files represent programs
(both source and object forms) and data.Data may be numeric,alphabetic, or alphanumeric.Files
may be free-form,such as text files,or may be rigidly formatted.

106) List some of the file modes


1) ios::in
2)ios::out
3)ios::ate
4)ios::app
5)ios::trunk
6)ios::nocreate
7)ios::noreplace
8)ios::binary
Structure Of MST

Roll
No.

Date

Total No. of questions: Total no. of Pages:

COLLEGE
PROGRAM (DEPARTMENT) (Semester)
First Mid-Semester Examination
Subject:
Subject Code:
Time: 1.0 Hr. Max. Marks*: 24
INSTRUCTIONS TO CANDIDATES:
1. Section-A is compulsory consisting of four questions carrying two marks each.
2. Section-B contains three questions carrying four marks each and students have to attempt any two questions.
3. Section-C contains two carrying four marks each and students have to attempt any four questions.
Course Outcomes
CO…:

CO…:
CO…:
Bloom’s Taxonomy Levels
L1-Remembering L2-Understanding L3-Applying L4-Analysing L5-Evaluating L6-Creating
Section – A (4 questions × 2 marks = 8 marks)
(2) (CO...) Level of Q. based on Bloom’s taxonomy
1
.
(2) (CO...) Level of Q. based on Bloom’s taxonomy
2
.
(2) (CO...) Level of Q. based on Bloom’s taxonomy
3

4 (2) (CO...) Level of Q. based on Bloom’s taxonomy


.
Section – B (2 questions × 4 marks = 8 marks)
(4) (CO...) Level of Q. based on Bloom’s
taxonomy
5.

(4) (CO...) Level of Q. based on Bloom’s


taxonomy
6

(4) (CO...) Level of Q. based on Bloom’s


7. taxonomy

Section – C (2 questions × 8 marks = 8 marks)


(8) (CO...) Level of Q. based on Bloom’s
8. taxonomy

(8) (CO...) Level of Q. based on Bloom’s


taxonomy
9.
MST SAMPLE SHEETS
MINUTES OF MEETINGS
ASSIGNMENTS WITH CO MAPPING

COLLEGE
PROGRAM (DEPARTMENT) (Semester)

Assignment :1

Subject and Subject code: Object Oriented Programming using C++( UGCA 1909) Semester:2

Date on which assignment given: 4/02/2020 Date of submission of assignment:

Course Outcomess

Relevance
Assignment related to COs
to CO
No.
Q Write a program that generates the CO
1. following output 1
10
20
19
Q Use an integer constant for the 10 ,an CO
2. arithmetic assignment operator to 1
20,and a decremwnt operator to
generate the 19.
Q Explain the OOP’s.What are the basic features CO
3. of OOP’s. 1
Q Differentiate POP and OOP. CO
4. 1
SAMPLES OF CHECKED ASSIGNMENT SHEETS
EVALUATION SCHEME: TOTAL INTERNAL MARKS (SESSIONAL
MARKS+ ASSIGNMENT MARKS+ ATTENDANCE MARKS)

Evaluation for 2019-20: Total Internal Marks (Sessional marks: average of best two +
Assignment marks + Attendance marks)

Internal Record:- Section A……………..

Marks obtained by Marks obtained Marks Tot


the students in the by the students obtained by al
Sessionals in the the students Mar
ASSIGNMENT in ks
S ATTENDAN
CE
S R Avera Avera
NAM I I I I
. o ge ge of
E I I
N ll Two Two
o. N
o
1

.
.
.
.
STUDENTWISE INTERNAL ASSESMENT MARKS
CO ATTAINMENT OF THE COURSE
LIST OF ACADEMICALLY WEAK STUDENTS
ACTION TAKEN AND OUTCOME
HAND WRITTEN NOTES

C/C++ language provides the following user-defined data types (except classes that we will discuss
later in this book) which are actually a collection of primary or in-built data types.
1. The structure
2. The union
3. The bit-field
4. The enumeration
5. The typedef

STRUCTURE
Suppose we have to store the related information of a student such as name, rollno, address,
age, class, etc. One way is to take a variable each of an appropriate data type to represent above
data items. In such case, all the data items will be dealt independently despite the fact that all the
data items are related to the entity ‘student’. To represent such a relationship among different data
items, C provides an aggregate data type known as ‘structure’.
A structure is a collection of related data items held together in a single unit and is referenced
by a single name. The data items can be of different data types. The data items enclosed within a
structure are known as structure members or elements or fields.
A structure usually represents an entity of the real world. e.g. if we want to store details of a
student, we can use structure which wraps all the features of a student in a single unit.
structure studentsstructure
{
char name[10];
int age; data items of different data types
bundled int rollno; together as a single unit.
char address[50];

};
Such bundling of various data elements in an array is not possible.

Structure Declaration
A structure groups various variables into a single record. A structure declaration specifies the
grouping of variables of different types in a single unit. It acts as a template or blueprint that may
be used to create structure variables.
The syntax of declaring a structure in ‘C’ is
Keyword struct struct-name
{
datatype variablename1;
datatype variablename2; dataitems of different datatypes
.... .....
datatype variablename3;
};
The declaration begins with the keyword ‘struct’ following by the structure name or tag which
is user defined. Then comes the beginning of the body of the structure marked by ‘{‘.
Thereafter, take the data items and their data types to be wrapped inside the structure. Finally,
close the body of structure by a ‘}’.
A structure declaration do not allocate any memory space.
e.g. struct student
{
char name[20]
int age, rollno; data members of the
structure char address[40];
}; This declaration do not allocate any memory space to the structure ‘student’.

Structure Definition
Structure definition creates structure variables and allocates storage space for them. No storage
space is allocated at the time of structure declaration. All the structure members are allocated
contiguous space in the memory.
Structure variables can be defined in two ways. One way is just similar to any data variable
declaration. e.g. consider the declared structure ‘student’. To define the variables of the data type
structure ‘student’, the statement.

struct student sl; analogues to variable declaration in

int x;

Data Type variable declaration

data type
variable
creates one variable s1 of the type student and allocates memory to its members as
The figure depicts that all the members of structure are allocated required memory space in a
contiguous fashion. The total memory allocated to s1 will be the sum of memory needed by its
individual members. Thus, memory reserved for structure variable s1 is equal to 20 bytes for name,
2 bytes for age, 2 bytes for rollno and 40 bytes for address. Therefore, structure variable s1
consumes total of 64 bytes.
Similarly, we can define more than one structure variable by using comma (,) operator
as struct student s1, s2, s3;

data type variables declared


Second way of defining a structure variable is during structure declaration. e.g. consider the
structure definition
struct student
{
char name[20];
int age, rollno;
char address[40];
} s1, s2;
The above statements defines variables s1 and s2 of the type structure student.
As the structure declaration & definition is clubbed together at the same place, so the structure
tag name can be omitted as shown below:
struct
{
char name[20];
int age, rollno;
char address[40];
} s1, s2;

Accessing Structure Members


After defining the structure variables, the structure members can be accessed by using dot
operator (.). In the above example, the members of the structure student variable s1 can be accessed
by using a dot operator as
s1.name — will access the name of variable s1.
s1. age, s1. rollno, s1. address will access age, rollno and address of 81.
Similarly,
s2 name — will access the name of variable s2.
Let us consider a program in C to illustrate the use of dot operator to access structure members.

Consider the following program to print the data of two students


1. #include<iostream.h>
2. struct student /*structure declaration*/
3. {
4. char name[20];
5. int age, rollno;
6. };
7. void main( )
8. {
9. struct student s1, s2; /*structure variable definition*/
10. cout<<“\n Enter details of student 1 \n”;
11. cin>>s1.name>>s1.age>>s1.rollno;
12. cout<<“\n Enter details of student 2 \n”;
13. cin>>s2.name>>s2.age>>s2.rollno;
14. cout<<“\n Displaying details of students \n”;
15. cout<<“Student 1 —“<<s1.name<<s1.age<<s1.rollno;
16. cout<<“\n Student 2-“<<s2.name<<s2.age<<s2.rollno;
17. }
Output
Enter details of student 1
Amit 21 2051
Enter details of student 2
Varun 20 2059
Displaying details of students
Student 1 — Amit 21 2051
Student 2 — Varun 20 2059

Note:The struct student is declared before main, which makes it global and accessible to other
functions in the program.

Consider the following program to assign values to the members of the structure
1. #include<iostream.h>
2. struct student
3. {
4. char name[20];
5. int age, rollno;
6. }s1;
7. void main( )
8. {
9. s1. name = “Amit”;
10. s1. age = 21
11. s1. rollno = 2051;
12. cout<<“Details of student 1:”;
13. cout<<s1.name<<s1.age<<s1.rollno;
14. }
Output
Details of student 1: Amit 21 2051

Structure Initialization
The structure variables can be initialized at the time of its definition. The values to be assigned
to the members of structure variable are written within the braces and should appear in the same
order as the order of the declared members of the structure.
Let us consider an example of book structure declared as
struct book
{
char name[20];
char author[20];
int no_pages;
};
The struct variable can be defined and initialized as
struct book b1 = {“Graphics”, “ABCD”, 460};
The above statement initializes the values to structure variable b1 as b1. name = Graphics, b1.
author = ABCD, no.pages = 460

Consider the following program to demonstrate initialization of structure variables & various
operators:
1. #include<iostream.h>
2. struct book
3. {
4. char name[20];
5. char author[20];
6. int no.pages;
7. };
8. void main( )
9. {
10. struct book b1 = {“C Programming”, “Robert”, 460);
11. struct book b2 = {“Graphics”, “ABCD”, 490};
12. struct book b3;

13. cout<<“\nB1:Name=”<<b1.name<<”Author=”<<b1.author<<”Pages=”
<<b1.pages;
14. cout<<“\nB2:Name=”<<b2.name<<”Author=”<<b2.author<<”Pages=”
<<b2.pages;
15. b3 = b2; /*Assignment Operator*/
16. cout<<“\nB3:Name=”<<b3.name<<”Author=”<<b3.author<<”Pages =”<<b3.pages;
17. if(b1. no.pages > b2. no.pages)
18. cout<<“\n Pages in B1 are more”;
19. else if (b1. no.pages = = b2. no.pages)
20. cout<<“\n Pages in B1 and B2 are equal”;
21. else
22. cout<<“\n Pages in B2 are more”;
23. }
Output
B1: Name = C Programming, Author = Robert, Pages = 460
B2: Name = Graphics, Author = ABCD, Pages = 490
B3: Name = C Programming, Author = Robert, Pages = 460
Pages in B2 are more

NESTING OF STRUCTURE
Nesting means one insider another. If a structure is taken as a member of another structure,
then this is known as nesting of structures.
Let us consider an example of employee structure. The members of employee structure are
empid, empdept and empdoj [Date of joining] empid is of int type, empdept is a string and empdoj
is a structure date type. Thus, a structure employee enclosing another structure ‘date’ as its member
is known as nesting of structures.
struct employee struct date
{ {
int empid; int dd;
char empdept[20]; int mm;
struct date empdoj; int yy;
} e1; };
It is important to note that the structure (inner) which is a member of some other structure must
be declared before it is used. Further, there is no limit to nesting of structures and can be to any
depth.
Another way of declaring a nested structure is
as struct employee — Outer structure
{
int empid;
char empdept[20];
struct date — Inner structure
{
int dd;
int mm;
int yy;
} empdoj;
}el;
The inner structure ‘date’ is declared and defined inside the declaration of structure
‘employee’.

Accessing of Nested Members


In order to access the inner structure member, add another dot operator (.) to access inner
members. e.g.
employee el.empdoj
dd mm yy
Thus, if we want to access month of joining of employee e1, use
e1. emploj .mm
extra dot operator
Memory allocation of e1 will be as

Thus, e1 will consume 28 bytes of memory.


Note:As the level of nesting increases, the number of dot operators also increase accordingly. For
one level of nesting, 2 dot operators are used, for 2 levels of nesting, 3 dot operators are used to
access members of innermost structure and so on.
Consider the following program to demonstrate nested structures
1. struct date
2. {
3. int dd;
4. int mm;
5. int
yy; 6. };
7. struct employee
8. {
9. int empid;
10. char empdept[20];
11. struct date empdoj;
12. };
13. void main( )
14. {
15. struct employee e1;

16. cout<<“\n Enter employee details:”;


17. cin>>e1.empid>>e1. Empdept>>e1. empdoj.dd>>e1.empdoj.mm>>e1.empdoj.yy;
18. cout<<“\n Details of employees are”;
19. cout<<e1.empid<<e1.empdept<<e1. empdoj.dd<< e1.emoloj.mm<< e1.empdoj.yy;

20. }
Output
Enter employee details
141 Purchase Dept 15 03 2008
Details of employees are : 141 Purchase Dept 15:03:2008
Structure and Array
Structures and arrays can be used together in two way : Array of structures and structure
containing array.
1. Structure Containing Array
2. Array of Structures

Structure Containing Array


Structure containing array means some members of a structure is a collection of values of some
type e.g. consider an example of a structure ‘student’ storing marks of 5 subjects of a student. It can
be represented as
struct student
{
int rollno;
int marks[5]; /*Array of 5 integers*/
float percent;
}s1;
The individual marks can be accessed as
s1. marks[0], s1. marks[1], s1. marks[2] and so on.
Memory representation is as in the figure

Consider the following program to demonstrate structure containing array


1. #include<iostream.h>
2. struct student
3. {
4. int rollno;
5. int marks[5];
6. float percent;
7. };
8. void main( )
9. {
10. int i, total =0;
11. struct student s1;
12. cout<<“Enter student details \n”;
13. cout<<“\n Enter rollno :”;
14. cin>>%d”, & s1. rollno);
15. cout<<“\n Enter marks in 5 subjects”;
16. for(i = 0; i < 5; i ++)
17. cin>>s1.marks[i];
18. for(i = 0; i < 5; i ++)
19. total = total + s1. marks[i];
20. s1. percent = total / 5;
21. cout<<“Percentage of student = “<<s1. percent;
22. getch();
23. }
Output
Enter student details
Enter rollno : 529
Enter marks in 5 subjects 70 71 60 75 70
Percentage of student = 69.2

Array of Structure
An array of structure refers to an array in which each element is a structure. As an array of 5
integers is a collection of 5 integer values, similarly, an array of 5 students [structure] is a collection
of details of 5 student structure type. Consider an example of student structure:
struct student
{
int rollno;
char name[20];
float percent;
}
Suppose one want to store details of 10 students, create an array of student structure with 10
index instead of declaring 10 separate variables of student structure like s1, s2, s3, ... s10. Handling
10 students with array of structure will be very convenient as compared to handling 10 separate
variables s1, s2, ..., s10.
The definition of such an array will
be student s[10];
data type array of 10 elements of type student.
s[0] will refer to student1
s[0]. rollno — rollno of student 1
s[0]. name — name of student 1
s[0]. percent — percent of student 1
s[1] will refer to student 2
s[1]. rollno — rollno of student 2
s[1]. name — name of student 2
s[1]. percent — percent of student 2
and so on.
Memory representation is contiguous as in the case of array of basic data types. e.g. student
s[10] occupies contiguous memory for all elements as follows:

Consider the following program to demonstrate array of structures


1. #include<iostream.h>
2. struct student
3. {
4. int rollno;
5. char name[20];
6. float percent;
7. };
8. void main( )
9. {
10. struct student s[10];
11. int i;
12. cout<<“\n Enter student details \n”;
13. for(i = 0; i < 10; i ++)
14. {
15. cout<<“Enter rollno, name and percentage”;
16. cin>>s[i].rollno>>s[i].name>>s[i].percent;
17. }
18. cout<<“\n Entered details are”;
19. for(i = 0; i < 10; i ++)
20. cout<<“\n Name: “<<s[i].name<<” Rollno: ”<<s[i].rollno<<” Percent: ”
<<s[i].percent;

21. }

Initializing Array of Structure


An array of structure can be initialized by placing values in curly braces. Consider an example:
struct employee
{
int empid;
char empnamep[20];
char empdept[20];
};

employee e[3] = {500, “Amit”, “Purchase”, 5002, “Varun”,


“Marketing”, 5003, “Rahul”, “Computer”
};
Here, e is an array of 3 elements. The values of each element is initialized according to
required data types.
e[0] — empid = 5001, empname = Amit, empdept = “Purchase”
e[1] — epid = 5002, empname = Varun, empdept = Marketing
e[2] — empid = 5003, empname = Rahul, empdept = Computer

STRUCTURES AND POINTERS


Since pointer is a variable that stores address, it can be used to store the address of a structure
variable. Ampersand (&) operator is used to store the address of a structure variable consider an
example:
struct date
{
int dd;
int mm;
int yy;
};

struct date dt, *ptr;


ptr=& dt;/*ptr stores address of the structure variable dt;
i.e. 5001*

In this example, a structure date contains members dd, mm, yy. ‘dt’ is a structure variable and
ptr is a pointer variable that points to any variable of the type struct date. Finally, ptr stores the
starting address of ‘dt’ variable. The statement.
ptr = & dt;
assigns the address of structure variable dt to the pointer variable ptr by using & operator.
To access the structure members through a pointer variable, 2 operators are used: dot operator
(.) and operator.

Using dot Operator


To access any member of a structure, use *ptr followed by a dot operator followed by member
name.
(*ptr).membername
( ) is used since precedence of .is higher than *operator.
*ptr .membername is wrong
eg. (*ptr) .dd — refers to dd of dt
(*ptr) .mm — refers to mm of dt
(*ptr) .yy — refers to yy of dt
operator: is used to access structure memebr through a pointer variable as
ptr membername
e.g.

ptr refers to dd of dt
ptr mm refers to mm of dt

ptr refers to yy of dt

Consider the following program to demonstrate use of pointer to a structure


1. #include<iostream.h>
2. struct date
3. {
4. int dd;
5. int mm;
6. int
yy;
7. };
8. void main( )
9. {
10. struct date dt, *ptr;
11. ptr = & dt;
12. cout<<“Enter date:”;
13. cin>>ptr dd>>ptr mm>>ptr yy;
14. cout<<“\n Enter date is”);
15. cout<<ptr dd<<ptr mm<<ptr yy;
16. }
Output
Enter date : 15 11 2010
Entered date is 15-11-2010

13.5 STRUCTURES AS FUNCTION ARGUMENTS


We can pass individual structure members to a function or an entire structure variables.
When an individual structure member is passed to a function as an argument, it behaves in the
same manner when any of the basic data type variable is passed to a function as an argument.

Consider the following program to demonstrate passing structure member as an argument to a


function
1. #include<iostream.h>

2. struct student
3. {
4. char name[20];
5. int rollno;
6. int total;
7. };
8. int incr(int, int);
9. void main( )
10. {
11. int x;
12. struct student s = {“Amit”, 100, 530};

13. cout<<“\n Before function call, name =“<<s.name<<”rollno =<<s.rollno


<< “total =”<< s. total;
14. x = incr(s. rollno, s. total); /*function call*/
15. cout<<“After function call, rollno = “<<r.rollno<<” total = ”<<x;

16. }
17. int incr(int r, int t)
18. {
19. r = r+ 10;
20. t = t+20;
21. cout<<“In function, rollno = “<<r<<” total = “<< t;
22. return(t);
23. }
Output
Before function call, name = Amit, rollno=100, total = 530
In function, rollno = 110, total = 550
After function call, rollno = 100, total = 550

Here, the structure members, rollno and total, are passed to the function as arguments. It works
like pass by value where changes made in function are visible to the called part only if some value
is returned.
The entire structure can also be passed as an argument to a function. It will work similar to the
way as an array is passed to a function. The entire structure can be passed as pass by reference to
the function.

Consider the following program to demonstrate passing entire structure to function


1. #include<iostream.h>
2. struct book
3. {
4. char name[20];
5. int pages;
6. float price;
7. };
8. void display (struct book*);
9. main( )
10. {
11. struct book b = {“C Programming”, 340, 275};

12. cout<<“Before function call”<<b.name<<b.pages<< b.price;


13. display(&b);
14. cout<<“After function call ”<< b.name<<b.pages<< b.price;

15. }
16. void display(struct book *ptr)
17. {
18. ptr name = “Graphics”;
19. ptr pages = 460;
20. ptr price = 450;
21. cout<<“In function:”<< ptr name<<ptr pages<< ptr price;
22. }
Output
Before function call: C Programming, 340 247.00
In function: Graphics, 460, 450.00
RETURNING STRUCTURES FROM FUNCTION
Besides returning basic data types, functions can also return a structure through return
statement. Although any number of structure variables can be passed to a function as arguments,
but only one structure variable can be returned through return statement.

Consider the following program to demonstrate functions returning structure


1. #include<iostream.h>
2. struct student
3. {
4. int rollno;
5. float percent;
6. } s1;
7. struct student incr(struct student *);
8. void main( )
9. {
10. struct studnet s ={25, 85.2};
11. s1 = incr(&s); /*Function returning structure*/
12. cout<<“\n Details of s1: RollNo:”<<s1.rollno<<” Percentage = ”<<s1.percent;
13. }
14. struct student incr(struct student *p)
15. {
16. struct student x;
17. x. rollno = p-> rollno + 1;
18. x. percent = p -> percent + 2.5;
19. return(x);
20. }
Output:
Details of s1: Rollno = 26, Percentage = 87.7
Consider another program, in which we are adding two heights represented in feet and inches:
1. #include<iostream.h>
2. struct height
3. {
4. int feet;
5. float inches;
6. };

7. void main()
8. {
9. height add(height,height);
10. height obj1,obj2,obj3;
11. cout<<"\n Enter two hiehgts ";
12. cin>>obj1.feet>>obj1.inches;
13. cin>>obj2.feet>>obj2.inches;
14. obj3=add(obj1,obj2);
15. cout<<endl<<obj3.feet<<"'"<<obj3.inches<<"\"";
16. }
17. height add(height obj1, height obj2)
18. {
19. height obj3;
20. obj3.feet=obj1.feet+obj2.feet;
21. obj3.inches=obj1.inches+obj2.inches;
22. return obj3;
23. }
- In line 14, we have called add function and sending obj1 and obj2 of type structure. After
adding the heights in line 22, we have returned obj3.
-

SELF-REFERENTIAL STRUCTURES
Self-Referential means referring to itself. Self referential structure is one in which one of the
structure member refers to the structure as one of the structure members is a pointer data type which
refers to the structure itself. Since the pointer points to the structure, so the data type of the pointer
is the structure
e.g. struct list
{
int x; A pointer in structure
struct list *ptr; pointing to the structure
itself
};
Such type of self-referential structures are used in the handling of data structures like linked
lists, trees and graphs.

UNIONS
Union is another user-defined data type that groups data items of different types in a single
unit. By definition, it seems similar to the structure but it is different from the structure.
Since all the members of a structure are allocated separate memory but the members of the
union share the same storage space. The total memory allocated to a union is the memory required
by such a member of union whose space requirement is the largest. Whereas, the memory allocation
to a structure is sum total of the requirements of all its members.
Declaration of a union is similar to that of a
structure. union a
(Keyword) (tag or name)
{
int x; /*members of the union a*/
float y;
char z;
};
Here, the total memory allocated to union a is 4 bytes since float requires largest memory.
The declaration begins with the keyword ‘union’ follow by the tag or name, x, y, z are the
members of the union.
After the declaration, variable definition allows to make use of the union
as: union a obj;
data type variable
The variable can also be defined at the end of the declaration as:
union a
{
int x;
float y;
char z;
} obj;
e.g. from ‘let us c’.

Accessing a Union Member


As with the structures, union members are also accessed by using a dot operator (.).

Consider the following program to demonstrate accessing of union members


1. #include<iostream.h>
2. union book
3. {
4. char name[20];
5. float price;
6. } b;
7. void main( )
8. {
9. cout<<“Enter book name”;
10. gets(b.name);
11. cout<<“Book name is”;
12. puts(b.name);
13. cout<<“Enter book price”;
14. cin>>b.price;
15. cout<<“\n Price of book = <<b.price;
16. }
Output
Enter book name C Programming
Book name is C Programming
Enter book price 325.50
Price of book = 325.50

Note: Observe that in case of union, only one member can be accessed at a time. Only after book
name is read & displayed, its price can be used as in above program.

Initializing a Union
Initialization of all the members of a union can not be done at one time because all the
members of union share same memory space. So, whenever a member of union is required,
initialize it at that time of usage. At a particular moment of time, the value contained by the union
members is the one assigned to any of its member most recently.

Consider the following program to demonstrate initialization of a union


1. #include<iostream.h>
2. union item
3. {
4. int x;
5. int y;
6. int z;
7. };
8. void main( )
9. {
10. union item obj;
11. obj. x = 10;
12. obj. y = 20;
13. obj.z = 50;
14. cout<<“x = %d”, ob.x;
15. cout<<“\n y = %d”, obj.y;
16. cout<<“\n z =%d”, obj.z;
17. }
Output
x = 50
y = 50
z = 50

Since memory space is shared, so the value assigned in the last will be contained in all
members.
13.9 DIFFERENCES BETWEEN A STRUCTURE AND A UNION

Structure Union

1. It is a collection of data items of different It is a collection of data items of different types


types in a single unit and memory required in a single unit and memory required is same as
by a structure is sum total of the space of the member with largest memory
requirement of all the members. requirement.

2. Syntax of declaration is Syntax of declaration is


struct tag name union tag name
{ {

data type member1 data type member1


data type member2 data type member2

data type memberx data type memberx


}; };
e.g. struct item e.g. union item
{ {
int x; int x;
float y; float y;
char z; char z;
}; };
Here, memory required is 2+4+1 = 7 bytes Here, memory required is same as of largest
member requirement i.e. 4 bytes.
3. Values assigned to all the members are Value assigned recently is available for use at any
preserved at all the times. time and other values are not preserved.
4. For example: For example:
#include<iostream.h> #include<iostream.h>

struct AB union AB
{ {
int a; int a;
float b; float b;
}; };
void main( ) void main( )
{ {
struct AB t; union AB t;

t.a = 4; t.a = 4;

t.b = 3.9; t.b = 3.9;


cout<<t.a<<endl<<t.b; cout<<t.a<<endl<<t.b);
} }
Output: Output:
4 8126
3.900000 3.900000
where 8126 is a garbage value.

typedef
It is an operator that allows users to define new data types which are equivalent to existing data
types. Thereafter, new variables can be declared in terms of new data type.
Syntax: Keyword Built in data type User-defined data
type typedef int Integer
Hereafter, one can use ‘Integer’ in place of the data type name int. In other words, typedef is
used to change the name of existing datatype. eg.
1. #include<iostream.h>
2. typedef int integer;
3. void main( )
4. {
5. integer x;
6. cin>x;
7. cout<<“\n x =”, x);
8. }
Output
5
x=5
Similarly, we can rename any structure using typedef
struct student
{
int rollno, age
char name[20];
}; typedef struct student STUD;

Now, from this point onwards, we can use ‘STUD’ in placeof ‘struct student’ in the program.
The program below shows the use of typedef. In this program, name of int datatype, float
datatype and char datatypes are changed using typedef.
1. #include<iostream.h>
2. typedef int AB;
3. typedef float CD;
4. typedef char EF;
5. void main( )
6. {
7. AB a;
8. CD b;
9. EF c;
10. a = 4;
11. b = 2.47;
12. c = ‘Z’;
13. cout<<“Integer =”<<a;
14. cout<<“\nCharacter =”<<c;
15. cout<<“Floating Point Number = %f”<<b;
16. }
In the above program AB represents int datatype, CD represents float datatype, EF represents
character datatype. The output of above program is:
Integer = 4
Character = Z
Floating Point Number = 2.470000

3.11 DIFFERENCE BETWEEN ARRAYS AND STRUCTURES


Arrays Structures
1. In arrays, all the elements should have Elements of structure may not have same

same datatype. datatype.


2. Square brackets[ ] are used for creation Keyword struct is used for creating a structure
of an array.

3. Syntax of array is
datatype arrayname[size]; Syntax of structure is:
struct structurename
{

element1;
element2;
.
.
.
elementn;
};
4. For example: For example:
/*Program using array*/ /*Program using structure*/
#include<iostream.h> #include<iostream.h>

void main( ) struct AB


{ {
int a[3],i; int a;
float b;
cout<<“Enter elements in an };
array”;
for(i = 0; i < 3; i ++) void main( )

{ {
cin>>a[i]; struct AB t;
}
cout<<“Ements of array are: cout<<“Enter elements in a
\n”; structure”;
for(i = 0; i < 3; i + +) cin>>t.a>>t.b;
{ cout<<“Elements of structure :
cout<<“%d \n”, a[i]; \n”);
} cout<<t.a<<t.b);

} }
Output: Output:
Enter elements in an array 10 Enter elements in a structure 4
20 3.9
15

Elements of array are : Elements of structure :


10 4
20 3.900000
15
6. Structure may have bit-fields Structure may have bit-fields

ENUMERATION
Enumeration is a user defined datatype which is used to specify constant integer values starting
from 0, 1, 2, 3, ... etc. Enumeration is supported by all C-compilers. Enumeration datatypes are also
available in other high level langauges such as C++, Pascal, Ada etc. An enumeration datatype is a
set of values represented by identifiers called enumeration constants. Keyword enum is used for
making enumeration datatype. The syntax of creating enumeration is:
enum enumerationame
{
element1, element2, element3, - - -
};

Consider the following program using enumeration:


1. #include<iostream.h>
2. enum Day
3. {
4. Monday, Tuesday,Wednesday, Thursday, Friday, Saturday, Sunday
5. };
6. void main( )
7. {
8. enum Day a, b, c, d, e, f, g;
9. a = Monday;
10. b = Tuesday;
11. c = Wednesday;
12. d = Thursday;
13. e = Friday;
14. f = Saturday;
15. g = Sunday;
16. cout<<“\na =”<<a;
17. cout<<“\nb =”<<b;
18. cout<<“\nc =”<<c;
19. cout<<“\nd =”<<d;
20. cout<<“\ne =”<<e;
21. cout<<“\nf =”<<f;
22. cout<<“\ng =”<<g;
23. }
Output
a=0
b=1
c=2
d=3
e=4
f=5
g=6

Note:The elements of enumeration are assigned integers values automatically starting from 0, 1, 2,
... etc. But if any value is assigned to an element of enumeration, then that element have assigned
value whereas next element have value 1 more than assigned value. For example:
(i) enum Day
{
Monday,Tuesday=5,Wednesday,Thursday=20,Friday,Saturday, Sunday
};
The C-compiler assigns the values to elements of enumeration as
Monday = 0
Tuesday = 5

Wednesday = 6
Thursday = 20
Friday = 21
Saturday = 22
Sunday = 23
(ii) One can also assign negative integer values to the constants of enumeration. For
example: enume Day
{
Monday, Tuesday=-2,Wednesday,Thursday,Friday,Saturday,Sunday
};
The C-compiler assigns the values to elements of enumeration as
Monday = 0
Tuesday = - 2
Wednesday = -1
Thursday = 0

Friday = 1
Saturday = 2
Sunday = 3

BIT FIELDS
A bit field is a user defined datatype which is used to divide the 16 bits of an integer in
different parts. The bit fields can be either integer or the unsigned integer type of variables only. A
bit field is a special type of structure member in which several bit fields can be packed into int. The
bit fields can be declared only as the members of a structure. The formal declaration of a bit field is
same as the declaration of a structure but there is a difference in accessing and using a bit field in a
structure. The number of bits required by a variable must be specified and followed by a colon(:)
while declaring a bit field. It may be noted that the total sum of bit fields can be 16 because int
takes 16 bits of memory. The bit fields can be signed or unsigned integer from 1 to 16 bits in length.
The syntax for bit field is
struct structurename
{
datatype element1 : number of bits;
datatype element2 : number of bits
.

.
};
It may be noted that the sum of number of bits can minimum and maximum 16. For example:
struct Date
int d : 6; /*d is of 6 bits*/
int m : 4; /*m is 4 bits*/
int y : 6; /*y is of 6 bits*/
};

The memory allocation of above bit field is shown below:

Consider the following program - Enter and display date using bit field
1. #include<iostream.h>
2. struct Date
3. {
4. int d : 6;
5. int m : 4;
6. int y :
6 7. };
8. void main( )
9. {
10. struct Date t;
11. cout<<“Enter day”;
12. cin>>t.d;
13. cout<<“Enter month”;
14. cin>>t.m;
15. cout<<“Enter year”;
16. cin>>t.y;
17. cout<<“Date = ”<<t.d<<”-“<<t.m<<”-“<<t.y);

18. }
Output
Enter day 11
Enter month 6
Enter year 10
Date = 11-6-10
The “object approach”, which is the fundamental idea in the conception of C++programs, consists
of building the program as an interaction between objects:
1. In all part of the program that use a given object, it is defined by themethods you can use on it ;
2. You can take an existing object type (called a class) and add to it dataand methods to manipulate
it.
The gains of such an approach are:
1. Modularity: each object has a clear semantic (Employer or DrawingDevice),a clear set of
methods (getSalary(), getAge(), or drawLine(), drawCircle().
2. Less bugs: the data are accessed through the methods and you can usethem only the way to
object’s creator wants you to.
3. Reutilisability: you can extend an existing object, or you can build a newone which could be used
in place of the first one, as long as it has all themethods required (for example the Employer could
be either the CEO ora worker, both of them having the required methods but different
dataassociated to them, Drawing Device could either be a window, a printer,or anything else).

Classes and structures


Structures used in the C language can only declare the data members, but not the member
functions. Aclass is syntactically similar to a structin the C, except that we cannot declare
member functions in struct. But the relationship between aclass and a struct is far closer in
C++ than you may at first think. In C++, the role of the structurewas expanded, making it an
alternative way to specify a class. The onlydifference between a class and a struct is that by
default all members are public in astruct and private in a class. In all other respects, structures
and classes are equivalent.That is, in C++, a structure defines a class type.
Consider the example of employee class, mentioned above using the keyword struct:

1. struct
employee 2. {
3. private :
4. int emp_id;
5. float salary;
6. char name[20];
7. public :
8. void getdata()
9. {
10. cout<<” Enter employee’s id”;
11. cin>>emp_id;
12. cout<<” Enter employee’s name”;
13. cin>>name;
14. cout<<” Enter employee’s salary”;
15. cin>>salary;
16. }
17. void showdata()
18. {
19. cout<<” Enter employee’s id ”<<emp_id;
20. cout<<” Enter employee’s name”<<name;
21. cout<<” Enter employee’s salary”<<salary;
22. }
23. };
24. void main()
25. {
26. employee obj1,obj2;
27. obj1.getdata();
28. obj2.getdata();
29. obj1.showdata();
30. obj2.showdata();
31. }

- Here, we have changed the keyword to struct from the class but there is no change in the
output of the program. So, struct keyword also defines a class type which satisfies all the
properties of oop, except that if access specifier is not mentioned then by default members
remain public and which hardly matters. We can consider struct keyword equivalent to class
for defining a class type.
- Now, if struct and class both keywords are near about equivalent then, why C++
contains both?
o It is the step to increase the capabilities of struct by letting them
to include member function with data variables.
o It is easy to upgrade the program written in C to C++.
- Most of the programmers (using C++) use keyword class for declaring a class and struct
for declaring structure as in C. And this approach is comparatively good rather than using
class and struct interchangeably to declaring a class type.

Classes and Union

We can also use union keyword to declare a class type. It means union may contain data member
and member functions both. But we will find lot of difference in the properties of instances of class
type declared using union keyword.
- All the data elements share the same memory location.
- Like the structure, union members are public by default.
- uniondo not supports the concept of inheritance. Union cannot inherit any other classes
of any type and cannot be a base class.
- A union cannot have virtual member functions (will discuss later).
- No static variables can be members of a union.
- No object can be a member of a union if the object has an explicit constructor or
destructor function

1. #include<iostream.h>
2. #include<conio.h>
3. union demo
4. {
5. private :
6. int i;
7. float f;
8. char c;
9. public :
10. void setdata()
11. {
12. i=100;
13. c='a';
14. f=100.99;
15. }
16. void showdata()
17. {
18. cout<<"\n i= "<<i;
19. cout<<"\n c= "<<c;
20. cout<<"\n f= "<<f;
21. }
22. };
23. void main()
24. {
25. demo d1;
26. d1.setdata();
27. d1.showdata();
28. getch();
29. }
Output :
i= -1311
c= ß
f= 100.989998
- In the above example, we have declared a class demo using keyword union. So when we
create d1, object of demo in line 25, it gets the memory for the data member which
requires more bytes. It means d1will get 4 bytes of memory space for float f and all the
data members will share the same memory location.
- Now in setdata() member function, we have assigned following
values : i=100;
c='a';
f=100.99;
But the output is :
i= -1311

c= ß
f= 100.989998
Reason being, i, c, and f will share 4 bytes (32bits) of memory space and when we
assign ‘a’ to variable c, it will overwrite the bits which holds the value of i i.e 100.
Similarly, when we assign 100.99 to f, it will also overwrite the previous values. Hence we
will get incorrect values of i and c, whereas f will hold correct value. It means the data
member assigned with a value, after other data members will hold the correct value.

Defining inline functions within a Class


We had already discussed inline functions as short functions declared using the keyword inline.
When we call the inline function, the cursor does not jump to the start of the function, but the
calling statement is replaced by the code of function. We can declare inline function as member
function of a class. If we define a short function within a class declaration, it will be automatically
convertedto inlinefunction (if possible) by the compiler. It is not necessary to precede its
declarationwith the inline keyword. Consider the following program :
1. #include<iostream.h>
2. #include<conio.h>
3. class Demo
4. {
5. int a, b;
6. public:
7. void setdata(int x, int y)// automatic inline
function 8. {
9. a=x;
10. b=y;
11. }
12. void showdata()
13. {
14. cout << a << " " << b << "\n";
15. }
16. };
17. void main()
18. {
19. Demo d1;
20. d1.setdata(10, 20);
21. d1.showdata();
22. getch();
23. }
- In the above program, the setdata() member function initializes, the data members, with the
values send to the function as arguments. The time required for executing two assignment
operations ( line no. 9 and 10) are very less compare to the overhead of function call. So
the compiler will automatically make it inline member function.
- In general, the I/O statements take more time as compare to the overhead of control
transfer due to function call. So the compiler will not implicitly make showdata() inline
member function.
- However, we can explicitly define showdata() as inline functions as show below.
1. #include<iostream.h>
2. #include<conio.h>
3. class Demo
4. {
5. int a, b;
6. public:
7. void setdata(int x, int y) // automatic inline
function 8. {
9. a=x;
10. b=y;
11. }
12. inline void showdata();
13. };
14. inline void demo :: showdata();
15. {
16. cout << a << " " << b << "\n";
17. }
18. void main()
19. {
20. Demo d1;
21. d1.setdata(10, 20);
22. d1.showdata();
23. getch();
24. }

- Remember, it depends upon the optimization algorithms used in the design of the
compiler, that whether or not to make any function inline implicitly

Files and Streams


Why Use Files?
All the programs we have looked at so far use input only from the keyboard, and output only to the
screen. If we were restricted to use only the keyboard and screen as input and output devices, it
would be difficult to handle large amounts of input data, and output data would always be lost as
soon as we turned the computer off. To avoid these problems, we can store data in some secondary
storage device, usually magnetic tapes or discs. Data can be created by one program, stored on
these devices, and then accessed or modified by other programs when necessary. To achieve this,
the data is packaged up on the storage devices as data structures called files.
The easiest way to think about a file is as a linear sequence of characters. In a simplifed picture
(which ignores special characters for text formatting) these lecture notes might be stored in a file
called "Lecture_4" as:

Figure 4.1.1
Streams
Before we can work with files in C++, we need to become acquainted with the notion of a stream.
We can think of a stream as a channel or conduit on which data is passed from senders to receivers.
As far as the programs we will use are concerned, streams allow travel in only one direction. Data
can be sent out from the program on an output stream, or received into the program on an input
stream. For example, at the start of a program, the standard input stream "cin" is connected to the
keyboard and the standard output stream "cout" is connected to the screen.
In fact, input and output streams such as "cin" and "cout" are examples of (stream) objects. So
learning about streams is a good way to introduce some of the syntax and ideas behind the object-
oriented part of C++. The header file which lists the operations on streams both to and from files is
called "fstream.h". We will therefore assume that the program fragments discussed below are
embedded in programs containing the "include" statement
#include<fstream.h>
As we shall see, the essential characteristic of stream processing is that data elements must be sent
to or received from a stream one at a time, i.e. in serial fashion.

Creating Streams
Before we can use an input or output stream in a program, we must "create" it. Statements to create
streams look like variable declarations, and are usually placed at the top of programs or function
implementations along with the variable declarations. So for example the statements
ifstream in_stream;
ofstream out_stream;
respectively create a stream called "in_stream" belonging to the class (like type) "ifstream" (input-
file-stream), and a stream called "out_stream" belonging to the class "ofstream" (output-file-
stream). However, the analogy between streams and ordinary variables (of type "int", "char", etc.)
can't be taken too far. We cannot, for example, use simple assignment statements with streams (e.g.
we can't just write "in_stream1 = in_stream2").
Connecting and Disconnecting Streams to Files
Having created a stream, we can connect it to a file using the member function "open(...)". (We
have already come across some member functions for output streams, such as "precision(...)" and
"width(...)", in section 2.) The function "open(...)" has a different effect for ifstreams than for
ofstreams (i.e. the function is polymorphic).
To connect the ifstream "in_stream" to the file "Lecture_4", we use the following
statement: in_stream.open("Lecture_4");
This connects "in_stream" to the beginning of "Lecture_4". Diagramatically, we end up in the
following situation:
To connect the ofstream "out_stream" to the file "Lecture_4", we use an analogous statement:
out_stream.open("Lecture_4");
Although this connects "out_stream" to "Lecture_4", it also deletes the previous contents of the file,
ready for new input. Diagramatically, we end up as follows:

Figure 1.2
To disconnect connect the ifstream "in_stream" to whatever file it is connected to, we write:
in_stream.close();
Diagramatically, the situation changes from that of Figure 1.2 to:

Figure 1.3
The statement:
out_stream.close();
has a similar effect, but in addition the system will "clean up" by adding an "end-of-file" marker at
the end of the file. Thus, if no data has been output to "Lecture_4" since "out_stream" was
connected to it, we change from the situation in Figure 1.2 to:

Figure 1.4
In this case, the file "Lecture_4" still exists, but is empty.
File operations, such as opening and closing files, are a notorious source of errors. Robust
commercial programs should always include some check to make sure that file operations have
completed successfully, and error handling routines in case they haven't. A simple checking
mechanism is provided by the member function "fail()". The function call
in_stream.fail();
returns TRUE if the previous stream operation on "in_stream" was not successful (perhaps we tried
to open a file which didn't exist). If a failure has occurred, "in_stream" may be in a corrupted state,
and it is best not to attempt any more operations with it. The following example program fragment
plays very safe by quitting the program entirely, using the "exit(1)" command from the library
"stdlib.h":
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

int main()
{
ifstream in_stream;

in_stream.open("Lecture_4");
if (in_stream.fail())
{
cout<< "Sorry, the file couldn't be opened!\n";
exit(1);
} ..

Character Input and


Output Input using
"get(...)"
Having opened an input file, we can extract or read single characters from it using the member
function "get(...)". This function takes a single argument of type "char". If the program is in
the state represented in Figure 4.2.1, the statement
in_stream.get(ch);
has two effects: (i) the variable "ch" is assigned the value "'4'", and (ii) the ifstream "in_stream" is
re- positioned so as to be ready to input the next character in the file. Diagramatically, the new
situation is:

Figure 1.5
Output using "put(...)"
We can input or write single characters to a file opened via an ofstream using the member
function "put(...)". Again, this function takes a single argument of type "char". If the program is in
the state represented in 1.2 the statement
out_stream.put('4');
changes the state to:

Figure 1.6
The "putback(...)" Function
C++ also includes a "putback(...)" function for ifstreams. This doesn't really "put the character
back" (it doesn't alter the actual input file), but behaves as if it had. Diagramatically, if we started
from the state in 1.1, and executed the statement
in_stream.putback(ch);
we would end up in the state:

Figure 1.7
Indeed, we can "putback" any character we want to. The alternative statement
in_stream.putback('7');
would result in:

Figure 1.8

Checking for the End of an Input File

End-of-file Checking For Systems Which Implement "eof()"


Special care has to be taken with input when the end of a file is reached. Most versions of C++
incorporate an end-of-file (EOF) flag, and a member function called "eof()" for ifstreams to test if
this flag is set to TRUE or FALSE. It's worth discussing such systems briefly, since many text
books assume this useful facility.
In such systems, when an ifstream is initially connected to a file, the EOF flag is set to FALSE
(even if the file is empty). However, if the ifstream "in_stream" is positioned at the end of a file,
and the EOF flag is FALSE, the statement
in_stream.get(ch);
will leave the variable "ch" in an unpredictable state, and set the EOF flag to TRUE. Once the EOF
flag is set to TRUE, no attempt should be made to read from the file, since the results will be
unpredictable. To illustrate with a diagramatic example, if we start from

Figure 1.9
and then execute the statement
in_stream.get(ch);
this results in the state

Figure 1.10
If we again execute the statement
in_stream.get(ch);
this now results in the state

Figure 1.11
The boolean expression
in_stream.eof()
will now evaluate to TRUE.

Below is a simple program which uses these techniques to copy the file "Lecture_4" simultaneously
to the screen and to the file "Copy_of_4". Note the use of a while loop in this program. "While"
loops are simplified versions of "for" loops, without the initialisation and update statements in the
"()" parentheses (we will look at such statements again in the next section).

#include <iostream.h>
#include <fstream.h>

int main()
{
char character;
ifstream in_stream;
ofstream out_stream;

in_stream.open("Lecture_4");
out_stream.open("Copy_of_4");

in_stream.get(character);
while (!in_stream.eof())
{

cout<< character;
out_stream.put(character);
in_stream.get(character);
}

out_stream.close();
in_stream.close();

return 0;
}
This doesn't matter too much, as long as we are careful not to use "in_stream" for any more
operations. For such systems, the program can be rewritten as

#include <iostream.h>
#include <fstream.h>

int main()
{
char character;
ifstream in_stream;
ofstream out_stream;

in_stream.open("Lecture_4");
out_stream.open("Copy_of_4");

in_stream.get(character);
while (!in_stream.fail())
{

cout<< character;
out_stream.put(character);
in_stream.get(character);
}

out_stream.close();
in_stream.close();

return 0;
}
Streams as Arguments in Functions
Streams can be arguments to functions, but must be reference parameters (not value parameters).
Below is another version of the program which uses the function "copy_to(...)".
#include <iostream.h>
#include <fstream.h>

void copy_to(ifstream& in, ofstream& out);

/* MAIN PROGRAM: */
int main()
{
ifstream in_stream;
ofstream out_stream;

in_stream.open("Lecture_4");
out_stream.open("Copy_of_4");
copy_to(in_stream, out_stream);
out_stream.close();
in_stream.close();

return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO COPY A FILE TO ANOTHER FILE AND TO THE SCREEN: */


void copy_to(ifstream& in, ofstream& out)
{
char character;

in.get(character);
while (!in.fail())
{

cout<< character;
out.put(character);
in.get(character);
}

}
/* END OF FUNCTION */

Input and Output Using ">>" and "<<"


So far we have only talked about writing and reading individual characters to and from files. At the
lowest level, ofstreams and ifstreams only deal with files which are sequences of characters. So data
of other types ("int", "double", etc.) has to be converted into character sequences before it can be
written to a file, and these character sequences have to be converted back again when they are input.
However, the operators ">>" and "<<", which we have already met in the context of keyboard input
and screen output, do some of this conversion automatically. For example, from the state

Figure 1.12
execution of the statement
out_stream<< 437 << ' ';
will result in the new state

Figure 1.13
When using these higher level facilities, it is important to include at least one "' '" (blank) character
(or a new-line character) after each item of data written. This ensures that the data items are
correctly separated in the file, ready for input using ">>". For example, from the state
Figure 1.14
where "n" has been declared as of data type "int", execution of the statement
in_stream >> n;
will result in the new state

Figure 1.15
Notice that the operation ">>" has skipped over the blank space "' '" before the number 437. It
always does this, no matter what data type it has been reading or expects to read (even characters).
The following program, which first creates a file called "Integers" containing the integers 51, 52,
53, 54 and 55, further illustrates these techniques.
#include <iostream.h>
#include <fstream.h>

int main()
{
char character;
int number = 51;
int count = 0;
ofstream out_stream;

ifstream in_stream1; /* Stream for counting integers. */


ifstream in_stream2; /* Stream for counting characters. */

/* Create the file */


out_stream.open("Integers");
for (count = 1 ; count <= 5 ; count++)
out_stream << number++ << ' ';
out_stream.close();

/* Count the integers in the file */


in_stream1.open("Integers");
count = 0;
in_stream1 >> number;
while (!in_stream1.fail())
{

count++;
in_stream1 >> number;
}
in_stream1.close();
cout<< "There are " << count << " integers in the file,\n";

/* Count the non-blank characters */


in_stream2.open("Integers");
count = 0;

in_stream2 >> character;


while (!in_stream2.fail())
{
count++;
in_stream2 >> character;
}
in_stream2.close();
cout<< "represented using " << count << " characters.\n";
}
Branch and Loop Statements
Boolean Values, Expressions and Functions
In this lecture we will look more closely at branch and loop statements such as "for" and "while"
loops and "if ... else" statements. All these constructs involve the evaluation of one or more logical
(or "Boolean") expressions, and so we begin by looking at different ways to write such expressions.
As we have seen, in reality C++ represents "True" as the integer 1, and "False" as 0. However,
expressions such as
condition1 == 1
or
condition2 = 0

aren't particularly clear - it would be better to be able to follow our intuition and write
condition1 == True
and

condition2 = False
Furthermore, it is desirable to have a seperate type for variables such as "condition1", rather than
having to declare them as of type "int". We can achieve all of this with a named enumeration:
enum Logical {False, True}
which is equivalent to
enum Logical {False = 0, True = 1}

This line acts a kind of type definition for a new data type "Logical", so that lower down the
program we can add variable declarations such as:
Logical condition1, condition2;
Indeed, we can now use the identifier "Logical" in exactly the same way as we use the identifiers
"int", "char", etc. In particular, we can write functions which return a value of type "Logical". The
following example program takes a candidate's age and test score, and reports whether the
candidate has passed the test. It uses the following criteria: candidates between 0 and 14 years old
have a pass mark of 50%, 15 and 16 year olds have a pass mark of 55%, over 16's have a pass mark
of 60%:
#include <iostream.h>
Logical acceptable(int age, int score);

/* START OF MAIN PROGRAM */


int main()
{
int candidate_age, candidate_score;

cout<< "Enter the candidate's age: ";


cin>> candidate_age;
cout<< "Enter the candidate's score: ";
cin>> candidate_score;

if (acceptable(candidate_age, candidate_score))
cout<< "This candidate passed the test.\n";
else
cout<< "This candidate failed the test.\n";

return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO EVALUATE IF TEST SCORE IS ACCEPTABLE */


Logical acceptable(int age, int score)
{
if (age <= 14 && score >= 50)
return True;
else if (age <= 16 && score >= 55)
return True;
else if (score >= 60)
return True;

else

}
return False;
/*END OF FUNCTION */

Note that since "True" and "False" are constants, it makes sense to declare them outside the scope
of the main program, so that the type "Logical" can be used by every function in the file. An
alternative way to write the above function "acceptable(...)" would be:
/* FUNCTION TO EVALUATE IF TEST SCORE IS ACCEPTABLE */
Logical acceptable(int age, int score)
{
Logical passed_test = False;

if (age <= 14 && score >= 50)


passed_test = True;
else if (age <= 16 && score >= 55)
passed_test = True;
else if (score >= 60)
passed_test = True;

return passed_test;
}
/*END OF FUNCTION */
Defining our own data types (even if for the moment they're just sub-types of "int") brings us
another step closer to object-oriented programming, in which complex types of data structure (or
classes of objects) can be defined, each with their associated libraries of operations.
"For", "While" and "Do ... While" Loops
We have already been introduced to "for" loops in section 2 and to "while" loops in section 4.
Notice that any "for" loop can be re-written as a "while" loop. For example, the program from
section 2, which was:
#include <iostream.h>

int main()
{
int number;
char character;

for (number = 32 ; number <= 126 ; number = number + 1) {

character = number;
cout<< "The character '" << character;
cout<< "' is represented as the number ";
cout<< number << " in the computer.\n";
}

return 0;
}
can be written equivalently as
#include <iostream.h>

int main()
{
int number;
char character;

number = 32;
while (number <= 126)
{
character = number;
cout<< "The character '" << character;
cout<< "' is represented as the number ";
cout<< number << " in the computer.\n";
number++;
}

return 0;
}

Moreover, any "while" loop can be trivially re-written as a "for" loop - we could for example
replace the line
while (number <= 126)
with the line
for ( ; number <= 126 ; )
in the program above.
There is a third kind of "loop" statement in C++ called a "do ... while" loop. This differs from "for"
and "while" loops in that the statement(s) inside the {} braces are always executed once, before the
repetition condition is even checked. "Do ... while" loops are useful, for example, to ensure that
the program user's keyboard input is of the correct format:
...
...
do
{
cout<< "Enter the candidate's score: ";
cin>> candidate_score;
if (candidate_score > 100 || candidate_score < 0)
cout<< "Score must be between 0 and 100.\n";
}
while (candidate_score > 100 || candidate_score < 0);
...
...

This avoids the need to repeat the input promt and statement, which would be necessary in the
equivalent "while" loop:
...
...
cout<< "Enter the candidate's score: ";
cin>> candidate_score;
while (candidate_score > 100 || candidate_score < 0)

{
cout<< "Score must be between 0 and 100.\n";
cout<< "Enter the candidate's score: ";
cin>> candidate_score;

}
...
...

Multiple Selection and Switch Statements


We have already seen (section 1) how "if" statements can be strung together to form a "multiway
branch". Here's a simplified version of the previous example:
...
...
if (total_test_score >=0 && total_test_score < 50)
cout<< "You are a failure - you must study much harder.\n";
else if (total_test_score < 60)
cout<< "You have just scraped through the test.\n";
else if (total_test_score < 80)
cout<< "You have done quite well.\n";
else if (total_test_score <= 100)
cout<< "Your score is excellent - well done.\n";

else

...
...
cout<< "Incorrect score - must be between 0 and 100.\n";
Because multiple selection can sometimes be difficult to follow, C++ provides an alternative
method of handling this concept, called the switch statement. "Switch" statements can be used when
several options depend on the value of a single variable or expression. In the example above, the
message printed depends on the value of "total_test_score". This can be any number between 0 and
100, but we can make things easier to handle by introducing an extra integer variable
"score_out_of_ten", and adding the assignment:
score_out_of_ten = total_test_score / 10;
The programming task is now as follows: (i) if "score_out_of_ten" has value 0, 1, 2, 3 or 4, print
"You are a failure - you must study much harder", (ii) if "score_out_of_ten" has value 5, print "You
have just scraped through the test", (iii) if "score_out_of_ten" has value 6 or 7, print "You have
done quite well", and finally (iv) if "score_out_of_ten" has value 8, 9 or 10, print "Your score is
excellent - well done". Here's how this is achieved with a "switch" statement:
...
...
score_out_of_ten = total_test_score / 10;

switch (score_out_of_ten)
{
case 0:
case 1:
case 2:
case 3:
case 4: cout << "You are a failure - you ";
cout<< "must study much harder.\n";
break;

case 5: cout << "You have just scraped through the test.\n";
break;

case 6:
case 7: cout << "You have done quite well.\n";
break;

case 8:
case 9:
case 10: cout << "Your score is excellent - well done.\n";
break;

}
...
...
default: cout << "Incorrect score - must be between "; cout<< "0 and
100.\n";

In general, the syntax of a "switch" statement is (approximately):


switch (selector)
{

caselabel1: <statements 1>


break;
...
...
...
caselabelN: <statements N>
break;

default: <statements>
}
There are several things to note about such "switch" statements:
● The statements which are executed are exactly those between the first label which
matches the value of selector and the first "break" after this matching label.

● The "break" statements are optional, but they help in program efficiency and clarity and
should ideally always be used to end each case. When a "break" is encountered within a
case's statement, control is transfered immediately to the first program statement following
the entire "switch" statement. Otherwise, execution continues.

● The selector can have a value of any ordinal type (e.g. "char" or "int" but not "float").

● The "default" is optional, but is a good safety measure.

Blocks and Scoping


We have already seen how compound statements in C++ are delimited by "{}" braces. These braces
have a special effect on variable declarations. A compound statement that contains one or more
variable declarations is called a block, and the variables declared within the block have the block as
their scope. In other words, the variables are "created" each time the program enters the block, and
"destroyed" upon exit. If the same identifier has been used both for a variable inside and a variable
outside the block, the variables are unrelated While in the block, the program will assume by
default that the identifier refers to the inner variable - it only looks outside the block for the variable
if it can't find a variable declaration inside. Hence the program
#include <iostream.h>
int integer1 = 1;
int integer2 = 2;
int integer3 = 3;

int main()
{
int integer1 = -1;
int integer2 = -2;
{

int integer1 = 10;


cout<< "integer1 == " << integer1 << "\n";
cout<< "integer2 == " << integer2 << "\n";
cout<< "integer3 == " << integer3 << "\n";
}
cout<< "integer1 == " << integer1 << "\n";
cout<< "integer2 == " << integer2 << "\n";
cout<< "integer3 == " << integer3 << "\n";

return 0;
}

produces the output


integer1 == 10
integer2 == -2

integer3 == 3
integer1 == -1
integer2 == -2
integer3 == 3
The use of variables local to a block can sometimes be justified because it saves on memory, or
because it releases an identifier for re-use in another part of the program. The following program
prints a series of "times tables" for integers from 1 to 10:
#include <iostream.h>

int main()
{
int number;

for (number = 1 ; number <= 10 ; number++)


{
int multiplier;

for (multiplier = 1 ; multiplier <= 10 ; multiplier++)


{
cout<< number << " x " << multiplier << " = ";
cout<< number * multiplier << "\n";
}

cout<< "\n";
}
...
...

However, we can achieve the same effect, and end up with a clearer program, by using a function:
#include <iostream.h>

void print_times_table(int value, int lower, int upper);


{
int number;

for (number = 1 ; number <= 10 ; number++)


{

}
...
...
}
print_times_table(number,1,10); cout<< "\n";

void print_times_table(int value, int lower, int upper)


{
int multiplier;

for (multiplier = lower ; multiplier <= upper ; multiplier++)


{
cout<< value << " x " << multiplier << " = ";
cout<< value * multiplier << "\n";
}
}
or eliminate all variable declarations from "main()" using two functions:
#include <iostream.h>

void print_tables(int smallest, int largest);


int main()
{
print_tables(1,10);
...
...
}

void print_tables(int smallest, int largest)


{
int number;

for (number = smallest ; number <= largest ; number++)


{
print_times_table(number,1,10);
cout<< "\n";
}

void print_times_table(int value, int lower, int upper)


{
int multiplier;

for (multiplier = lower ; multiplier <= upper ; multiplier++)


{
cout<< value << " x " << multiplier << " = ";
cout<< value * multiplier << "\n";
}
}
Arrays and Strings
The Basic Idea and Notation
Although we have already seen how to store large amounts of data in files, we have as yet no
convenient way to manipulate such data from within programs. For example, we might want to
write a program that inputs and then ranks or sorts a long list of numbers. C++ provides a
structured data type called an array to facilitate this kind of task. The use of arrays permits us to set
aside a group of memory locations (i.e. a group of variables) that we can then manipulate as a
single entity, but that at the same time gives us direct access to any individual component. Arrays
are simple examples of structured data types - they are effectively just lists of variables all of the
same data type ("int", "char" or whatever). Later in the course you will learn how to construct more
complicated structures, designed for the specific needs of the problem or task in hand.

Declaring an array
The general syntax for an array declaration is:
<component type> <variable identifier>[<integer value>];
For example, suppose we are writing a program to manipulate data concerning the number of hours
a group of 6 employees have worked in a particular week. We might start the program with the
array declaration:
int hours[6];
or better,
const int NO_OF_EMPLOYEES = 6;
int hours[NO_OF_EMPLOYEES];
Indeed, if we are going to use a number of such arrays in our program, we can even use a type
definition:
const int NO_OF_EMPLOYEES = 6;
typedef int hours_array[NO_OF_EMPLOYEES];
hours_array hours;
hours_array hours_week_two;

In each case, we end up with 6 variables of type "int" with identifiers


hours[0] hours[1] hours[2] hours[3] hours[4] hours[5]
Each of these is referred to as an element or component of the array. The numbers 0, ..., 5 are the
indexes or subscripts of the components. An important feature of these 6 variables is that they are
allocated consecutive memory locations in the computer. We can picture this as:

Figure1.1

Assignment Statements and Expressions with Array Elements


Having declared our array, we can treat the individual elements just like ordinary variables (of type
"int" in the particular example above). In particular, we can write assignment statements such as
hours[4] = 34;
hours[5] = hours[4]/2;
and use them in logical expressions, e.g.

if (number < 4 && hours[number] >= 40) { ...


A common way to assign values to an array is using a "for" or "while" loop. The following program
prompts the user for the number of hours that each employee has worked. It is more natural to
number employees from 1 to 6 than from 0 to 5, but it is important to remember that array indexes
always start from 0. Hence the program subtracts 1 from each employee number to obtain the
corresponding array index.
#include <iostream.h>

const int NO_OF_EMPLOYEES = 6;


typedef int hours_array[NO_OF_EMPLOYEES];

int main()
{
hours_array hours;
int count;

for (count = 1 ; count <= NO_OF_EMPLOYEES ; count++)


{
cout<< "Enter hours for employee number " << count << ": ";
cin>> hours[count - 1];
}

return 0;
}
A typical run might produce the following input/output:
Enter hours for employee number 1: 38
Enter hours for employee number 2: 42
Enter hours for employee number 3: 29
Enter hours for employee number 4: 35
Enter hours for employee number 5: 38
Enter hours for employee number 6: 37
in which case our block of variables would then be in the state:

Figure 1.2
It is instructive to consider what would have happened had we forgotten to subtract 1 from the
variable "count" in the "cin ..." statement (within the "for" loop) in the above program Unlike some
languages, C++ does not do range bound error checking, so we would have simply ended up in the
state:

Figure 1.3 - A Range Bound Error


In other words, C++ would have simply put the value "37" into the next integer-sized chunk of
memory located after the memory block set aside for the array "hours". This is a very undesirable
situation - the compiler might have already reserved this chunk of memory for another variable
(perhaps, for example, for the variable "count").
Array elements can be of data types other than "int". Here's a program that prints itself out
backwards on the screen, using an array of type "char".
#include <iostream.h>
#include <fstream.h>

const int MAX = 1000;


typedef char
file_array[MAX];

int main()
{
char character;
file_array file;
int count;
ifstream in_stream;

in_stream.open("6-1-2.cp");
in_stream.get(character);
for (count = 0 ; ! in_stream.fail() && count < MAX ; count++)

{
file[count] = character;
in_stream.get(character);
}

in_stream.close();

while (count > 0)


cout<< file[--count];
return 0;
}
Arrays as Parameters in Functions
Functions can be used with array parameters to maintain a structured design. Here is a definition of
an example function which returns the average hours worked, given an array of type "hours_array"
float average(hours_array hrs)
{
float total = 0;
int count;
for (count = 0 ; count < NO_OF_EMPLOYEES ; count++)
total += float(hrs[count]);
return (total / NO_OF_EMPLOYEES);

}
We could make this function more general by including a second parameter for the length of the
array:
float average(int list[], int length)
{
float total = 0;
int count;
for (count = 0 ; count < length ; count++)
total += float(list[count]);
return (total / length);

}
It is quite common to pass the array length to a function along with an array parameter, since the
syntax for an array parameter (such as "int list[]" above) doesn't include the array's length.
Although array parameters are not declared with an "&" character in function declarations and
definitions, they are effectively reference parameters (rather than value parameters). In other words,
when they execute, functions do not make private copies of the arrays they are passed (this would
potentially be very expensive in terms of memory). Hence, like the reference parameters we have
seen in Lecture 3, arrays can be permanently changed when passed as arguments to functions. For
example, after a call to the following function, each element in the third array argument is equal to
the sum of the corresponding two elements in the first and second arguments:
void add_lists(int first[], int second[], int total[], int length)
{
int count;
for (count = 0 ; count < length ; count++)
total[count] = first[count] + second[count];
}

As a safety measure, we can add the modifier "const" in the function head:
void add_lists(const int fst[], const int snd[], int tot[], int len)
{

int count;
for (count = 0 ; count < len; count++)
tot[count] = fst[count] + snd[count];
}

The compiler will then not accept any statements within the function's definition which potentially
modify the elements of the arrays "fst" or "snd". Indeed, the restriction imposed by the "const"
modifier when used in this context is stronger than really needed in some situations. For example,
the following two function definitions will not be accepted by the compiler:
void no_effect(const int list[])
{
do_nothing(list);
}

void do_nothing(int list[])


{
;
}
This is because, although we can see that "do_nothing(...)" does nothing, its head doesn't include
the modifier "const", and the compiler only looks at the head of "do_nothing(...)" when checking to
see if the call to this function from within "no_effect(...)" is legal.
Sorting Arrays
Arrays often need to be sorted in either ascending or descending order. There are many well known
methods for doing this, the bubble sort and quick sort algorithms are among the most efficient.
This section briefly describes one of the easiest sorting methods called the selection sort.
The basic idea of selection sort is:
For each index position I in turn:
1. Find the smallest data value in the array from positions I to (Length - 1), where "Length" is
the number of data values stored.

2. Exchange the smallest value with the value at position I.

To see how selection works, consider an array of five integer values, declared as
int a[5];and initially in the state:

Figure1.4
Selection sort takes the array through the following sequence of states:

Figure1.5
Each state is generated from the previous one by swapping the two elements of the array marked
with a "bullet".
We can code this procedure in C++ with three functions. The top level function "selection_sort(...)"
(which takes and array and an integer argument) sorts its first (array) argument by first calling the
function "minimum_from(array,position,length)", which returns the index of the smallest element in
"array" which is positioned at or after the index "position". It then swaps values according to the
specification above, using the "swap(...)" function:
void selection_sort(int a[], int length)
{
for (int count = 0 ; count < length - 1 ; count++)
swap(a[count],a[minimum_from(a,count,length)]);
}

int minimum_from(int a[], int position, int length)


{
int min_index = position;

for (int count = position + 1 ; count < length ; count ++)


if (a[count] < a[min_index])
min_index = count;
return min_index;
}

void swap(int& first, int& second)


{
int temp = first;
first = second;
second = temp;
}

Two-dimensional Arrays
Arrays can have more than one dimension. In this section we briefly examine the use of two-
dimensional arrays to represent two-dimensional structures such as screen bitmaps or nxm matrices
of integers.
A bitmap consists of a grid of Boolean values representing the state of the dots or pixels on a
screen. "True" means "on" or that the pixel is white; "False" means "off" or the pixel is black. Let's
suppose the screen is 639 pixels wide and 449 pixels high. We can declare the coresponding array
as follows:
enum Logical {False, True};
const int SCREEN_WIDTH = 639;
const int SCREEN_HEIGHT = 449;
Logical screen[SCREEN_WIDTH][SCREEN_HEIGHT];

References to individual data elements within the array "screen" simply use two index values. For
example, the following statement assigns the value "True" to the cell (pixel) in row 4, column 2
of the array.
screen[3][1] = True;

Strings
We have already been using string values, such as ""Enter age: "", in programs involving output to
the screen. In C++ you can store and manipulate such values in string variables, which are really
just arrays of characters, but used in a particular way.

The Sentinel String Character '\0'


The key point is that, to use the special functions associated with strings, string values can only be
stored in string variables whose length is at least 1 greater than the length (in characters) of the
value. This is because extra space must be left at the end to store the sentinel string character "'\0'"
which marks the end of the string value. For example, the following two arrays both contain all the
characters in the string value ""Enter age: "", but only the array on the left contains a proper string
representation.
Figure 1.6
In other words, although both "phrase" and "list" are arrays of characters, only "phrase" is big
enough to contain the string value ""Enter age: "". We don't care what characters are stored in the
variables "phrase[12]" and "phrase[13]", because all the string functions introduced below ignore
characters after the "'\0'".

String Variable Declarations and Assignments


String variables can be declared just like other arrays:
char phrase[14];
String arrays can be initialised or partially initialised at the same time as being declared, using a list
of values enclosed in "{}" braces (the same is true of arrays of other data types). For example, the
statement
char phrase[14] = {'E','n','t','e','r',' ','a','g','e',':',' ','\0'};
is equivalent. If the "14" is omitted, an array will be created just large enough to contain both the
value ""Enter age: "" and the sentinel character "'\0'", so that the two statements
char phrase[] = {'E','n','t','e','r',' ','a','g','e',':',' ','\0'};
char phrase[] = "Enter age: ";
are equivalent both to each other and to the statement
char phrase[12] = "Enter age: ";
However, it is important to remember that string variables are arrays, so we cannot just make
assignments and comparisons using the operators "=" and "==". We cannot, for example, simply
write
phrase = "You typed: ";
Instead, we can use a special set of functions for string assignment and comparison.
DETAILS OF HARD COPY OF PPT'S

Hard copy of PPT’s


Introduction to classes
ANY OTHER

You might also like