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

C & C Material 2022

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

C & C Material 2022

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

ABHYUDAYA MAHILA DEGREE COLLEGE

GUNTUR

II B.Com
Programming with C & C++

P.Y.KUMAR
PROGRAMMING WITH C & C++
Unit-I

Introduction: Introduction - Structure of C program ñ C character set, Tokens:


Constants, Variables, Keywords, Identifiers - C data types - C operators
(arithmetic, relational, logical, increment and decrement) - Standard I/O in C
(scanf, printf) - Conditional Control statements (if and Switch) Statements.

Unit-II

Loops And Arrays: Repetitive statements: While, Do While and For Loops - Use
of Break and Continue Statements -Arrays: Introduction ñ Types of arrays, one
dimensional arrays - Declaration of one dimensional arrays-Accessing array
elements -Storing values in an array -Two Dimensional Arrays Declaration of
two dimensional arrays ñ Accessing array elements- Storing values in 2-D
arrays.

Unit- III

Strings and Functions: Strings: Definition, Declaration and Initialization of


String Variables - String Handling Functions - Functions: Defining Functions -
Function Call - passing parameters: Call By Value, Call By Reference.

Unit- IV

Classes and Objects Introduction to OOP and its basic features - C++ program
structure - Classes and objects - Friend Functions- Static Functions -
Constructor - Types of constructors ñ Destructors – Operators

Unit-V

Inheritance: Inheritance - Types of Inheritance -Types of derivation- Public -


Private - Protected Hierarchical Inheritance - Multilevel Inheritance - Multiple
Inheritance - Hybrid Inheritance

Page Np :2
Introduction to C:

C is like many other modern languages derived from ALGOL.In 1967,


Martin Richards developed a language called BCPL at CAMBRIDGE UNIVERSITY
(in UK.) a powerful and basic language was developed called B-LANGUAGE. This
was developed by Ken Thompson. The original name of B-LANGUAGE is BCPL
(Here BCPL stands for Basic Combined Programming Language and it is a
preliminary language of B. Afterwards the BCPL was renamed called B-
LANGUAGE from its first alphabet. This language has number of advance
features than BCPL.

From 1972 (some research say 1970) at BELL-LABORATORIES (which is


the part of AT & T) in U.S.A. by the scientist Dennis Ritche developed powerful
software tool which has a big facility (compilation and linkage facility in
combined form) called C-LANGUAGE. C-LANGUAGE was renamed from the
BCPL's second alphabet.

After many years research, C language was developed and become


popular. C-LANGUAGE has different versions from time to time. First version of C
LANGUAGE is 1.0 in 1983 Afterwards an Object oriented programming (OOP)
software was developed from the CLANGUAGE that is called C++.

2) Explain Structure of C program.

A C-program can be developed from a general structure. The general


structure of C-program is as shown below (which is also called overview of a C-
program):

Documentation Section
Preprocessor directives or compiler directives Section or Macro.
Link Section
Definition Section
Global Declaration Section
Main C-program function called main
Beginning of the program by using left brace
{
Local declaration or local variable declaration;
Executable Part or C-executable statements;
End of the main program using right brace.
}
Sub-program Section having user-defined functions.
Return-datatype function-name(parameter)

Page Np :3
local declaration;

executable statements;

return (argument);

Note that a function sub-program further has two sections:


 local declaration
 executable part of the function sub-program.
Documentation section or Comments:

In Documentation section we give a comment. Here comment statement


is the Executable statement. Comment can be started by using "/*" and end
with “*/”. Note that it is an optional section.
General syntax is:
/* Text Line or message line or comment line */
Also you can apply a comment more than one line (to the multiple lines) as
/* This is a sample C program
developed by Computer Students. */
Preprocessor Directives:
These are compiler preprocessor statements. These are also optional
statements, but become compulsory if your compiler has INCLUDE and LIB
subdirectories. Pre-compiler statements are divided into two sections. One is
called Section, second is called Definition Section.
In the Link Section, we can link the compiler function like printf ( ),sqrt(
), fmod ( ),sleep( ), clrscr( ) etc. with the #include subdirectories, special
header files like stdio.h, math.h, dos.h, conio.h, alloc.h,stdlib.h etc. It
becomes very useful delimiters of compilation and the linkage phase. The header
file with include subdirectories linked as:
#include <header file>
Or
#include "header file"
For example:
#include <stdio.h>
#include <conio.h>
#include "dos.h” /* This type of declaration specifies the header file
is in the current working directory */
The second section is the Definition section by using which we can define
a variable with its value. For this purpose define statement is used. The general
syntax used is as:
#define variable name value

For example: following are the some valid definition statements:

#define pi 3.142
#define m 200
#define name "Yugandhar"
Page Np :4
3. Global Declaration Section:
In some programs we use function sub-programs. So we declare some
variables in the main program and function sub program having common name
this creates the duplicity or redundancy in defining the variables. So we can take
the common variable declaration above the main program, which is also called
global variable declaration. The global variables are automatically initialized with
zero; hence there is no chance of garbage value. The global variable declaration
can be done by the statement as below:
data type vl,v2,v3 vn;
Here data types are int, float, char, double etc. vl,v2,v3, vn is the list of
global variables. For example: following are the some valid global declaration
statement as:
int a,b,c;
float x,y,z;
char h, nm[ 10],name[ 10] [20];
main( ):
main( ) program is the C-program's main structure in which we process
some statements. It is defined as below:
main( )

Beginning of the main program:


The beginning of the main program can be done by using left curly braces {

a) Local Variable Declaration:


Variables which are used in the main program are declared by using the variable
declaration statement having local variables. So it is called Local Variable
Declaration Section. Local variables are declared as:

data type vl,v2,v3,…vn;

Here data types are int, float, char, double etc. For example, some valid local
variable declaration statements are as:

int a, b, c;
float x, y, z ;
char nm, name[10], array[20] [30];
b) Executable Statements:
This section has reading, writing and processing statements having input/output
function, library function, formulas, conditional statements, looping statements
and function calling statements. In this section, all the C statements except
control statements end with ";" (semicolon).

Ending of the main program:

By using the right curly brace } we can end the main program
User Defined Function Section:

In this section, we define the function sub-program or called program, which are
called by a calling statement from the main program. Further, in this section
Page Np :5
every function sub-program has local declaration variable section and executable
statement section similar to the main program. Every function sub-program ends
with the return statement with or without any argument and return the
computed value to the main program according to the user's requirement. The
structure of a function sub-program is as:

Return-datatype function-name(parameter)
{
local declaration;
executable statements;
return (argument);
}
3) What are the Character Sets available in C?

Character Set means that the characters and symbols that a C Program can
understand and accept. These are grouped to form the commands, expressions,
words, c-statements and other TOKENS for C Language. Character Set is the
combination of alphabet or character, digit, special characters and white spaces.
More about a C program we can say that it is a sequence of characters. These
characters from the character set play the different role in different way in the
C-compiler.
Character set

1. Letter character
2. Digit
3. Special character
4. Empty Space

Letter or Alphabet
In the character set, character or alphabet are represented by A-Z or a-z.
CLanguage is case sensitive so it takes different meaning for small and upper
case letters.. There are total 26 letters used in C-programming.
Digit
In the character set digit are represented by 0-9 or by combination of
these digits.. There are total 10 digits used in the C-programming.
Special Characters
All the keyboard keys except alphabet, digits and white spaces are the
special character. These are some punctuation marks and some special symbols
used for special purpose. There are total 30 special characters used in the C-
programming. Special characters are used for C-statements like to create an
arithmetic statement +, -, * etc., to create relational statement <, >, <=, >=,
== etc., to create assignment statement =, to create logical statement &&, 11
etc. are required.
Empty space Character or White spaces
White spaces has blank space, new line return, Horizontal tab space,
carriage ctrl, Form feed etc. are all used for special purpose. Also note that
Turbo-C Compiler always ignores these white space characters in both high level
and low-level programming.
Page Np :6
4) Keywords and Identifiers (rules of identifiers)?
C-language has some reserve words, which cannot be used as variables or
identifiers. These reserve words are keywords of C-language. These are the part
of the C-Tokens. There are mainly 40 keywords among which 32 are used by
many C compilers (also called Standard Keywords) for high level programming.
The standard keywords are:

auto extern sizeof default

Break float static long

Case For struct unsigned

Char goto switch do

constant If typedef register

continue Int union void

Double return volatile else

Short enum while signed

Identifiers are some words or names, which identify whether it is a


constant, variable or it is a keyword. These are the data names used by the
programmer. Identifier gives us the unique identification having unique
sequence of character (from the character set) used for special purpose.
Following are the some rules,
n

Some valid Identifiers are


pay, address, phone3, roll_number, r, R etc.
names are unique
Some Invalid Identifiers are
12 th (first should not be a digit),
amount$ (special character at end should not be used),
net-pay (hyphen should not be used),
for (reserve word or keyword should not be used),
roll no (blank space or white space should not be used), etc.

5) Explain Constants in C:
Constant uses the secondary storage area. Constants are those quantities
whose value does not vary during the execution of the program i.e. value is
fixed. Constants in every language are the same.
For example: in the C-language some valid constants are:
const float pi=3.14;

In C-language constants are mainly of two types:

Page Np :7
 Numeric constant
 Non-numeric or Character Constant
These are further sub-divided into more categories as shown below:
Numeric constant
 Integer: Decimal, Octal, Hexa decimal
 Float : with or without exponent
Character Constant (Non-numeric)
 Single
 String
 Backslash character
Numeric constant:
These have numeric value having combination of sequence of digits i.e.
from 0-9 as alone digit or combination of 0-9 with or without decimal point
(precision value) having positive or negative sign; these are further sub-divided
into two categories as:

I. Integer Numeric Constant


II. Real or float Numeric Constant

I. Integer Numeric Constant:


Integer Numeric constants have integer data combination of 0-9 without any
decimal point or without precision with any sign positive or negative sign. These
are further subdivided into three parts:
a) Decimal Integer Numeric Constant: These have no decimal point in
it and are either be alone or be the combination of 0-9 digits. These have either
+ve or -ve sign. For example: 124, -321, 0, 24, -8, +9 etc.
b) Octal Integer Numeric Constant: These consist of combination of
digits from 0-7 with positive or negative sign. It has leading with 0 or o (upper
or lower case) means Octal or octal. For example: 037, 00, -0450 etc.
c) Hexadecimal Integer Numeric Constant: These have hexadecimal
data. These have combination of 0-9 and A-F alone. The letters a-f or A-F
represents the numbers 10-15.
II. Real or float Numeric Constant:
Some constants, which have a decimal point or a precision value within it
having any positive or negative sign is called Real Numeric Constant. It is also
called Floating Point Constant or Float value. For example some valid real
numeric constant are as: 22.33, -9.8, 9.34E-5, 4.6E3 etc. Real Numeric
constants are further divided into two parts. One is Mantissa Part and the other
is Exponent Part. These two parts in a Real number are represented as:
mantissa E exponent
a) Mantissa part: The part without E and having a decimal point is called
Mantissa Real part e.g. 25.3, -40.33, .5 etc. it is also called without exponent
part

Page Np :8
b). Exponent part: The exponent part has an E within it. It is also called
a scientific notation. Here E has base value 10. It computes the power. For
example: 3.5x 1 02 Can be written as 3.5E2, 4.2x- 5 can be written as 4.2E-5.
Similarly some more valid real numeric constant are as: 23.23 E -2, 57.9 E +22
etc.

II. Character Constant:


Character constants have either a single character or group of characters
or a character with backslash used for special purpose. These are further
subdivided into three types:

1. Single Character Constant


2. String Character Constant
3. Backslash Character Constant

1. Single Character Constant:


These have a single character within single quote ('). So these are also called
single quote character constant. For example: 'a', 'M', '5', '+', '?' etc. are some
valid single character constant.
2. String Character Constant:
A string is the combination of characters or group of characters. A string
character constant or a string is enclosed within double quotes ("). So it is also
called 'Double quote' character constant. For example: "kumar", "Hello", "1999",
"1999 - 2000", "5+3", "?+!" etc. are some valid string character constant. These
are used for printing purpose or display purpose in the C-program's output
statements. These can also be used for assigning the string data to the character
(string) type variables.
3. Backslash Character Constants:
These are used for special purpose in the C-language. These are used in output
statements like printf ( ), puts ( ), fprintf etc. Another name of Backslash
character constant is 'Escape sequence'.

6) Escape Sequences:

Page Np :9
Constant Meaning
'\a' or "\a" Audible bell (To ring a beep)

'b' or "\b" Backspace (it moves one space back)

'\n' or "\n" New line (Move control to next line)

Form feed (move one page next). It is used in the printing


'\f' or "\f" the hard copy only.

Horizontal tab (it moves five spaces of tab).User can also


'\t' or "\t" set the Tab spaces according to his/her requirement.

Vertical tab (it moves five lines down). It does not work in
'\v' or "\v" the Turbo-C compiler.
Carriage return (it replaces a word or string from the
beginning of the other string). For example, an output
statement in a C program: printf("\n Kite is Beautiful \r
'\r' or "\r" Bike"); will display the output: Bike is Beautiful.
It displays a single quote in output statement. For
example, an output statement in a C-program: printf("\n
Kumar \'s address"); will display the output: Kumar's
‘\'’or "\' " address.
It displays a double quote in output statement. For
example, an output statement in a C-program: printf("\n
Want more data "yes/no" will display the output: Want
'\" ' or "\" " more data "yes/no" :
Null character (it tells us the end of the string and used in
\0' or "\0" string handling

7) What is a Variables:
Variables use the primary storage area. Variables are those quantities
whose value changes during the execution of the program. Variables are
basically memory locations, which are given names, and these locations are
refereed in the program by variable names to read and write data in it.
Ex:
int x;  this is declaration of variable

int x=10;  this is initialization and declaration of variable

Page Np :10
8 Explain different Data Types in C.

data types are further sub-divided into more categories

Data type

scalar
derived User defined void pointer

(enum) (empty)

char
union
int structure Array of Strings
float double

1. Scalar or Standard Data Type or fundamental data typeor primary datatype

. These are sub-divided into four categories


a) Integer data type
b) Float data type or Single precision real data type
c) Double precision real or Double or Longfloat data type
d) Character data type
The fundamental data types are explained in detail as:
a). Integer Data type:
These are of integral type. These are without decimal point. These are
signed or unsigned. These data types are small int (short int), int, long int.
b). Real (float) Data Type:
These are also called precision real or single percussion value with a very
small real number. These data type have at least one digit with a decimal point.
These are also signed or unsigned..
c). Double Data Type:
These data types have ver large floating data, so are also called large real
number.
Also there are long double or long float having 80 bits size.
d). Character Data Type:
These have either single character or combination of characters (called
String). Characters are either signed or unsigned but mostly characters are used
as unsigned type. These have 8 bit (1byte) internal storage. Also their range
varies from 0-255 in the case of unsigned character and -128 to 127 in the case
of signed character.

Below is the table with different data types having data bit size and
ranges according to their data inputting as

Page Np :11
Type size(bytes) Range
Char or Signed char 1 -128 to 127

Unsigned char 1 0 to 255

int or signed int 2 -32768 to 32767

Unsigned int 2 0 to 65535

Short int 1 -128 to 127


Or Signed short int

Unsigned short int 1 0 to 255

Long int 4 -2,147,483,648


Or Signed long int to
2,147,483,647

Unsigned long int 4 0to 4,294,967,295

Float 4 3.4E-38 to 3.4E+3 8

Double 8 1.7E-308to1.7E+308

Long double 10 3.4E-4932to3.4E+4932


2. Structured Data Type or Derived data type:
Derived data types are derived from the scalar data type by adding some
additional relationship with the various elements of the primary or scalar data
types. Note that derived data type may be used for representing a single value
or multiple values. As these data types have different structure depending on
the C-coding, these are also called Structured data type. These are also called
secondary data type. These are further sub divided into three categories
a)Arrays and Strings(combination of characters or number with in “ “)
b)Structures
c)Unions
Array: collection of homogeneous data type(similar data type) referenced by
unique name
Structure and union means collection of heterogeneous (different data type)
3. Enumerated Data Type or User defined data type:
This is also used for type definition, i.e. it allows the users to define a
variable or an identifier, which is used for representation of existing data types.
Page Np :12
In other words, it provides us a way to define our own data type and also can
define the value of a variable or an identifier stores into the main memory.
There are two types of User-defined data types. These are Enumerated and
typedef data type. Enumerated data type can be defined as:

enum identifier {v1, v2, v3 ..vn };

Here enum is the reserve word and vl,v2,v3,…vn all are the values,
which are also, called enumeration constants. Also variable can be defined with
the enumerated variable. For example, some values can be assigned to the
enumerated identifier and the variable as:

enum month { “Jan”, “Feb”, “Mar”, …”Dec”};


OR
enum year {1999, 2000, 2001, 2005};

Example program
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday,
saturday};
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}

Also there is another user-defined data type typedef. This is used to


represent the existing data type i.e. by using this; the new type can be used in
place of the old type anywhere in a C program. Also we can create the typedef
variables (meaningful data type names) for improving the readability of the
program. Typedef data type can be defined as:
typedef data-type identifier;
Here data-type may be int, float, double and char. Identifier gives us the
information of new name given to the data type. Note that typedef cannot create
a new type. For example, some valid typedef statements are as follows:

typedef int pay;


typedef float salary;

Here pay tells us the link with int and salary with the float and these can
be used for the declaration of the variable as:
pay p1, p2;
salary s1, s2, s3;

4. Void or Empty Data Type:


Void or empty data type is used in the user-defined function or user
defined sub-programs. These are used when the function sub-program returns

Page Np :13
nothing. Also it is used when a function or any sub-program have not any
argument in it.

5. Pointer data type:


Pointer data types are used to handle the data at their memory locations

9) Explain different Operators available in C?

There are mainly eight operators used in C-language. These are :


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment/Decrement operators
6. Conditional operators or Ternary operator
7. Bit wise operators
8. Special operators

1. Arithmetic Operators:
There are mainly five arithmetic operators used in C-language. These all
are given in the table below.

Operator Meaning
* multiplication
/ division
% modulus (remainder after division)
+ addition
- subtraction

Mixed mode Arithmetic: When one of the operands is real and the other is
integer the expression is a mixed mode arithmetic expression.
eg: 15/10.0 = 1.500000
15/10 = 1
10/15 = 0
-10.0/15 = -0.666667
2. Relational Operators:
These operators are used to create logical relationship between two
operands. Relational operators are used for comparison purpose. There are
mainly six relational operators used in the C-language. First four operators are in
the comparison section and last two are in the equality section. These all are
given in the table as:
Relational Operator Meaning
< less than
<= less than and equal to

Page Np :14
> greater than
>= greater than and equal to
== comparsion
= equal to
!= not equal to

3. Logical Operators:
These operations are used for compound relational expressions or logical
expressions. When more than one relational expression occurs in a C expression
using logical operators, then such type of expressions are called Compound
Relational Expressions or logical expression. These are used in decision-making
statement and some looping statements like if, switch, do while, while and for
etc. These statements have either True (1) branch or false (0) branch. In other
worlds, these are used to form complex expression to take the decision. There
are mainly three logical operators used in C language as in the table below:

Logical Operators Meaning Priority


! Logical NOT Highest
(Not process the condition)
|| Logical OR Intermediate
(Process any one of the conditions.)
&& Logical AND Lowest
(Process two or more than two relational expressions)

Truth table of Logical AND and Logical OR:

A B A&&B A||B
0 0 0 0
1 0 0 1
0 1 0 1
1 1 1 1
Truth table for Logical NOT.
A !A
0 1
1 0

4. Assignment Operators:
Assignment operators are used for assigning an expression or value
(constant) to a variable. Assignment operators are further subdivided into two
types:

a) Simple Assignment Operator


b) Short hand Assignment Operator OR Arithmetic Assignment Operator
Page Np :15
These are used in Assignment Expression or Arithmetic Assignment Expression.
a). Simple Assignment Operator:
Simple assignment operator is (equal to). The general syntax of simple
assignment operator is as
V=constant value or expression;
Example x=10;
C=a+b;
where v is the variable and expression be any arithmetic expression.
b). Short hand or Arithmetic Assignment Operator:
These operators have equal to (=) sign with all the arithmetic operators.
The general syntax of short hand assignment or arithmetic assignment operator
is as:
v arithmetic operator = constant value or expression;
Where v is the variable and expression is an arithmetic expression. Here
the arithmetic operators used are *, /, +, -, %. For example, some valid
expressions having simple assignment and short hand assignment are as shown
in table:

Simple Assignment Shorthand Assignment


i=i+ 10; i += 10;
t=t*m-k; t *= m-k;

5. Conditional Operators:
Conditional Operators are also called ?: operators or Ternary operator.
These operators are used instead of block if statement (if-else statement). The
general syntax of conditional operator is as :
exp1 ? exp2 : exp3;

Here first of all exp I will be computed, which is a conditional expression. If exp1
is true, then exp2 will be executed. But if exp1 is false, then exp3 will be
executed. Note that exp2 and exp3 are either a single constant value or a single
variable or an arithmetic expression. For example, below is an if statement
having a and b two variables as:
a= 10; b = 5;
if (a> b)
c = a-b;
else
c = a + b;
The above if statement can be used by using the conditional operator in a single
c statement as below:
c = (a > b) ? a - b : a+ b;
The above expression is also called conditional expression.
6. Unary operators: c supports 3 unary operators 1 unary minus, Increment ,
Decrement Operators:

Page Np :16
These operators are also sometimes called special operators or unary
special operators. Another name of Increment / Decrement Operator is Counter
Operator. These are two as: ++ (increment operator) and - - (decrement
operator). Increment operators are used for incrementing the value one by one.
Similarly decrement operators are used for decrementing the value one by one.
These are further subdivided into two categories:

a) Prefix increment / Decrement Operator


b) Postfix Increment/ Decrement Operator a). Prefix Operator.

In the Prefix Increment operator, first of all value will be incremented and then
incremented value will be assigned to a variable. Similarly in the prefix
decrement operator first of all value will be decrement and then decremented
value be assigned to the variable. The general way is represented as:
++V; and - - V;
where v is the variable.

b). Postfix Operator:


In the postfix increment operator, first of all value will be assigned to the
variable and then it will be incremented. Similarly in the postfix decrement
operator, first of all value will be assigned and then it will be decremented. The
general way to represent the postfix operator is as:
V++; and V - -;
where v is the variable.
For example, suppose x is a variable having value 7 then y is another
variable which will be computed by using x variable. Here in case of increment
operator, it is computed as:

X=7; x=7;
y =++x; (prefix increment) y=x++ ; (postfix increment)
After processing: After processing
The value of y is 8. The value of y is 7.
The value of x is 8. The value of x is 8.

7. Bit wise Operators:


These are special operators for low-level programming. These operators
are used for the manipulation of binary data (bits). Note that Bit wise operators
should not be of float or double type. There are six types of Bit wise operator.
The table for Bit wise operators is as:
Bit wise Operator Meaning
& Bit wise AND
| (pipe symbol) Bit wise OR
^ Bit wise exclusive OR
<< Bit wise left
>> Bit wise right
~ (tilde) Bit wise NOT ( complement operator)

Page Np :17
Bitwise and(&)
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z=x&y 1 0 0 0

Bitwise or(|).
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z=x|y 1 1 1 0
Bitwise XOR
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z=x^y 0 1 1 0

Bitwise NOT

Variable b3 b2 b1 b0
x 1 1 0 0
z = ~x 0 0 1 1
<< Left Shift
a = 13 Binary 00001101 b = 6 00000110 Consider a << 2 which Shifts two bits to left , that is 2 zeros
are inserted at the right and two bits at the left are
moved out. 00001101
Moved 00110100
Finally the result is 00110100 . Deci 52 (13x4)
7. Special Operators:
These are used for special purposes in C-language. These operators are
used in pointers, structures and unions etc. Some types of special operators are
as:
1. Comma Operator
2. Sizeof Operator
3. Type Operator
4. Pointer Operator
5. Member Selection Operator

Page Np :18
2. Comma Operator:
When number of statements occur in a C-program having a relation ship
between expressions, then we can write all the expressions or statements in a
single expression using comma operator. This is explained by below examples:
int a,b,c;
3. Sizeof () Operator:
It is also called compiler operator or compile time operator. It displays
number of bytes (size) covered by a variable or an expression. The general
syntax of sizeof operator is as
N=sizeof (v or e);
Here n should be of integer type. Here v is variable and e is an arithmetic
expression. For example:

int a, b;
float x = 1500;
a = sizeof (x);
b = sizeof (x * 12-13/1000);
Note that result be in integer form stored in the variable a and b.

9) TYPE CONVERSION AND TYPE CASTING

Type conversion and type casting of variables refers to changing a variable of


one data type into another.
While type conversion is done implicitly, casting has to be done explicitly by the
programmer.
Type conversion is done when the expression has variables of different data
types. So to evaluate the expression, the data type is promoted from lower to
higher level where the hierarchy of data types can be given as: double, float,
long, int, short and char.
Example: type conversion is automatically done when we assign an integer
value to a floating point variable

Ex:
float x;
int y=3;
x=y;
Now x=3.0
Type casting is also known as forced conversion. It is done when the value of a
higher data type has to be converted in to the value of a lower data type.
Ex: we need to explicitly type cast an integer variable into a floating point
variable.
float salary=10000.00;
int sal;
sal=(int)salary;

Page Np :19
Typecasting can be done by placing the destination data type in parentheses
followed by the variable name that has to be converted.
5. Pointer Operator:
There are two types of pointer operators used in C-language. These are &
(it is not Bit wise AND) and * (it is not multiplication sign or an arithmetic
operator). Pointer means it access the address of variable stored in the memory
6. Member Selection Operator:
These operators are used in structure and union. These operators are used to
create a relationship between owner and member within a structure or union
data. These are (dot operator) and -> (relationship operator or member
operator)
10) What are the Input / Output Statements available in C?

Input Statements:
Input statements are used for reading integer, real, character,
string and mixed type data. For this purpose some standard input
functions are used, which are embedded in stdio.h (standard input output
header file). These are of five types as below:

1. getchar( ) 2. scanf( ) 3. gets ( )


4. getch( ) 5. getche( )

1. getchar( ):
This function is used for reading a single character from the keyboard.
Note that the variable in which you want to store a single character should be of
character type. The general syntax is as:
char v;
v = getchar( );
Where v is the variable of character type.

For example:
char x;
x = getchar( );
A simple C-program to read a single character from the keyboard is as:

/* To read a single character from the keyboard using the getchar statement */
#include<stdio.h>
#include<conio.h>
main ( )
{
char x;
printf ("\n Press any key from the keyboard");
x = getchar( );
}

2. scanf ( ):

Page Np :20
The scanf input statement is used for reading mixed data type. You can
read integer, float, character, hexadecimal, octal, decimal data by using its
control codes or format codes. The general syntax is:

scanf ("control string ", &v1, &v2, &v3, ... &vn);

Where arg1, arg2 ... argn are the arguments for reading and v1, v2... vn are all
the variables. Here control string has some format codes or format specifier or
conversion characters used for different data types. The scanf format code
(specifier) is as shown in the below table:
Format Code Meaning
%c to read a single character
%d to read a signed decimal integer (short)
%ld to read a signed long decimal integer
%e to read a float value exponential
%f to read a float (short) or a single precision value
%if to read a double precisian float value
%g to read a float double
%h to read a short integer
%i to read a integer (decimal, octal, hexadecimal)
%o to read an octal integer only
%x to read a hexadecimal integer
%u to read an unsigned decimal integer (used in pointers)
%s to read a string
%[..] to read a string of words from the defined range
%[^] to read a string of words f\which are not from the defined

For example, suppose you want to read a single character from the keyboard,
an integer numeric value, a numeric value having decimal point (real or float
value)
and a string , then the procedure to read all these different types of values by
using the
scanf()input statement is described in the below simple C program procedure as:

main ( )
{
char x, y[20];
int a;
float z;
printf ("\n Enter a single character, name, integer data and a real value");
scanf ("\n%c %s %d %f “, &x, y, &a, &z);
getche( );
Page Np :21
}

3. gets ( ):
The purpose of the gets( ) statement is to read a string. It will read a
string until you press enter key from the keyboard. It will mark null character
('\O') in the memory at the end of the string when you press the enter key. The
general syntax is as:
gets (V);
Here v is the string variable i.e. char variable (character type).
For example:
char x[80];
gets (x);
Now if you type "vinoothna", then x string variable will store the value
"vinoothna".
4. getch( ):
It will store any value (a single character) from the keyboard and also
displays it on the screen. The general syntax is as follows:
getch ( );
If you press 1, then it will not display the output on the screen and it will
store the data in the garbage. It can also be used at the end of the 'program to
terminate the output from output screen to the program editor screen.
5. getche ( ):
It will store any value (a single character) from the keyboard and also
displays it on the screen. The general syntax is as follows:
getche ( );
If you press 1, then it will display I on the screen. If you press enter key
or space then it will display blank space on the screen. It can also be used at the
end of the program to terminate the output from output screen to the program
editor screen.
Output Statements:
Output statements are used for writing, displaying or printing integer,
real, character, string and mixed type data. For this purpose C-compiler has
some standard output functions, which are embeded in stdio.h file. These are of
three types as below:
1. putchar ( )
2. printf ( )
3. puts ( )

1. putchar ( ):
Putchar( ) is an output statement. The purpose of putchar statement is to
display a single character on the screen. The general syntax of putchar is
putchar (v);
where v is the variable of character type in which a single character data
is stored.
For example, Suppose x is a character type variable having a value 'R' and it can
be displayed by using the putchar as:

Page Np :22
char x;
putchar (x);
2. printf ( ):
The printf() statement is used to display a text message or a value stored
in the variable. The general syntax used is as:
printf ("Control string", v1, v2 ... vn);
or
printf ("Message line or Text line");

Where v1, v2, ... vn are all variables.


The control string uses some printf( ) format codes or format specifier or
conversion characters. These all are discussed in the below table as

Code Meaning
%c to print a single character
%s to print a string
%d to print a signed decimal integer (short)
%ld to print a signed long decimal integer
%f to print a signed float or single precision real value
%lf to print a signed double precision value
%e to print an exponent float
%g to print a double
%o to print an octal number
%x to print hexadecimal no.
%u to print an unsigned integer

3. puts ( ):
The purpose of the puts statement is to the print or display a string
inputted by the gets statement. The general syntax of puts statement is
puts (V); or
puts ("text line");
Where v is the string variable.
For example: "I am a good boy" is a string stored in name variable. Then
it can be printed by using puts( ) statement. It is described by using the C
program as:
main ( )
{
char name[20];
gets (name);
puts ("you r name is”); puts (name);
getche( );
}

11) Explain different Control Statements available in C?


Page Np :23
In the term software or computer programming, it has a set of instruction
(in simple or complex form,) called Program. These instructions are also called
statements, which occurs sequentially or in either conditional way or in the
iterative way. To handle such types of statements, some flow controls required.
These flow controls are called Control statements.

These are illustrated as below:

a) if statement:

The if statement is a powerful decision making statement which can


handle a single condition or group of statements. These have either true or false
action. There are mainly four Types of if statements used in the C programming
as:

(i) Simple if statement


(ii) if-else statement
(iii) nested if statement
(iv) else-if or ladder if or multi-condition if statement

(i) Simple if statement:

When only one condition occurs in a statement, then simple if statement


is used having one block. The general syntax and general flow symbol of simple
if statement is:

if (condition)
{
true-statement block;
}
statement - x;

Page Np :24
(ii)if-else statement:

This statement also has a single condition with two different blocks. One is
true block and other is fialse block. The general syntax and generalflow symbol
used is as:

if (Condition)
{
true statement block;
}
else
{
false statement block;
}
statement-x;

(iii). Nested if statement:

When an if statement occurs within another if statement, then such type


of is called nested if statement. The general syntax of this statement is as

Page Np :25
if (condition-1)
{
if (condition-2)
st-1;
else
sf-1;
}
else
{
if (condition-3)
st-2;
else
sf-2 ;
}
statement-x;

(iv). Ladder if or else if statement:


When in a complex problem number of conditions arise in a sequence,
then we can use Ladder-if or else if statement to solve the problem in a simple
manner. In this statement first condition will be checked, if it is true then action
will be taken, otherwise further next condition will be checked and this process
will continue till the end of the condition.
The general flow chart look like a ladder, so it is called Ladder-if statement.

The general syntax is as:

Page Np :26
if (condition-1)
st-1;
else if (condition-2)
st-2;
else if (condition-3)
st-3;
.
.
.
else if (condition-n)
st-n;
else
default-statement;

statement-x;

The general flow chart is as:

b). Switch Statement:

When number of conditions (multiple conditions) occurs in a problem and


it is very difficult to solve such type of complex problem with the help of ladder if
statement, then there is need of such type of statement which should have
different alternatives or different cases to solve the problem in simple and easy
way. For this purpose Switch statement is used. It is also called Case statement
because it has different cases and different blocks. It is also called multi-decision
statement having multiple blocks. V data type is not accept float data type.

The general syntax of this statement is as:

Page Np :27
switch (e or v)
{
case value1: block1;
break ;
case value2: block2;
break;
case value3: block3;
break;
case value n: block n;
break;
default: block n + 1;
break;
}
statement-x;
Where e is an arithmetic expression and v is the variable.
2. Looping Statements:
When a single statement or a group of statements will be executed again and
again in a program (in an iterative way), then such type processing is called
loop.

(i). Entry Control Loop:


. while statement or while loop
In entry control loop first of all condition is checked, if it is true, then body of
loop is executed, otherwise the control is moved out of the loop i.e. we can exit
from the loop, when the condition becomes false. The while loop and for loop are
the example of the entry controlled loop.

The flow symbol for entry control loop is as:

ii). Exit Control loop:

Do statement or do loop

In the exit control loop, first body of loop is executed and then condition is
checked. If condition is true, then again body of the loop is executed. If the
condition is false, then control will move out from the loop. Example of exit
control loop is do statement. The general flow symbol is:

Page Np :28
a) While statement:

The general syntax is


while (test condition)
{
block of statements;
}
statement-x;

b) Do statement or Do-loop:
. The syntax of do-loop is as follows:
do
{
block of statements;
}
while (condition);
statement-x;

Note : semicolon must be at the end of the while condition.

c) For statement or for loop:


It a-looping statement, which repeat again and again till it satisfies the
defined condition. It is one step loop, which initialize, check the condition and
increment decrement the step in the loop in a single statement.
The general syntax is as:

for (initialvalue; testcondition; increment/ decrement)


{
body of the loop;
}
statement-x;

It is also entry controlled loop, where first condition is checked and the body
of the loop be executed. In this case, first we initialize the value, then in the

Page Np :29
loop we apply the condition and further we increment or decrement the loop
according to requirement. After execution or completion of the body of the
loop when the condition becomes false, the statement-x will be executed.

d) Nested for statement:


When a for statement is executed within another for statement, then it is
called nested for statement. We can apply number of nested for statements in C-
language.
The general syntax is:

for (initial value1; test condition1; incrementl /decrement1)


{
for (initial value2; test condition2; increment2 /decrement2)
{
inner- body of the loop;
}
outer-body of the loop;
}
statement-X;

For one value of outer loop, inner loop will repeat n times. So inner loop will be
completed first and then outer loop will be completed. After completion of inner
and outer loop, statement-x will be executed.

3 Jumping Statement:

There are three different controls used to jump from one C program
statement to another and make the execution of the programming procedure
fast. These three Jumping controls are:

a). goto statement


b). break statement
c). continue statement

Page Np :30
a). goto statement:

The powerful Jumping Statement in the C language is goto statement. It


is sometimes also called part of branching statement. The go to moves the
controls on a specified address called label or label name. The goto is mainly of
two types. One is conditional and the other is unconditional. Also jump can be
either in forward direction or in backward direction. The different types of goto
statement is:

(i) Forward goto


(ii) Backward goto

(i). Forward goto:


In this the control moves forward at a specified label either according to a
condition or without condition. The general syntax is as:

sl;
s2;
goto label;
s3;
s4;

label:

s5;
s6;

Note that here first statement sl and s2 will be executed, then specified
label (in C-language it is label name) and execute the statements s5 and s6. It
will skip a part of the program i.e. s3 and s4 statements. In C-language label
name is either a single character or combination of characters.

(ii). Backward goto:

The backward go to or backward jump moves the control back to the


specified addresses and so creates a loop. In the case of conditional backward
statement, it creates finite looping, but in the case of unconditional backward go
to or jump, it I creates infinite looping. The general syntax of backward jump
statement is as follows:

s1;
label: s2;
s3;
goto label;
s4;

Here first of all statements sl, s2 and s3 will be executed. Then it will find
a backward go to statement with a specified address and again s2, s3 statement
will repeat either according to a condition or infinite times if there is no
Page Np :31
condition. Below written example is of both conditional and unconditional
backward go to:
main( )
{
int x, y;
start :
printf ("\n Enter the value of x”);
scanf ("%d", &x);
if (x < 0)
goto start;
y = sqrt (x);
printf ("\n Square root of %d is %d", x, y);
getche( );
}
The output is:

Enter the value of x -5


Enter the value of x 25
Square root of 25 is 5

Q)Break and Continue Statement:

Break statement always used with the decision-making statement like if


and switch statements. The statement will quit from the loop when the condition
is true. The general syntax for break statement is as:

break;

This statement is used within do-loop, while loop and for loop. The use of
break statement within the while loop structure is as:

while (condition-1)
{
…..
if (condition-2)
break; …..
}
statement-x;
By using the structure of the for loop, the break statement is used as:
for (initial value; condition; increment / decrement)
{
if (condition-1)
break;
}
statement-x;
As in the above structure, when condition-I becomes true, then it will
break the loop and quit from the for loop and move to the statement-x, i.e. after
exiting from the for loop, statement-x will be executed. For example, suppose
Page Np :32
you are computing the sum of first n positive integer number (i =1 to n) and the
computation will quit if the value of the i becomes 7. The procedure be as
follows:
#include<stdio.h>
main( )
{
int n, i, sum;
printf("\n Please Enter the value of N: “);
scanf(" %d", &n);
sum=0;
for( i=1 ; i < = n; i++)
{
sum = sum + i;
if ( i==7)
break;
}
printf("\n SUM is: %d", sum);
getche( );
}

The output is:


Please Enter the value of N: 10
SUM is: 28
Continue statement:
Continue statement also comes with if statement. This statement is also
used within any loop statement like do loop, while loop and for statement. The
general syntax of this statement is as:
continue;
This statement will skip some part of iteration (loop) and comes to the
next looping step i.e. it will increment / decrement the loop value, when
continue occurs. The general structure of the continue statement is as:
while (condition-1)
{

sl;

s2;

if (condition-2)

continue;

s3;

s4;

Statement-x;

Also by using the for loop the continue statement be described as:
Page Np :33
for (initial value; condition-1; increment/decrement)
{
sl;
s2;
if (condition-2)
continue;
s3;
s4;
}
satement-x;

In all the above structure, First off all the statement sl and s2 will be
executed. When a condition met within the loop and if the condition becomes
true, then the continue statement be executed and it will move to start the next
looping iteration by skipping the statement s3 and s4. When condition becomes
false, then the statement s3 and s4 will execute. After completion of the loop,
the statement-x will be executed. For example, suppose if you want to find
average of the different n positive numbers and it will ignore the sum of the
given negative number. The procedure be as follows:

/* Program to illustrate the concept of continue statement ?*/


#include<stdio.h>
#include<conio.h>
main()
{
int n, i, sum = 0, a;
float av;
clrscr( );
printf("\n Please Enter the value of N:”);
scanf("%d", &n);
for( i =1; i < = n; i++)
{
printf("\n Enter any number:”);
scanf(" %d ", &a);
if(a < 0)
continue;
sum= sum + a;
}
printf("\n SUM IS: %d ", sum);
av= (float) sum /n;
printf("\n Average is :%f av);
getche( );
}
The output is.,
Please Enter the value-of N: 5
Enter any number 20
Enter any number -8
Page Np :34
Enter any number 3 0
Enter any number -2
Enter any number 10
SUM is: 60
Average is : 12.00

Q)Write a short notes on arrays in C?


Array is similar type of data collection referenced by unique name i.e. it
is a collection of same data type elements.or An array is a group of related
data items, which share common name. or It is the set of homogeneous data.
Types of Array:

The types of the array depends upon the given problem. Array are mainly
of two types:

(i) Linear Array


(ii) Non-Linear Array
(i). Linear Array:

This type of array is also called one Dimensional Array. This is also called
list array. Another name of linear array is called single-dimensional array. These
array are of ladder type. In the linear array only one subscript is used. It is
written either in row or in column form. The syntax to define or declare linear
array is

data-type array-name [size];

Where data types are integer (int), real(float), double and character(char) . size
is started 0 to size-1. For example, some of the valid one dimensional array
declaration statements are written as below:

int x[50];
float salary[30];
char nm[20];
Suppose if you want to store the data "AMRITSAR' in the array name city, then
the representation for declaration be as char city[9]; We can declare that data
type char for city variable and you can store maximum 8 character in the
different cells of the city variable. So we see that when we declare character
type array, size should be one cell more than the given data length, because last
cell should be empty or null cell i.e. the end of the string has null character. It is
denoted by "\0".
char city[9];

A M R I T S A R \0

How to declaration of array which have fixed or constant value is defined as:

static data-type array-name [size] = {list of values};

For example, the above said different values can be assigned to the array as

Page Np :35
static int numbers [5] = {55, 35, 40, 47, 33};

Now if we assign data as:

static int number[5]={55, 35, 40};

then the different values assigned to different array variables as:

number[0]=55, number[1]=35, number[2]=40, number[3]=0, number[4]=0.

Similarly we can declare and define values in float type of variables.


For example:
static float a[4] = {10. 3, 50, 7.2};
Here a[0] = 10.3,
a[l] = 50.0,
a[2] = 7.2,
a[3] = 0.0.

Also you can declare character type data in the array as:

static char name[ ]= { ‘D’, ‘H’, ‘E’, ‘E’, ‘R’, ‘A’, 'J'};

Here data to the character variable be assigned as: name[0] = 'D', name[1] =
'H', name[2] = 'E', name[3] ='E', name[4] = 'R', name[5] = 'A', name[6] = 'J',
name[7] = '\0',

(ii). Non-Linear Array:


Array of having different dimensions or n subscript is in the form of
Nonlinear array. Non-linear array are further of n different types as:
(a) Two Dimensional Array
(b)Three Dimensional Array
a). Two Dimensional Array:
These arrays are also called double dimensional array. Another
name of two-dimensional array is Tabular or Rectangular Array. These arrays are
in row and column form, so these are also called Row-Column array or square
Array. These arrays have two subscripts and also called double subscripted
array. We can write the double dimensional array in the matrix form as below
and so these are also known as matrix array. The syntax used for declaration of
two dimensional array is as:
data-type array-name [row size] [column size];

For example, some of the valid double dimensional arrays are written as below:

int a[10][10];
float b[50][50];
char name[10][20];

Page Np :36
Also you can declare two-dimensional array in static form i.e. these type of array
declarations have fixed value or constant value. The syntax used for static two
dimensional array is as follows:

static data-type array-name [row size][column size = {list of value};

For example, suppose you want to assign some fixed value to a variable array
named table by using the static two-dimensional array as.

static int table [2][3] = {15, 7, 12, 2, 20, 8};

Here the values assigned to the tabular array-name is as:

table[0][0] = 15
table[0][1] = 7
table[0][2] = 12
table[l][0] = 2
table[l][1] = 20
table[l][2] = 8
Also we can write the above statement as:
static int table[ ][ ] = {15, 7, 12, 2, 20, 8};
Above statement fails in some cases.
Another way to write the above statement is as follows:
static int table[][]={ {5, 7, 12} , {2, 20, 8} };

char table[2][30]={“kumar”,”dheeraj”};

b)Multi Dimensional Array:

It is a collection of double dimension arrays. Each double dimension array is


identified by with ‘i’ each array is identified by ‘j’ and each value is identified
by with ‘k’

Syntax: Datatype variable[no_of_dd_arrays][row_size][col_size];

Eg: int a[2][3][3];

initialization of array
int a[2][3][3] ={
{
{1,2,3},
{4,5,6},
{7,8,9}
},

{
{1,2,3},
{4,5,6},
{7,8,9}
},
Page Np :37
};

Int a[2][3][3]= {
{{1,2,3},{4,5,6},{7,8,9} }},

{{1,2,3},{4,5,6},{7,8,9} }},
};
Accessing into one dimentional array
Ex:

int a[5] , i ;

for(i=0; i<5; i++)

scanf(“%d”,&a[i]);

Accessing into two dimentional array

Ex:

int a[3][3] , i , j;

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

for(j=0; j<3; j++)

scanf(“%d”, &a[i][j]);

Q)Explain different String Handling Functions in C? or


miscellaneous strings ?

C-language is rich in library functions, but to handle or operate some


operations with string, we use some powerful string-handling functions. All these
function are linked with the "string.h" header file stored in the include sub-
directory in the Turbo-C compiler. Here we explain the five commonly used
string handling function as:
(i) strcat ( )
(ii) strcmp ( )
(iii) strcpy ( )
(iv) strlen ( )
(v) strrev ( )
(i) strcat ( )

The purpose of this string handling function strcat( ) is to concatenate or


combine two different strings together. The general syntax used for this is as:
strcat(string1, string2);
Here string1 is combined with string2 and result will be stored (combined
string) in string1. For example, suppose x is "HELLO" and y is "DEAR", then after
applying the strcat( ) function, the result will be "HELLO DEAR" and it will be
stored in the x. The representation can be done by using the procedure as:
Page Np :38
char x[80], y[30];
scanf("%s%s",x,y);
strcat (x, y);
printf ("%s", x);

strcmp( ):
The purpose of this function is to compare two strings. It will check which
string is alphabetically above the others. For comparison ASCII (American
Standard Code for Information Interchange) values are used. The general syntax
is as:
strcmp (string1, string2);-

If the ASCII difference of each character in the two different strings from
the first alphabet (till null character of any string occurs first) is zero, then both
the strings are equal. If difference is +ve, then string2 is larger than the string1,
but if the difference is -ve, then string1 is larger than the string2. For example,
suppose you have two character string variables having two different strings i.e.
"their" is stored in the string1 variable and "there" is stored in the string2
variable, then you can compare these two strings by using the strcmp function
as:

char string1[20] , string2[20];


strcmp (string1, string2);
Here the ASCII difference between string1 and string2 is negative and so
the string1 is alphabetically above than the string2. Similarly you can apply
some more operations using this function.

strcpy( ):
The purpose of this function is to copy one string into another string. Note
that target or destination field should be larger than the source field. In other
words size of the string1 should be larger to receive the contents of the string2.
The syntax is as follows:
strcpy(string1, string2);
It will copy the data from the string2 to the string1 variable. Also note
that the length of the string1 should be larger than string2. For example, if you
want to copy the data "BOMBAY" to the string variable city, then the procedure
is as follows:
char city[30];
strcpy (city, "BOMBAY");

strlen( ):
The purpose of this function is to count the number of character in a
string i.e. to find the length of the string. The general syntax is as:
n = strlen (string);

Where n should be of integer type and string variable should be of character


type. For example, suppose if you want to find the number of character (length

Page Np :39
of the string) of the string "I am a good boy" assigned to the string variable ct,
then this can be done as

int n;
char ct[20];
n = strlen(ct);
printf ("length is = %d", n);
It will display the result 15 (space character is also included).

Note that counting ends at the NULL character i.e. Null character "\0" is not
included in the counting of characters.

strrev( ):
The purpose of this function is to reverse a string. This function takes
string variable as its single (only one) argument. Here the first character
becomes last and last character becomes first in a string. It is very useful to find
whether a string is palindrome or not.. The general syntax used for this function
is as follows:
strrev(st);
Here st is a string (character type) variable. For example, if you have a
string data "vinoothna” the string variable st, then after using the function as:
strrev(st);
printf("\n Reversed string is:%s",st);
The string variable st will display the result "anhtooniv”.

Q )Explain string taxonomy?

In c string can store either in fixed length format or in variable length format
Fixed length string : we need specify an appropriate size for string variable. If
the size is too small, then you will not be able to store all the elements in the
string. If the string is large, then unnecessarily memory space will be wasted.
Variable length string: in this string can be expanded or contracted to
accommodated the elements in it. This can be done either by using length
controlled string or a delimiter.
Length controlled string: in a length controlled string u need to specify the
number of characters in the string.
Delimited string:
The string is ended with a delimiter. This identify the end of the string.

Page Np :40
Q)What is a Function, what are the advantages of the functions
(why we need for functions)?

Subprogram is the independent and complete program. It is also called


function program or function sub-program. In other words sub-programs are
complete because, these are the programs, which have the global as well as
local declaration statement, executable statement and function calling statement
like main program. Subprograms in the C-language are called user-defined
functions. A sub-program is independent because it can be called by the main
program or other sub-program. As C has number of library function, which are
in-built in the C-compiler (compiler's library cannot provide built-in library
functions used in all the situations), but user defined functions are declared and
defined by user according to his/her requirement and problem definition. So we
can say functions are mainly of two types represented as:

Function or Sub-Program

Library Function User-defined Function

or or

Standard in-built Function self-contained Program

or or

Compiler Function Call-by-value &

Call-by-reference

Example:
(like sqrt( ), pow( ), tan( ) etc.) (like addition( ), rajan( ), etc.)

Advantages of a function sub-program (Why we need function):


Following are the some advantages of functions:
(i) Function makes the lengthy and complex program easy and in short
forms. It means large program can be sub-divided into self-contained
and convenient small modules having unique name.
(ii) The length of source program can be reduced by using function by
using it at different places in the program according to the user's
requirement.
(iii) By using function, memory space can be properly utilized. Also less
memory is required to run program if function is used.
(iv) A function can be used by many programs.
(v) Function increases the execution speed of the program’ and makes the
programming simple.
(vi) By using the function, portability of the program is very easy.
(vii) It removes the redundancy (occurrence of duplication of programs) i.e.
avoids the repetition and saves the time and space.

Page Np :41
(viii) Debugging (removing error) becomes very easier and fast using the
function sub-programming.
(ix) Functions are more flexible than library functions.
(x) Testing (verification and validation) is very easy by using Functions.
(xi) User can build a customized library of different function used in daily
routine having specific goal and link with the main program similar to
the library functions.

Q) Explain categories of functions? Or types

Depending on the process the function can be defined in 3 categories

1. Functions with no arguments and no return values.


2. Functions with arguments and no return values.
3. Functions with arguments and return values.

1) Functions with no arguments and no return values:


When a function has no arguments, it doesn’t receives any data
from calling function. Similarly when it doesn’t return any value,
the calling function doesn’t receives any data from the called
function. That is, there is no data transfer from calling function
and the called function.

Control

main () No Input
Function 1()
{
{
……………..
………………..
…………….
No Output ………………..
Function1 ();

Control

/*************************************************************************
EXAMPLE FOR FUNCTION WITHOUT ARGUMENTS AND WITH OUT RETURN VALUES
**************************************************************************/
#include<stdio.h>
#include<conio.h>
void DrawLine();
void main()
{
clrscr();
DrawLine();
printf(“WELCOME TO LAB”);
Page Np :42
DrawLine();
getch();
}

void DrawLine( )
{
int i;
for(i=1;i<=30;i++)
printf(“_”);
printf(“\n”);

Output:
---------------------------------
WELCOME TO LAB

---------------------------------

2) Functions with arguments and no return values:


In this method there is a data transfer from calling function to called
function, however there is no data transfer from called function to calling
function. The parameters are used to transfer the values from calling function to
called function.

Values of

Arguments
main ()
Function1( int a)
{
{
……………..
………………..
…………….
………………..
/**********************************************************************************
EXAMPLE FOR FUNCTION WITH ARGUMENTS AND WITH OUT RETURN VALUES
**********************************************************************************/

#include<stdio.h>
#include<conio.h>
void swap(int a,int b);
void main()
{
int a,b;
clrscr();
printf("enter 2 values");
scanf("%d%d",&a,&b);

Page Np :43
swap(a,b); //Calling function
getch();
}

void swap(int a,int b) /*Called Function*/


{
int temp;
temp=a;
a=b;
b=temp;
printf("\n After swaping..%d,%d",a,b);
}

3) Functions with arguments and with return values:

In this method there is a data transfer from calling function to called


function and called function to calling function. The parameters are used to
transfer the values from calling function to called function. The return statement
is used to transfer the value from called function to calling function. The return
statement can always return only one value.

Values of

arguments

main ()
int Square( int no)
{
{
……………..
………………..
…………….
………………..
Res = Square (10)
/********************* EXAM PROGRAM ************************

Program for Functions with arguments with return values


(or)
W.a.Function to determine the largest 3 given values

**********************************************************/

#include<stdio.h>
#include<conio.h>
int big(int ,int, int );
void main()
{
int a,b,c,max;
clrscr();

Page Np :44
printf(" enter 3 nos");
scanf("%d%d%d",&a,&b,&c);
max=big(a,b,c);
printf("\n The biggest no is: %d",max);
getch();
}

int big(int a, int b, int c)


{
if(a>b && a>c )
return a;
else if( b > c )
return b;
else
return c;
}

OUTPUT:

enter 3 nos....5 2 4

The biggest no is ... 5

Q) Call by value and call by reference

Call by value in C
In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.
In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
In call by value, different memory is allocated for actual and formal parameters since
the value of the actual parameter is copied into the formal parameter.
The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.

#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);

Page Np :45
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Call by reference in C
In call by reference, the address of the variable is passed into the function call as the
actual parameter.
The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored
at the address of the actual parameters, and the modified value gets stored at the same
address.
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Page Np :46
1. Explain about procedure-oriented programming?

A. Procedure oriented programming is nothing but the high level language like C,
COBOL, and FORTRAN etc. In this the program is divided into number of functions. A
function is nothing but the set of instructions the computer has to follow. The
structure of procedure oriented programming is as shown below:

main Program

Function-1 Function-2 Function-3

Function-4 Function-5

Function-6 Function-7 Function-8

In procedure-oriented programming we concentrate more on the development of the


function rather than on the data, that is used in the functions. Here we have global
variables that can be used any where in the program and local variables that are
being restricted to a particular function only.

Global Variable Global Variable

Local Variable Local variable Local variable

Page No : 46
In the larger programs it is difficult to identify which data is used in a specific
function. If we want to use the external data we need to move to all the functions
that access this data in which there is a chance of coming errors.

2. What are the characteristics of procedure-oriented programming?

A. The characteristics of procedure oriented programming include:


 Larger program is divided into smaller functions.
 Functions share global data.
 Data moves openly from one system to another.
 Here we concentrate mainly on functions.
 Employs top down approach.

3. Explain about object oriented programming?

A. The main aim of object-oriented programming is to remove the problems occurred in


procedure-oriented programming.
In this, data is being considered as the major factor & does not allow it to flow
freely from one system to another. Here, we restrict the data to a particular function
only. The problem here is divided into a number of objects. Objects consist of data
and functions. The arrangement of data and functions in an object is as shown
below:
Object-A Object-B

Data Data

Function Communication Function

Data

Function

Object-C

47
Here every object has its own data, which is used by that object’s function only. That is
Object-B cannot access the data of object-A or object-B. In this way we can secure the
data in our program.

4. Explain the concepts of object-oriented programming?


A. The concepts of object-oriented programming include:
1. Object
2. Class
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8.Message passing

1. Object: Object may denote a thing, a person a place or some data in our
program. It consists of data and functions. They are the run time entities of the
system.
When a program is executed object interact with each other through messages.
For example consider two objects “customer” and “account”. The “customer” object
sends a message to the “account” object requesting to send the bank balance details.
When the “account” object gets the message, it sends the bank balance details back
to the “customer” object. Each object communicates with other objects with out
knowing the details of data or code. It is enough if we know the type of the message
we send and the message we receive. Objects can be denoted as follows:

Student
Object: Student

Data:
Name: Total
DOB:
Marks:
Average
Function:
Total( )
Average( )

2. Class: The objects can be made user defined data types with the help of the
class. Objects are the variables of the type class. Once a class is created we can
define any number of objects for that class. For example, consider mango, apple and
orange are the members of the class fruit then
fruit mango;
helps us to add a new object belonging to the class fruit.

48
3. Data Abstraction: Abstraction represents the essential features of the class
without back ground details. Since classes use the concept of data abstraction they
are known as “abstract data types”.

4. Data Encapsulation: Wrapping up of data and functions into a single unit is


called as data encapsulation. This is the most striking feature of the class. We use
the data only to the function that are used in the class. This way of isolating the
data from the direct access is called as data encapsulation.

5. Inheritance: Inheritance is the process in which the objects of one class acquire
the properties of another class. It supports hierarchal classification. Inheritance
provides the idea of reusability of the code. The property of inheritance is as
shown below:

Birds
Attributes:
Feathers
Lays eggs

Flying Birds Non Flying Birds


Attributes: Attributes:

Robin Swallow Penguin Kiwi

Attributes: Attributes: Attributes: Attributes:

If we consider the example bird “Robin” which is a part of flying bird which again a
part of bird. This tells us that a derived class has some characteristics of the class
from which it is derived. We can add new features to the class with out changing it.

6. Polymorphism: It is a Greek term, which means the ability to make more than
one form. It is divided into two types. They are run time polymorphism and
compile time polymorphism. The compile time polymorphism consists of operator
overloading and function overloading. An operator exhibiting different behaviors

49
at different times is called as operator overloading. For example, consider the
symbol ‘+’ . If it is put in between two numbers it will display sum. If the same
symbol is placed between strings it will concatenate the strings and produces the
third string. In the similar way a function having a similar name with different
argument is called as function overloading. An example of function overloading is
as shown below:
Shape
Draw ()

Circle (object) Box (object) Triangle (object)


Draw (circle) Draw (Box) Draw (Triangle)

Polymorphism is used along with polymorphism.

7. Dynamic Binding: It is also called as late binding. It means that the code of the
procedure is not known until run time. It is linked with inheritance and
polymorphism.

8. Message passing: Objects communicate with each other by sending the


information like we do communicate with one another. Message passing helps to
build the system and share the information. To pass a message we need to name
of the object, the name of the function and the information to be sent.
Ex: employee.salary(name);

5. What are the advantages of object-oriented programming?


A. Object oriented programming provides different benefits to the designer and the
user.
 The data hiding helps to build secured programs.
 It is easy to work with objects.
 Through inheritance we reduce the code and extend the use of classes.
 Message passing helps to communicate between objects.
 Software complexity is easily managed.
6. Explain the applications of object-oriented programming?
A. The various applications of object-oriented programming include:
 Used in real time systems.
 Artificial intelligence and expert systems.
 Neural networks and parallel programming.

50
 CAD/CAM/CIM systems.
 Object oriented database.

7. What are the characteristics of object-oriented programming?

A. The characteristics of object-oriented programming include:


 The program here is divided into a number of objects.
 Data is hidden and cannot be accessed by the other external functions.
 Objects communicate with each other through functions.
 We concentrate more on data and do not allow it flow freely.
 New data and functions can be added easily.
 Follows bottom up programming.
Finally an object oriented programming is defined as an approach of dividing the
program into data and functions that can be used as templates for creating copies of
such modules on demand.

51
I/O STREAMS

1. Explain about I/O streams?


A. A stream is a sequence of bytes. It may be the source from which the input is
obtained or the destination to which the output has to be sent. The source stream
stream that provides the data to the program is called as the input stream and
the destination stream that receives the data from the program is called as the
output stream i.e.; the program extracts the data from the input stream and inserts
the bytes into the output stream.

Input stream
Extract from
Input
Input Device
stream

Program

Output device

Output stream insert


into
output
stream

The data from the input stream can come from the keyboard or any other storage device.
Similarly, the output from the output stream can be displayed on the screen or any other
output device. C++ has some predefined streams that are opened automatically when the
program begins its execution. They include the “cin “ and “cout” that are frequently used in the
program.
In C++, I/O system contains a hierarchy of classes that are used to
define various stream. These classes are called as the stream classes. The stream
classes must be defined with the header file “iostream.h”. The hierarchy of the
stream classes is as shown below:

IOS

I STREAM STREAM BUF O STREAM

IO STREAM
Page No: 52
In the figure “ios” is the base class for the istream (input stream) and for the ostream
(output stream). The class “ios” is declared as the virtual base class so that one copy of its
members is inherited by “iostream”. The class “ios” provides the basic support for the
formatted and the unformatted I/O operations. The class “istream” is used to handle
formatted and unformatted input while the “ostream” provides the facilities for handling
formatted output. Thje classes “istream_with assign” , “ostream_with assign” and
“iostream_ with assign add assignment operator to these classes. The stream classes for its
console operations is as shown below:

1. Contains basic facilities that are used for all other input
IOS and output classes.
(General input/output 2. Also contains pointer to buffer objects.
stream class) 3. Declares constants and functions that are necessary for
formatted input and output operations.
1. Inherits the properties of “ios”.
I STREAM 2. Declares the input functions such as get(), get line ( )
(Input Stream) and read( ).
3. Contains overloaded extraction operator “>>”.

1. Inherits the properties of “ios”.


O STREAM 2.Declares the output functions such as put() and write( ).
(Output Stream) 3. Contains overloaded insertion operator “<<”.

1. Inherits the properties of I stream & Ostream through


I/O STREAM multiple inheritance and thus contains all input and output
(Input/Output Stream) functions.

1. Provides an interface to physical devices through buffer


Streambuf 2. Acts as a base for filebuf class used in “ios” files.

Unformatted I/O operations:


They include 1. overloaded operator : >> and <<
2. get( ) and put( ) functions and
3. getline( ) and write( ) functions.

Overloaded operators:
The “>>” (extraction) operator is overloaded in istream class. The following the
general format for reading the data from the keyboard.

Page No: 53
Syntax: cin>>var1>>var2>>var3>> ................. >>varn;
Here var1,var2, ........... varn are the variable names. The operator”>>” reads a character
from the keyboard and assigns it into an indicated location.

The operator “<<” (insertion) is overloaded with the help of the ostream class. The
following is the general format for displaying output on the screen.
Syntax: cout<<var1<<var2<<var3<<.................. <<varn;

Example:
void main( )
{
clrscr( );
int x;
cout<<”Enter a number:”<<endl;
cin>>x;
cout<<”The value of the number is:”<<x<<endl;
getch( );
}

Put( ) and get( ) functions:


The class istream and ostream defines two new functions get( ) and put( ) that are used to
handle single character input and output operation.
get( ): There are two types of get functions they are:
1. get (void) and 2. get (char *)
These both are used to fetch a character including a blank space or a new line character. The
get (void) returns an input character where as the get (char *) assigns input character to
its arguments.
Put( ): The put( ) is a member function of the ostream and can be used to output a line of
text, character by character.

Example:
/* Character I/O with put( ) and get( ) functions */
# include <iostream.h>
# include <conio.h>
void main( )
{
int count = 0;
char c;
cout <<”Enter the input text:”<<endl;
cin. get(c );
while (c!=’\n’)
{
cout.put(c );
count++;
cin.get( c);
}
cout<<”The number of characters is:”<<count<<endl;
getch( );
}
Getline( ) and write( ) functions:

Getline( ): The getline( ) function reads a whole line of text that end with a new line
character. The function can be invoked with the help of the cin object.
Page No: 54
Syntax: cin.getline (line, size);
Example:
void main( )
{
clrscr( );
int size = 20;
char city[20];
cout<<”Enter the name of the city:”<<endl;
cin >>city;
cout<<”The city name is :”<<city<<endl;
cout<<”Enter the name of the other city:”<<endl;
cin. getline(city, size);
cout<<”The name of the other city is:”<<city<<endl;
getch( );
}

Write( ): It displays the entire line on the screen.

Syntax: cout. write (line, size);

Example:
void main( )
{
clrscr( );
int size = 20;
char city[20];
cout<<”Enter the name of the city:”<<endl;
cin >>city;
cout<<”The city name is :”<<city<<endl;
cout<<”Enter the name of the other city:”<<endl;
cin. getline(city, size);
cout<<endl;
cout.write(city, size);
cout<<endl;
getch( );
}

Formatted I/O operations:


C++ supports a number of features that could be used for formatting the output. They
include:
1. IOS class functions and flags. 2. Manipulators and
2. User defined output functions.

The “IOS” class contains a large number of functions that help us to format the output in a
number of ways. Some of them are as shown below:

Page No: 55
Width( ) To specify the required field size for displaying the output
Value.

Precision( ) To specify the number of the digits to be displayed after


Decimal point of the float value.

Fill( ) To specify the character that is used to fill the un used


Portion of the field.

Setf( ) To specify the format flags that can control the form of
Output display (Such as left, right and center justification)

Unsetf( ) To clear the flag specified.

To access these manipulators we have to include “iomanip.h ” header file in our program.

Width( ): It is used to define the width of the field. As it is a member function we use an
object to invoke it as shown below:
Syntax: cout.width(w); where w is field width
Example:
void main( )
{
cout. width(5);
cout<<543<<12<<”\n”;
cout . width(15);
cout<<543;
cout<<width(5);
cout<<12<<”\n”;
}
output:
5 4 3 1 2

Precision( ): By default a floating point number prints six digits after the decimal point. We
can specify the number the number of digits to be displayed after the decimal point in the
floating point number using the precision( ) member function.
Syntax: cout.precision (d);
Example:
void main( )
Page No: 56
{
cout.precision(3);
cout<<sqrt(2)<<”\n”;
cout<<3.14159<<”\n”;
getch( );
}

Fill( ): This is used to fill the un used positions by any desired character. It is as
follows:
Syntax: cout.fill(ch); where ch denotes a character which is used for filling
the un used position.

Example:
void main( )
{
cout.fill(‘*’);
cout.width(10);
cout<<5250<<”\n”;
getch( );
}
Output:
* * * * * * 5 2 5 0

Padding: This is used to change the style of filling the character.

Example:
void main( )
{
cout. Fill(‘<’);
cout. precision(3);
for (int n =1;n<=6;n++)
{
cout. Width(5);
cout<<n;
cout.width(10);
cout<<1.0/float(n)<<”\n”;
if (n = = 3)
cout. Fill(‘>’);
}
cout<<”\n Padding changed \n \n”<<endl;
cout.fill (‘#’);
cout.width(15);
cout<<12.345678<<”\n”;
getch( );
}

Output:
<<<<1<<<<<<<<<1
<<<<2<<<<<<<0.5
<<<<3<<<<<0.3333
>>>>4>>>>>>0.25
>>>>5>>>>>>>0.2
>>>>6>>>>>>0.167
Page No: 57
padding changed
###########12.3

Formatted flags, Bit-fields & setf( ):


Setf( ): The setf( ) is a member function of ios class. Setf( ) stands for set flag which is a
function and is used as follws:
Syntax: cout . setf(arg1,arg2);
Where arg1 is a flag defined in the class ios. The formatted flag specifies the option
required for the output. Another arg2 is known as the bit field tells us the group to
which formatted flag belongs. This flag is used to print the text as left , right justified
or getting a floating point number printed in scientific notation.
Example:
void main( )
{
cout. setf (ios : : left, ios : : adjust field);
cout . width(15);
cout<<”Table1”<<”\n”;
getch( );
}
Output:

T A B L E 1 * * * * * * * *

Example2:
void main( )
{
cout. fill (‘*’);
cout. Setf (ios : : internal, ios: : adjust field);
cout . setf (ios : : scientific , ios : : float field);
cout .width(15);
cout<<-12.34567<<”\n”;
getch( );
}
Output:
- * * * * * 1 . 2 3 5 e + 0 1

The sign here is left justified and the value is right justified. The space between them
is padded with stars.

Flags & bit fields for setf( ) function:

Format flags Flag (Arg1) Flag (Arg2)

Format required Flag (arg1) Bit field (arg2)

Left justified output ios : : left ios :: adjust field

Right justified output ios : : Right ios :: adjust field


Padding after sign
Or base indicator ios :: internal ios :: adjust field

Page No: 58
Scientific notation ios :: scientific ios :: float field

Fixed point notation ios :: fixed ios :: float field

Decimal base ios :: dec ios :: base field

Octal base ios :: oct ios :: base field

Hexa decimal base ios : : hex ios : : base field

Page No: 59
CLASSES AND OBJECTS

1. Explain about classes?


A. Object-oriented programming came out with a new data type called as the “class”.
Defining the variables for the class data type is called class initialization and such
variables are called as objects. A class encloses of data & functions that operate on the
single unit. A class can be denoted as follows:

Data

Data 1
Data2
Data 3

Function

Function1 ( )
Function2 ( )
Function3 ( )

The data variable & functions enclosed in a class are called as the data members and
member functions. Placing data & functions into a single unit is the main concept of object
oriented programming. A class as specified can have two parts:
1. class declaration
2. Class function definition
Class declaration: This describes the type and the scope of the members.
Class function definition: This tells us how the class functions are implemented .

Syntax:
class classname
{
Private:
Variable declaration;
Function declaration( );
Public:
Variable declaration;
Function declaration( );
};
Here the keyword class specifies that class name is an abstract data type.
The body of the class is enclosed in a pair of curly braces followed by the semi colon
that
indicates the end of the class. The body of the class encloses data members and
member
functions. The class members are grouped into two sections. They are public and
private.
The class members declared as private can be accessed only with in that class and the
class members declared in the in the public can be accessed from outside the class.

Page No: 60
Example:
Class student
{
Int rno;
Char mane [30];
Public:
Void getdata ()
{
Cout<<”Enter the name of the student”<<endl;
Cin>>name;
Cout<<”Enter the roll number of the student:”<<endl;
Cin>>rno;
}
Void putdata( )
{
Cout<<”The name of the student is :”<<name<<endl;
Cout<<”The roll number of the student
is:”<<rno<<endl;
}
};
Note:
 Keywords public and private must be followed by “ : “.
 By default all the class members are private.

2. How to create the objects of the class and access the class members?
A. The process of creating the objects, i.e. , variables of a class is called class
initialization.

Syntax:
class name object1, object2, .................... , object n;
Placing names immediately after the clasing braces can also create object.
Example:
class student
{
……………..
……………..
……………..
} s2, s2 ;

C++ allows us to create objects at any point whenever they are created.

Accessing class members: Once a class has been created there is a need to access its
members. By using the dot (.) operator we can access the class members. The dot
operator is called the member access operators. The syntax for accessing the member
functions of the class is

Syntax:
Object name . function name (argument list );
Here object name is the name of the object. Dot is the member function accessing
operator. Function name is the name of the function and argument list is the number of

Page No: 61
the arguments in the function.

3. How to define the member functions of the class?


A. The data members of the class must be declared within the body of the class but the
member functions can be declared in any of the two ways:
1. Inside the class specification &
2. Outside the class specification.

Inside the class specifications:


The syntax for specifying the member functions of the class is similar to that of the
normal function. Here all the member functions defined within the body of the class are
treated as inline function by default.

Example:
Program to display name and roll number and name of the student using classes

class student
{
int rno;
char mane [30];
public:
void getdata ()
{
cout<<”Enter the name of the student”<<endl;
cin>>name;
cout<<”Enter the roll number of the student:”<<endl;
cin>>rno;
}
void putdata( )
{
cout<<”The name of the student is :”<<name<<endl;
cout<<”The roll number of the student is:”<<rno<<endl;
}
};
void main ( )
{
student s;
clrscr( );
s. getdata ( );
s. putdata ( );
getch ( );
}

Outside the class specification:


In this method the function prototype has to be declared within the body of the class and
then we have to mention function definition outside the class. Scope resolution operator
informs the compiler that the function, which is declared outside the class, belongs to the
class which is mentioned above.

Syntax:
class class name

Page No: 62
{
………………
………………
public:
Return type member function (argument list );
};

Return type class name : : member function (argument list )


{
……………
……………
}
Example:
Program to display name and roll number and name of the student using member
functions outside the class

class student
{
int rno;
char mane [30];
public:
void getdata ( );
void putdata( );
};
void student : : getdata ()
{
cout<<”Enter the name of the student”<<endl;
cin>>name;
cout<<”Enter the roll number of the student:”<<endl;
cin>>rno;
}
void student : : putdata( )
{
cout<<”The name of the student is :”<<name<<endl;
cout<<”The roll number of the student is:”<<rno<<endl;
}
void main ( )
{
student s;
clrscr( );
s. getdata ( );
s. putdata ( );
getch( );
}

4. How to make outside functions as inline functions?


A. Member functions which are defined outside the class can be made inline by prefixing

Page No: 63
inline to its definition.
Syntax:
Return type class name : : member function (argument list )
{
……………
……………
}

Example:
/*Program to display name and roll number and name of the student using
member functions outside the class as inline functions */

class student
{
int rno;
char mane [30];
public:
void getdata ( );
void putdata( );
};
inline void student : : getdata ()
{
cout<<”Enter the name& rno of the student”<<endl;
cin>>name>>rno;
} }
inline void student : : putdata( )
{
cout<<”The name & rno of the student is
:”<<name<<rno<<endl;
}
void main ( )
{
student s;
clrscr( );
s. getdata ( );
s. putdata ( );
getch ( );
}

5. How can we pass objects as arguments in a class?


A. We know that functions accept variables as arguments. Similarly functions accept
objects of the class as arguments in the following ways:
 Pass by value: A copy of the entire object is passed into the function.
 Pass by reference: The address of the object is passed implicitly to the
function.
 Pass by pointer: The address of the object is passed explicitly to the function.
Pass by value: A copy of the entire object is passed to the function and any
modifications made to the object inside the function are not reflected on the objects
used to call the function.

Page No: 64
Example:
Program to calculate distance in feet and inches format
class distance
{
float feet, inches;
public:
void input (float ft , float in)
{
feet = ft;
inches = in;
}
void read ( )
{
cout <<”Enter feet and inches:”<<endl;
cin>>feet>>inches;
}
void display ( )
{
cout<<”Feet:”<<feet<<endl<<”Inches:”<<inches<<endl;
}
void add ( distance d1, distance d2)
{
feet = d1.feet + d2. Feet;
inches = d1. Inches + d2. Inches;
if (inches > 12.0)
{
feet = feet + 1.0;
inches = inches – 12.0;
}
}
};
void main ( )
{
distance d1, d2, d3;
clrscr( );
d1.input (11.0, 6.35);
d1.read ( );
cout <<”Details of D1 are :”<<endl;
d1.display ( );
cout<<endl;
cout <<”Details of D2 are :”<<endl;
d1.display ( );
cout<<endl;
d3.add (d1, d2);
cout << “d3:d1 + d2”<<endl;
cout<<endl;
d3.display ( );
getch();}
Pass by reference (or ) pointer: The address of the object is passed to the function any
changes made to the objects i9nside the function is reflected in the actual argument.

Page No: 65
Example:
Given account number and balance of two accounts. This program transfers a specified sum
of these accounts to other and then updates the balance of both the account.

class account
{
int ano;
float bal;
public:
void getdata ( )
{
cout<<”Enter the account number of the object 1:”<<endl;
cin>>ano;
cout<<”Enter the balance:”<<endl;
cin>>bal;
}
void setdata ( int accin)
{
ano = accin;
bal = 0;
}
void setdata ( int accin , float balin)
{
ano = accin;
bal = balin;
}
void display ( )
{
cout<<”The account number is:”<<ano<<endl;
cout<<”Balance is:”<<bal<<endl;
}
void money_trans (account &ac, float amount )
{
bal = bal – amount;
ac.bal = ac.bal + amount;
}
};
void main ( )
{
clrscr ( );
int transmoney;
account ac1, ac2, ac3;
ac1. getdata ( );
ac2. setdata (10);
ac3. setdata (20, 750.0);
cout<<”account information is as follows :”<<endl;
cout<<endl;
ac1.display( );
cout<<endl;
ac2.display( );
cout<<endl;
ac3.display( );

Page No: 66
cout<<endl;
cout<<”The amount of money to be transferred from ac3 to ac1 is:”<<endl;
cin>>transmoney;
ac3.moneytrans (ac1, transmoney);
cout<<”Updated account information is as follows:”<<endl;
cout<<endl;
ac1.display ( );
cout<<endl;
ac2.display ( );
cout<<endl;
ac3.display ( );
cout<<endl;
getch ( );
}

6. Explain about friend functions?


A. We know that the private data members or the member functions cannot be accessed
outside the class. But there is a situation where two classes have to share a function in
common. In such cases C++ allows the common function to be friendly with both the
classes. Such functions can access the private data of these classes. That function need
not be a member of any class. To make outside functions to be friendly with the other
class we simply declare that function as a friend of the class.

Syntax:
class classname
{
…………..
…………..
public:
friend return type function name (argument list);
};

The declaration of the friend function must be preceded by the keyword “friend”. The
function can be declared any where in the program like a normal function. The function does
not use the keyword “friend” or the “ : : “ operator. The function that is declared with the
keyword friend is called as the friend function. A function can be declared friend to any
number of classes.
Example:
/* Program to calculate the mean of two numbers using the friend functions */
# include <iostream.h>
# include <conio.h>
class sample
{
int a,b;
public:
void getdata( )
{
cout<<”Enter the two number:”<<endl;
cin>>a>>b;
}
friend float mean (sample s);

Page No: 67
};
float mean (sample s)
{
return (s.a + s.b) / 2;
}
void main( )
{
clrscr( );
sample x;
x.getdata( );
cout<<”The mean of the numbers is:” <<mean (x) <<endl;
getch( );
}

Characteristics of the friend function:

 Since it is not in the scope of the class, the objects of the class cannot call it.
 It can be called like normal; function with out the help of objects.
 It can be declared either in the public or the private part of the class.
 It has objects as arguments.

7. Differentiate between the friend functions of the class and the member
functions of the class?
A. A friend function and the member function can be same in that they can be used as any
members of the class (public or private) in the function declaration. The dot operator is
not used when the function is a friend. A member function can be called using the object
name and the dot operator. The member function includes the scope resolution operator
also.

8. How do the friend function work as the bridge between the classes?
A. We can declare all members of the class as a friend function of another class. In such
cases we declare that class as a friend class.
Example:
/* Program to find the maximum of two numbers in two different classes */
# include <iostream.h>
#include <conio.h>
class abc; //forward declaration
class xyz

Page No: 68
{
int x;
public:
void setvalue (int I)
{
x = I;
}
friend void max (xyz, abc);
};
class abc
{
int a;
public:
void setvalue (int I)
{
a = I;
}
friend void max (xyz, abc);
};
void max ( xyz m , abc n)
{
clrscr( );
abc p;
p.setvalue (10);
xyz q;
q.setvalue (20);
max (q, p);
getch( );
}

9. Differentiate between the structures and classes?


A.

STRUCTURES CLASSES

1. Structure combines the logically 1. The class encloses of data and function
related data items into a single unit. that operate on a single unit.

2. In structure we have data members only 2. In a class we have data members and
member functions also.
3. Are the members of the structure are 3. Are the members of the class are
by default “public”. by default “private”.
4. In structures we use the key word 4. In classes we use the key word
“struct”. “Class”.
5. There is not data security in the 5. Information about the module is
Structure. “Private” i.e., restricted unless
declared as public.

Page No: 69
INHERITANCE
1. Define inheritance with its benefits?
A. Inheritance is the process of creating a new class from the old class. The
old class is called as the base class and the new class is called as the derived
class. It supports the concept of hierarchical classification. The advantages of
inheritance are:
 Reusability of the code.
 To increase the reliability of the code, and
 To add some enhancements to the base class.
In object oriented programming, inheritance provides the idea of reusability.
This means that we can add additional features to an existing class with out
modifying it. This is possible by deriving a new class from the existing class.
The new class has the combined feature of both the classes.
For example, bird Robin is a part of flying bird, which is again a part of the
class bird. The principle behind this is that, each derived class shares
common characteristics with the class from which it is derived.

BIRD
Attributes:
Feathers
Lay Eggs

Flying Bird Non Flying Birds


Attributes Attributes
………….. …………..

Robin Swallow Penguin Kiwi


Attributes Attributes Attributes Attributes
………….. ………….. ………….. …………..

2. How can you define a derived class?


A. A derived class can be specified by defining a relation ship with the base
class in addition to its own details. The general form for defining a derived
class is as mentioned as below:

Page No: 70
class derived class name: visibility mode base class name
{
…………….
…………….
};
The colon indicates that the derived class name is derived from the base
class name. The visibility mode is optional and if present it may be either
public or private. The default visibility mode is private.

3. Explain the different forms of inheritance with examples?


A. Inheritance is broadly classified into the following forms depending on the
levels of inheritance and interrelation among the classes.
 Single Inheritance
 Multiple Inheritance
 Multi Level Inheritance
 Hybrid Inheritance
 Hierarchal Inheritance
Single Inheritance:
A derived class with only one base class is called as single inheritance. It as
shown below:

B
Multiple Inheritance:
A derived class with more than one base class is called as the multiple
inheritance. It is as shown below:

A B

Hierarchical Inheritance:
The properties of one class may be inherited by more than one class is called
hierarchical inheritance. The example is as shown below:

Page No: 71
B C D

Multi Level Inheritance:


It the process of deriving a class from another derived class is called multi
level inheritance. It is as shown below:

C
Hybrid Inheritance:
Deriving a class having more than one form of inheritance is called as the
hybrid inheritance. It is a combination of multiple and multi level inheritance.

B C

D
4. Explain about control access specifiers?
(Or)
Explain about public, private and protected?

A. A discussion of the keywords public, private, and protected is useful when


discussing inheritance. The three keywords are used to control access to functions
and variables stored within a class. Let us now discuss about them in detail.
Public:
The most open level of data hiding is public. Anything that is public i.e., it may be a
data variable or member function is available to all derived classes. Functions marked
public are generally those the class that take information from the outside the class.
The rest of the class should be hidden from the user using private or protected data
(This hidden nature and the highly focused nature of classes is known collectively as
encapsulation).
The syntax for public is:

Page No: 72
public:
Everything following is public until the end of the class or another data hiding
keyword is used. In general, a well-designed class will have no public fields--
everything should go through the class's functions. Since, the public part of the class
is intended for use by others, it is often sensible to put the public section at the top
of the class.
Protected:
Variables and functions marked protected are inherited by derived classes; however,
these derived classes hide the data from code outside of any instance of the object.
Protected is a useful level of access control for important aspects to a class that must
be passed on without allowing it to be accessed. The syntax is the same as that of
public. Specifically,
protected:
Private:
Private is the highest level of data hiding. Not only are the functions and variables
marked private not accessible by code outside the specific object in which that data
appears, but also private variables and functions are not inherited (in the sense that
the derived class cannot directly access these variables or functions). On the other
hand, if you do not wish derived classes to access a method, declaring it private is
sensible.

private:

5. Explain the visibility modes for different members of the base class
in the derived class with the help of the example?
A. We have three visibility modes in C++. They are public, private and protected.
When the data in the base class is defined as public it can be used by any number of
derived classes. If the base class data is private the data is restricted to that class
only. If the data in the base class is protected it is accessible only by the members of
its immediate derived class.
We can declare the data in the base class as public, private or protected.
In the similar way we can access the base class members in the derived class as
public, private or protected. This is as shown below:
Base class Public Private Protected

Private Not inherited Not inherited Not inherited

Protected Protected Private Protected

Public Public Private Protected

In the base class we can declare the data in three ways i.e., as public, private & protected. It
can be inherited in the derived class as public, private & protected.
In the base class if the data is private it cannot be inherited in the other derived class.

Page No: 73
In the base class if we declare the data as public we can inherit the properties of the base
class into the derived class as public i.e. the data in the base class is accessible for all the
further classes.
In the base class if we declare the data as public and we inherit the properties of the base
class into the derived class as private, the data in the base class is restricted as private to the
derived class and cannot be accessed using the objects of the derived class.
In the base class if we declare the data as public and we inherit the properties of the base
class into the derived class as protected, the data in the base class becomes protected to the
derived class.
In the base class if we declare the data as protected and we inherit the properties of the base
class into the derived class as public, the data in the base class becomes protected to the
derived class.
In the base class if we declare the data as protected and we inherit the properties of the base
class into the derived class as protected, the data in the base class becomes protected to the
derived class.
In the base class if we declare the data as protected and we inherit the properties of the base
class into the derived class as private, the data in the base class becomes private to the
derived class.
The effect of inheritance on the visibility of members pictorially represented as follows:

Class B

Not inheritable Not inheritable


Private

Protected

Public
Class D1: public B Class D1: Private B

Private Private

Protected Protected

Public Public

Class X: public D1, protected D2

Private

Protected

Public

6. Explain single inheritance in public/private mode?

Page No: 74
A. Single inheritance is the process of creating a new class from the existing class.
The existing class is called as the direct base class and the newly created class is a
singly derived class.
Defining a derived class:
 The keyword class.
 The name of the derived class.
 A single semicolon.
 The type of derivation (public, private or protected).
 The name of the base or the parent class.

Syntax:
class derived classname : public/private/protected base class name
{
private:
………..
public:
………..
………..
protected:
……….
………
};

/* Program for single inheritance public mode */


# include <iostream.h>
# include <conio.h>
class student
{
int sno;
public:
void getno( )
{
cout<<”Enter student number:”;
cin>>sno;
}
void putno( )
{
cout<<”Student number is:”<<sno;
}
};
class marks : public student
{
int m1, m2, m3;
public:
void getm ( )
{
cout<<”Enter any three subjects marks:”;
cin>>m1>>m2>>m3;
}
void putm( )
Page No: 75
{
cout<<”m1:”<<m1<<”m2:”<<m2<<”m3:”<<m3;
}
};
void main ( )
{
clrscr( );
marks m;
m.getno( );
m.getm( );
m.putno( );
m.putm( );
getch ( );
}

/* Program for single inheritance private mode */


# include <iostream.h>
# include <conio.h>
class student
{
int sno;
public:
void getno( )
{
cout<<”Enter student number:”;
cin>>sno;
}
void putno( )
{
cout<<”Student number is:”<<sno;
}
};
class marks : private student
{
int m1, m2, m3;
public:
void getm ( )
{
getno( );
cout<<”Enter any three subjects marks:”;
cin>>m1>>m2>>m3;
}
void putm( )
{
putno( );
cout<<”m1:”<<m1<<”m2:”<<m2<<”m3:”<<m3;
}
};
void main ( )
{
clrscr( );
Page No: 76
marks m;
m.getm( );
m.putm( );
getch ( );
}

7. Explain multiple inheritance with an example?


A. A class inherits the attributed of two or more classes is known as multiple
inheritance. The syntax of a derived class with multiple base classes is as shown
follows:

class derived classname: visibility mode base class1, visibility mode base
class 2, ..
{
…………
………….
};
Where visibility may be either public or private. Commas separate the base classes.

/* Program for the multiple inheritance */

# include <iostream.h>
# include <conio.h>
class student
{
protected:
int sno;
public:
void getno( )
{
cout<<”Enter student number:”;
cin>>sno;
}
void putno( )
{
cout<<”Student number is:”<<sno;
}
};
class marks
{
protected:
int m1, m2, m3;
public:
void getm ( )
{
cout<<”Enter any three subjects marks:”;
cin>>m1>>m2>>m3;
}
void putm( )
{
cout<<”m1:”<<m1<<”m2:”<<m2<<”m3:”<<m3;
Page No: 77
}
};
class result : public student, public marks
{
int total;
public:
void display ( )
{
total=m1+m2+m3;
putno( );
putm( );
cout<<”Total is:”<<total;
}
};
void main ( )
{
clrscr( );
result r;
r.getno( );
r.getm( );
r.display( );
getch ( );
}

8. Explain about multi level inheritance with an example?


A. It is not uncommon that a class is derived from another derived class as shown in
the picture (see multi level inheritance figure in question 2) The class A serves as a
base class for the derived class B, which in turn serves as a base class for the derived
class C. The class B is known as the intermediate base class as it acts as an interface
between A and C classes. The chain of ABC is called as the inheritance path.

A derived class with multilevel inheritance is declared as follows:


class A //Base class
{
……..
};
class B : public A //B derived from A
{
…………..
};
class C : public B // C derived from B
{
……….
};

/* Program for multilevel inheritance*/


# include <iostream.h>
# include <conio.h>
class student
{
Page No: 78
protected:
int sno;
public:
void getno( )
{
cout<<”Enter student number:”;
cin>>sno;
}
void putno( )
{
cout<<”Student number is:”<<sno;
}
};
class marks : public student
{
int m1, m2, m3;
public:
void getm ( )
{
cout<<”Enter any three subjects marks:”;
cin>>m1>>m2>>m3;
}
void putm( )
{
cout<<”m1:”<<m1<<”m2:”<<m2<<”m3:”<<m3;
}
};
class result : public marks
{
int total;
public:
void display ( )
{
total=m1+m2+m3;
putno( );
putm( );
cout<<”Total is:”<<total;
}
};
void main ( )
{
clrscr( );
result r;
r.getno( );
r.getm( );
r.display( );
getch ( );
}

9. Explain hybrid inheritance with an example?

Page No: 79
A. Hybrid inheritance is a combination of multiple and multi level inheritance.
Derivation of a class involving more than one form of inheritance is called as hybrid
inheritance.

/* Program for hybrid inheritance */


# include <iostream.h>
# include <conio.h>
class student
{
protected:
int sno;
public:
void getno( )
{
cout<<”Enter student number:”;
cin>>sno;
}
void putno( )
{
cout<<”Student number is:”<<sno;
}
};
class marks : public student
{
int m1, m2, m3;
public:
void getm ( )
{
cout<<”Enter any three subjects marks:”;
cin>>m1>>m2>>m3;
}
void putm( )
{
cout<<”m1:”<<m1<<”m2:”<<m2<<”m3:”<<m3;
}
};
class sports
{
protected:
int score;
public:
void gets( )
{
cout<<”Enter score in the sports:”;
cin>>score;
}
void puts( )
{
cout<<”The score is:”<<score;
}
};
Page No: 80
class result : public marks , public sports
{
float total;
public:
void display ( )
{
total=m1+m2+m3+score;
putno( );
putm( );
puts( );
cout<<”Total is:”<<total;
}
};
void main ( )
{
clrscr( );
result r;
r.getno( );
r.getm( );
r.gets( );
r.display( );
getch ( );
}

10. Explain hierarchical inheritance with an example?


A. The properties of one class may be inherited by more than one class is called
hierarchical inheritance.

/* Program for hierarchical inheritance. */


# include <iostream.h>
# include <conio.h>
class vehicle
{
protected:
char name[30];
int nowheeels;
public:
void getdata( )
{
cout<<”Enter name and number of wheels for a vehicle:”;
cin>>name>>nowheels;
}
void display( )
{
cout<<”the name of the vehicle is:”<<name;
cout<<”The number of wheels for the vehicle are:”<<nowheels;
}
};
class lightmotor : public vehicle
{
protected:
Page No: 81
int speedlimit;
public:
void getdata( )
{
vehicle : : getdata( );
cout<<”Enter the speed limit:”;
cin>>speedlimit;
}
void display( )
{
vehicle : : display( );
cout<<”The speedlimit is:”<<speedlimit;
}
};
class heavymotor : public vehicle
{
protected:
int loadcapacity;
public:
void getdata( )
{
vehicle : : getdata( );
cout<<”Enter load capacity of the vehicle:”;
cin>>loadcapacity;
}
void display( )
{
vehicle : : display( );
cout<<”Total capacity is:”<<totalcapacity;
}
};
void main( )
{
clrscr( );
lightmotor l;
heavymotor h;
l.getdata( );
h.getdata( );
l.display( );
h.display( );
getch( );
}

11. Explain about virtual base class?


(Or)
Explain of multi path inheritance?
A. A situation where three kinds of inheritance are invoked are called multi path
inheritance. It is a combination of multi level, multiple and hierarchical inheritance.

Student
Page No: 82
Marks Sports

Result

In the above picture result has two directed base classes called marks and sports.
Both these classes have a common base class called student. Result inherits the
features of student in two different paths. It can also inherit student features directly
as shown in the broken lie. The student class is called as indirect base class. The
above figure has some problems. The public and protected members of student are
inherited into result twice, which creates an ambiguity. This problem can be avoided
by making the common base class as virtual base class.

/* Program for virtual base class */


# include <iostream.h>
# include <conio.h>
class student
{
protected:
int sno;
public:
void getno( )
{
cout<<”Enter student number:”;
cin>>sno;
}
void putno( )
{
cout<<”Student number is:”<<sno;
}
};
class marks : public virtual student
{
int m1, m2, m3;
public:
void getm ( )
{
cout<<”Enter any three subjects marks:”;
cin>>m1>>m2>>m3;
}
void putm( )
{
cout<<”m1:”<<m1<<”m2:”<<m2<<”m3:”<<m3;
Page No: 83
}
};
class sports : virtual public student
{
protected:
int score;
public:
void gets( )
{
cout<<”Enter score in the sports:”;
cin>>score;
}
void puts( )
{
cout<<”The score is:”<<score;
}
};
class result : public marks , public sports
{
float total;
public:
void display ( )
{
total=m1+m2+m3+score;
putno( );
putm( );
puts( );
cout<<”Total is:”<<total;
}
};
void main ( )
{
clrscr( );
result r;
r.getno( );
r.getm( );
r.gets( );
r.display( );
getch ( );
}

12. Define an abstract class?


A. The abstract class is one that is used not to create objects. An abstract class is
only designed to act as a base class (to be inherited by the other classes). It is used
for the development of the program i.e., it acts as base from which other classes
may be developed.

Page No: 84
CONSTRUCTORS AND DESTRUCTORS
1. Explain about constructors?
A. C++ allows a special member function that makes an object to initialize itself
when it is created. This is known as the automatic initialization of objects. These
functions are called as constructors.
Example:
# include <iostream.h>
# include <conio.h>
class integer
{
int m, n;
public:
integer (void); //constructor declared
…………
…………
};
integer : : integer (void )
{
m= 0;
n = 0;
}
void main( )
{
clrscr( );
integer I;
I .display( );
getch( );
}
When a class contains a constructor like above the object created by the class will
be initialized automatically. For example
integer I; //object I is created
The above statement not only creates the object but also initializes the data member
of the class integer m, n to zero.

2. Explain the characteristics of the constructor?


A. The characteristics of the constructor are as mentioned below:
 The name of the constructor is similar to that of the class name.
 They should be declared in the public section only.
 They are invoked automatically when the objects are created.
 They do not have any return values not even void.
 They cannot be inherited.
 Like other C++ functions they can have default arguments.
 Constructors cannot be virtual.
 Constructors cannot refer addresses.
 Constructors are used to initialize variables and allocate memory.

Page No: 85
3. Explain the various types of constructors?
A. Constructors are of four types. They are :
1. Parameterized constructor
2. Default constructor
3. Copy constructor &
4. Dynamic constructor.

Parameterized constructor:
The constructor that takes arguments is called as the parameterized constructor.

Example:
/* Program to display numbers of two variables *
# include <iostream.h>
# include <conio.h>
class integer
{
int m, n;
public:
integer (int x, int y); //constructor declared
void display( )
{
cout << “M:” << m <<endl;
cout << “N:” <<n <<endl;
};
integer : : integer (int x, int y )
{
m= x;
n = y;
}
void main( )
{
clrscr( );
integer I(0,100); //Implicit way of assigning parameters
I .display( );
Integer i1= integer (25, 75); // Explicit way of assigning parameters
I1.display( );
getch( );
}
When a constructor is parameterized the object declaration statement such as
integer I ; does not work as we have to pass arguments to the constructor.
We can pass arguments to the constructor in two ways:
1. By calling the constructor explicitly.
Integer i1= integer (25, 75) ;
2. By calling the constructor implicitly.
integer I(0,100);

Page No: 86
Default constructor:
The constructor that has no parameters is called as the default constructor.

Example:
/* Program for default constructor */
# include <iostream.h>
# include <conio.h>
class student
{
char * name;
int rno, age;
public:
student ( );
void display ( );
};
student : : student ( )
{
name = “Rama”;
rno = 1;
age = 19;
}
void student : : display( )
{
cout << “ Name of the student is :” <<name<<endl;
cout << “ Roll number of the student is :” <<rno<<endl;
cout << “ Age of the student is :” <<age<<endl;
}
void main ( )
{
clrscr( );
student a;
cout<< “Demonstration of the default constructor”<<endl;
a.display( );
getch( );
}

Copy constructor:
A copy constructor takes reference of an object of the same class itself as an argument.

/* Program for the copy constructor */


# include <iostream.h>
# include <conio.h>
class code
{
public:
code ( )
{

Page No: 87
}
code ( int a)
{
id=a;
}
code (code &x)
{
id = x.id;
}
void display( )
{
cout << “ The value is : “<<id <<endl;
}
};
void main ( )
{
clrscr( );
code A(100);
code B = A;
cout << “ Id of A is :”<< endl;
A.display( );
cout <<”Id of B is :”<<endl;
B.display( );
getch( );
}
This is used to declare and initialize the object from another object.
code B = A;
Here we create an object B and initialize it to A (value of A). The above example
can also be written as
code B (A);
The process of initialization through a copy constructor is called as copy initialization.

Note: A reference variable is used as an argument in the copy constructor. We


Cannot pass the argument by value in the copy constructor.

Dynamic constructor:
Allocation of memory to an object at the time of construction is known as the dynamic
construction of the objects. The memory allocation is done with the help of the new
operator.
Example:
/* Program for the dynamic constructor */
# include <iostream.h>
# include <conio.h>
# include <string.h>
class string
{
char * name;
int length;

Page No: 88
public:
string( char *s )
{
length = strlen(s);
name = new char [length +1];
strcpy (name,s);
}
void display( )
{
cout <<”The name is :”<<name<<endl;
}
};
void main( )
{
clrscr( );
char * first = “HELLO”;
string name1 (first);
string name2 (“WORLD”);
name1.display( );
name2. display( );
getch( );
}
5. Explain about destructors?
A. It is a special member function whose work is to destroy the object that has been created by
the constructor.
Rules of the destructor:
 The name of the destructor must be similar to that of the class name.
 Destructor must be preceded by the tilda (~) symbol.
 It never takes arguments.
 It does not return any value.
 It should be declared in the public section only.
 The compiler invokes it implicitly when we exit the program.
Example:
/* Program for the destructor */
# include <iostream.h>
# include <conio.h>
class integer
{
int m, n;
public:
integer (int x, int y);
void display( )
{
cout << “M:” << m <<endl;
cout << “N:” <<n <<endl;
}
~ integer ( )

Page No: 89
{
cout <<”Object destroyed”<<endl;
}
};
integer : : integer (int x, int y )
{
m = x;
n = y;
}
void main( )
{
clrscr( );
integer I(0,100);
I .display( );
getch( );
}

Page No: 90
OPERATOR OVERLOADING

1. Define operator overloading with its syntax?


A. Overloading is the new exciting feature of C++. Earlier we have seen how C++
tries to make user defined data types as built in data types. For example, C++
tries to add two variables of user defied data types with the same syntax as that of
the built in data types. This means that C++ is providing the operator a special
meaning for the data type. This mechanism of giving a special meaning to the
operator is called operator overloading. We can over load all C++ operators
except
 Class member access operator (. , .*)
 Scope resolution operator ( : :)
 Size of operator
 Conditional operator
Here when the operator is overloaded the original meaning is not lost. For instance, the operator ‘+’
which has been overloaded to add two integers can be still used to add two string and is called as
concatenation.

Definition of operator overloading:


Operator overloading is an additional task to an operator, with the help of the special function
called as the operator function, which described about the task. The general for of the
operator function is as follows:

Syntax:
Return type class name : : operator op (argument list)
{
…………….
……………. Function body
…………….
}

Here the return type is the type of the value to return by the special operation and ‘op’ is the
operator that has to be overloaded. The operator ‘op’ must be preceded by the keyword ‘operator’.
Operator ‘op’ is the function name. Operator function can be a member function or a friend function.
The basic difference is that when a member function is used in unary operator overloading it will not
have any arguments where as when a friend function is used with unary operator over loading we use
one argument. when a member function is used in binary operator overloading it will have any one
argument where as when a friend function is used with binary operator over loading we use two
argument. This is because the object used to invoke the member function is passed implicitly and
there fore is available for the member function. Arguments in a function can be passed either by
value or by reference. The process of operator overloading involves the following steps:

 Create a class that defines the data type that is used in the overloading operation.
 Declare the operator op( ) function in the public part of the class.
 Define the operator function to implement the required operation.

Page No: 91
2. Explain the rules of the operator overloading and its types?
A. There are two types of over loadings. They are :
 Unary operator over loading
 Binary operator over loading
The limitations for over loading the operator function are as mentioned below:
 Only existing operators can be over loaded. New operator cannot be created.
 The overloaded operator must have at least one operand that is of user defined
data type.
 We cannot change the basic meaning of the operator. For example, we cannot
redefine the plus (+) operator to subtract one value from another.
 Over loaded operators must follow the syntax of the original operator. They cannot
be over ridden.
 There are some operators that cannot be over loaded when we are using the friend
functions. They are:
 = Assignment operator
 () Function call operator
 [ ] Subscripting operator
 -> Class member access operator

o Binary arithmetic operators such as +, -, *, / must explicitly return a value.


3. Explain of the unary operator over loading with an example?
A. Generally a unary operator changes the sign of the operand when applied to the basic data
item. When we over load this operator it can be applied to an integer or a float variable. The
unary minus when applied to an object changes the sign of each data item.

/* Program for unary operator overloading with member functions */


# include <iostream.h>
# include <conio.h>
Class space
{
int x, y, z;
public:
void getdata (int a, int b, int c);
void display( );
void operator –( );
};
Void space : : getdata (int a, int b, int c)
{
x=a;
y=b;
z=c;
}
Void space : : display( )
{
cout<< x << “ “;
cout<< y << “ “;
cout<< z<< “ “;
}
Page No: 92
Void space : : operator -( )
{
x= -x;
y = -y;
z = -z;
}
Void main( )
{
clrscr();
space s;
s.getdata (10, -20 , 30);
cout<<”s:”;
s.display( );
cout<<endl;
-s;
cout<<”s:”;
s.display( );
cout<<endl;
getch();
}

/* Program for operator overloading using friend functions */


# include <iostream.h>
# include <conio.h>
Class space
{
int x, y, z;
public:
void getdata (int a, int b, int c);
void display( );
friend void operator –(space &s );
};
Void space : : getdata (int a, int b, int c)
{
x=a;
y=b;
z=c;
}
Void space : : display( )
{
cout<< x << “ “;
cout<< y << “ “;
cout<< z<< “ “;
}
Void operator - (space &s )
{
s.x= -s.x;
s.y = -s.y;
s.z = -s.z;
}
Page No: 93
Void main( )
{
clrscr();
space s;
s.getdata (10, -20 , 30);
cout<<”s:”;
s.display( );
cout<<endl;
-s;
cout<<”s:”;
s.display( );
cout<<endl;
getch();
}
Here the argument is passed by reference. It will not work if it is pass argument
by value because only one copy of the object that activated the call is passed to
operator-( ). Therefore changes made inside the operator function will not reflect
in the called object.

4. Explain of binary operator overloading with an example?


A. In this we are going to perform complex number addition using binary operator
overloading.
# include <iostream.h>
# include <conio.h>
class complex
{
float real, imag;
public:
complex( )
{
}
complex (float real, float imag)
{
x=real;
y=imag;
}
complex operator + (complex);
void display (void );
};
complex complex : : operator + (complex c)
{
Complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return temp;
}
Void complex : : display ( void)
{
cout <<x << ”+i” <<y <<”\n”;
}
Page No: 94
void main( )
{
clrscr( );
complex c1, c2, c3;
c1 = complex ( 2.5, 8.9);
c2= complex (4.6 , 6.9);
c3= c1+ c2;
cout <<”c1:”;
c1. display( );
cout << endl;
cout <<”c2:”;
c2. display( );
cout <<endl;
cout <<”c3:”;
c3. display( );
cout << endl;
getch( );
}
In the above program the function operator +, adds two complex values and return a
complex value as the result but receives only one value as the argument.
Let us look at the statement that invokes the function
C3 = c1 + c2 ;
We know that only an object of the same class invokes a member function. Here the object
c1 takes the responsibility of invoking the function and c2 plays the role of the argument
that is passed to the function. The above statement is equal to
C3 = c1. Operator + (c2);
Therefore in the operator +( ) function, the data member of c1 are accessed indirectly and
the data members of c2 are accessed using the dot operator. Thus both objects are
available for the function.
For example, in the statement temp.x = x + c.x;
c.x refers to object c2 and x refers to object c1. temp.x real part of the temp that has
been created to hold the results of addition of c1 and c2. The function returns the complex
temp to the assigned to c3.
The rule in overloading of binary operators is the left hand operand is used to invoke the
operator function and the right hand operator is passed as an argument.

/* Program for binary operator over loading with friend functions */


# include <iostream.h>
# include <conio.h>
class complex
{
float real, imag;
public:
complex( )
{
}
complex (float real, float imag)
{
x=real;
y=imag;
Page No: 95
}
friend complex operator + (complex, complex);
void display (void );
};
complex operator + (complex c1, complex c2)
{
Complex temp;
temp.x = c1.x + c2.x;
temp.y = c1.y + c2.y;
return temp;
}
void complex : : display ( void)
{
cout <<x << ”+i” <<y <<”\n”;
}
void main( )
{
clrscr( );
complex c4, c5, c6;
c4 = complex ( 2.5, 8.9);
c5= complex (4.6 , 6.9);
c6= c4+ c5;
cout <<”c4:”;
c4. display( );
cout << endl;
cout <<”c5:”;
c5. display( );
cout <<endl;
cout <<”c6:”;
c6. display( );
cout << endl;
getch( );
}

/* Program for the concatenation and comparison of two strings using operator
operator overloading */

# include <iostream.h>
# include <conio.h>
# include <string.h>
class string
{
int length;
char *p;
public:
string ( )
{
}
string (char *s)
{
Page No: 96
length = strlen(s);
p= new char [length + 1];
strcpy (name,s);
}
string (string &s)
{
length = s.length;
p = new char [ length +1];
strcpy (p, s.p);
}
~ string ( )
{
delete p;
}
friend void show ( string s);
friend string operator + (string &s , string &t);
friend int operator <= (string &s, string &t);
};
void show (string s)
{
cout <<s.p<<endl;
}
string operator + (string &s , string &t)
{
string temp;
temp. length = s. length + t. length;
temp. p = new char [temp. length +1];
strcpy (temp. p, s. p);
strcat (temp. p, t.p);
return temp;
}
int operator <=( string &s, string &t)
{
int m= strlen (s.p);
int n = strlen (t.p);
if (m<=n)
return 1;
else
return 0;
}
void main( )
{
clrscr( );
string s1 = “New”;
string s2 = “York”;
string s3 = “Delhi”;
string t1, t2, t3;
t1 = s1;
t2 = s2;
t3 = s1 + s3;
Page No: 97
cout<<”t1:”;
show (t1);
cout<<”t2:”;
show (t2);
cout<<”t3:”;
show (t3);
if (t1<=t3)
{
show (t1);
cout<< “ is smaller than :”<<endl;
show (t3);
}
else
{
show (t3);
cout<< “ is smaller than :”<<endl;
show (t1);
}
getch( );
}

Page No: 98

You might also like