OOP Couse File
OOP Couse File
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)
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
Unit-II
Unit-III
Unit-IV
Text Books:
1. Object Oriented Programming with C++, E. Balagurusami, Fourth Edition,
TataMc-Graw Hill, 2009.
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
1. Linked Lists
2. Function Overloading
3. Storage Classes
COLLEGE OF ENGINEERING -CGC
Department of Sciences and Computing
Lecture Plan
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
C Course
O outcomes
#
CO1 To learn programming from real world examples.
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
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
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 :
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;
};
// 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.
className objectVariableName;
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.
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
allocate memory for all the Union variable will allocate common
separately.
Example:
Example:
union Employee{
struct Employee{
int age;
int age;
char name[50];
char name[50];
float salary;
float salary;
};
};
memory
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.
/* 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.
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.
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:
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
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;
}
he unary operators operate on a single operand and following are the examples of Unary operators
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;
}
int main() {
Distance D1(11, 10), D2(-5, 11);
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
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:
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;
};
#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";
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.
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>
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.
class class_name
... .. ...
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
... .. ...
... .. ...
return_type functionName(argument/s)
... .. ...
... .. ...
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
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
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.
3. #include <iostream>
5. char a = 'm';
7.
8. int main() {
9. char a = 's';
10.
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
return 0;
}
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. };
A virtual function whose declaration ends with =0 is called a pure virtual function. For example,
class Weapon
public:
};
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>
class Base {
public:
};
public:
void display() {
};
int main() {
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;
}
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>
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;
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];
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
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
}
};
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
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.
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";
Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.
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:
4 int main ()
{
5 int n;
cout << "Enter the starting
6 number > ";
cin >> n;
7
while (n>0) {
8 cout << n << ", ";
--n;
9 }
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 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
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
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.
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.
1
0
1
1
Jump statements.
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:
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)
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.
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.
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;
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.
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.
71) List out the operators that cannot be overloaded using Friend function.
• Assignment operator =
• Function call operator ( )
• Subscripting operator [ ]
• Class member access operator
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.
except
exception
K object name or
Catch(T) nameless object
{
// actions for handling an exception
}
Catch(…)
{
//actions for handling an exception
}
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
Throw
block
i
If(failure)
o
Throw object;
istream
Catch block
iostream
103) Draw the stream classes for hierarchy filebuf
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
Roll
No.
Date
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
COLLEGE
PROGRAM (DEPARTMENT) (Semester)
Assignment :1
Subject and Subject code: Object Oriented Programming using C++( UGCA 1909) Semester:2
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)
.
.
.
.
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.
int x;
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;
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’.
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
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:
21. }
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.
ptr refers to dd of dt
ptr mm refers to mm of dt
ptr refers to yy of dt
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};
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.
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.
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’.
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.
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
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;
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. 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>
{ {
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
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, - - -
};
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*/
};
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).
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.
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.
- Remember, it depends upon the optimization algorithms used in the design of the
compiler, that whether or not to make any function inline implicitly
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);
} ..
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
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>
/* 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 */
in.get(character);
while (!in.fail())
{
cout<< character;
out.put(character);
in.get(character);
}
}
/* END OF FUNCTION */
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;
count++;
in_stream1 >> number;
}
in_stream1.close();
cout<< "There are " << count << " integers in the file,\n";
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);
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 */
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;
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;
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;
}
...
...
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";
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").
int main()
{
int integer1 = -1;
int integer2 = -2;
{
return 0;
}
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;
cout<< "\n";
}
...
...
However, we can achieve the same effect, and end up with a clearer program, by using a function:
#include <iostream.h>
}
...
...
}
print_times_table(number,1,10); cout<< "\n";
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;
Figure1.1
int main()
{
hours_array hours;
int count;
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:
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();
}
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);
}
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)]);
}
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.