C & C Material 2022
C & C Material 2022
GUNTUR
II B.Com
Programming with C & C++
P.Y.KUMAR
PROGRAMMING WITH C & C++
Unit-I
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
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
Page Np :2
Introduction to C:
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);
#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( )
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).
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:
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;
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:
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.
6) Escape Sequences:
Page Np :9
Constant Meaning
'\a' or "\a" Audible bell (To ring a beep)
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
Page Np :10
8 Explain different Data Types in C.
Data type
scalar
derived User defined void pointer
(enum) (empty)
char
union
int structure Array of Strings
float double
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
Double 8 1.7E-308to1.7E+308
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:
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;
}
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;
Page Np :13
nothing. Also it is used when a function or any sub-program have not any
argument in it.
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:
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:
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:
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.
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.
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.
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( ):
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:
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");
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( );
}
a) if statement:
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;
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;
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;
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.
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:
b) Do statement or Do-loop:
. The syntax of do-loop is as follows:
do
{
block of statements;
}
while (condition);
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.
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:
Page Np :30
a). goto statement:
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.
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:
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( );
}
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:
The types of the array depends upon the given problem. Array are mainly
of two types:
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
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:
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};
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',
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:
For example, suppose you want to assign some fixed value to a variable array
named table by using the static two-dimensional array 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”};
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 ;
scanf(“%d”,&a[i]);
Ex:
int a[3][3] , i , j;
scanf(“%d”, &a[i][j]);
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:
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);
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”.
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)?
Function or Sub-Program
or or
or or
Call-by-reference
Example:
(like sqrt( ), pow( ), tan( ) etc.) (like addition( ), rajan( ), etc.)
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.
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
---------------------------------
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();
}
Values of
arguments
main ()
int Square( int no)
{
{
……………..
………………..
…………….
………………..
Res = Square (10)
/********************* EXAM PROGRAM ************************
**********************************************************/
#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();
}
OUTPUT:
enter 3 nos....5 2 4
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-4 Function-5
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.
Data Data
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.
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”.
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
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 ()
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.
50
CAD/CAM/CIM systems.
Object oriented database.
51
I/O STREAMS
Input stream
Extract from
Input
Input Device
stream
Program
Output device
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
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 “>>”.
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( );
}
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( );
}
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( );
}
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.
Setf( ) To specify the format flags that can control the form of
Output display (Such as left, right and center justification)
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
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
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.
Page No: 58
Scientific notation ios :: scientific ios :: float field
Page No: 59
CLASSES AND OBJECTS
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.
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 ( );
}
Syntax:
class class name
Page No: 62
{
………………
………………
public:
Return type member function (argument list );
};
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( );
}
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 ( );
}
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 ( );
}
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( );
}
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( );
}
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
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.
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
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?
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
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
Protected
Public
Class D1: public B Class D1: Private B
Private Private
Protected Protected
Public Public
Private
Protected
Public
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:
……….
………
};
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.
# 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 ( );
}
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.
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.
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.
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.
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.
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
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
/* 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