0% found this document useful (0 votes)
70 views57 pages

BCom - III Semester

The document discusses the history and structure of C programming language. It introduces various C programming concepts like tokens, variables, data types, operators, I/O functions, control structures like if-else and switch statements. It provides details about keywords, identifiers, variable declaration and initialization, constants and character constants in C.

Uploaded by

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

BCom - III Semester

The document discusses the history and structure of C programming language. It introduces various C programming concepts like tokens, variables, data types, operators, I/O functions, control structures like if-else and switch statements. It provides details about keywords, identifiers, variable declaration and initialization, constants and character constants in C.

Uploaded by

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

UNIT-1

Introduction and control structures

History of ‘C’ - Structure of C program – C character set, Tokens, Constants,


Variables, Keywords, Identifiers – C data types - C operators - Standard I/O in C
- Applying if and Switch Statements.

History:
C programming language was developed in 1972 by Dennis Ritchie at bell
laboratories of AT&T (American Telephone & Telegraph), located
in U.S.A.
Dennis Ritchie is known as the founder of c language.
It was developed to overcome the problems of previous languages
such as B, BCPL etc.Initially, C language was developed to be
used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.

Language Year Developed By


ALGOL 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K & RC 1978 Kernighan and Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee

The above table shows programming languages that were developed before C
language.

STRUCTURE OF A C PROGRAM

C program is collection of pre-processor commands, functions that are supported


by the C library. We can continuously add our functions to the ‘C library”.
Documentation Section:
The documentation section consists of a set of comment lines giving the name of
the program, the author and other details, which the programmer would like to
use later.C language supports 2 types of commenting.

Department Of Computer Science 1|Page


Single Line Comment: ‘//’ is used to
comment a single line. This is known as
a line comment. A line comment can be
placed anywhere on the line and it does
not require to be specifically ended as the
end of the line automatically that ends
the line.
Multi-Line Comment: A ‘/*’is ended
with ‘*/’ and all statements that lie
within these characters are treated as
comment lines. This type of comments is
known as Multi-line comments.
Link Section:
The link section provides instructions to
the compiler to link function from the pre-defined library (or) the user–defined
library.
This is performed by the pre-processor directive ‘include’ as follows:
#include <library name>
Eg(1): # include <stdio.h> Eg(2):# include<conio.h>
Definition section:
The definition section defines all symbolic constants using the #define directive.
Global Declaration Section:
There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration
section that is outside of all the functions.
main() Function Section: Every C program must have one main function
section. This section contains two parts; declaration part and executable part
Declaration part:
The declaration part declares all the variables used in the executable part.
Executable part:
There is at least one statement in the executable part. These two parts must
appear between the opening and closing braces. The program execution begins
at the opening brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in the declaration
and executable part end with a semicolon.

Subprogram section:
If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main ()
function, although they may appear in any order.

Department Of Computer Science 2|Page


TOKENS AND ITS TYPES

Tokens in C is the most important element to be used in creating a program in C.


We can define the token as the smallest individual element in C. For `example, we
cannot create a sentence without using words; similarly, we cannot create a
program in C without using tokens in C. Therefore, we can say that tokens in C is
the building block or the basic component for creating a program in C language.
Tokens in C language can be divided into the following categories:
Keywords
Identifiers
Strings
Operators
Constant
Special Characters

KEYWORDS
Keywords are the reserved words that have predefined meaning in that language.
These are the basic building blocks of the program. We cannot use it as a
variable name, constant name etc.C supports 32 keywords.
A list of 32 keywords in ‘c’ language is given below:

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

IDENTIFIERS
Identifiers refer to the names of variables, functions & arrays. Both uppercase &
lowercase letters are permitted, although lowercase letters are commonly used.
The underscore character is also permitted in identifiers.

Rules for assigning identifier are as follows:-


• The first character must be an alphabet or an underscore.
• It must consist of only letters, digits or underscore.
• Only first 31 characters are significant, i.e. if the user enters an identifier of
more than 31 characters, the compiler considers only first 31 characters &
deletes the others.
• A keyword cannot be used as an identifier name. It cannot contain any spaces.

Department Of Computer Science 3|Page


VARIABLES IN C
A variable can be considered as a name given to the location in memory. The
term variable is used to denote any value that is referred to a name instead of
explicit value. A variable is able to hold different values during execution of a
program, whereas a constant is restricted to just one value.
Rules for Defining Variable Name:
i. Characters Allowed :
Underscore(_)
Capital Letters ( A – Z )
Small Letters ( a – z )
Digits ( 0 – 9 )
ii. Blanks & Commas are not allowed
iii. No Special Symbols other than underscore(_) are allowed
iv. First Character should be alphabet or Underscore
v. Variable name Should not be Reserved Word

1. Declaring variables: Any variable used in the program must be declared


before using it in any statement. To declare the variables we must use the
following general form.
Syntax: data type variable_name;
Example: int a;
float b;
char c;
double d;
It is possible to declare the multiple variables by using the single declaration
statement.
Syntax: int a, b, c;
2. Assigning values to variables: We can assign a value to a variable by
using assignment statement.The expression having assignment statement is also
called assignment expression.In an assignment expression an assignment
operator is used.
Syntax: Variable = constant;
Variable = expression;
Ex: a = 10;
b =1;
c = a+b;
3. Initializing variables: While declaring the variables, we can also initialize
them with some value.
intemp_num = 7
float salary = 5000;
char grade = ‘A’;

Department Of Computer Science 4|Page


CONSTANTS IN C
It is an identifier whose value cannot be changed at the execution time of
program. In general constant can be used to represent as fixed values in a C
program. Constants are
classified into following
types.

1. NUMERIC CONSTANTS 2. CHARACTER CONSTANTS


Integer Constants Single character constants
Floating point constants String Constants
I. NUMERIC CONSTANTS
Numeric constants are the numeric values that can be represent either integer or
floating value. These are formed by using the digits 0 – 9 +ve or –ve and decimal
point. Numeric constants further classified into 2 types. They are
1. Integer constants: These have integer data combination of 0 to 9 without any
decimal point. These have either + or – sign.

2. Floating point constant: These constants have a decimal point within it


having + or – sign. These are represented in two different forms.
a) Decimal Form: 6.1,-2000.0
b) Exponential form: -7E+16, 6.2E13
II. CHARACTER CONSTANTS
Single Character Constant:
1. Character Constant can hold Single character at a time.
2. Contains Single Character Closed within a pair of Single Quote Marks
3. Single Character is smallest Character Data Type in C.
4. Integer Representation : Character Constant have Integer Value known as
‘ASCII’ value
5. It is Possible to Perform Arithmetic Operations on Character Constants

Examples of character Type:


1. ‘a’
2. ‘1’
3. ‘#’

Department Of Computer Science 5|Page


4. ‘<‘
5. ‘X’
Format Specifier for Character Variable:

• “%c” is used as format specifier for character inside C.


• However, we can also use “%d” as format specifier because “Each Character
have its equivalent integer value known as ASCII Value. “

String Constantin C Programming Language:


1. String is “Sequence of Characters“.
2. String Constant is written in Pair of Double Quotes.
3. String is declared as Array of Characters.
4. In C, String data type is not available.
5. Single Character String does not have Equivalent Integer Value i.e ASCII
Value
Format Specifier for string Variable:

• “%s” is used as format specifier for strings inside C.


Declare constant
const keyword are used to declare a constant.
Syntax: constint height = 100;
C ‘const’ keyword Example: The ‘const’ keyword is used to define constant in C
programming.
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include <stdio.h>
void main()
{
const float PI=3.14;
clrscr();
printf("The value of PI is: %f",PI);
getch();
}
Output:
The value of PI is: 3.140000
If we try to change the value of PI, it will render compile time error.
#include <stdio.h>
void main()
{
const float PI=3.14;
clrscr();
PI=4.5;
printf("The value of PI is: %f",PI);
getch();

Department Of Computer Science 6|Page


}
Output:
Compile Time Error: Cannot modify a const object

DATA TYPES IN C LANGUAGE


A data type defines a set of values and the operations that can be performed on
them. Every data type item (constant, variable etc.,) in a C- program has a data
type associated with it. C support several different types of data each of which
may be represented differently within the computer’s memory.
C supports three classes of data types.
Primary (or Basic) data types.
Derived data types
User defined data types.

I.BASIC DATA TYPES:


1. Integer data types:Integer data types represent all numeric values. Integer is
a number that cannot have any decimal points. Integer number can be formed
using the digits 0 to 9 and + or – sign. Integer data types further classified in to
different types. Its range and size can be shown in the following table.
Data type Size Range
Signed short int 1 byte -128 to 127
Unsigned short int 1 byte 0 to 255
Signed int 2 bytes -32,768 to 32 767
Unsigned int 2 bytes 0 to 65, 535
Signed long int 4 bytes -2,147, 483, 648 to 2, 147,483,647
Unsigned long int 4 bytes 0 to 4, 294,967,295
Note: Signed integer data types allows + or – sign
Unsigned integer values allows only positive values.
2. Floating point Data types : Floating point data types represents the real
numbers a number does have
Data type Size Range
decimal point is called floating
float 4 bytes 3.4e-38 to 3.4e38
point numbers or real
Double 8 bytes 1.7e-308 to 1.7e308
numbers.
long double 10 bytes 1.1.8e-4932 to 1.18e4932
Data type Size Range

Department Of Computer Science 7|Page


3. Character Data types: Character signed char 1 byte -128 to 127
data types can be used to represent unsigned char 1 byte 0 to 255
character type of value, character value
means a character that enclosed with the single quotes.
4. Void data type:Void or empty data types is used in the user defined functions
and pointers. It occupies zero bytes and its range in zero.

II. USER DEFINED DATA TYPES


C permits us to define another defined data types by using existing data types.
Those data type is called user defined data types. They are Structures, unions,
typedef and so on.

III. DERIVED DATA TYPES


Derived data types are derived by using the existing data types. They are arrays,
pointers, functions and so on.

OPERATORS AND ITS TYPES


An operator is a symbol that tells the computer to perform certain mathematical
or logical manipulations on operand. Operators are used in program to
manipulate data and variables. They usually form a part of the mathematical or
logical expressions. The data items that operators act upon are called operands.
Unary: A unary operator is an operator, which operates on one operand.
Binary: A binary operator is an operator, which operates on two operands
Ternary: A ternary operator is an operator, which operates on three operands.
TYPES OF OPERATORS
Arithmetic operators Relational Operators
Logical Operators Increment and Decrement
Conditional operator Bitwise Operators
Assignment Operators Special operators

Symbol Operator
Arithmetic Operators: C provides all the basic Name
arithmetic operators. There are five arithmetic + Addition
operators - Subtraction
* Multiplication
/ Division
% Modulus
Symbol Operator Name
> Greater Than
< Less Than
>= Greater Than Equal To
<= Less Than Equal To

Department Of Computer Science 8|Page


Relational operators: == Equal To
Relational operators are used to compare two != Not Equal To
quantities and depending on their relation it either return true or false i.e., 0 for
false and 1 for true. There are six relational operators. Relational operators are
used to Compare 2 values whether they are equal to each other, unequal or
whether one is greater than or less than the other and so on.
Logical operators:
Symbol Operator Name
In manysituations, it may become necessary to && Logical And
combine the results of relational expression. For || Logical Or
this purpose, c provides three logical operators. ! Logical Not
Exp1 !Exp1
Exp1 Exp2 Exp1 && Exp2 Exp1 || Exp2 True(1) False(0)
True(1) True(1) True(1) True(1) False(0) True(1)
False(0) True(1) False(0) True(1)
True(1) False(0) False(0) True(1)
False(0) False(0) False(0) False(0)

Increment and decrement operators: The increment operator is a unary


operator that increases the value of its operand by 1. Similarly the decrement
operator decrease the value of its operand by 1. For ex. –x is equivalent to writing
x = x-1.
++m is equivalent to m = m+1; (or m+=1)
--m is equivalent to m = m-1; (or m-=1)
A prefix operator adds 1 to the operand and then the result is assigned to the
variable on left. On the other hand, a postfix operator first assigns the value to
the variable on left and then the increments the operand.
Conditional Operator:
The conditional operator is C only ternary operator, meaning that it takes three
operands. Its syntax is
(Condition)? Operand1: Operand2;
If Condition evaluates to true (that is, nonzero), the entire expression evaluates to
the value of operand1. If condition evaluates to false (that is, zero), the entire
expression evaluates as the value of operand2.
Symbol Operator Name
| Bit wise Or
Bitwise operators: & Bit wise And
There are six bit wise operators, these ^ Bit wise Exclusive Or
<< Left shift
operators operates on binary value of an
>> Right shift
integer data (bit by bit level). ~ One’s Complement

Department Of Computer Science 9|Page


Assignment operator: This operator is used to assign the result of an expression
to a variable. It assigns the left hand side value to right hand side. Always on the
right hand side there should be variable and on the left hand side we have a
variable, constants or an expression. The general format of assignment statement
is:
Variable_name = expression;
Where expression may be as simple as a constant (or) as complex as an
expression. The operator ‘=’ is called assignment operator. The left of assignment
operator must be a variable.
Compound assignment operator: It combines two operator the arithmetic and
assignment operator. What appears on the left hand side need not be repeated
and therefore it becomes easier to write. They are
+= , -= , *= , /=, %=
For Example:
a+=b a= a+b;
a*=b a=a*b;
Special operators: These include sizeOf, comma operator(,), address of (&)
Size of operator: It is to display no. of bytes covered by a variable or an
expression.
Ex: inta,b;

INPUT AND OUTPUT STATEMENTS

FORMATTED INPUT: Input data can be entered into the computer from a
standard input device by means of the C library function scanf(). This function
can be used to enter any combination of numerical values, single characters and
strings. The function returns the number of data items that have been entered
successfully.
In general terms, the scanf() function is written as
scanf(“control string”, arg1,arg2,…,argn);
Where control string refers to a string containing certain required formatting
information and arg1, arg2,…arg n arqe arguments that specifies the address
locations where the data is stored.
Type specifiers for scanf() are
FORMAT SPECIFIER DESCRIPTION
%d Integer Format Specifier
%f Float Format Specifier
%c Character Format Specifier
%s String Format Specifier
%u Unsigned Integer Format Specifier
%ld Long int Format Specifier

Department Of Computer Science 10 | P a g e


The scanf() function ignores any blank spaces, tabs, and newlines entered by the
user. The function simply returns the number of input fields successfully
scanned and stored.
FORMATTED OUTPUT:
Output data can be written from the computer onto a standard output device
using the library function ‘printf’. This function can be used to output of any
combination of numerical values, single characters and strings. Simply the ‘printf’
function moves data from the computer memory to the standard output
device(monitor).
The ‘printf’ function is written as
printf(“control string”, arg1,arg2, …., arg n);
Where control string refers to a string that contains formatting information and
arg1, arg2,……argn are arguments that represent the individual output data
items.
Ex: printf(“\n Result : %d%c%f”, 12,’a’,2.3);
Result: 12 a 2.3

Single character input getchar():


The simplest of all input/output operations is reading a character from the
‘standard input’ unit and writing it to the ‘standard output’ unit. Reading a single
character can be done by using the function getchar(). The general form of
getchar() is
variable_name=getchar()
Single character output putchar():
Similarly putchar() function can be used for writing a one character at a time. The
general form
putchar(variable_name)
gets() : The gets() facilitates the transfer of strings between the computer and the
standard input/output devices.
gets() function is used to read a string. The general format is
gets(string-name);
where string name is a valid variable and must be declared as a string. The
string is terminated by a new line character.
puts() : This function is enable to print/display the string. The general format
is
puts(string-name);
Where string name should be a valid variable name and it should have been
declared a string.

Department Of Computer Science 11 | P a g e


CONTROL STATEMENTS
By default, statements are executed in sequence, one after another. We can,
however, modify that sequence by using control flow constructs which arrange
that a statement or group of statements is executed only if some condition is true
or false, or executed over and over again to form a loop. There are various
methods that C can control the flow of logic in a program.
They are used break the sequential execution of the program. There are two types
of control statements in C language
Conditional branching statements Looping statements
Conditional branching statements:Display set of statements based on
condition. There are set of conditional statements to verify the data. Those are
given below
1. if statement.
2. if else statement.
3. Nested if else statement.
4. switch case statement.
if statement:
The simplest way to modify the control flow of a
program is with an ‘if’ statement.
if(condition)
{
Statement_block;
}
If condition becomes true, statement block is
executed.

if else statement:
If is a keyword, it checks only single condition.
Suppose if we want to check two conditions we
may use if..else. The general syntax of an if else
statement is,
if (condition)
{
statement1;
}
else
{
statement2;
}
The first statement or block of statements is executed if the condition is true, and
the second statement or block of statements (following the keyword else) is
executed if the condition is not true.

Department Of Computer Science 12 | P a g e


Nested if else:When a series of decisions are involved, we may require to use
more than one if…else statement.
If an if statement is defined with in an if statement or else then this is known
nested if else statement. The nested if else form as shown
if (condition1)
{
if(condition2)
Statement 1;
else
Statement 2;
}
else
{
if (condition3)
Statement-3;
else
Statement-4;
}
If the condition-1 is true, then condition-2 is verified, if it is true statement-1 is
executed, otherwise statement-2 is executed. If condition-1 is false, then
condition-3 is verified, if it is true statement-3 is executed otherwise statement-4
is executed.

if-else-if Ladder:
A multi way decision can be written by using if-
else-if ladder construct. The conditions are
evaluated from the top. As soon as a true
condition is met, the associated statement
blocks get executed and rest of the ladder is by
passed. If none of the condition are met then
the finale else block gets executed. Its syntax is
if( expression1 )
statement1;
else if( expression2 )
statement2;
else
statement3;
next statement;

If the first expression, expression1, is true, statement1 is executed before the


program continues with the next statement. If the first expression is not true, the
second expression, expression2, is checked.
If the first expression is not true, and the second is true, statement2 is executed.
If both expressions are false, statement3 is executed. Only one of the three
statements is executed.

Department Of Computer Science 13 | P a g e


Switch case:Switch is a keyword. It is a multi-directional bi-conditional control
structure. The switch function depends upon case constants only. If matching
found it prints the current statement, if matching not found it goes to default
block and then statement-x is executed.
The general form of the switch statement is as follows:
switch (var)
{
case 1 : statement1; break;
case 2: statement 2; break;
...
case n: statement n; break;
default: statement-x;
}
In this statement, expression is any expression
that evaluates to an integer value: type long,
int, or char. The switch statement evaluates
expression and compares the value against the templates following each case
label, and then one of the following happens:
If a match is found between expression and one of the templates, execution is
transferred to the statement that follows the case label.
If no match is found, execution is transferred to the statement following the
optional default label.
If no match is found and there is no default label, execution passes to the first
statement following the switch statement's closing brace.

Department Of Computer Science 14 | P a g e


UNIT-2: Loops and Arrays
Loops And Arrays: Use of While, Do While and For Loops - Use of Break and
Continue Statements - Array Notation and Representation - Manipulating Array
Elements - Using Multi Dimensional Arrays.

Sequences of statements are executed until a specified condition is true. This


sequence of statements to be executed is kept inside the curly braces { } known as
the “LOOP BODY”. After every execution of loop body, condition is verified, and if
it is found to be true the loop body is executed again. When the condition check
returns false, the loop body is not executed.There are 3 types of loops in c
language
for loop
while loop
do..while loop
For loop:
For loop is used to execute a set of statements repeatedly until a particular
condition is satisfied. We can say it an open ended loop.
Syntax:
for(exp1;exp2;exp3 )
{
Statements;
}
Where, for -------- keyword
exp1------ Initialization
exp2------ condition
exp3------ Iteration ( increment / decrement)
In for loop we have exactly two semicolons, one after initialization and second
after condition. In this loop we can have more than one initialization or
increment/decrement, separated using comma operator. For loop can have only
one condition.
The for loop is executed as follows:
It first evaluates the initialization part.
Then it checks the condition expression.
If it is true, it executes the body of for loop.
Then it evaluates the increment/decrement part.
When the condition expression becomes false, it exits the loop.

Department Of Computer Science 15 | P a g e


While loop:
While loop is an entry controlled loop i.e. the condition is checked before
enetering into the loop. So if the condition is false for the first time, the
statements inside while loop may not be exeuted at all. The condition to be
checked can be changed inside loop by changing values of variables. When the
condition becomes false, the program control exits the loop.
While loop can be completed in 3 steps:
Variable initialization(e.gint x=0)
Condition(e.g x<=10)
Variable increment or decrement(x++ or x--)
Syntax:
variable initialization;
while (condition)
{
Statements;
Variable increment or decrement;
}

do while loop:
In some situations it is necessary to execute body of the loop before testing the
condition. Such situations can be handled with the help of do-while loop. do
statement evaluates the body of the loop first and at the end, the condition is
checked using while statement. It means that for at least
one time, the body of the loop will be executed, even
though the starting condition inside while is initialized to
false.
It is also known as EXIT loop.
The structure of the do...while loop is as follows:
do
{
Statement;
}while (condition);

Department Of Computer Science 16 | P a g e


BREAK AND CONTINUE

Break statement:
In C programming break is used to terminating
the loop immediately after it is encountered. The
break statement is used with conditional if
statement. The general syntax of break
statement is:
while(text expression){
if(text expression)
break;
}
The break statement can be used in terminating all the three loops as while, do
while and for.
Continue statement: it is sometimes desirable to
skip some statements inside the loop. In such
cases, continue statement is used. Continue
statement also can be used in all looping
statements.
The general syntax of the continue statement is:

while(text expression)
{
if(text expression)
continue;
}

ARRAYS

We know how to declare a variable with a specified data type, such as char, int,
float, or double. In many cases, you have to declare a set of variables that have
the same data type. Instead of declaring them individually, C allows you to
declare a set of variables of the same data type collectively as an array.
An array is a collection of variables that are of the same data type. Each item in
an array is called an element. All elements in an array are referenced by the name
of the array and are stored in a set of consecutive memory slots.
Declaring Arrays:
The following is the general form to declare an array:
data-type array-Name [array-Size];

Department Of Computer Science 17 | P a g e


Here data-type is the type specifier that indicates what data type the declared
array will be. Array-Name is the name of the declared array.
For example, an array of integers is declared in the following statement,
Int array_int[8];
where, int specifies the data type of the array whose name is array_int.
The size of the array is 8, which means that the array can store eight elements
(that is, integers in this case).
Indexing Arrays:
After you declare an array, you can access each of the elements in the array
separately.
For instance, the following declaration declares an array of characters:
Ex: char day[4];

day[0] day[1] day[2] day[3]

The array indexing starts at 0. In other words, the index to the first element in an
array is 0, not 1. Therefore, the first element in the array of day is day [0].
Because there are 4 elements in the day array, the last element is day [3], not day
[4].
Initializing Arrays:
We can initialize each element in an array.
intarray_name[5] = {50,60,70,80,90};
Here the integers inside the braces ({and}) are assigned to the corresponding
elements of the array_name.
void main()
{
int i;
int marks[5]= {50,60,70,80,90};
clrscr();
for (i=0; i<5; i++)
{
printf(” marks[%d] is %d \n”, i,marks[i]);
}
getch();
}

OUTPUT:
Marks[0]=50
Marks[1]=60
Marks[2]=70
Marks[3]=80
Marks[4]=90

Department Of Computer Science 18 | P a g e


TWO DIMENSIONAL AND MULTI DIEMNSIONAL ARRAYS

Two dimensional arrays will be in the form of rows and columns format.
Syntax: datatype arrayname[rows][cols];
Data type refers to the nature of the data elements in the array such as
character type, integer type, or float etc.,
array name refers to multidimensional array.
rows refers to the number of rows of the array.
cols refers to the number of columns of the array.
Two Dimensional Array in the memory:
0 1 2
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
The c language follows row major order to store the data in two-dimensional
array.
For instance the statement
int a[3][3]={{1,2,3},{4,5,6},{7,8,9} };
The above statement defines two dimensional array of order 3/3 and initializes all
its elements. The first subscript can be omitted. Hence the above definition can
be replaced by
int a[][3]={{1,2,3},{4,5,6},{7,8,9} }
Multi-dimensional Array:
Multidimensional arrays are defined in much the same manner as one
dimensional array except that a separate pair of brackets is required for each
subscript.
Thus a two dimensional array will require two pairs of square brackets, a three
dimensional array will require three pair of brackets and so on. In general terms a
multi-dimensional array definition can be written as:
data typearray name [size1][size2][size3]…..[size3];
Where the data type is built in or user defined data type, array name is the name
of the array, and size1, size2, size3….sizen are indicate the number of elements
associated with each subscript. The following are same valid array definition
statements.
int marks[2][10][5];//integer array of size 2*10*5=100elements.
char name[30][25];

Department Of Computer Science 19 | P a g e


ACCESSING MULTI DIMENSIONAL ARRAYS:
The elements of a multi-dimensional array can be accessed by the following
statement: marks[i][j][k];Where “i” refers to first subscript,”j” refers to second
subscript and so on. The subscript must be an integer constant or variables or
they can be expressions generating integer results.
Initialization and definition:-
Multi-dimensional arrays can be initialized during its definition as follows:
data type array name [size1][size2]….[size n]={
{Elements of the first row},
{Elements of the second row},
…………………………………,
…………………………………,
{Elements of the (n-1)th row }
}

OPERATIONS THAT CAN BE PERFORMED ON ARRAYS

There are a number of operations that can be performed on arrays. These


operations include:
1. Traversal: traversing the array element means accessing each and every
element of the array for a specific purpose. If A is an array of homogeneous data
elements, then traversing the data elements can include printing every element,
counting the total number of elements, or performing any process on these
elements.
2. Deletion: Deleting an element from the array means removing a data element
from an already existing array.
3. Insertion: Inserting an element in the array means adding a new data element
in an already existing array.
4. Merging: Merging two arrays in a third array means first copying the contents
of the first array into the third array and then copying the contents of the second
array into the third array. Hence the merged array contains the contents of the
first array followed by the contents of the second array.
5. Search: searching means to find whether a particular value is present in the
array or not. If the value is present in the array then searching is said to be
successful and the searching process gives the location of that value in the array.
6. Sorting: The term sorting means arranging the elements of the array in some
relevant order which may either be ascending or descending

Department Of Computer Science 20 | P a g e


UNIT-3: Strings and Functions
Strings and Functions: Declaration and Initialization of String Variables - String
Handling Functions - Defining Functions - Function Call - Call By Value, Call By
Reference – Recursion

STRING HANDLING FUNCTIONS

A string is combination of characters. Any set or sequence of characters defined


within double quotation symbols is a constant string.
Language recognizes that strings are terminated by null character and is a
different class of array by letting us input and output the array as a unit. To
array out many of the string manipulations library supports a large number of
string handling functions that can be used such as:strlen(), strlwr(), strcmp(),
strrev(), etc for string manipulation.
strlen() function: This function counts and returns the number of characters in
a particular string. The length always does not include a null character. The
syntax of strlen() is as follows: n=strlen(string);
Where n is the integer variable which receives the value of length of the string.
strcat() function:when you combine two strings, you add the characters of one
string to the end of the other string. This process is called as concatenation. The
strcat() function is used to joins 2 strings together. It takes the following form:
strcat(str1,str2);
strcmpfunction: In c, you cannot directly compare the value of 2 strings in a
condition like if(string1==string2) Most libraries however contain the function
called strcmp(),which returns a zero if 2 strings are equal, or a non zero number if
the strings are not the same. The syntax of strcmp() is given below:
strcmp(string1,string2);
strcpy() function: To assign the characters to a string,C does not allow you
directly as in the statement name=Robert; Instead use the strcpy() function found
in most compilers the syntax of the function is illustrated below.
strcpy(string1,string2);
strlwr() function: This function converts all characters in a string from
uppercase to lowercase. The syntax of the function strlwr is illustrated below
strlwr(string);
strupr() function: This function converts all characters in a string from lowercase
to uppercase. The syntax of the function strupr is illustrated below
strupr(string);
strrev() function: This function reverses the characters in a particular string.
The syntax of the function strrev is illustrated below
strrev(string);

Department Of Computer Science 21 | P a g e


/* Program for handling the string functions */
#include<stdio.h>
#include<string.h>
void main()
{
int n,t;
char str1[10],str2[10];
clrscr();
printf("\n ***Program for string functions***");
printf("\n Enter the two string:");
scanf("%s %s",str1,str2);
t=strcmp(str1,str2);
printf("\n1.String Comparison: %d",t);
n=strlen(str1);
printf("\n2.string length:%d",n);
printf("\n3.String Concatenation:%s",strcat(str1,str2));
printf("\n4.String Uppercase:%s",strupr(str2));
printf("\n5.String Lowercase:%s",strlwr(str2));
printf("\n6.String reverse:%s",strrev(str2));
getch();
}
Output:
***Program for string fuctions***
Enter the two strings: srisai
1. String Comparision: 17
2. String length: 3
3. String Concatenation: srisai
4. String Uppercase: SAI
5. String Lowercase: sai
6. String reverse: ias

Introduction:
If the program is lengthier then it is very difficult for the programmer to handle it.
such programs should be broken down into a number of small pieces called
modules and that phenomenon are called as a function.
Definition:
A function is a self-contained block of statements to perform a specific well
defined task.
By using functions, it is possible to reduce the size of a program by calling and
using them at different places in the program.
Types:
There are two types of functions available in C.
• Built in function or Library Function
• User defined function.

Department Of Computer Science 22 | P a g e


Library Functions:
Library functions are predefined functions which are defined by the compiler
designer at the time of designing the compiler. All the library functions are
grouped in the form of header file which have the extension ‘.h’.
Some standard built in functions are given below:
Name of the function Description
clrscr() It clears the screen
printf() It prints the message on the screen
scanf() It reads the data from key board
getch() It reads a single character from key board

User defined function:


Just like built in functions user also create their own functions name called "user
defined functions".
Syntax:
return datatype function_name (parameter list) Function Header
{
local variable declarations;
executable statements
----------------------- Function body
return statement;
}

Arguments used in a program are of two types the formal argument and the
actual argument. The arguments used in calling function are called as actual
arguments and arguments used in the called function are called as formal
arguments.

The advantage of dividing a program into function is:


• It facilitates top-down modular programming. In this programming style, the
high level logic is first while the details of the each lower level function are
addressed later.
• The length of a source program can be reduced by using functions at
appropriate places. This factor is particularly critical with microcomputers
where memory space is limited.
• It is easy to locate and isolate a faulty function for further investigations
• A function may be used by many other programs. This means that a C
programmer can build on what other have already done, instead of starting all
over again from scratch.

Department Of Computer Science 23 | P a g e


TYPES OF USER DEFINED FUNCTIONS

User defined functions can be divided into four types. They are:
1. A function without parameter and without return value:
In this type of function the control is just passed to the called function and after
execution of all the statements from the control is just returned back to the called
function without any value. There is no data transfer between the calling function
and called function.
void fun( ){
printf(“hello”);
} Calling Called
void main(){ Function Function
fun( );
}

2. A function with parameter and without return value.


In this type of function there is a one way communication. While moving from the
calling function to the called function along with the control, data is moved but
while returning from the called function only control is moved.
void fun( int a, int b){
printf(“hello \ta= %d \tb=%d”,a,b); Calling Called
} Function Function
void main(){
fun(5, 10 );
}

3. A function without parameter and with return value.


In this type of function there is a one way communication. While moving from the
calling to the called just control is moved but while moving back from the called
function to calling function along with control data is moved.
int fun( ){
printf(“hello”); Calling Called
return 10; Function Function
}
void main(){
int v;
v = fun( );
printf(“\nv=%d”,v);
}

4. A function with parameter and with return value.


It is a two way communication in which while moving the control from calling to
the called and back from called to the calling data is moved along the with
control.

Department Of Computer Science 24 | P a g e


int fun( int a, int b){
printf(“hello \ta= %d \tb=%d”,a,b); Calling Called
return a+b; Function Function
}
void main(){
int r;
r=fun(5,10);
printf(“\nr=%d”,r);
}

PARAMETER PASSING TECHNIQUES


1. In C Programming we have different ways of parameter passing schemes such
as Call by Value and Call by Reference.
2. Function is good programming style in which we can write reusable code that
can be called whenever require.
3. Whenever we call a function then sequence of executable statements gets
executed. We can pass some of the information to the function for processing
called argument.
Values to a function can be passed in two
1. Pass by Value 2. Pass by reference

Pass by value:In the pass by value mechanism, a copy of actual argument is


passed to the called function. So there will be two copies of variable one copy with
the actual argument and another with the formal argument. When any changes
are made in the formal will not reflect the actual argument, because the formal
argument is maintaining a separate copy.
void swap(int,int);
void main()
{
inta,b;
clrscr();
printf(“Enter two values:”);
scanf(“%d%d”,&a,&b);
printf(“\nValues before swapping A=%d,B=%d”,a,b);
swap(a,b);
}
void swap(intx,int y)
{
int t=x;
x=y;
y=t;
printf(“\nValues after swapping A=%d,B=%d”,x,y);

Department Of Computer Science 25 | P a g e


}

Output:
Enter two values: 4 5
Values before swapping A=4 B=5
Values after swapping A=5 B=4

Pass by Address:Rather than passing copy of actual argument here we pass the
address of actual argument. So formal argument will be pointer that holds the
address of actual argument. So performs manipulation on the actual argument
address. So in this case any changes made on the formal argument will reflect on
the actual argument.
void swap(int *,int *);
void main()
{ inta,b;
clrscr();
printf(“Enter two values:”);
scanf(“%d%d”,&a,&b);
printf(“\nValues before swapping A=%d,B=%d”,a,b);
swap(&a,&b);
printf(“\nValues after swapping A=%d,B=%d”,a,b);
}
void swap(int *x,int *y)
{ int t=*x;
*x=*y;
*y=t;
}
Output:
Enter two values: 4 5
Values before swapping A=5 B=4
Values after swapping A=5 B=4

DIFFERENCES BETWEEN PASS BY VALUE AND PASS BY REFERENCE

Pass by value Pass by reference

1. Pass by value is one of 1. Pass by reference is one of


parameter passing mechanism. parameter passing mechanism.
2. This mechanism passes 2. This mechanism passes address
value of the variable. of the variable.
3. Pass by value mechanism the 3. Pass by value mechanism the
changes made on formal changes made on formal arguments
arguments doesn’t reflect on actual will reflect on actual arguments.
arguments.

Department Of Computer Science 26 | P a g e


Pass by value Pass by reference

4. Pass by value mechanism 4. Pass by reference mechanism


uses formal variable uses formal pointer variable
void increment( int X ) void increment( int *X )
{ {
X = X+1; *X = *X+1;
} }
main() main()
{ int X=10; { int X=10;
printf(“\nBefore X=%d”,X); printf(“\n Before X=%d”,X);
increment( X ); increment( &X );
printf(“\n After X=%d”,X); printf(“\n After X=%d”,X);
} }

Output : Output :
Before X = 10 Before X = 10
After X = 10 After X = 11

RECURSIVE FUNCTION AND ITS TYPES

The basic idea behind a recursive function is that you can solve a problem by
breaking it into smaller pieces, solving each of those smaller pieces by breaking
them up into even smaller pieces, and so on.
The two basic parts of a recursive function:
1. The base case - without a base case, your recursive function will never
terminate. For functions of natural numbers, N=0 is usually the base case.
2. The recursive part - this part implements the concept that you can 'solve the
problem' by solving a smaller problem.
Types of recursion:
1. Direct recursion: a function is said to be directly recursive if it explicitly calls
itself.
2. Indirect recursion: a function is said to be indirectly recursive if it contains a
call to another function which ultimately calls it.
3. Tail recursion: a recursive function is said to be tail recursive if no operations
are pending to be performed when the recursive function returns to its caller.
When the called function returns, the returned value is immediately returned
from the calling function.

Department Of Computer Science 27 | P a g e


4. Linear and tree recursion: recursive functions can also be characterized
depending on the way in which the recursion grows in a linear fashion or
forming a tree structure.
/* write a program find factorial of given number using recursive function
*/
int fact (int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, fact (n));
return 0;
}
int fact (int n)
{
if(n!=1)
return n*fact (n-1);
}
Features:
There should be at least one if statement used to terminate recursion.
It does not contain any looping statements.

Advantages:
It is easy to use.
It represents compact programming structures.
Disadvantages:
It is slower than that of looping statements because each time function is called.

Department Of Computer Science 28 | P a g e


Unit-IV Classes and Object

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

Introduction to Object Oriented Programming


Object Oriented Paradigm
Object Oriented Programming is an approach to program organization and
development that attempts to eliminate some of the pitfalls of conventional
programming methods by incorporating the best of structured programming
features with several new concepts. Languages that support OOP features include
Smalltalk, C++, Ada, etc. Java is a pure object oriented language.
The major objective of object oriented approach is to eliminate some of the flaws
encountered in the procedural approach. OOP treats data as a critical element in
the program development and does not allow it to flow freely around the system.
It ties data more closely to the functions that operate on it and protects it from
unintentional modifications by other functions. OOP allows us to decompose a
problem into a number of entities called Objects and then builds data and
functions around these entities.

Method Method

Data
Method
Method

Object = Data + Methods


Some of the features of Object Oriented paradigm are:
• Emphasis is on data rather than procedure
• Programs are divided into Objects
• Data structures are designed such that they characterize the objects
• Methods that operate on data of an object are tied together in the data
structure
• Data is hidden and cannot be accessed by external functions
• Object may communicate with each other through methods
• New data and methods can be easily added whenever necessary
• OOP Follows bottom-up approach in program design.

Department Of Computer Science 29 | P a g e


Benefits and Applications of OOPs
OOP offers several benefits to both the program designer and the user. Object
orientation contributes to the solution of many problems associated with the
development and quality of software products.
The principle advantages are:
Through inheritance we can eliminate redundant code and extend the user of
existing classes.
Catch errors at compile time rather than at run time using exception handling.
The principle of data hiding helps the programmer to build secure programs
Reduces large problems into smaller ones, more manageable ones.
It is easy to partition the work in a project based on objects.
Object oriented systems can be easily upgraded from small to large system
With the concept of Message Passing techniques, we have communication
between objects.
Software complexity can be easily managed.

Applications of OOP
OOP are being used in many areas of computer programming. OOP are used in
solving complicated and complex based system because it can simplify a complex
problem. The most important application of OOP include
Real- Time systems
Simulation and Modeling
Object Oriented databases
Database management systems.
Web based applications.
Hypertext, hypermedia
AI and expert systems
Neural networks and parallel programming
Decision support and office & automation systems
CIM/CAD/CAM system
Introduction To C++:
C++, as we all know is an extension to C language and was developed by “ Bjarne
stroustrup” at bell labs. C++ is an intermediate level language, as it comprises a
confirmation of both high level and low level language features. C++ is a statically
typed, free form, multi paradigm, compiled general-purpose language.
C++ is an Object Oriented Programming language but is not purely Object
Oriented. Its features like Friend and Virtual, violate some of the very important
OOPS features, rendering this language unworthy of being called completely
Object Oriented. It’s a middle level language.
Features

Department Of Computer Science 30 | P a g e


C++ is object oriented programming language. It provides a lot of features that are
given below.

Simple
Machine Independent or Portable
Mid-level programming language
Structured programming language
Rich Library
Memory Management
Fast Speed
Pointers
Recursion
Extensible
Object Oriented
Compiler based
1) Simple: C++ is a simple language in the sense that it provides structured
approach (to break the problem into parts), rich set of library functions, data
types etc.
2) Machine Independent or Portable: Unlike assembly language, c programs
can be executed in many machines with little bit or no change. However, it is not
platform-independent.
3) Mid-level programming language: C++ is also used to do low level
programming. It is used to develop system applications such as kernel, driver etc.
It also supports the feature of high level language. That is why it is known as
mid-level language.
4) Structured programming language: C++ is a structured programming
language in the sense that we can break the program into parts using functions.
So, it is easy to understand and modify.
5) Rich Library: C++ provides a lot of inbuilt functions that makes the
development fast.

Department Of Computer Science 31 | P a g e


6) Memory Management: It supports the feature of dynamic memory allocation.
In C++ language, we can free the allocated memory at any time by calling the
free() function.
7) Speed: The compilation and execution time of C++ language is fast.
8) Pointer: C++ provides the feature of pointers. We can directly interact with
the memory by using the pointers. We can use pointers for memory, structures,
functions, array etc.
9) Recursion: In C++, we can call the function within the function. It provides
code reusability for every function.
10) Extensible: C++ language is extensible because it can easily adopt new
features.
11) Object Oriented: C++ is object oriented programming language. OOPs
makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size
grows.
12) Compiler based:C++ is a compiler based programming language, it means
without compilation C++ program can be executed. First we need to compile our
program using compiler and then we can execute our program.

Header File Declaration Section


General Structure Of a C++ Program
Global Declaration Section
C++ Programming language is most popular
Class Declaration
language after C Programming language. C++
And
is first Object oriented programming Method Definition Section
language. Main Function
Method Definition Section
Header File Declaration Section
Header files used in the program are listed here.
Header File provides Prototype declaration for different library functions.
We can also include user define header file.
All pre-processor directives are written in this section.
Global Declaration Section
Global Variables are declared here.
Global Declaration may include:
1. Declaring Structure
2. Declaring Class
3. Declaring Variable
Class Declaration Section
Actually this section can be considered as sub section for the global
declaration section.
Class declaration and all methods of that class are defined here.

Department Of Computer Science 32 | P a g e


Main Function
Each and every CPP program always starts with main function.
This is entry point for all the function. Each and every method is called
indirectly through main.
We can create class objects in the main.
Operating system calls this function automatically.
Method Definition Section
This is optional section. Generally this method was used in C Programming.

cin and cout objects:


C++ I/O operation is using the stream concept. Stream is the sequence of bytes
or flow of data. It makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a
network connection, etc., this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc
to main memory, this is called asinput operation.

I/O Library Header Files


Let us see the common header files used in C++ programming are:

Header File Function and Description


It is used to define the cout, cin and cerr objects, which
<iostream> correspond to standard output stream, standard input stream
and standard error stream, respectively.
<fstream> It is used to declare services for user-controlled file processing.
Standard output stream (cout)
The data can be printed or displayed on screen using a statement called cout
in CPP.
This statement is a combination of cout and <<.
The identifier cout is a pre defined object that represents the standard output
stream.
The standard output stream represents the screen. The syntax is as follows.
cout<<”text to be printed”;
The operator << is called the insertion operator or put to operator.
It inserts or sends the contents of a variable on its right to the object on its
left.
The operator << is also called bitwise left shift operator.

Department Of Computer Science 33 | P a g e


Let's see the simple example of standard output stream (cout):
#include <iostream.h>
#include<conio.h>
void main( ) {
char ary[] = "Welcome to C++ Programming";
cout << "Value of ary is: " << ary << “\n”;
}
Output:
Value of ary is: Welcome to C++ tutorial
Standard input stream (cin)
CPP supports one input statement through which user can provide data to the
program.
The statement looks like cout and it has a difference as shown below.
cin>> variable;
This is an input statement which causes the program to wait for the user to
give data.
The identifier cin is a predefined object in CPP that corresponds to the
standard input stream.
Here, the standard input stream represents the keyboard.
The operator >> is known as ‘extraction’ or ‘get from’ operator.
This operator extracts the value from the keyboard and assigns it to the
variable on its right.
We can also cascade input operator as shown below.
cin>> var1 >> var2;
The multiple use of >> in one statement is called cascading.
First variable1 will be assigned by a value then variable2 will be assigned a
value.
Let's see the simple example of standard input stream (cin):
#include <iostream.h>
#include<conio.h>
void main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Output:
Enter your age: 22
Your age is: 22

Department Of Computer Science 34 | P a g e


Basic concepts of OOPS
Object oriented programming is a method of programming where a system is
considered as a collection of objects that interact together to accomplish certain
task. Objects are entity that encapsulates data and procedure that operate on the
data.
The main purpose of object-oriented programming is to simplify the design,
programming and most importantly debugging a program.
Object Oriented programming is a programming style that is associated with the
concept of Class, Objects and various other concepts revolving around these two,
like Inheritance, Polymorphism, Abstraction, Encapsulation etc.
Some of the basic concepts of OOPs are:
Class
Object
Methods
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Message Passing

Class:
Class is a model for creating objects which consists of data members and member
functions. Data members are also known as properties or variables and member
functions are also known as actions or methods.
Declaring a Class: class may be declared as,
class Class_Name
{
< access specifiers > :
data members;
member functions();
< access specifiers > :
data members;
member functions();
}
Object:
These are the basic run time
entities in an object oriented
system. They may be represent
a person, a place, a bank
account, a table of data or any
item that the program to
handle. They may also represent
user defined data such as
vectors, trees and lists.

Department Of Computer Science 35 | P a g e


Methods
A method represents a group of statements to perform a well-defined task. Task
means calculating the data or generating the reports etc.
Methods are of two parts
Method header or method prototype
Method Body
Method Header or Method prototype:
It contains return type, method name and list of argument variables.
Syntax: return_typemethod_name( arg_list1, arg_list2,……..arg_listn)
Method Body: It contains logic to perform the task. It may be looks like
{
Statements;
}
Inheritance:
Inheritance is the process by which objects of one class acquires the properties of
objects of another class.
In other words, derives class inherits the properties of its base class features and
implementing their own.
The concept of inheritance gives “re-usability”.
Inheritances are of 6 types
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multipath Inheritance
Hybrid Inheritance

Polymorphism:
Polymorphism is a Greek word. Poly means many and morphism means forms.
Therefore, Polymorphism means many forms.
I.e., Ability to take more than one form are known as Polymorphism
The different classification of polymorphism can be shown above.
Data Abstraction:
Data abstraction refers to providing only essential information to the outside
world and hiding their background details, i.e., to represent the needed
information in program without presenting the details.
Encapsulation:
Packing of data or wrapping of data are known as Encapsulation.
In other words, to store data or functions in a single unit is known as
Encapsulation.

Department Of Computer Science 36 | P a g e


i.e. Data is not accessible to the outside world, and only those functions which
are wrapped in the class can access it.
Message Passing:
It is a process of sending request to
execute a function for an object. It involves
specifying the name of the object, name of the method and the information to
send.
Programming with these objects should be followed in steps shown below:
1. Declaring classes that define objects and their actions.
2. Declaring objects from classes
3. Implementing relation between objects.

Friend function in CPP


The private members of a class cannot be accessed from outside the class.
That is, a non-member function cannot have an access to the private data of a
class.
To overcome this problem CPP have the common function to be made friendly
with both the classes, thereby allowing the function to have access to the
private data of these classes.
To make an outside function friendly to a class, we have to simply declare this
function as a friend of the class as shown below.
class ABc{
……..
……..
public:
………
………
friend void xyz(void);
};
The function declaration should be preceded by the keyword friend.
The function can be defined elsewhere in the program.
The function definition does not use either the keyword friend or the scope
operator‘::’.
The functions that are declared with the keyword friend are known as friend
functions.
A friend function has full access rights to the private members of the class.
A function can be declared as a friend in any number of classes.
Characteristics of a friend function
A friend function possesses certain special characteristics:
It is not in the scope of the class to which it has been declared as friend.

Department Of Computer Science 37 | P a g e


Since it is not in the scope of the class, it cannot be called using the object of
that class.
It can be invoked like a normal function without the help of any object.
Unlike member functions, it cannot access the member names directly and
has to use an object name and dot membership operator with each member
name.
It can be declared either in the public or the private part of a class without
affecting its meaning.
Usually, it has the objects as arguments.

static member function:


A static member function is a special member function, which is used to
access only static data members, any other normal data member cannot be
accessed through static member function. Just like static data member, static
member function is also a class function; it is not associated with any class
object.
We can access a static member function with class name, by using following
syntax: class_name:: function_name(perameter);
Consider the example:
#include <iostream.h>
#include<conio.h>
class Demo{
private:
staticint X;//static data members
staticint Y;

public:
staticvoid Print(){//static member function
cout<<"Value of X: "<< X <<endl;
cout<<"Value of Y: "<< Y <<endl;
}
};

int Demo :: X =10;//static data members initialization


int Demo :: Y =20;

voidmain(){
Demo OB;

cout<<"Printing through object name:"<<endl;


OB.Print(); //accessing class name with object name

cout<<"Printing through class name:"<<endl;


Demo::Print();//accessing class name with class name
getch();
}

Department Of Computer Science 38 | P a g e


Value Constructors
A constructor is a special member function for automatic initialization of an
object, whenever an object is created the special member functions (constructors)
will be executed automatically.
Rules:
A constructor’s name must be
the same as that of the class
name.
It is declared with no return type not even void.
A constructor may have or may not have parameters.
If a constructor has no arguments, then it is called as “Default Constructor”.
If a constructor has one or more arguments, then it is called as a
“Parameterised constructor”.
It may not be static.
It should be public or protected access specifiers within the class and only in
rare circumstances, it should be declared as Private.
Syntax: class class_name{
access specifiers:
o data members;
o member functions();
class_name() { //constructor
o --------------;
--------------;
}
};
// Program to print Fibonacci number using the constructor where the
constructor member functions has been defined inside the class.
#include<iostream.h>
#include<conio.h>
class Fibonacci {
private:
long int f,f1,fib;
public:
Fibonacci() {
f=0;
f1=1;
fib=f+f1;
}
void increment() {
f=f1;
f1=fib;
fib=f+f1;
}
void display() {
cout<<”Fib:”<<fib<<endl;

Department Of Computer Science 39 | P a g e


}
};
void main(){
Fibonacci obj;
inti;
clrscr();
for(i=0;i<5;i++){
obj.increment();
obj.display();
}
getch();
}

Copy Constructor:
Copy constructors are used when the compiler has to create a temporary object of
class object. Copy constructors are used in the following situations.
The initialization of an object by another object of the same class.
Return of objects as a function value.
Stating the object as by value parameters of a function.
The copy constructor can accept a single argument of reference to same class
type.
Syntax: class_name::class_name(class_name&ptr)
Eg: X :: X(X &ptr)
The copy constructor n may be used in the following format also using a const
Keyword. Syntax:
class_name::class_name(constclass_name&ptr)

// program to demonstrate copy constructor


#include<iostream.h>
#include<conio.h>
class SampleCopyConstructor{
private:
int x, y; //data members

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

/* Copy constructor */
SampleCopyConstructor(constSampleCopyConstructor&samp){
x = sam.x;
y = sam.y;
}

Department Of Computer Science 40 | P a g e


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

Default Constructor:
The default constructor is a special member function which is invoked by C++
compiler, without any argument for initializing the objects of a class.
The purpose of default constructor is to construct a default object of that class
type.
Syntax: class class_name{
access specifier:
data members;
member functions();
class_name(){
-----------;
-----------;
}
};
// program to print student details using a default constructor
#include<iostream.h>
#include<conio.h>
class Student {
private:
char ename[20];
long introllno;
char gender;
float height,weight;
public:
Student();
void display();
};
Student::Student() {
ename[10]=’\0’;
rollno=0;
gender=’\0’;

Department Of Computer Science 41 | P a g e


height=0;
weight=0;
}
void display() {
cout<<”Name:”<<ename<<endl;
cout<<”RollNo:”<<rollno<<endl;
cout<<”Gender:”<<gender<<endl;
cout<<”Height:”<<height<<endl;
cout<<”Weight:”<<weight<<endl;
}

Parameterized Constructor:
A constructor, which has parameters, is called parameterized constructor. It is
used to provide different values to different objects of a class.
class class_name {
Access Specifier :
Member - Variables
Member - Functions
public:
class_name(variables) {
// Constructor code
}
//... other Variables & Functions
}

Overloaded Constructor:
The overloaded constructor is a concept in oops in which the same constructor
name is called with different arguments, the constructor will be invoked
automatically by the compiler to initialize the objects.
Or
Writing two or more constructors with a same name but different types of
arguments or number of arguments are known as Constructor Overloading.
// Program to demonstrate to print Overloaded Constructor
#include<iostream.h>
#include<conio.h>
class abc {
public:
abc();
abc(int);
abc(float);
abc(int,float);
};

Department Of Computer Science 42 | P a g e


abc::abc() {
cout<<"Calling Default Constructor:\n";
}
abc::abc(int a) {
cout<<"Calling Constructor with int:\n";
cout<<"a is:"<<a<<"\n";
}
abc::abc(float fa) {
cout<<"Calling Constructor with Float:\n";
cout<<"a is:"<<a<<"\n";
cout<<"fa is:"<<fa<<"\n";
}
abc::abc(int a, float fa) {
cout<<" calling Constructor with int and float:\n";
cout<<"a is:"<<a<<"\n";
cout<<"fa is:"<<fa<<"\n";
}

void main() {
abcobj;
clrscr();
abc(10);
abc(75.25);
abc(30, 10.25);
getch();
}

Destructors:
A Destructor is a function that automatically executes when an object is
destroyed. The primary usage of destructor function is to release space.
Syntax: class class_name{
access specifiers :
data members;
member functions();
class_name(); // constructor
~class_name(); // destructor
};
Rules for Destructors:
A destructor function name is the same as that of a class name. The first
character of the destructor name must be a “Tilde(~)”.
It is declared with no return type, not even void.
It takes no arguments and therefore cannot be overloaded.
It should have public access specifier in class declaration.
Program to demonstrate to print destructors
#include<iostream.h>
#include<conio.h>

// declare a class

Department Of Computer Science 43 | P a g e


class Hello {
public:
Hello() { // Constructor
cout<< "Constructor is Called." <<endl;
}

~Hello() { // Destructor
cout<< "Destructor is Called." <<endl;
}
// Member Function
int display() {
cout<< "Hello, Programmer." <<endl;
}
};

void main() {
Hello obj1; // create an object
obj1.display(); // Member function called
getch();
}

Output
Hey look I am in constructor
Hello, Programmer.
Operator Overloading:
Operator overloading is an important concept in C++. It is a type of polymorphism
in which an operator is overloaded to give user defined meaning to it. Overloaded
operator is used to perform operation on user-defined data type.
Operator that cannot be overloaded are as follows:
➢ Scope operator (::)
➢Sizeof
➢member selector(.)
➢member pointer selector(*)
➢ ternary operator(?:)
Syntax of Operator Overloading:
return_typeclass_name : : operator op(argument_list)
{
// body of the function.
}

Department Of Computer Science 44 | P a g e


Unary operators:
The unary operators operate on a single operand.
The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj, and
++obj but sometime they can be used as postfix as well like obj++ or obj--.

/* (1) cpp program to concatenate two strings using operator overloading*/


#include<iostream>
#include<string.h>

class String {
public:
char str[20];
void accept_string() {
cout<<"\n Enter String : ";
cin>>str;
}
void display_string() {
cout<<str;
}
String operator+(String x) { //’+’ operator overloading
String s;
strcat(str,x.str);
strcpy(s.str,str);
return s;
}
};
void main()
{
String str1, str2, str3;
str1.accept_string();
str2.accept_string();
cout<<"\n\n First String is : ";
str1.display_string(); //Displaying First String
cout<<"\n\n Second String is : ";
str2.display_string(); //Displaying Second String
str3 = str1 + str2; //String is concatenated. Overloaded '+' operator
cout<<"\n\n Concatenated String is : ";
str3.display_string();
}

/* (2) C++ Program to Compare Two Strings using operator "==" Overloading */
#include<iostream>
#include<stdio.h>
#include<string.h>

class String {
char str[20];

Department Of Computer Science 45 | P a g e


public:
void getdata() {
gets(str);
}
int operator ==(String s) {
if(!strcmp(str, s.str))
return 1;

return 0;
}
};

void main() {
String s1,s2;

cout<<"Enter first string :: ";


s1.getdata();
cout<<"\nEnter second string :: ";
s2.getdata();
if(s1==s2)
cout<<"\nStrigs are Equal\n";
else
cout<<"\nStrings are Not Equal\n";

getch();
}

Department Of Computer Science 46 | P a g e


Unit-V: Inheritance
Inheritance: Inheritance - Types of Inheritance -Types of derivation- Public –
Private - Protected Hierarchical Inheritance - Multilevel Inheritance – Multiple
Inheritance - Hybrid Inheritance.

INHERITANCE
Inheritance is one of the most powerful and essential characteristics of
OOP.

Inheritance is the process by which objects of one class acquires the


properties of objects of anotherclass.
Inheritance supports the concept of classhierarchy.
Inheritance concept provides the codereusability.
The class from which we derive the properties is called base class or
parent class or superclass.
Theclass to which we derive properties is called derived class or
childclass or subclass.
The existing classes are main components of inheritance. The new
classes are created from existing one. The properties of existing classes
are simply extended to the new classes. The new classes created using
such methods are known as derived classes and the existing classes are
known as base class. The relation between the base and derived class is
known as “ Kind of relationship”.
Advantages:The main advantage of inheritance are
Reusability of thecode
To increase the reliability of the code,and
Toaddsomeenhancementstothebaseclass.

Types of Derivation:
C++ provides a no. of ways to establish access to class members. One such
access control mechanism is the derived class are declared. A derived class can
be declared with one of the access control specifiers private, public or protected
and thus there are 3 types of derivations. The access specifier determines how the
derived class inherits the elements of the base class.
Public Derivation:
When the access specifier for the inherited base class is public, all public member
of the base class become public member of the derived class. All protected
members of the base class become protected members of the derived class. All

Department Of Computer Science 47 | P a g e


private members of the base class remain private to it and are inaccessible by the
derived class.
Eg: class base A{
private:
public:
int a; //member data
};
class derivedB: public basea{
private:
public:
};
void main(){
derivedB test;
cin>>test.A;
cout<<test.A;
}

Private Derivation:
If the access specifier is private, all public members of the base class becomes
private member of the derived class and they are accessible by the member
function of the derived class. All protected members of the base class also
becomes private members of the derived class. All private members of the base
class are remain to it and are inaccessible by the derived class.
Eg: class baseA{
private:
public:
int a;
};
class derived: private baseA{
private:
public:
void read(){
cin>>a;
}
void display(){
cout<<a;
}
};
void main(){
derived sample;
sample.read();
sample.disp();
}

Protected Derivation:
A base class can also be inherited with the access specifier protected by a derived
class then the public and protected members of the base class become protected
member of the derived class. All private members of the base class remains

Department Of Computer Science 48 | P a g e


private to it and are inaccessible by the derived class.
Eg: class baseA{
private:
protected:
int a;
public:
};
class derived: public baseA{
private:
public:
void read(){
cin>>a;
}
void disp(){
cout<<a;
}
};
void main(){
derivedB sample;
sample.read();
sample.disp();
}

Types of Inheritance:
Inheritances are of five types.
Singleinheritance
MultipleInheritance
MultilevelInheritance
HierarchicalInheritance
Hybrid, and
MultipathInheritance

Single Inheritance
Single Inheritance is the process of creating new
classes from an existing base class. The existing class
is known as the base class and the newly created
class is called as derived class.
Single inheritance is the ability of a derived class to
inherit the member functions and data members of
the existing base class.

Department Of Computer Science 49 | P a g e


Defining the derived class:
The declaration of a singly derived class is as that same of an ordinary
class a derived class. A derived class consists of the following
components.
The keywordclass
The name of the derivedclass
A singlecolon
Thetypeofderivation(public,private,protected)
The name of the base a parentclass.

The general syntax of the derived class declaration is:


class derived_class_name : public/private/protectedbase_class_name{
private:
Data members;
Member functions();
public:
Data members;
Member functions();
protected:
Data members;
Member functions();
};
Example Program:Inheritance with data member
class Account {
public:
float salary=60000;
};

class programmer : public Account {


public:
float bonus=5000;
};

void main() {
programmer p;
clrscr();
cout<<"Salary :"<<p.salary<<"\n";
cout<<"Bonus :"<<p.bonus<<"\n";
getch();
}

Inheritance with member functions :


#include<iostream.h>
#include<conio.h>
class Animal {
public:
void eat() {

Department Of Computer Science 50 | P a g e


cout<<"Eating\n";
}
};
class Dog : public Animal {
public:
void bark() {
cout<<"Barking……\n";
}
};
void main() {
Dog d;
clrscr();
d.eat();
d.bark();
getch();
}

MULITPLE INHERITANCE
It is the process of creating a new class from more than one base classes.
The syntax for multiple inheritance is similar to that of single inheritance.
Syntax:
class baseA{
;
;
};
Class baseB{
;
;
};
Class C : public baseA, public baseB{
;
;
};

The class C is derived from both classes baseA and baseB


Eg: To find out the student details using multiple inheritance.
#include<iostream.h>
#include<conio.h>
class student {
protected:
intrno, m1, m2;
public:
void get() {
cout<<"Enter the Roll no :"; cin>>rno;
cout<<"Enter marks in #2 Subjects: ";
cin>>m1>>m2;
}
};
class sports {

Department Of Computer Science 51 | P a g e


protected:
intsm; // sm = Sports mark public:
void getsm() {
cout<<"\nEnter the sports mark :";
cin>>sm;
}
};
class statement : public student, public sports {
int tot, avg;
public:
void display() {
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n";
cout<<”Total : "<<tot<<"\n";
cout<<"\n\tAverage:"<<avg;
}
};
void main() {
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}

MULTI - LEVEL INHERITANCE


A class which derives a sub class, that sub class is again derived another
sub class, is called multi-level inheritance.In the above example A is derived
inclassB;Bisderivedinto classC.
Syntax:
class A{
//Do something
}
class B : public A{
//Do something
}
class C : public B{
//Do something
}
Eg:
#include<iostream>
#include<stdio.h>
#include<conio.h>
class Employee {
inteno;
char name[20], des[20];

Department Of Computer Science 52 | P a g e


// Private members cannot call from outside class.
public:
void getEmpDetails() {
cout<< "\nEnter the Employee number:";
cin>>eno;
cout<< "Enter the Employee name:";
cin>>name;
cout<< "Enter the Employee designation:";
cin>>des;
}
void employee_display() {
cout<<"\nEmployee number:"<<eno;
cout<<"\nEmployee name:"<<name;
cout<<"\nEmployee designation:"<<des;
}
};
class Salary : private Employee {
//Private Base Class, We cannot access outside the dervied Class
float bp, hra, da, pf, np;
public:
void getPayDetails() {
getEmpDetails();
cout<< "Enter the Basic pay:";
cin>>bp;
cout<< "Enter the Humen Resource Allowance:";
cin>>hra;
cout<< "Enter the Dearness Allowance :";
cin>>da;
cout<< "Enter the Profitablity Fund:";
cin>>pf;
calculate();
}
void calculate() {
np = bp + hra + da - pf;
}
void salary_display() {
employee_display();
cout<<"\nEmployee Basic pay:"<<bp;
cout<<"\nEmployeeHumen Resource Allowance:"<<hra;
cout<<"\nEmployee Dearness Allowance:"<<da;
cout<<"\nEmployeeProfitablity Fund:"<<pf;
cout<<"\nEmployee Net Pay:"<<np;
}
};

class BankCredit : private Salary {


char bank[20], ifsc_code[20];
intaccount_number;
public:

Department Of Computer Science 53 | P a g e


void getBankDetails() {
getPayDetails();
cout<< "Enter the Bank Name:";
cin>>bank;
cout<< "Enter the IFSC:";
cin>>ifsc_code;
cout<< "Enter the Account Number :";
cin>>account_number;
}
void display() {
salary_display();
cout<<"\nEmployee Bank Name:"<<bank;
cout<<"\nEmployeeIFSC:"<<ifsc_code;
cout<<"\nEmployee Account Number:"<<account_number<<"\n";
}
};
void main() {
inti, n;
char ch;
BankCredit s[10];
cout<<"Multi Level Inheritance Example Program : Payroll System\n";
cout<< "Enter the number of employee:";
cin>>n;
for (i = 0; i< n; i++) {
cout<< "\nEmployee Details # "<<(i+1)<<" : ";
s[i].getBankDetails();
}
for (i = 0; i< n; i++) {
s[i].display();
}
getch();
}

Hierarchical Inheritance:
Hierarchical Inheritance in C++ refers to the type
of inheritance that has a hierarchical structure
of classes. A single base class can have multiple
derived classes, and other subclasses can further
inherit these derived classes, forming a hierarchy of classes.
classA{
public void methodA(){
//Do Something
}
};
class B : public A{

Department Of Computer Science 54 | P a g e


public voidmethodB(){
//DoSomething
}
};
class C : public A{
public voidmethodC(){
//DoSomething
}
}
Hierarchical Inheritance Example Program
// C++ program to demonstrate hierarchical inheritance
#include <iostream.h>
#include <conio.h>

class Animal { // base class


public:
void info() {
cout<< "I am an animal." <<endl;
}
};

class Dog : public Animal {// derived class 1


public:
void bark() {
cout<< "I am a Dog. Woof woof." <<endl;
}
};

class Cat : public Animal { // derived class 2


public:
void meow() {
cout<< "I am a Cat. Meow." <<endl;
}
};

void main() {
Dog dog1; // Create object of Dog class
cout<< "Dog Class:" <<endl;
dog1.info(); // Parent Class function
dog1.bark();

Cat cat1; // Create object of Cat class


cout<< "\nCat Class:" <<endl;
cat1.info(); // Parent Class function
cat1.meow();
}

Department Of Computer Science 55 | P a g e


/*Here, both the Dog and Cat classes are derived from the Animal
class. As such, both the derived classes can access the info() function
belonging to the Animal class. */

Hybrid Inheritance
The process of combining more than one type of Inheritance together while
deriving subclasses in a program is called a Hybrid Inheritance.

Hybrid in C++ follows the following pattern - Multiple Inheritance, Single


Inheritance, and Hierarchical Inheritances are combined together. As stated
earlier, in Multiple Inheritance, a sub-class derives properties from multiple
superclasses.

Hybrid Inheritance in C++ is also known as multipath inheritance. This is known


so due to the fact that a sub class derives or inherits properties of the super
class following various paths. Therefore, Hybrid Inheritance is generally applied
where we need to apply more than one form of
Inheritance.

The following diagram demonstrates the process of


Hybrid Inheritancewhich is a combination of Multiple
Inheritance and Single Inheritance.
For multiple Inheritance, Class D is inherited from two other classes. It is derived
from both Class B and Class C.In a similar way, for single Inheritance, Class B
has derived from Class A. Therefore, this chain of various paths of Inheritances
constitutes the Hybrid Inheritance.
For the previous example where the Hybrid Inheritance in C++ was a
combination of Single and Multiple Inheritances, the following syntax can be
followed in C++ -

class A {
// block of statement(s)
}:
class B: public A { // class B derived from a single class A -- follows single
inheritance
// block of statement(s)
};
class C {
// block of statement(s)
};
class D: public B, public C {
// class D derived from two classes, class B and class C -- follows multiple
//inheritance
// block of statement(s)
};

Department Of Computer Science 56 | P a g e


Syntax for Hybrid Inheritance in C++ where a combination of Multilevel
Inheritance and Single Inheritance is considered:
class A {
// block of statement(s)
};
class B: public A { // class B derived from class A
// block of statement(s)
};
class C: public B { // class C derived from class B
// block of statement(s)
};
class D: public B { // class D derived from class B
// block of statement(s)
};

Example : Combination of Multiple Inheritance and Single Inheritance


#include <iostream.h>
class Animals { // indicates class A
public:
Animals() {
cout<< "This is an animal\n";
}
};

class Mammals: public Animals { // indicates class B derived from class A


public:
Mammals() {
cout<< "This is a mammal\n";
}
};

class Herbivores { // indicates class C


public:
Herbivores() {
cout<< "This is a herbivore\n";
}
};

class Cow: public Mammals, public Herbivores {


// indicates class D derived from class B and class C
public:
Cow() {
cout<< "A cow is a herbivore mammal\n";
}
};

void main() {
Cow c;
}

Department Of Computer Science 57 | P a g e

You might also like