0% found this document useful (0 votes)
26 views69 pages

Basireddy Memorial Degree College Nandikotkur

The document provides an introduction to programming language paradigms, focusing on C and C++ for II B.Com (CA) and II B.A (CA) students. It covers various programming paradigms such as imperative, procedural, object-oriented, and declarative programming, along with the software development life cycle (SDLC) phases. Additionally, it explains the structure of C programs, the use of algorithms and flowcharts, and the basic elements of the C programming language including tokens, constants, and operators.

Uploaded by

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

Basireddy Memorial Degree College Nandikotkur

The document provides an introduction to programming language paradigms, focusing on C and C++ for II B.Com (CA) and II B.A (CA) students. It covers various programming paradigms such as imperative, procedural, object-oriented, and declarative programming, along with the software development life cycle (SDLC) phases. Additionally, it explains the structure of C programs, the use of algorithms and flowcharts, and the basic elements of the C programming language including tokens, constants, and operators.

Uploaded by

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

BASIREDDY MEMORIAL DEGREE

COLLEGE
NANDIKOTKUR

II B.Com (CA) & II B.A (CA)

NAME : _____________________________

GROUP : _____________________________

ROLL NO: _____________________________

II B.Com (CA) & B.A (CA) C & C++ Page 1


UNIT-I

Introduction to programming language paradigms – Problem solving methods Flowcharts and Algorithms,
Introduction to C-Structure of C, Compilation and Execution, Character set, identifiers & Keywords, variables and
constants, data types, expressions, operators in C, Input and output statements in C.

Introduction of Programming Paradigms


Paradigm can also be termed as method to solve some problem or do some task. Programming paradigm is an
approach to solve problem using some programming language or also we can say it is a method to solve a
problem using tools and techniques that are available to us following some approach. There are lots for
programming language that are known but all of them need to follow some strategy when they are implemented
and this methodology/strategy is paradigms. Apart from varieties of programming language there are lots of
paradigms to fulfill each and every demand.

1. Imperative programming paradigm:


It is one of the oldest programming paradigms. It features close relation to machine architecture. It is based on
Von Neumann architecture. It works by changing the program state through assignment statements. It performs
step by step task by changing state. The main focus is on how to achieve the goal. The paradigm consists of
several statements and after execution of all the result is stored.
Advantage:
1. Very simple to implement
2. It contains loops, variables etc.
Disadvantage:
1. Complex problem cannot be solved
2. Less efficient and less productive
3. Parallel programming is not possible
Procedural programming paradigm –
 This paradigm emphasizes on procedure in terms of under lying machine model.
 There is no difference in between procedural and imperative approach.
 It has the ability to reuse the code and it was boon at that time when it was in use because of its
reusability.
Object oriented programming –
 The program is written as a collection of classes and object which are meant for communication.
 The smallest and basic entity is object and all kind of computation is performed on the objects only.
 More emphasis is on data rather procedure.
 It can handle almost all kind of real life problems which are today in scenario.
2. Declarative programming paradigm:
 It is divided as Logic, Functional, and Database. In computer science the declarative programming is a
style of building programs that expresses logic of computation without talking about its control flow.
 It often considers programs as theories of some logic. It may simplify writing parallel programs.
 The focus is on what needs to be done rather how it should be done basically emphasizing on what
code is actually doing.
 It just declares the result we want rather how it has be produced. This is the only difference between
imperative (how to do) and declarative (what to do) programming paradigms.
 Getting into deeper we would see logic, functional and database.

Logic programming paradigms –


 It can be termed as abstract model of computation.

II B.Com (CA) & B.A (CA) C & C++ Page 2


 It would solve logical problems like puzzles, series etc. In logic programming we have a knowledge
base which we know before and along with the question and knowledge base which is given to
machine, it produces result. In normal programming languages, such concept of knowledge base is not
available but while using the concept of artificial intelligence, machine learning we have some models
like Perception model which is using the same mechanism.
 In logical programming the main emphasize is on knowledge base and the problem. The execution of
the program is very much like proof of mathematical statement, e.g., Prolog
Functional programming paradigms –
 The functional programming paradigms have its roots in mathematics and it is language independent.
 The key principal of these paradigms is the execution of series of mathematical functions.
 The central model for the abstraction is the function which is meant for some specific computation and
not the data structure. Data are loosely coupled to functions.
 The function hides their implementation. Function can be replaced with their values without changing
the meaning of the program. Some of the languages like Perl, JavaScript mostly uses this paradigm.
Database/Data driven programming approach –
 This programming methodology is based on data and its movement. Program statements are defined
by data rather than hard-coding a series of steps.
 A database program is the heart of a business information system and provides file creation, data entry,
update, query and reporting functions.
 There are several programming languages that are developed mostly for database application.
 For example SQL. It is applied to streams of structured data, for filtering, transforming, aggregating
(such as computing statistics), or calling other programs. So it has its own wide application.
Explain about the phases in software development life cycle (SDLC)? Or
Problem solving methods

The design and development of correct, efficient and maintainable programs depend on the approach
adopted by the program to perform various activities that need to be performed during the development
process. The entire program or software development process is divided into a no. of phases. The output of
one phase provides the input for it’s subsequent phase.

Requirement Analysis:- in this phase user expectations are


gathered to known why software has to be built. Then, all the
gathered requirements are analyzed to arrive at the scope or the
objective of the over all software product.

Design:- The requirements documented in the previous phase


acts as an input to the design phase. In the design phase, a plan
of actions in made before the actual development process can
start. In this phase, the core structure of the program is broken
down into modules. The solution of the program is then specified
for each module in the form of algorithms or flowcharts.

Implementation:- in this phase, the designed algorithms are converted into program code using any of
the high level language. The program codes are tested by the programmers to ensure the correctness.

Testing:- In this phase, all the modules are tested together to ensure that the over all system works.
Well as a whole product. In this phase, the software is tested using a large no. of varied different inputs
to ensure that the software is working as expected by the user’s requirements that were identified in
the requirements analysis phase.

Software deployment, training and support:- After the code is tested, the program has been approved
by the user, it is installed or deployed in the production environment. After installation and
deployment of software the developers will give the training classes to the end user regarding how to
use the software.

II B.Com (CA) & B.A (CA) C & C++ Page 3


Maintenance: - It is a going activity that is done to go with newly discovered problems or new
requirements.
Introduction to Algorithms
Algorithms are a procedure for performing some calculations. it gives the logic of the program i.e. a
step by step description of how to arrive at a solution. Algorithm provides a blue print for writing a
program to solve a particular problem. a Well defined algorithm always provides an answer and it
guaranteed to terminate.
Characteristics of Algorithms:
Algorithms generally have the following characteristics:
 Input: The algorithm receives input. Zero or more quantities are externally supplied.
 Output: The algorithm produces output. At least one quantity is produced.
 Precision: The steps are precisely stated. Each instruction is clear and unambiguous.
 Feasibility: It must be feasible to execute each instruction.
 Flexibility: It should also be possible to make changes in the algorithm without putting
so much effort on it.
 Generality: The algorithm applies to a set of inputs.
 Finiteness: Algorithm must complete after a finite number of instruction have been
executed.
Example: Algorithm/pseudo code to add two numbers

Step 1: Start
Step 2: Read the two numbers in to a,b
Step 3: c=a+b Step
4: write/print c
Step 5: Stop.

Flow Charts
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts use
simple geometric shapes to depict processes and arrows to show relationships and process/data flow.
Advantages
1) It is a communication tool to explain the logic of a system.
2) The are also used for program documentation.
3) The act as a guide or blue print for a the programmers to code the solution in any
Programming language.
4) They can be used to debug programs that have errors.
Limitations
1) It is a laborious and time consuming activity.
2) Flow chart of a complex program becomes complex.
3) a little bit of alteration in the solution may require complete redrawing of the flowchart.
4) There are no well defined standard that limit the details that must be in corporate into a
flow chart.

II B.Com (CA) & B.A (CA) C & C++ Page 4


Examples on flow chart

1. Calculate Sum of two Numbers 2. Find Biggest Number

Introduction to C
C is a general-purpose High Level programming language that is extremely popular, simple, and flexible
to use. It is a structured programming language that is machine-independent and extensively used to
write various applications.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
Initially, C language was developed to be used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

II B.Com (CA) & B.A (CA) C & C++ Page 5


Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Features of C Programming Language:


 Procedural Language
 Fast and Efficient
 Modularity
 Statically Type
 General Purpose Language
 Rich set of built in Operators
 Libraries with rich Functions
 Middle Level Language
 Portability
 Easy to Extend
Structure of C Program
Documentation Section: The documentation section
consists of a set of comment lines giving the name of the
program, the author and other details.
Link Section: The link section provides instructions to the
compiler to link functions from the system library.
Definition Section: The definition section defines all
symbolic constants.

Global Declaration Section: There are some variable


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.
This section also declares all the user-defined functions.
main ()
Every C program must have one main () function section
This section contains two parts, declaration part and
executable part. The declaration part declares all the
variable used 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. All
statements in the declaration and executable parts end with semicolon.
Subprogram Session
The subprogram section contains all the user-defined functions that are called in the main function.
User-defined functions are generally placed immediately after main function, although they may
appear in any order.

Writing the First C Program


/* This is my first program in C*/
#include<stdio.h>

II B.Com (CA) & B.A (CA) C & C++ Page 6


main()
{
printf("\n Welcome to C Program ");
}
FILES USED IN A C PROGRAM:

Source file
Source file contains the source code of the program. it
defines the main function and may be other functions.
These files will have the extension name “.C”.

Header files:
These files contain the definitions of the functions. These
files will have the extension name “.h”.
stdio.h – input – output functions.
string.h -- for string handling functions.
math.h – for mathematical functions.
alloc.h – for dynamic memory allocation.
conio.h – for clearing the screen
Object file:
Object file is generated by compiler. it contains binary code of the function definitions. linker uses this
file to produce an executable files. These files will have extension name “.obj”.
Executable file: Executable file is generated by linker. These files are directly executed. These file will
have extension name “.exe”.
USING COMMENTS
Comments are just a way of explaining what a program does. It is mainly an internal program
documentation. The compiler ignores the comments when forming the object file. This means that the
comments are non-executable statements.
C supports two types of commenting.
// is used to comment a single statement. 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 ends the line.
/* is used to comment multiple statements. A /* is ended with */ and all statements that lie within
these characters are commented.

Tokens in C language
The smallest individual units with in a program are known as a tokens. The tokens are classified as 6
types.

Keywords: All keywords have fixed meanings and these meanings cannot be changed. Keywords serve
as basic building blocks for program statements. All keywords must be written in lowercase
A list of 32 keywords in the c language is given below:
auto break case char const continue default do

II B.Com (CA) & B.A (CA) C & C++ Page 7


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: An identifier is a name given to various program elements to identify an object.Variables,
functions, arrays, …..Etc.
1. An identifier may consist of alphabets and digits, but the first character must be an alphabet.
2. it cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc)
3. The “_” (underscore) character is also permitted in identifiers. It is namely used to link between
two letters.
4. Keywords cannot be used as identifiers
5. Identifier should not contain more than 31 characters.
Constants: constant refers to fixed values that do not changed during the execution of a program.
Example: 45,56.6,-67,78.
Strings: - String means a Group of Charecters is called String .or a sequence of characters is called
String .String Enclosed with in a double quotation mark.
Example: - “college”, “Ramana “ .
Special Symbols: - C language supports Different type of special symbols to perform specific
declaration or Tasks. Example: (,.{,[
Operators: - An operator is a symbol that tells to the computer to perform operations on operands.
Ex:- +,-,* etc.
Constants :
A constant in “C” language refers to the fixed value that does not change during the program
execution. The ‘C’ language supports several types of consonants. They are

Integer Constant :
An Integer constant refers to a sequence of digits. There are 3 types of integer constants
namely decimal, octal, and hexa decimal.
The decimal integers consists of a set of digits from 0-9 and preceded by an optional ‘+’ or ‘- ’ sign.
Ex : 565, -123, +676.
An octal integer consist of the combination of digits from the set 0-7 with a leading ‘0’.
Ex : 0123, 0456, 0321, etc.
A sequence of digits preceded by ‘ox’ or ‘OX’ is considered as hexa-decimal integer. It may also
include alphabets from A to F and digits from 0-9.
Ex : ox67AB, oxAB123, ox56F
Real/ Float Constants : The integer numbers are inadequate to represent quantities likes prices,
distances, heights, weights, etc. there quantities are represented by numbers containing fractional part
like 5.67, 70.62 etc., and such numbers are called real or floating point constants.
II B.Com (CA) & B.A (CA) C & C++ Page 8
Ex : -2.16, 3.34 80.318
A real no may also represents in an exponential format. Ex : The value 215.65 can be
represented in an exponential format is 2.1565E2.
Single Character Constants :
It contains a single character enclosed in a single quotation marks.
Ex : ‘5’, ‘x’, ‘+’ etc.
String Constant :
A sequence of character can be enclosed in a double quotation marks are called string
constants. Ex : “123”, “ABC”, “A123” etc.
Variables
A variable is a data name that may be used to store a data value. The variable value can change
during the program exhibition. The value of a variable is a varied from time to time.
Syntax: data type variable list;
Ex: int a; //declaring 2 variable of integer type
float b;
char c;
int a=10,b=20; //initialization 2 variable of integer type
float f=20.8;
char c='A';
Rules :
1. They must begin with an alphabet, some compilers may accept underscore(_) as the first character
also.
2. The maximum length of a variable is almost 31 characters, but the first 8 characters are treated as a
variable name by most of the compilers.
3. Upper case and lower case or significant that is the variable Total is not equal to total.
4. The variable should not be a reserved word.
5. Spaces are not allowed in between the variable.

DATA TYPES
C supports several different types of Data Types. The variety of data types available, allow the
Programmer to select the data type appropriate to the needs of the application. C supports three
Classes of data types.
1. Primary (or Fundamental) data types
2. Derived data types
3. User-defined data types
I . Primary Data Types :
Integer data type (int) : Integer are whole number with a range of values supported by a
particular machine. Generally an integer occupies 2-4 bytes of storage and the word is size varies
from machine to machine. namely short int, int and long int, in both signed and unsigned forms
Float data type :
The float numbers (real) are stored in 32 bits (4 bytes or 1 word) with 6 digits of precessions.
The floating point numbers are defined by the keyword “float”, If we specify the data types as
“double”, it uses 64 bits (8 bytes) and giving a precision of 14 digits.
Character data type :

II B.Com (CA) & B.A (CA) C & C++ Page 9


A single character can be defined as a character type data (char). The characters are usually
stored in 8 bits of internal storage. The signed characters have the values from -128 to 127, and
unsigned have the values from 0 to 255.

II.Derived Data Types: Derived data type is the aggregation of fundamental data
type. Character, integer, float, and void are fundamental data types. Pointers, arrays, structures and
unions are derived data types
III.User Define Data Types: Those data types which are defined by the user as per his/her will are
called user-defined data types. Examples of such data types are structure, union and enumeration.
OPERATORS
C operators are symbols that are used to perform mathematical or logical manipulations. The C
programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions . They are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators :
‘C’ provides a few basic arithmetic operators. The operators ‘+’, ‘-’, ‘*’, etc are work in
the same way as they do in the other languages also.
Operator Meaning
+ (plus) Addition
- (unary) Subtraction
* Multiplication
/ Division
% Modules or Remainder
2. Relational Operators :
Relational operators are also known as a comparison operator, it is an operator that compares two
values. Expressions that contain relational operators are called relational expressions.
Operator Meaning
< Less than
> Greater than
<= Less than equal to
II B.Com (CA) & B.A (CA) C & C++ Page 10
>= Greater than equal to
== Equal to
!= Not equal to
3. Logical Operators :
‘C’ has three types of logical operators. They are
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
4. Assignment Operators :
The assignment operator is used to assign a value to a variable or to assign the result of
an expression to a variable. The assignment operator in ‘C’ language is “=”. They are
Variable = expression

Ex : x=5; y=a+b;
5. Increment or Decrement Operators :
‘C’ has two very useful operators, not generally found in other languages. These are the
increment(++) and decrement(--) operators. The operator ‘++’ adds “1” to the operand. While ‘- -’
subtracts “1” from the operand. Both are called unary operators.
Here ++m is equivalent to m=m+1
-- m is equivalent to m=m-1 or m=-1
++m is called pre incrementation, m++ is called post incrementation. Similarly --m is
called pre decrementation and m- - is called post decrementation.
6. Conditional Operator (Ternary) :
A ternary operator pair “?” is available in ‘C’ language to construct a conditional
expression. The syntax is
Variable=exp1 ? exp2 : exp 3;
Example : a=10, b=15
X=a>b ? a:b
In this example first it will evaluate the exp 1. If it is true the value of a (exp2) will be assigned to
x. If the condition is false, the value of b(exp3) will be assigned to x.
7. Bitwise Operators :
‘C’ has a distinction of supporting some operators called as bitwise operators and are
used for manipulation of data at bit level. These operators are used for testing the bits or shifting
them from right to left, left to right etc., They are
Operator Meaning
& Bitwise AND
| (pipe symbol) Bitwise OR
^ Bitwise x-OR (ap)
~ /S Complement (tilde)
<< Left shift
>> Right shift
8. Special Operators :
‘C’ supports some special operators, such as comma(,) operaor, “size=of” operator, point
operators (& and *), member selection operators (. and ).

II B.Com (CA) & B.A (CA) C & C++ Page 11


INPUT/OUTPUT Statements in C
In C language, all input/output operations are carried out through function calls such as printf and
scanf. There exists several functions that have more or less become standard for input and output
operations in C. These functions are collectively known as the standard I/O library. Each program that
uses a standard input/output function must contain the statement #include <stdio.h>

OUTPUT STATEMENTS:
1. putchar()
2. printf()
3. puts()
4. putch()
i) printf()
This function is used for displaying the output on the screen i.e the data is moved from the
computer memory to the output device.
Syntax: printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They are the
general characters which will be displayed as they are .arg1, arg2 are the output data items.
Example: Demonstrating the printf function
 printf(“Enter a value:”);
printf will generally examine from left to right of the string.
 The characters are displayed on the screen in the manner they are encountered until it
comes across % or \.
 Once it comes across the conversion specifiers it will take the first argument and print it in
the format given.
ii. putch()
this function is a counterpart of getch. Which means that it will display a single character on the screen.
The character that is displayed is returned.
Syntax: int putch(int);
putch(ch); where,
ch - the character that is to be printed.

iii. putchar
This function is the other side of getchar. A single character is displayed on the screen.
Syntax:
putchar(ch);
iv. puts():
This statement is used to print string .
Syn: Puts(s);
INPUT STATEMENTS:
1. getchar()
2. scanf()
3. gets()
4.getch()
5.getche()
i. scanf()
scanf is used when we enter data by using an input device.
Syntax: scanf (“format string”, &arg1, &arg2, …..);

The number of items which are successful are returned.


Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&). Array
II B.Com (CA) & B.A (CA) C & C++ Page 12
names should never begin with an ampersand.
Example: Demonstrating scanf
int avg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade);

scanf works totally opposite to printf. The input is read, interprets using the conversion specifier and
stores it in the given variable. The conversion specifier for scanf is the same as printf.
scanf reads the characters from the input as long as the characters match or it will terminate. The order
of the characters that are entered are not important. It requires an enter key in order to accept an
input.
ii.getch
This function is used to input a single character. The character is read instantly and it does not require
an enter key to be pressed. The character type is returned but it does not echo on the screen.
Syntax: int getch(void);
ch=getch();
where,
ch - assigned the character that is returned by getch.
iii. getche
This function is used to input a single character. The main difference between getch and getche is that
getche displays the (echoes) the character that we type on the screen.
Syntax: int getch(void);
ch=getche();
iv. getchar
This function is used to input a single character. The enter key is pressed which is followed by the
character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar;
v. gets() :
Reading a String can be done by using the function gets. The gets takes the following form.
gets (a);

II B.Com (CA) & B.A (CA) C & C++ Page 13


UNIT-II

Control structures – Decision making and branching, looping structures, switch-case, break and continue, goto
statement, functions – advantages, storage classes, creating user defined functions, recursion, Parameter
passing, arrays- types of arrays, arrays and functions.- Introduction to pointers-pointer declaration, pointer
operators, Dynamic memory allocation.
Decision making Statements / Control Statements
A C program is a set of statements, which are normally executed sequentially in the order in which they
appear. We have a number of situations, where we may have to change the order of execution of
Statements based on certain condition.
C conditional statements allow you to make a decision, based upon the result of a condition. These
statements are called Decision Making Statements or Conditional Statements.
C Language supports 4 Type of decision making statements.
1. Simple if Statement
2. if-else Statement
3. Nested if-else Statement
4. else-if Ladder
1. Simple IF Statement:
The ‘statement-block’ may be a single statement or a group of statements. If the test condition
is true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x.
Syntax:
if( test condition )
{
statement – block ;
}
statement –x
Example: #include<stdio.h>
void main()
{
int a = 15, b = 20;
if (b > a)
{
printf("b is greater");
}
}
2. If – else Statement:

II B.Com (CA) & B.A (CA) C & C++ Page 14


If the test condition is true, then the True statement- block; immediately following the if statement, are
executed; otherwise, the False- statement- block are executed. In any case, either True statement-
block or False- statement- block will be executed, not both. After executing any one block of
statements, the control is transfers to the statement-x.
Syntax:
if( test condition )
{
True-statement- block;
}
else {
False- statement- block;
}
Statement –x
Example:
#include<stdio.h>
void main()
{
int a, b;
printf("Please enter the value for a:");
scanf("%d", &a);
printf("\nPlease the value for b:");
scanf("%d", &b);
if (a > b) {
printf("\n a is greater");
} else {
printf("\n b is greater");
}
3. else-if Ladder:
If-Else Ladder or Else if Ladder is a multiple decision making statement. In this statement, First
Condition 1 Will is tested. IF the condition is true the statement1 will be execute .If the condition false
the Second condition will be tested. If the Second condition will be true the statement 2 will be
execute. if the condition 2 false condition3 will be execute and so on …..
Syntax:
If (test condition1)
{
Statement - block-1;
}
else
{if ( test condition2 )
{
Statement - block-2;
}
else
{
if ( test condition3)
{
Statement - block-3;
}
else
{
Default Statement - block
II B.Com (CA) & B.A (CA) C & C++ Page 15
} }}}
Statement –x;
Example: #include<stdio.h>
void main()
{
int a, b;
printf("Please enter the value for a:");
scanf("%d", &a);
printf("\nPlease enter the value for b:");
scanf("%d", &b);

if (a > b)
{
printf("\n a is greater than b");
}
else if (b > a)
{
printf("\n b is greater than a");
}
else
{
printf("\n Both are equal");
}
}
3. Nested if Statement:
Nested if is also a multiple decision making statement. In this statement. First Condition will be tested if
the condition is true another if condition will be execute if the condition is false false statement
execute and so on….
if( test condition1 )
{
if ( test condition2 )
{
Statementblock- 1;
}
else
{
Statementblock- 2;
}
}
else
{
Statement - block-3;
}
Statement –x;
Example: #include<stdio.h>
void main()
{
int x=20,y=30;
if(x==20)
{
if(y==30)
II B.Com (CA) & B.A (CA) C & C++ Page 16
{
printf("value of x is 20, and value of y is 30.");
}
}
}

Switch case Statement


A program is having no. of alternatives; the program becomes difficult to read and follows. Sometimes
it may confuse even the person who designed it. The ‘C’ language is having built in multi-way decision
statement known as ‘switch’ statement.
This statement test the value of the given expression against list of case values, when match is found, a
block of statement associated with that case is executed.
 The break statement will terminate the control from the switch statement.
 If the passed expression does not matches with any one of the case value then default block will be
executed.
Syntax:
switch(expression)
{
case value 1 :
Statements ;
break;

case value 2 :
Statements ;
break;

case value 3 :
Statements ;
break;
default :
default Statements ;
break;
}
Example: #include<stdio.h>
void main()
{
int a;
printf("Please enter a no between 1 and 5: ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("You chose One");
break;
case 2:
printf("You chose Two");
break;
case 3:
printf("You chose Three");
II B.Com (CA) & B.A (CA) C & C++ Page 17
break;
case 4:
printf("You chose Four");
break;
case 5:
printf("You chose Five.");
break;
default :
printf("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
Iterative statements / Looping Statements
A computer can perform repetitive operations; like in every computer language must have features
that instruct a computer to perform such a repetitive tasks. “The process of repeatedly executing a
block of statements is known as looping”. The statements may be executed any number of times, from
zero to infinite number, if a loop continues forever, it is called infinite loop. In looping, a sequence of
statements is executed until our desired conditions are satisfied.

C Language there are three types of looping statements available they are
 While Loop
 Do- While loop
 For loop

While Loop :
While loop is a Entry control loop. Here, the test condition is evaluated first. If the condition is true, the
body of the loop is executed. After execution of the body the controls transfers to the test condition
again the test condition is evaluated until the condition false the statements will be execute again and
again.
syntax: while ( test condition )
{
Body of the loop;
Updation;
}

Example: #include<stdio.h>
int main ()
{
int n = 1,times=5; /* local variable Initialization */
while( n <= times ) /* while loops execution */
{
printf("C while loops: %d\n", n);
n++;
}
return 0;
}
Do-While Loop :
Do-while is an exit control loop. Here in the do-while structure first the statements will be executed
and then test the condition. If it is true the same statements will be executed. After executing the
statements. Once again it will test the condition and if it is true the same statements will be executed
II B.Com (CA) & B.A (CA) C & C++ Page 18
repeatedly and so on. This process will be continued as long as the condition is true. Whenever the
condition becomes false, it comes outside the loop and executes the remaining statements in the
sequential order. The main draw back in the do-while structure is the statements will be executed at
least once even though the condition is initially false.
Syntax: do
{
Statement -1;
Statement -2;
----------
}
While (condition)
Example: #include<stdio.h>
int main ()
{
int n = 1,times=5; /* local variable Initialization */
do /* do loops execution */
{
printf("C do while loops: %d\n", n);
n = n + 1;
}while( n <= times );
return 0;
}
For –Loop: The for loop is another entry-controlled loop that provides more concise loop control
Statement. The general form of for loop is
Syntax:
Syntax: for( initialization ; test condition ; inc/dec )
{
Body of the loop;
}
Example: #include<stdio.h>
int main ()
{
int n,times=5; /* local variable Initialization */
for( n = 1; n <= times; n = n + 1 ) /* for loops execution */
{
printf("C for loops: %d\n", n);
}
return 0;
}
Initialization of the control variable is done first, using assignment statement such as I = 1 .Next the
condition will be execute. The test condition is such as I < 10 that determine when the loop will exit. If
condition is true, the body of the loop is executed; otherwise the loop is terminated and execution
When the body of the body of loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop. The control variable is updated using an test assignment
Statement such as i++, i- - . . This process is continuing the value of control variable fails to satisfy the
test condition

Jump statements
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test condition.
The number of times a loop is repeated is decided in advanced and the test condition is written to
II B.Com (CA) & B.A (CA) C & C++ Page 19
achieve this. Sometimes, when executing a loop it becomes desirable to skip a part of the loop or leave
the loop as soon as a certain condition occurs.
1. break
2. Continue
3. goto
BREAK Statement: An early exit from a loop can be accomplished (done) by using the break statement.
When the break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are nested, the
break would only exit from the loop containing it i.e. the break will exit only a single loop.

Continue Statement :
During the loop operation, it may be necessary to skip a part of the body of the loop under certain
condition. The continue, as the name implies, causes the loop to be continued with the next iteration
after skipping any statements in between. Continue statement tells to the compiler:”SKIP THE
FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.

GOTO – LABLE Statements:


C supports the goto statement to branch unconditionally from one point to another in the program.
Although it may not be essential to use the goto statement in a highly structured language like C, there
may be occasions when the use of goto might be desirable. The goto requires a label in order to
identify the place where the branch is to be made. A label is any valid variable name, and must follow
by a colon. The label is placed immediately before the statement where the control is to be transferred.
The general forms of goto and label statements are shown below:

II B.Com (CA) & B.A (CA) C & C++ Page 20


Functions
Function is a group of logically set of statements that perform a specific task. The function contains the
set of programming statements enclosed by {}. A function can be called multiple times to provide
reusability and modularity to the C program. The function is also known as procedure or subprogram.
Advantage of functions in C
Avoid repetition of codes.
Increases program readability.
Divide a complex problem into simpler ones.
Reduces chances of error.
Modifying a program becomes easier by using function.
It supports top down design approach

Types of function
There are two types of function in C programming:
1) Standard library functions ( Built in Functions )
2) User-defined functions
Standard Library Functions :
Library functions are the built in function that are already defined in the C library. The prototype of
these functions is written in header files. So we need to include respective header files before using a
library function. For example scanf( ), printf( ), getchar( ),puts( ),gets( ), the prototype of math functions
like pow(),sqrt(), etc is present in math.h, String functions strrev(),Strcmp() etc is in string.h and so on.
User-Defined Functions :
Those functions that are defined by user to use them when required are called user-defined function.
Function definition is written by user. main() is an example of user-defined function.
Implementation Of User Defined Functions
A function usually has three components. They are:
1. Function Prototype/Declaration
2. Function Definition
3. Function Call

1. Function Prototype/Declaration
Function declaration is a statement that informs the compiler about
 Name of the function
 Type of arguments
 Number of arguments
 Type of Return value
Syntax for function declaration
returntype function_name ([arguments type]);
Ex:-
void sort(int []);
int product(int,int);

2. Function Definition
Function definition consists of the body of function. The body consists of block of statements that
specify what task is to be performed. When a function is called, the control is transferred to the
function definition.
Syntax for function definition
returntype function_name ([arguments])
{

II B.Com (CA) & B.A (CA) C & C++ Page 21


statement(s);
... ... ...
}
Return Statement
A return statement is used to return values to the invoking function by the invoked function. The data
type of value a function can return is specified during function declaration. A function with void as
return type don't return any value. Beside basic data type, it can return object and pointers too. A
return statement is usually place at the end of function definition or inside a branching statement.

For example,
int product (int x, int y)
{
int p = x*y;
return p;
}
In this function, the return type of product() is int. So it returns an integer value p to the invoking
function.
3. Function call
A function call can be made by using a call statement. A function call statement consists of
function name and required argument enclosed in round brackets.
Syntax for function call
function_name ([actual arguments]);
For example,
sort(a);
p = product(x,y);
Example for functions:
#include<stdio.h>
int addition(); /* function declaration */
int main()
{
int answer; //local variable definition
answer = addition(); //calling a function to get addition value.
printf("The addition of the two numbers is: %d\n",answer);
return 0;
}
int addition() //function returning the addition of two numbers
{
int num1 = 10, num2 = 5; // local variable definition
return num1+num2;
}
Passing Parameters to a Function
While calling a function, the arguments can be passed to a function in two ways. they are
1. call by value.
2. call by reference.
Call by value
 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.

II B.Com (CA) & B.A (CA) C & C++ Page 22


 When a function is called by value, a copy of actual argument is passed to the called function.
The copied arguments occupy separate memory location than the actual argument. If any
changes done to those values inside the function, it is only visible inside the function only. Their
values remain unchanged outside it.
Example of call by value:
#include <stdio.h>
void swap(int x, int y);
main()
{
int a,b;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Before swapping\n");
printf("a = %d\n",a);
printf("b = %d\n",b);
swap(a,b); // function call by Value
printf("After swapping\n");
printf("a = %d\n",a);
printf("b = %d\n",b);
}
void swap(int x, int y) // function definition
{
int temp;
temp =x;
x = y;
y = temp;
printf("Swapping Values \n");
printf("a = %d\n",x);
printf("b = %d\n",y);
}

Call by reference
The call by reference method of passing arguments to a function copies the address of an argument
into the formal parameter. Inside the function, the address is used to access the actual argument used
in the call. It means the changes made to the parameter affect the passed argument. Their values
remain changed outside it.
Example of call by reference:
#include <stdio.h>
void swap(int *x, int *y);
main()
{
int a,b;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Before swapping\n");
printf("a = %d\n",a);
printf("b = %d\n",b);
swap(&a,&b); // function call by Value
printf("After swapping\n");
II B.Com (CA) & B.A (CA) C & C++ Page 23
printf("a = %d\n",a);
printf("b = %d\n",b);
}
void swap(int *x, int *y) // function definition
{
int temp;
temp =x*;
x* = y*;
y* = temp;
printf("Swapping Values \n");
printf("a = %d\n",*x);
printf("b = %d\n",*y);
}

RECURSION FUNCTION
Recursion can be defined as the technique of replicating or doing again an activity in a self-similar way
calling itself again and again, and the process continues till specific condition reaches. In the world of
programming, when your program lets you call that specific function from inside that function, then
this concept of calling the function from itself can be termed as recursion, and the function in which
makes this possible is called recursive function.
Syntax of Recursive Function:
Return type recursive_func ([argument list])
{
Statements;
... ... ...
recursive_func ([actual argument]);
... ... ...
}
EXAMPLE: Finding factorial of a number using recursion.
#include<stdio.h>
int fact(int);
main()
{
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
}
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1)); /*fact Function calling again*/
}
STORAGE CLASSES IN C
Storage classes of a variable define the scope and life time of a variable and functions declared with in
a c program. C language supports four types of storage classes. They are
1) Automatic Storage Class (Auto)
II B.Com (CA) & B.A (CA) C & C++ Page 24
2) External Storage Class (Extern)
3) Register Storage Class (Register)
4) Static Storage Class (Static)

1) Automatic Storage Class (Auto) :


 These variables are stored in Computer’s memory (RAM).
 The default value is unpredictable (garbage).
 The scope is local to that block in which they are defined.
 if we won’t specify any storage class by default the computer will assume as auto only.
Example:-
void main()
{
int detail;
or
auto int detail;
}
2) External storage class (extern) / Global variables:-
 These variables are stored in Computer’s memory (RAM).
 The default value is 0.
 The scope is global.
 The life is as long as the program is executing.
Example :-
#include
int number; //global variable
void main()
{
number=10;
printf("I am in function main. My value is %d\n",number);
fun1(); //function calling, discussed in next topic
fun2(); //function calling, discussed in next topic
}
fun1()
{
number=20;
printf("I am in function fun1. My value is %d",number);
}
fun2()
{
printf("\nI am in function fun2. My value is %d",number);
}
3) Register storage class (register):-
 These variables are stored in CPU registers.
 The default value is unpredictable (garbage).
 The scope is local to that block in which they are defined.
 The life is fill the control remains with in the block.
 These variables are accessed faster than variables which are declared with in the computer
memory.
Example :-
void main()
{
register int detail;
II B.Com (CA) & B.A (CA) C & C++ Page 25
}
4) static storage class (static) :-
 These variables are stored in Computer’s memory (RAM).
 The default value is 0.
 The scope is local to that block in which they are defined.
 The life is global i.e. the value of a variable contains between different function calls.
Example :-
void test();
main()
{
test();
test();
test();
}
void test()
{
static int a = 0;
a = a+1;
printf("%d\t",a);
}
output :
123

ARRAYS
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc.

It also has the capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly accessed by using
its index number.
Properties of Array
The array contains the following properties
 Each element of an array is of same data type and carries the same size, i.e., int = 2 bytes.
 Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.

 Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Declaration of C Array
We can declare an array in the c language in the following way.
Syntax: data_type array_name [array_size];
EX: int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.

II B.Com (CA) & B.A (CA) C & C++ Page 26


1. marks[0]=80; //initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

int marks[5]={20,30,40,50,60}; //initialization of array


int marks[]={20,30,40,50,60}; //initialization of array

Arrays are generally categorized into following types


1. One-dimensional arrays
2. Two-dimensional arrays
3. Multi dimensional arrays
1. One-dimensional arrays:”A list of items can be given one variable name using only one subscript and
such a variable called single-subscripted variable or a one-dimensional array”. It represents only one
row or column of elements.

Declaration of One Dimension array:


Like variable, array must be declared and created in the computer memory before they are used. Array
can be declared in two forms:
Syntax: datatype arrayname[size];
Here datatype may be int, float, or char and size indicates the maximum number of elements that can
be stored inside the array.
Eg: int marks[10]
In above example, declares the marks to be an array containing 10 real elements.
Initialization of values into one dimensional array:-
We can assign the values into one dimensional array at the time of
declaration of an array or after the declaration of array.
Example : int a[5];
a[0]=1, a[1]=2 , a[2]=4, a[3]=8, a[4]=16;
OR
int a[5]={ 1,2,4,8,16};
Example of one dimensional array:
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
for(i=0;i<5;i++) //traversal of array
{
printf("%d \n",marks[i]);
}
return 0;
}
2. Two Dimensional Array :- A list of items can be given to one variable name using two subscripts and
such a variable is called a two subscripted variable or two dimensional array..

II B.Com (CA) & B.A (CA) C & C++ Page 27


Declaration of Two Dimension Array :-
type variable _name[row_size][column_size];
type – data type, variable_name – name of the array, row_size – no of rows, column_size – no of
columns of an array.
Example:-
Int a[3][3];
Initialization of values into two dimensional array:-
We can assign the values into two dimensional array at the time of declaration of an array or after the
declaration of array.
1) int a[ ][ ] = {{1,2,3}, {4,5,6}, {7,8,9}};
Or
2) int a[3][3];
a[0][0]=1, a[0][1]=2, a[0][2]=3, a[1][0]=4, a[1][1]=5

Two Dimensional array representations:-

Two-dimensional array example in C


#include<stdio.h>
int main()
{
Int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; //traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
} //end of j
} //end of i
return 0;
}
3. Three Dimensional Array: - A list of items can be given to one variable name using more than two
subscripts and such a variable is called a three dimensional array..
Declaration:-
datatype variable _name [s1][s2]… [sn];
Example:-
int a [2][2][2];
Initialization of values Multi dimensional array:-
II B.Com (CA) & B.A (CA) C & C++ Page 28
We can assign the values into three dimensional arrays at the time of declaration of an array or after
the Declaration of Multi Dimension array.
int a[2][2][2];
a[0][0][0]=1, a[0][0][1]=2, a[0][0][2]=3, a[0][1][0]=4, a[0][1][1]=5

Pointers
Pointer is a variable that can hold the address of another variable. It is a derived data type and the
pointer variables are declared from the built in data type. Therefore a pointer, is a variable that
represents the location of a data item.
Applications of a pointers / Advantages of pointers:
 it is used to pass information back and forth between a function and its reference points.
 Pointers are enable the programmers to return multiple data items from a function via function
arguments.
 It provides an alternative way to access individual elements of the array.
 Pointers are used to pass arrays and strings as function arguments.
 Pointers are used to create complex data structures such as trees, linked list, linked stack, linked
queue and graphs.
 Pointers are used for dynamic memory allocation of a variable.

Declaring pointer variables:


The declaration of a pointer variable takes the following form:
data_type *pt_name;

This tells to compiler three things about the variable pt_name.


1. The asterisk(*) tells that the variable pt_name is a pointer
variable.
2. pt_name points to a variable of type data_type.

E.g: int *p;


declares the variable p as a pointer variable that points to an
integer data type.

Accessing the address of a variable:

The actual location of a variable in the memory is system dependent and therefore, the address of a
variable is not known to us immediately. We can access the address of a variable by using address
operator ‘ & ’ . The operator & immediately preceding a variable returns the address of the variable
associated with it.
e.g: x=&p;
The address operator can be used only with a simple variable or array elements.
Initializing of pointer variables:
The process of assigning the address of a variable to a pointer variable is known as initialization of
pointer
variable. Once a pointer variable has been declared we can use the assignment operator to initialize
the variable.
int quantity=10;
int *p;
p=&quantity;
Remember that is an initialization of p and not *p.
Accessing a variable through its pointer:
II B.Com (CA) & B.A (CA) C & C++ Page 29
Once a pointer has been assign the address of a variable, then we can access the variable by using
asterisk
(*) operator, usually known as the indirection operator. Another name for the indirection operator is
the
dereferencing operator. Consider following example
int num,*p,n;
num=179;
p=&num;
n=*p;
The first line declares num and n as integer variables and p as a pointer variable pointing to an integer.
The second line assigns the values 179 to num and the third line assigns the address of num to the
pointer variable p. The fourth line contains the indirection operator *. When the operator * is placed
before a pointer variable in an expression, the pointer returns the value of the variable of which the
pointer value is
the address. In this case, *p returns the value of the variable num, because p is the address of num. the
*
can be remembered as ‘value at address’.
Example: #include <stdio.h>
void swap(int *x, int *y);
main()
{
int a,b;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Before swapping\n");
swap(&a,&b);
}
void swap(int *x, int *y)
{
int temp;
temp =x*;
x* = y*;
y* = temp;
printf("Swapping Values \n");
printf("a = %d\n",*x);
printf("b = %d\n",*y);
}

Memory Allocation in C Program


C supports three types of memory allocation.
i) static size allocation :-
 When we declare static or global variables, static allocation is done for the variables.
 Each static or global variable is allocated a fixed size memory space.
 The no.of bytes reserved for the variable cannot be changed during execution of the program.
ii) Automatic allocation:-
 When we declare automatic variables, such as a function argument or a local variables,
automatic memory allocation is done.
 A space for an automatic variable is allocated.
 The compound the declaration enters and is freed.
 When it exist from a compound statement.

II B.Com (CA) & B.A (CA) C & C++ Page 30


iii) Dynamic memory allocation:-
The process of allocation memory for the variable at run time is known as dynamic memory allocation.
The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h
header file.
1. malloc()
2. calloc()
3. realloc()
4. free()

1. malloc()
malloc function is used to allocate space in memory during the execution of the program.
malloc function does not initialize the memory allocated during execution. It carries
garbage value.
malloc function returns null pointer if it couldn't able to allocate requested amount of
memory.
Example program for malloc() in C
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *mem_alloc; //memory allocated dynamically
mem_alloc = malloc( 15 * sizeof(char) );
if(mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"w3schools.in");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}
2. calloc()
calloc () function and malloc () function is similar. But calloc () allocates memory for zero-initializes.
However, malloc () does not.
Example program for calloc() in C
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *mem_alloc; //memory allocated dynamically
mem_alloc = calloc( 15, sizeof(char) );
if( mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
II B.Com (CA) & B.A (CA) C & C++ Page 31
else
{
strcpy( mem_alloc,"w3schools.in");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}
3. realloc()
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function.
In short, it changes the memory size.
Let's see the syntax of realloc() function.
ptr=realloc(ptr, new-size)
4. free()
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Let's see the syntax of free() function.
free(ptr)

II B.Com (CA) & B.A (CA) C & C++ Page 32


UNIT-III

Introduction to object oriented programming – Difference between function oriented programming


and object oriented programming, Features of OOP, Applications of OOP, structure of C++ program
with simple C++ program, basics of console Input and Output, C++ data types, Operators in C++, Control
Structures, Functions-inline functions, default arguments, function overloading.

Introduction to object oriented programming


“Object oriented programming as an approach that provides a way of modularizing
programs by creating partitioned memory area for both data and functions that can be used as
templates for creating copies of such modules on demand”.

Q. Features of the Object


Oriented programming
1. Emphasis is on doing rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together in the data structure.
5. Data is hidden and can’t be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added.
8. Follows bottom-up approach in program design.

Q.BASIC CONCEPTS OF OBJECTS ORIENTED PROGRAMMING


1. Objects
2. Classes
3. Data abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing

II B.Com (CA) & B.A (CA) C & C++ Page 33


1. Objects
 Objects are the basic run-time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program must handle.
 The fundamental idea behind object oriented approach is to combine both data and function
into a single unit and these units are called objects. The term objects means a combination of
data and program that represent some real word entity.
 For example: consider an example named Amit; Amit is 25 years old and his salary is 2500. The
Amit may be represented in a computer program as an object. The data part of the object
would be (name: Amit, age: 25, salary: 2500)
 The program part of the object may be collection of programs (retrieve of data, change age,
change of salary). In general even any user –defined type-such as employee may be used. In the
Amit object the name, age and salary are called attributes of the object.

2. Classes
 A group of objects that share common properties for data part and some program part are
collectively called as class.
 In C ++ a class is a new data type that contains member variables and member functions that
operate on the variables.

3. Data abstraction
 Abstraction refers to the act of representing essential features without including the back
ground details or explanations.
 Classes use the concept of abstraction and are defined as size, width and cost and functions to
operate on the attributes.

4. Encapsulation
 The wrapping up of data and function into a single unit (called class) is known as encapsulation.
 The data is not accessible to the outside world and only those functions which are wrapped in
the class can access it.
 These functions provide the interface between the objects data and the program.

5. Inheritance
 Inheritance is the process by which objects of one class acquire the properties of another class.
 In the concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it.
 This is possible by designing a new class will have the combined features of both the classes.

6. Polymorphism
II B.Com (CA) & B.A (CA) C & C++ Page 34
 The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism.
 Poly refers too many. That is a single function or an operator functioning in many ways
different upon the usage is called polymorphism.

7. Dynamic binding

 Binding refers to the linking of a procedure call to the code to the executed in response to the
call.
 Dynamic binding means the code associated with a given procedure call is not known until the
time of the call at run-time.
 It is associated with a polymorphic reference depends upon the dynamic type of that reference.

8. Message passing
 An object oriented program consists of a set of objects that communicate with each other.
 A message for an object is a request for execution of a procedure and therefore will invoke a
function (procedure) in the receiving object that generates the desired result.
 Message passing involves specifying the name of the object, the name of the function
(message) and information to be sent.

Q. Applications of OOP:
Object-Oriented programming has several advantages over procedural languages. As OOP is faster and
easier to execute it becomes more powerful than procedural languages like C++. OOPs is the most
important and flexible paradigm of modern programming. It is specifically useful in modeling real-world
problems. Below are some applications of OOPs:

 Real-Time System design: Real-time system inherits complexities and makes it difficult to build
them. OOP techniques make it easier to handle those complexities.

 Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored, searched,
and edited easily. Hypermedia on the other hand is a superset of hypertext. OOP also helps in
laying the framework for hypertext and hypermedia.

AI Expert System: These are computer application that is developed to solve complex problems
which are far beyond the human brain. OOP helps to develop such an AI expert System

 Neural networking and parallel programming: It addresses the problem of prediction and
approximation of complex-time varying systems. OOP simplifies the entire process by simplifying
the approximation and prediction ability of the network.

 Stimulation and modeling system: It is difficult to model complex systems due to varying
specifications of variables. Stimulating complex systems require modeling and understanding
interaction explicitly. OOP provides an appropriate approach for simplifying these complex
models.

 Object-oriented database: The databases try to maintain a direct correspondence between the
real world and database object in order to let the object retain it identity and integrity.

 Client-server system: Object-oriented client-server system provides the IT infrastructure


creating object-oriented server internet (OCSI) applications.

II B.Com (CA) & B.A (CA) C & C++ Page 35


 CIM/CAD/CAM systems: OOP can also be used in manufacturing and designing applications as
it allows people to reduce the efforts involved. For instance, it can be used while designing
blueprints and flowcharts. So it makes it possible to produce these flowcharts and blueprint
accurately.

Q. Difference between function oriented programming and object oriented


programming

Functional Programming Object Oriented Programming

This programming paradigm emphasizes on the use This programming paradigm is based on object
of functions where each function performs a oriented concept. Classes are used where
specific task. instance of objects are created

Fundamental elements used are variables and Fundamental elements used are objects and
functions. The data in the functions are immutable methods and the data used here are mutable
(cannot be changed after creation). data.

Importance is given to data rather than


Importance is not given to data but to functions.
procedures.

It follows declarative programming model. It follows imperative programming model.

It uses recursion for iteration. It uses loops for iteration.

It is parallel programming supported. It does not support parallel programming.

The statements in this programming paradigm does The statements in this programming paradigm
not need to follow a particular order while need to follow an order i.e., bottom up
execution. approach while execution.

Has three access specifiers namely, Public,


Does not have any access specifier.
Private and Protected.

Provides an easy way to add new data and


To add new data and functions is not so easy.
functions.

No data hiding is possible. Hence, Security is not Provides data hiding. Hence, secured programs
possible. are possible.

Introduction to C++
C ++ is an object oriented programming language, C ++ was developed by Jarney Stroustrup at AT & T
Bell lab, USA in early eighties. C ++ was developed from c and simula67 language. C ++ was early called
‘C with classes’.

II B.Com (CA) & B.A (CA) C & C++ Page 36


Features of C++:
 Simple: It is a simple language in the sense that programs can be broken down into logical units and
parts, has a rich library support and a variety of data-types.
 Machine Independent but Platform Dependent: A C++ executable is not platform-independent
(compiled programs on Linux won’t run on Windows), however they are machine independent.
 Mid-level language: It is a mid-level language as we can do both systems-programming (drivers,
kernels, networking etc.) and builds large-scale user applications (Media Players, Photoshop, Game
Engines etc.)
 Rich library support: Has a rich library support (Both standard ~ built-in data structures, algorithms
etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid development.
 Speed of execution: C++ programs excel in execution speed. Since, it is a compiled language, and
also hugely procedural. Newer languages have extra in-built default features such as garbage-
collection, dynamic typing etc. which slow the execution of the program overall. Since there is no
additional processing overhead like this in C++, it is blazing fast.
 Pointer and direct Memory-Access: C++ provides pointer support which aids users to directly
manipulate storage address. This helps in doing low-level programming (where one might need to
have explicit control on the storage of variables).
 Object-Oriented: One of the strongest points of the language which sets it apart from C. Object-
Oriented support helps C++ to make maintainable and extensible programs. i.e. Large-scale
applications can be built. Procedural code becomes difficult to maintain as code-size grows.
 Compiled Language: C++ is a compiled language, contributing to its speed.

Basic Structure of C++ Program


A C++ program is structured in a specific and particular manner. In C++, a program is divided into the
following three sections:
//Part 1: Header Files/Preprocessor/Namespace
#include <iostream>
using namespace std;
//Part 2: Global Part (Optional)
//Part 3: Class (Optional)
//Part 4: Main Function
int main ()
{
cout << "my first program in C++!";
return 0;
}

1. Standard Libraries Section


2. Main Function Section
3. Function Body Section

1. Standard libraries section


 #include is a specific preprocessor command that effectively copies and pastes the entire text of
the file, specified between the angle brackets, into the source code.
II B.Com (CA) & B.A (CA) C & C++ Page 37
 The file <iostream>, which is a standard file that should come with the C++ compiler, is short
for input-output streams. This command contains code for displaying and getting an input from
the user.
 std is the namespace where ANSI C++ standard class libraries are defined. All ANSI C++
programs must include this directive. This will bring all the identifiers defined in std to the
current global scope. Using and namespace are the new keyword of c++.
 This code is saying: Use the cout and endl tools from the std toolbox.
2. Main function section
 The starting point of all C++ programs is the main function.
 This function is called by the operating system when your program is executed by the computer.
 {Signifies the start of a block of code, and} signifies the end.
3. Function body section
 The name cout is short for character output and displays whatever is between the << brackets.
 Symbols such as << can also behave like functions and are used with the keyword cout.
 The return keyword tells the program to return a value to the function int main
 After the return statement, execution control returns to the operating system component that
launched this program.
 Execution of the code terminates here.

Q. C++ Basic console Input/output:

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 as input operation.
I/O Library Header Files
Let us see the common header files used in C++ programming are:
Header File Function and Description

<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision
and setw.

<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout):

The cout is a predefined object of ostream class. It is connected with the standard output device, which
is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to
display the output on a consol
Let's see the simple example of standard output stream (cout):
#include <iostream>
using namespace std;
int main( ) {
II B.Com (CA) & B.A (CA) C & C++ Page 38
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}

Standard input stream (cin):


The cin is a predefined object of istream class. It is connected with the standard input device, which is
usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to read the
input from a console.

Let's see the simple example of standard input stream (cin):

#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line characters and flushes
the stream.
Let's see the simple example of standard end line (endl):
#include <iostream>
using namespace std;
int main( ) {
cout << "C++ Tutorial";
cout << " Javatpoint"<<endl;
cout << "End of line"<<endl;
}
DATA TYPES
C++ supports several different types of Data Types. The variety of data types available, allow the
Programmer to select the data type appropriate to the needs of the application. C supports three
Classes of data types.
1. Primary (or Fundamental) data types
2. Derived data types
3. User-defined data types
I . Primary Data Types :
Integer data type (int) : Integer are whole number with a range of values supported by a
particular machine. Generally an integer occupies 2-4 bytes of storage and the word is size varies
from machine to machine. namely short int, int and long int, in both signed and unsigned forms
Float data type :
The float numbers (real) are stored in 32 bits (4 bytes or 1 word) with 6 digits of precessions.
The floating point numbers are defined by the keyword “float”, If we specify the data types as
“double”, it uses 64 bits (8 bytes) and giving a precision of 14 digits.

Character data type :


II B.Com (CA) & B.A (CA) C & C++ Page 39
A single character can be defined as a character type data (char). The characters are usually
stored in 8 bits of internal storage. The signed characters have the values from -128 to 127, and
unsigned have the values from 0 to 255.

II.Derived Data Types: Derived data type is the aggregation of fundamental data
type. Character, integer, float, and void are fundamental data types. Pointers, arrays, structures and
unions are derived data types
III.User Define Data Types: Those data types which are defined by the user as per his/her will are
called user-defined data types. Examples of such data types are structure, union and enumeration.

OPERATORS
C operators are symbols that are used to perform mathematical or logical manipulations. The C
programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions . They are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators :
‘C’ provides a few basic arithmetic operators. The operators ‘+’, ‘-’, ‘*’, etc are work in
the same way as they do in the other languages also.
Operator Meaning
+ (plus) Addition
- (unary) Subtraction
* Multiplication
/ Division
% Modules or Remainder

2. Relational Operators :

II B.Com (CA) & B.A (CA) C & C++ Page 40


Relational operators are also known as a comparison operator, it is an operator that compares two
values. Expressions that contain relational operators are called relational expressions.
Operator Meaning
< Less than
> Greater than
<= Less than equal to
>= Greater than equal to
== Equal to
!= Not equal to
3. Logical Operators :
‘C’ has three types of logical operators. They are
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
4. Assignment Operators :
The assignment operator is used to assign a value to a variable or to assign the result of
an expression to a variable. The assignment operator in ‘C’ language is “=”. They are
Variable = expression

Ex : x=5; y=a+b;
5. Increment or Decrement Operators :
‘C’ has two very useful operators, not generally found in other languages. These are the
increment(++) and decrement(--) operators. The operator ‘++’ adds “1” to the operand. While ‘- -’
subtracts “1” from the operand. Both are called unary operators.
Here ++m is equivalent to m=m+1
-- m is equivalent to m=m-1 or m=-1
++m is called pre incrementation, m++ is called post incrementation. Similarly --m is
called pre decrementation and m- - is called post decrementation.
6. Conditional Operator (Ternary) :
A ternary operator pair “?” is available in ‘C’ language to construct a conditional
expression. The syntax is
Variable=exp1 ? exp2 : exp 3;
Example : a=10, b=15
X=a>b ? a:b
In this example first it will evaluate the exp 1. If it is true the value of a (exp2) will be assigned to
x. If the condition is false, the value of b(exp3) will be assigned to x.
7. Bitwise Operators :
‘C’ has a distinction of supporting some operators called as bitwise operators and are
used for manipulation of data at bit level. These operators are used for testing the bits or shifting
them from right to left, left to right etc., They are
Operator Meaning
& Bitwise AND
| (pipe symbol) Bitwise OR
^ Bitwise x-OR (ap)
~ /S Complement (tilde)
<< Left shift
II B.Com (CA) & B.A (CA) C & C++ Page 41
>> Right shift
8. Special Operators :
‘C’ supports some special operators, such as comma(,) operaor, “size=of” operator, point
operators (& and *), member selection operators (. and ).

Control structures in c++


C++ Language supports 4 Type of decision making statements.
1. Simple if Statement
2. if-else Statement
3. Nested if-else Statement
4. else-if Ladder
1. Simple IF Statement:

The ‘statement-block’ may be a single statement or a group of statements. If the test condition
is true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x.
Syntax:
if( test condition )
{
statement – block ;
}
statement –x
Example: #include <iostream>
using namespace std;
int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
2. If – else Statement:
If the test condition is true, then the True statement- block; immediately following the if statement, are
executed; otherwise, the False- statement- block are executed. In any case, either True statement-
block or False- statement- block will be executed, not both. After executing any one block of
statements, the control is transfers to the statement-x.
Syntax:
if( test condition )
{
True-statement- block;
}
else {
False- statement- block;
}
Statement –x
Example:
#include <iostream>
using namespace std;
int main () {
II B.Com (CA) & B.A (CA) C & C++ Page 42
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}
3. else-if Ladder:
If-Else Ladder or Else if Ladder is a multiple decision making statement. In this statement, First
Condition 1 Will is tested. IF the condition is true the statement1 will be execute .If the condition false
the Second condition will be tested. If the Second condition will be true the statement 2 will be
execute. if the condition 2 false condition3 will be execute and so on …..
Syntax:
If (test condition1)
{
Statement - block-1;
}
else
{if ( test condition2 )
{
Statement - block-2;
}
else
{
if ( test condition3)
{
Statement - block-3;
}
else
{
default Statement - block
} }}}
Statement –x;
Example: #include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
II B.Com (CA) & B.A (CA) C & C++ Page 43
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}

3. Nested if Statement:
Nested if is also a multiple decision making statement. In this statement. First Condition will be tested if
the condition is true another if condition will be execute if the condition is false false statement
execute and so on….
if( test condition1 )
{
if ( test condition2 )
{
Statementblock- 1;
}
else
{
Statementblock- 2;
}
}
else
{
Statement - block-3;
}
Statement –x;
Example: #include <iostream>
using namespace std;
int main () {
int a = 100;
int b = 200;
if( a == 100 ) {
if( b == 200 ) {
cout << "Value of a is 100 and b is 200" << endl;
}
}
II B.Com (CA) & B.A (CA) C & C++ Page 44
cout << "Exact value of b is : " << b << endl;
return 0;
}

Switch case Statement


A program is having no. of alternatives; the program becomes difficult to read and follows. Sometimes
it may confuse even the person who designed it. The ‘C’ language is having built in multi-way decision
statement known as ‘switch’ statement.
This statement test the value of the given expression against list of case values, when match is found, a
block of statement associated with that case is executed.
 The break statement will terminate the control from the switch statement.
 If the passed expression does not matches with any one of the case value then default block will be
executed.
Syntax:
switch(expression)
{
case value 1 :
Statements ;
break;

case value 2 :
Statements ;
break;

case value 3 :
Statements ;
break;
default :
default Statements ;
break;
}
Example: #include <iostream>
using namespace std;
int main () {
int num;

cout<<"Enter a number to check grade:";


cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}

INLINE FUNCTION:

II B.Com (CA) & B.A (CA) C & C++ Page 45


To eliminate the cost of calls to small functions C++ proposes a new feature called inline function. An
inline function is a function that is expanded inline when it is invoked .That is the compiler replaces the
function call with the corresponding function code.
The inline functions are defined as follows:-

Syntax: inline function-header


{
function body;
}
Example: inline double cube (double a)
{
return(a*a*a);
}
The above inline function can be invoked by statements like
c=cube(3.0);
d=cube(2.5+1.5);
remember that the inline keyword merely sends a request, not a command to the compliler. The
compiler may ignore this request if the function definition is too long or too complicated and compile
the function as a normal function.
Some of the situations where inline expansion may not work are:
1. For functions returning values if a loop, a switch or a go to exists.
2. for function s not returning values, if a return statement exists.
3. if functions contain static variables.
4. if inline functions are recursive,.
Example: #include <iostream.h>
#include<stdio.h>
inline float mul(float x, float y)
{
return(x*y);
}
inline double div(double p.double q)
{
return(p/q);
}
main( )
{
float a=12.345;
float b=9.82;
cout<<mul(a,b)<< endl;
cout<<div(a,b)<< endl;
}
output:- 121.227898
1.257128
Default Values for Parameters
When you define a function, you can specify a default value for each of the last parameters. This value
will be used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the function
definition. If a value for that parameter is not passed when the function is called, the default given
value is used, but if a value is specified, this default value is ignored and the passed value is used
instead. Consider the following example −

II B.Com (CA) & B.A (CA) C & C++ Page 46


#include <iostream>
using namespace std;
int sum(int a, int b = 20) {
int result;
result = a + b;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;

// calling a function to add the values.


result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total value is :300
Total value is :120

Q. FUNCTION OVERLOADING:
 Overloading refers to the use of the same thing for different purposes.
 C++ also permits overloading functions .This means that we can use the same function name to
create functions that perform a variety of different tasks. This is known as function
polymorphism in oops.
 Using the concepts of function overloading, a family of functions with one function name but
with different argument lists in the functions call.
 The correct function to be invoked is determined by checking the number and type of the
arguments but not on the function type.
 For example an overloaded add () function handles different types of data as shown below.

//Declaration

int add(int a, int b); //prototype 1


int add (int a, int b, int c); //prototype 2
double add(double x, double y); //prototype 3
double add(double p , double q); //prototype 4
//function call
cout<<add(5,10); //uses prototype 1
cout<<add(5,10,15); //uses prototype 2
cout<<add(12.5,7.5); //uses prototype 3
cout<<add(15,10.0); //uses prototype 4
II B.Com (CA) & B.A (CA) C & C++ Page 47
cout<<add(0.75,5); //uses prototype 5
A function call first matches the prototype having the same no and type of arguments and then calls
the appropriate function for execution.
The function selection invokes the following steps:-

a) The compiler first tries to find an exact match in which the types of actual arguments are the same
and use that function.

b) If an exact match is not found the compiler uses the integral promotions to the actual arguments
such as:
char to int
float to double
to find a match
c) When either of them tails, the compiler tries to use the built in conversions to the actual arguments
and them uses the function whose match is unique. If the conversion is possible to have multiple
matches, then the compiler will give error message.
Example: long square (long n);

double square(double x);

A function call such as: - square (lO)

Will cause an error because int argument can be converted to either long or double .There by creating
an ambiguous situation as to which version of square ( ) should be used.

Example for function overloading:


#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}

II B.Com (CA) & B.A (CA) C & C++ Page 48


UNIT-IV

Classes and Objects: Specifying a class, defining member functions, Access control, constructors and
destructors, Friend functions – Inheritance – Class hierarchy, derived classes, types of inheritance,
Polymorphism-static binding, dynamic binding, method overloading with virtual functions, pure virtual
functions, abstract classes.

CLASS:-
 Class is a group of objects that share common properties and relationships.
 In C++, a class is a new data type that contains member variables and member functions that
operates on the variables.
 A class is defined with the keyword class. It allows the data to be hidden, if necessary from
external use.
 When we defining a class, we are creating a new abstract data type that can be treated like any
other built in data type.

Generally a class specification has two parts:-


a) Class declaration
b) Class function definition
the class declaration describes the type and scope of its members. The class function definition
describes how the class functions are implemented.

Syntax:- class class-name


{
private:
variable declarations;
function declaration ;
public:
variable declarations;
function declaration;
};
The members that have been declared as private can be accessed only from within the class. On the
other hand, public members can be accessed from outside the class also. The data hiding is the key
feature of oops. The use of keywords private is optional by default; the members of a class are private.
The variables declared inside the class are known as data members and the functions are known as
members mid the functions. Only the member functions can have access to the private data members
and private functions. However, the public members can be accessed from the outside the class. The
binding of data and functions together into a single class type variable is referred to as encapsulation.
Syntax:- class item
{

II B.Com (CA) & B.A (CA) C & C++ Page 49


int member;
float cost;
public:
void getldata (int a ,float b);
void putdata (void);
The class item contains two data members and two function members, the data members are
private by default while both the functions are public by declaration. The function getdata() can be
used to assign values to the member variables member and cost, and putdata() for displaying their
values . These functions provide the only access to the data members from outside the class.
CREATING OBJECTS:
Once a class has been declared we can create variables of that type by using the class name.

Example: item x;

Creates a variables x of type item. In C++, the class variables are known as objects. Therefore x is called
an object of type item.
item x, y ,z also possible.
class item
{
-----------
-----------
-----------
}x ,y ,z;
would create the objects x ,y ,z of type item.

ACCESSING CLASS MEMBER:


The private data of a class can be accessed only through the member functions of that class. The main()
cannot contains statements that the access number and cost directly.
Syntax: object name.function-name(actual arguments);
Example:- x. getdata(100,75.5);
It assigns value 100 to number, and 75.5 to cost of the object x by implementing the getdata() function
. Similarly the statement
x. putdata ( ); //would display the values of data members.
x. number = 100 is illegal .Although x is an object of the type item to which number belongs , the
number can be accessed only through a member function and not by the object directly.
Example: class xyz
{
Int x;
Int y;
public: int z;
};
---------
---------- xyz p;
p. x =0; error . x is private
p, z=10; ok ,z is public

II B.Com (CA) & B.A (CA) C & C++ Page 50


Q. HOW TO DEFINING MEMBER FUNCTION TO A CLASS?

Members can be defined in two places


 Outside the class definition
 Inside the class function

OUTSIDE THE CLASS DEFlNAT1ON


Member functions that are declared inside a class have to be defined separately outside the
class. Their definitions are very much like the normal functions.
An important difference between a member function and a normal function is that a member
function incorporates a membership. Identify label in the header. The ‘label’ tells the compiler which
class the function belongs to.
Syntax: return type class-name::function-name(argument declaration)
{
Function-body
}
The member ship label class-name :: tells the compiler that the function function - name
belongs to the class class-name. That is the scope of the function is restricted to the classname
specified in the header line. The :: symbol is called scope resolution operator.
Example: void item :: getdata (int a , float b )
{
number=a; cost=b;
}
void item :: putdata ( void)
{
cout<< ”number=:” << number<<endl;
cout<< ”cost=”<<cost <<endl;
}
The member functions have some special characteristics that are often used in the program
development.
 Several different classes can use the same function name. The "membership label" will resolve
their scope, member functions can access the private data of the class .A non member function
can't do so.
 A member function can call another member function directly, without using the dot operator.
INSIDE THE CLASS DEF1NATION:
Another method of defining a member function is to replace the function declaration by the actual
function definition inside the class .
Example: class item
{
Int number;
float cost;
public:
II B.Com (CA) & B.A (CA) C & C++ Page 51
void getdata (int a ,float b);
void putdata(void)
{
cout<<number<<endl;
cout<<cost<<endl;
}
};
A C++ PROGRAM WITH CLASS:
# include< iostream. h>
class item
{
int number;
float cost;
public: void getdata ( int a , float b);
void putdala ( void)
{
cout<<“number:”<<number<<endl;
cout<<“cost:”<<cost<<endl;
}
};
void item :: getdata (int a , float b)
{
number=a;
cost=b;
}
main ( )
{
item x;
cout<<”\nobjectx”<< endl;
y. getdata(200,175.5);
y. putdata();
}

Q. What is a CONSTRUCTOR?
A constructor is a special member function whose task is to initialize the objects of its class. It is special
because its name is the same as the class name. The constructor is invoked whenever an object of its
associated class is created. It is called constructor because it construct the values of data members of
the class. A constructor is declared and defined as follows:
//'class with a constructor
class integer
{
int m,n;
public: integer! void); //constructor declared
------------
------------
};
integer:: integer(void)
{
m=0;
n=0;
II B.Com (CA) & B.A (CA) C & C++ Page 52
}
There are four types of constructors used in C++.
1. Default constructor
2. Dynamic constructor
3. Parameterized constructor
4. Copy constructor
1. Default constructor
A constructor that accepts no parameter is called the default constructor. The default constructor for
class A is A :: A( ). If no such constructor is defined, then the compiler supplies a default constructor.
Therefore a statement such as: - A a; //invokes the default constructor of the compiler of the compiler
to create the object "a”;
The constructor functions have some characteristics:-
 They should be declared in the public section.
 They are invoked automatically when the objects are created.
 They don't have return types, not even void and therefore. They cannot return values.
 They cannot be inherited, though a derived class can call the base class constructor.
 Like other C++ function , they can have default arguments,
 Constructor can't be virtual.
 An object with a constructor can't be used as a member of union.

Example of default constructor:


#include <iostream.h>
#include<conio.h>
class abc
{
private:
char nm[];
public:
abc ( )
{
cout<<”enter your name:”;
cin>>nm;
}
void display( )
{
cout<<nm;
}
};
int main( )
{
clrscr( );
abc d;
d.display( );
getch( );
return(0);
}
2. PARAMETERIZED CONSTRUCTOR:

II B.Com (CA) & B.A (CA) C & C++ Page 53


The constructors that can take arguments are called parameterized constructors. Using parameterized
constructor we can initialize the various data elements of different objects with different values when
they are created.
Example:-
class integer
{
int m,n;
public:
integer( int x, int y);
--------
---------
};
integer:: integer (int x, int y)
{
m=x;
n=y;
}
The argument can be passed to the constructor by calling the constructor implicitly.
integer int 1 = integer(0,100); // explicit call
integer int 1(0,100); //implicite call

3. COPY CONSTRUCTOR:
A copy constructor is used to declare and initialize an object from another object.
Example: - the statement
integer 12(11);
Would define the object 12 and at the same time initialize it to the values of 11.
Another form of this statement is : integer 12=11;
The process of initialization through a copy constructor is known as copy initialization.
Example:-
#include<iostream.h>
class code
{
int id;
public code ( ) {} //constructor
code (int a) { id=a; } //constructor
code(code &x)
{
Id=x.id;
}
void display( )
{
cout<<id;
}
};
int main( )
{

II B.Com (CA) & B.A (CA) C & C++ Page 54


code A(100);
code B(A);
code C=A;
code D;
D=A;
cout<<” \n id of A:”; A.display( );
cout<<” \n id of B :”; B.display( );
cout<<” \n id of C :”; C.display( );
cout<<” \n id of D:”; D.display( );
}
output :- id of A:100
id of B:100
id of C:100
id of D:100

4. DYNAMIC CONSTRUCTOR:-
The constructors can also be used to allocate memory while creating objects. This will enable the
system to allocate the right amount of memory for each object when the objects are not of the same
size, thus resulting in the saving of memory. Allocate of memory to objects at the time of their
construction is known as dynamic constructors of objects. The memory is allocated with the help of
new operator.
Example:-
#include <iostream.h>
#include<conio.h>
class string
{
char *name;
int length;
public:
string ( )
{
length=0;
name= new char [length+1]; /* one extra for \0 */
}
string( char *s) //constructor 2
{
length=strlen(s);
name=new char [length+1];
strcpy(name,s);
}
void display(void)
{
Cout<<name<<endl;
}
void join(string &a .string &b)
{
length=a. length +b . length;
delete name;
name=new char[length+l]; /* dynamic allocation */
strcpy(name,a.name);
II B.Com (CA) & B.A (CA) C & C++ Page 55
strcat(name,b.name);
}
};
int main( )
{
char * first = “Joseph” ;
string name1(first),name2(“louis”),naine3( “LaGrange”),sl,s2;
sl.join(name1,name2);
s2.join(s1,name3);
namel.display( );
name2.display( );
name3.display( );
s1.display( );
s2.display( );
}
output :- Joseph
Louis
Language
Joseph Louis
Joseph Louis Language

Q. Explain about DESTRUCTOR.


A destructor, us the name implies is used to destroy the objects that have been created by a
constructor. Like a constructor, the destructor is a member function whose name is the same as the
class name but is preceded by a tilde.

For Example:- ~ integer( ) { }

A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the
compiler upon exit from the program to clean up storage that is no longer accessible. It is a good
practice to declare destructor in a program since it releases memory space for future use.
Delete is used to free memory which is created by new.
Example:- matrix : : ~ matrix( )
{
for(int i=0; i<11;i++)
delete p[i];
delete p;
}
Example of destructor:
#include <iostream.h>
#include <conio.h>
using namespace std;
class Hello {
public:
//Constructor
Hello () {
cout<< "Constructor function is called" <<endl;
}
//Destructor
II B.Com (CA) & B.A (CA) C & C++ Page 56
~Hello () {
cout << "Destructor function is called" <<endl;
}
//Member function
void display() {
cout <<"Hello World!" <<endl;
}
};
int main(){
//Object created
Hello obj;
//Member function called
obj.display();
return 0;
}

Q. Friend function
 A friend function of a class is defined outside that class' scope but it has the right to access all
private and protected members of the class. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.

 By using the keyword friend compiler knows the given function is a friend function.

 For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.
Declaration of friend function in C++
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
Characteristics of a Friend function:
 The function is not in the scope of the class to which it has been declared as a friend.
 It cannot be called using the object as it is not in the scope of that class.
 It can be invoked like a normal function without using the object.
 It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
 It can be declared either in the private or the public part.

Friend function Example:


#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};

II B.Com (CA) & B.A (CA) C & C++ Page 57


int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}

Q. Inheritance
Reaccessability is yet another feature of OOP's. C++ strongly supports the concept of reusability. The
C++ classes can be used again in several ways. Once a class has been written and tested, it can be
adopted by another programmer. This is basically created by defining the new classes, reusing the
properties of existing ones. The mechanism of deriving a new class from an old one is called
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class being
defined "is" also an object of inherited class. The old class is called 'BASE' class and the new one is
called 'DERIEVED' class.

Defining Base and Derived Classes


class derived-class: access-specifier base-class
class xyz //base class
{
members of xyz
};
class ABC : public xyz //public derivation
{
members of ABC
};
class ABC : XYZ //private derivation (by default)
{
members of ABC
};

Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.

Modes of Inheritance
1.Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.
2.Protected mode: If we derive a sub class from a Protected base class. Then both public member
and protected members of the base class will become protected in derived class.
3.Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.

Types of Inheritance
 Single inheritance

II B.Com (CA) & B.A (CA) C & C++ Page 58


 Multiple inheritance
 Hierarchical inheritance
 Multilevel inheritance
 Hybrid inheritance

Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited from the only one
base class.
Example:
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}

Multilevel Inheritance:
When the inheritance is such that, the class A serves as a base class for a derived class B which in turn
serves as a base class for the derived class C. This type of inheritance is called ‘MULTILEVEL
INHERITENCE’.
Example:
#include<iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
// first sub_class derived from class vehicle
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
II B.Com (CA) & B.A (CA) C & C++ Page 59
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car: public fourWheeler {
public:
Car()
{
cout << "Car has 4 Wheels\n";
}
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Hierarchical Inheritance:
In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than
one derived class is created from a single base class.
Example:
#include<iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// first sub class


class Car: public Vehicle
{

};
// second sub class
class Bus: public Vehicle
{

};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.

II B.Com (CA) & B.A (CA) C & C++ Page 60


Car obj1;
Bus obj2;
return 0;
}

Multiple Inheritance:
Multiple Inheritances is a feature of C++ where a class can inherit from more than one classes. i.e
one sub class is inherited from more than one base classes.
Examples:
#include<iostream>
using namespace std;
// first base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
// second base class
class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};
// sub class derived from two base classes
class Car : public Vehicle, public FourWheeler {
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Hybrid Inheritance
There could be situations where we need to apply two or more types of inheritance to design a
program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
Examples:
#include<iostream>
using namespace std;
// base class
class Vehicle
{
public:
II B.Com (CA) & B.A (CA) C & C++ Page 61
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
//base class
class Fare
{
public:
Fare()
{
cout << "Fare of Vehicle\n";
}
};
// first sub class
class Car : public Vehicle
{

};
// second sub class
class Bus : public Vehicle, public Fare
{

};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}

Polymorphism
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a
hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be
executed depending on the type of object that invokes the function.

 Compile time polymorphism: The overloaded functions are invoked by matching the type and
number of arguments. This information is available at the compile time and, therefore, compiler
selects the appropriate function at the compile time. It is achieved by function overloading and
operator overloading which is also known as static binding or early binding. Now, let's consider the
case where function name and prototype is same.
II B.Com (CA) & B.A (CA) C & C++ Page 62
 Run time polymorphism: Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time. It is achieved by method overriding which is also
known as dynamic binding or late binding.

Q. Method overloading with Virtual function


Virtual function
 A C++ virtual function is a member function in the base class that you redefine in a derived
class. It is declared using the virtual keyword.
 It is used to tell the compiler to perform dynamic linkage or late binding on the function.
 There is a necessity to use the single pointer to refer to all the objects of the different classes.
So, we create the pointer to the base class that refers to all the derived objects. But, when base
class pointer contains the address of the derived class object, always executes the base class
function. This issue can only be resolved by using the 'virtual' function.
 A 'virtual' is a keyword preceding the normal declaration of a function.
 When the function is made virtual, C++ determines which function is to be invoked at the
runtime based on the type of the object pointed by the base class pointer.
Rules of Virtual Function
 Virtual functions must be members of some class.
 Virtual functions cannot be static members.
 They are accessed through object pointers.
 They can be a friend of another class.
 A virtual function must be defined in the base class, even though it is not used.
 The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will consider
them as the overloaded functions.
 We cannot have a virtual constructor, but we can have a virtual destructor
 Consider the situation when we don't use the virtual keyword.
#include <iostream>
Class A
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()

II B.Com (CA) & B.A (CA) C & C++ Page 63


{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Q. Pure Virtual Functions
Generally a function is declared virtual inside a base class and we redefine it the derived classes. The
function declared in the base class seldom performs any task.
Characteristics of a pure virtual function
o A pure virtual function is a "do nothing" function. Here "do nothing" means that it just provides
the template, and derived class implements the function.
o It can be considered as an empty function means that the pure virtual function does not have
any definition relative to the base class.
o Programmers need to redefine the pure virtual function in the derived class as it has no
definition in the base class.
o A class having pure virtual function cannot be used to create direct objects of its own. It means
that the class is containing any pure virtual function then we cannot create the object of that
class. This type of class is known as an abstract class.
The following program demonstrates how a pure virtual function is defined, declared and invoked from
the object of a derived class through the pointer of the base class. In the example there are two classes
employee and grade. The class employee is base class and the grade is derived class. The functions
getdata ( ) and display ( ) are declared for both the classes. For the class employee the functions are
defined with empty body or no code inside the function. The code is written for the grade class. The
methods of the derived class are invoked by the pointer to the base class.
#include<iostream>
using namespace std;
class B
{
public:
virtual void s() = 0; // Pure Virtual Function };
class D:public B
{
public:
void s()
{
cout << "Virtual Function in Derived class\n";
}
};
int main()
{
B *b;
D dobj;
b = &dobj;
b->s();
}

II B.Com (CA) & B.A (CA) C & C++ Page 64


Q. Abstract class
 An abstract class is a class in C++ which has at least one pure virtual function.
 Abstract class can have normal functions and variables along with a pure virtual function.\
 Abstract class cannot be instantiated, but pointers and references of Abstract class type can be
created.
 Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
 If an Abstract Class has derived class, they must implement all pure virtual functions, or else
they will become Abstract too.
 We can’t create object of abstract class as we reserve a slot for a pure virtual function in Vtable,
but we don’t put any address, so Vtable will remain incomplete.
class B //abstract class
{
public:
virtual void s() = 0; // Pure Virtual Function };
class D:public B
{
public:
void s()
{
cout << "Virtual Function in Derived class\n";
}
};

II B.Com (CA) & B.A (CA) C & C++ Page 65


UNIT-V

Operator overloading-this pointer, applications of this pointer, operator function, operator


overloading. Exception handling- Try, throw and catch, Dynamic Memory management, new and delete
operators, object copyiing, copy constructor.

Q. Operators Overloading
 Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type.
 Operator overloading is used to overload or redefines most of the operators available in C++. It
is used to perform the operation on the user-defined data type.
 For example, C++ provides the ability to add the variables of the user-defined data type that is
applied to the built-in data types.
 Operator overloading provides a flexible option for the creation of new definations for most of
the C++ operators.
 We can overload all the C++ operators except the following:
 Scope operator (::)
 Sizeof
 member selector(.)
 member pointer selector(*)
 ternary operator(?:)
 Although the semantics of an operator can be extended, we can't change its syntax, the
grammatical rules that govern its use such as the no of operands precedence and associatively.
 For example the multiplication operator will enjoy higher precedence than the addition
operator.
 When an operator is overloaded, its original meaning is not lost.
 For example, the operator +, which has been overloaded to add two vectors, can still be used
to add two integers.
DEFINING OPERATOR OVERLOADING
return-type class-name::operator op(arg-list)
{
function body
}
 Where return type is the type of value returned by the specified operation and op is the
operator being overloaded.
 The op is preceded by the keyword operator, operator op is the function name.
Rules for Operator Overloading
 Existing operators can only be overloaded, but the new operators cannot be overloaded.
 The overloaded operator contains at least one operand of the user-defined data type.
 We cannot use friend function to overload certain operators. However, the member function
can be used to overload those operators.

II B.Com (CA) & B.A (CA) C & C++ Page 66


 When unary operators are overloaded through a member function take no explicit arguments,
but, if they are overloaded by a friend function, takes one argument.
 When binary operators are overloaded through a member function takes one explicit argument,
and if they are overloaded through a friend function takes two explicit arguments.

Example for operator overloading:


#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() //operator overloading
{
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}

Q. this pointer
 Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions. Therefore,
inside a member function, this may be used to refer to the invoking object.
 Friend functions do not have a this pointer, because friends are not members of a class. Only
member functions have a this pointer.

#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;

II B.Com (CA) & B.A (CA) C & C++ Page 67


this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}

Q. Exception Handling
 An exception is a problem that arises during the execution of a program.
 A C++ exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
 Exceptions provide a way to transfer control from one part of a program to another.
 C++ exception handling is built upon three keywords: try, catch, and throw.
 throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
 catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the catching
of an exception.
 try − A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks.
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try
{
z = division(x, y);
cout << z << endl;
}
catch (const char* msg)
{
II B.Com (CA) & B.A (CA) C & C++ Page 68
cerr << msg << endl;
}
return 0;
}

Q. Dynamic memory allocation in C++


 There are times where the data to be entered is allocated at the time of execution.
 For example, a list of employees increases as the new employees are hired in the organization
and similarly reduces when a person leaves the organization. This is called managing the
memory. So now, let us discuss the concept of dynamic memory allocation.
 Dynamically we can allocate storage while the program is in a running state, but variables
cannot be created "on the fly". Thus, there are two criteria for dynamic memory allocation -
 A dynamic space in the memory is needed.
 Storing the address to access the variable from the memory
 In C++, memory is divided into two parts -
 Stack - All the variables that are declared inside any function take memory from the
stack.
 Heap - It is unused memory in the program that is generally used for dynamic memory
allocation.
new and delete Operators
 You can allocate memory at run time within the heap for the variable of a given type using a
special operator in C++ which returns the address of the space allocated. This operator is
called new operator.
 If you are not in need of dynamically allocated memory anymore, you can use delete operator,
which de-allocates memory that was previously allocated by new operator.
Syntax :
Pointer_variable = new data_type;
int *m = new int(20);
Float *d = new float(21.01);
Syntax :
delete pointer_variable_name
Example
delete m; // free m that is a variable
delete arr[]; // Release a block of memory

II B.Com (CA) & B.A (CA) C & C++ Page 69

You might also like