0% found this document useful (0 votes)
3 views177 pages

Fundamentals of Programming

The document outlines the curriculum for a programming course at SRI Vidya Mandir Arts & Science College, focusing on C and C++ programming fundamentals. It covers topics such as data types, control structures, object-oriented programming concepts, and file handling. The document also includes information on the structure of C programs, constants, variables, and operators, along with recommended textbooks and reference materials.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views177 pages

Fundamentals of Programming

The document outlines the curriculum for a programming course at SRI Vidya Mandir Arts & Science College, focusing on C and C++ programming fundamentals. It covers topics such as data types, control structures, object-oriented programming concepts, and file handling. The document also includes information on the structure of C programs, constants, variables, and operators, along with recommended textbooks and reference materials.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

SRI VIDYA MANDIR ARTS & SCIENCE COLLEGE

(AUTONOMOUS)
Katteri - 636 902, Uthangarai, Krishnagiri District
[An Autonomous Institution Affiliated to Periyar University, Salem]
[Accredited by NAAC with ―A‖ Grade [3.27]]
[Recognized 2(f) & 12(B) under UGC Act of 1956]

PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS


___________________________________________________________________________

Fundamentals of Programming

Unit I

Introduction to C: Overview of C - Introduction - Character set - C tokens -


keyword & Identifiers - Constants - Variables - Data types - Declaration of
variables - Assigning values to variables - Defining Symbolic Constants -
Arithmetic, Relational, Logical, Assignment, Conditional, Bitwise, Special,
Increment and Decrement operators - Arithmetic Expressions - Evaluation
of expression - precedence of arithmetic operators - Type conversion in
expression – operator precedence & associativity – Mathematical functions -
Reading & Writing a character - Formatted input and output.

Unit II

Decision Making , Looping and Arrays: Decision Making and Branching:


Introduction – if, if….else, nesting of if …else statements else if ladder – The
switch statement, The ?: Operator – The go to Statement. Decision Making
and Looping: Introduction- The while statement- the do statement – the for
statement-jumps in loops. Arrays – Character Arrays and Strings

Unit III

Introduction to C++ - key concepts of Object-Oriented Programming–


Advantages– Object Oriented Languages –I/O in C++- C++Declarations.
Functions in C++-inline functions– Function Overloading. Classes and
Objects: Declaring Objects– Defining Member Functions– Static Member
variables and functions–array of objects–friend functions–Overloading
member functions–Bit fields and classes –Constructor and destructor with
static members.

Unit IV

Inheritance Operator Overloading: Overloading unary, binary operators –


Overloading Friend functions – type conversion – Inheritance: Types of
Inheritance – Single, Multilevel, Multiple, Hierarchal, Hybrid ,Multipath
inheritance –Virtual base Classes–Abstract Classes.

Unit V

Pointers & Files: Pointers–Declaration–Pointer to Class, Object– this pointer–


Pointers to derived classes and Base classes–Arrays– Characteristics–array of
classes. Files–File stream classes–file modes– Sequential Read/Write
operations–Binary and ASCII Files –Random Access Operation–Templates–
Exception Handling– Miscellaneous functions.

Text Book(s)

1. E Balagurusamy: Computing Fundamentals & C Programming – Tata


McGraw-Hill, Second Reprint 2008

2. Ashok N Kamthane ,Object-Oriented Programming with Ansi and Turbo


C++,Pearson Education,2003.

Reference Books

1. Ashok N Kamthane: Programming with ANSI and Turbo C, Pearson, 2002.

2. E. Balagurusamy, Object-Oriented Programming with C++,TMH,1998

3. Maria Litvin &Gray Litvin, C++foryou,Vikaspublication,2002.

4. JohnRHubbard, Programming with C, 2ndEdition,TMH publication,2002


UNIT– I
OVERVIEW OF C
The Origins and History of C
 ‗C‘ was developed from the ‗Basic Programming Language (BCPL)‘
known as ‗B‘ language.
 It is a general-purpose programming language.
 C was developed by Dennis Ritchie between 1969 and 1973 at AT&T
Bell Labs.
 It is developed with UNIX operating system.
 It is standardized by ANSI (American National Standard Institute).
 Today C is available with many operating systems such as MS-DOS,
windows, etc.
 To develop C program we need C compiler.

Importance/Features of C
 It is very easy to read, write and understand.
 It is easy to learn.
 There are only 32 keywords.
 C is portable language.
 The C program is efficient and faster.
 C language program is 50 times faster than Basic program.
 It combines the features of high-level language and assembly language
so it is known as the middle level language.
 Program written in C can be easily modified and we can add new
features in our program.
 It follows structured programming technique.
 C is general purpose programming language.
 Portability: we can compile or execute C program in any operating
system (Unix, DOS, Windows).
 C is case sensitive language.
Compiler: is a translator program that translates high-level language to
machine level language.
Portable language: Program written on one computer can run easily on
another computer without any modification.
Applications of C
 Used for creating computer applications.
 Used in writing embedded software.
 Used to implement various operating system operations.
 UNIX kernel is completely developed using C language.
 Used for creating compilers.
BASIC STRUCTURE OF C PROGRAM
Structure of C is defined by set of rules called protocol. The basic structure
of C Program has been followed as,
1. Documentation section:
It consists of a set of comment lines. It gives the name of the program
and other details. Comments can be given in two ways:
a. Single line comment // Your Comments Here
b. Multi line comment
/* comment line1
comment line2
comment line3 */
The characters given between ―/*‖ and ―*/‖ will be ignored by C
compiler during compilation.
Eg:
/* C basic structure program
Author: JAAS
Date: 01/01/2012 */
2. Link Section
It provides instructions to the compiler to link functions from the system
library.
Eg:
#include <stdio.h>
#include <conio.h>
3. Definition Section
It defines all symbolic constants.
Eg:
#define pi 3.14
#defineMAX 10
4. Global Declaration Section
When a variable is to be used throughout the program, that variable can
be defined in this section. Global variables are defined above main() in
the following way:-
Eg:
int total=10; //globalvariable
main()
{
}
5. Function prototype declaration section
Function prototype gives much information about a function like return
type, parameter names used inside the function.
Eg: int sum (int, int);

6. Main function:
Every C program must have one main function section. This section
contains two parts, declaration and executable part.
a. Variable declaration section: Used to declare private variable.
b. Function declaration section: Used to declare functions of program.
Then, executable statements are placed for execution.
The declaration and executable part must appear between the opening
and closing braces. All statements in the declaration part should end
with the semicolon.
Eg:
main()
{
printf(― THIS IS MAIN FUNCTION‖);
}
7. User defined function section
It contains all the user defined functions that are called in the main
function.
Eg:
void add(int a, int b)
{
int c= a+b;
printf(―c=%d‖, c);
}
Example Program
/*Documentation Section: program to find the area of
circle*/
#include <stdio.h> /*link section*/
#include <conio.h> /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declarationsection*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); //executable part
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}
Step By Step Execution of C Program
Step 1: Edit
 The first step is Creating or Editing Program.
 First Write C Program using Text Editor.
 Save Program by using [.C] Extension.
 File Saved with [.C] extension is called ―Source Program―.
Step 2: Compiling
 Compiling C Program
 Program can be compiled using key [Alt + F9 ].
 If source code is error-free then Code is converted into Object File
[.Obj ].
Step 3: Checking Errors
 If there is any error, User has to re-edit the program.
 If program is error-free then program is linked with appropriate
libraries.
Step 4: Linking Libraries
 Program is linked with included header files.
 Program is linked with other libraries.
 This process is executed by Linker.
Step 5: Execution
 Program can be executed using key [Ctl + F9 ]
 If run time error occurs then ―Run-time‖ errors are reported to user.
 Again programmer has to review code and check for the solution.

CONSTANTS, VARIABLES AND DATA TYPES


Character Set
The character set is the fundamental raw material of any language and they
are used to represent information. They are:
a. Alphabets (A-Z and a-z)
b. Digits (0-9)
c. Special Characters (!@#$%^&*)
d. White Spaces (Tab or New line or Space)
Trigraph Character
 A trigraph is a three-characters replacement for a special or
nonstandard character in a text file.
 A trigraph can be used in place of a symbol that is not present on a
keyboard or in a character set.
Trigraph
Sequences Equivalent
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~
C TOKENS
Each and every individual unit in C program is known as tokens. It is a
basic building block in C language. They are as follows:

Eg:
int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
printf ("Total = %d \n", total);
}
where,
main – identifier
{,}, (,) – Special Symbols
int – keyword
x, y, total – identifier
main, {, }, (, ), int, x, y, total – tokens
1. Keywords
 Keywords are the pre-defined words.
 Each keyword performs a specific function.
 Each keyword has fixed meanings that do not change during
execution.
 White spaces are not allowed in keywords.
 Keyword may not be used as an identifier.
 Keywords should be written in small letters.
 No header file is needed to include the keywords.
 There are 32 keywords in C.
int float double long
short signed unsigned const
if else switch break
default do while for
register extern static struct
typedef enum return sizeof
goto union auto case
void char continue volatile

2. Identifiers
 Names given to identify Variables, functions and arrays are referred as
identifiers.
 They are user-defined names.
Rules for naming Identifiers:
 First character should be an alphabet or underscore.
 Succeeding characters might be digits or letter.
 Punctuation and special characters are not allowed except
underscore.
 Identifiers should not be keywords.
 Its name length is maximum 32 characters long.
 White space is not allowed.
 Its case sensitive ie there is difference between uppercase and
lowercase.
 Eg. Total and total are two different variables.
Eg: total, avg_mark
3. Constants
 Constants refer to fixed values that do not change during the
execution of a program.
 It‘s also called as literals.
Types of Constant
1) Integer constants
2) Real or Floating point constants
3) Octal & Hexadecimal constants
4) Character constants
5) String constants
6) Backslash character constants

Constant type Data type (Example)

int (53, 762, -478 etc )


unsigned int (5000u, 1000U etc)
Integer constants
long int, long long int
(483,647 2,147,483,680)

Real or Floating point float (10.456789)


constants double (600.123456789)

Octal constant int (Example: 013 /*starts with 0 */)

Hexadecimal constant int (Example: 0x90 /*starts with 0x*/)

character constants char (Example: ‗A‘, ‗B‘, ‗C‘)

string constants char (Example: ―ABCD‖, ―Hai‖)

Rules for constructing C constant


1. Integer constants
 An integer constant must have atleast one digit.
 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign proceeds, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.
2. Real constants
 A real constant must have at least one digit
 It must have a decimal point
 It could be either positive or negative
 If no sign proceeds, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.
3. Character and String constants
 A character constant is a single alphabet, a single digit or a single
special symbol enclosed within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.
4. Backslash Character Constants
 These are some characters with special meaning.
 They should be preceded by backslash symbol.
 Few are listed below:
Backslash character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\‖ Double quote
\‘ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a C program?


We can define constants in a C program in the following ways.
1. By ―const‖ keyword
2. By ―#define‖ preprocessor directive
4. Operators
An operator is a symbol that performs certain mathematical or logical
operations.
Eg: +, -, *, %, <<, >>, &&
5. String
A string is a collection of characters enclosed within double quotes ― ‖.
Eg: ―program‖ ―hello‖

6. Special Symbols
Special symbols have some special meaning which cannot be used for any
other purpose.
[] () {} , ; : * … = #
VARIABLES
“A variable is a data name that may be used to store a value”. It will vary
during execution.
Rules for naming the variable:
 First character should be letter or alphabet.
 Keywords should not be used as a variable name.
 White space is not allowed.
 It is case sensitive i.e. UPPER and lower case are significant.
 Only underscore, special symbol is allowed between two characters.
 The length of identifier may be up to 31 characters but only the first 8
characters are considerable by compiler.
Declaration of variable: -
Variables should be declared before to use. Declaration of variable performs
two tasks:
1. It tells the compiler what is the variable name.
2. It specifies what type of data the variable hold such as integer, float,
double, or character
Eg int a;
The above declaration statement tells to complier ‗a‘ is the variable name
and it is of type integer. The format of variable declaration is:
data-type1 variable1;
data-type2 variable2;
Here we can declare the variable of different data-types:
Eg: int a;
float b;
char c;
You can declare the variable of same data-type by separating with comma
operator:
Eg: float a,b, c;
int n1,n2;
Initialization of variable: -
The process of giving initial value to your variable is known as initialization.
Variable initialization also can be performed during the variable declaration
as under:
data-type variable-name = some constant value;
Also you can perform the initialization after declaration of variable.
Eg
int total_marks=100; //Initialization during declaration
float pi=3.14;
double distance;
distance=34.244; // Initialization after declaration
Difference between Variable Declaration & Definition
Variable declaration Variable definition
Declaration tells the compiler about Definition allocates memory for the
data type and size of the variable. variable.
Variable can be declared many times It can happen only one time for a
in a program. variable in a program.
The assignment of properties and Assignments of storage space to a
identification to a variable. variable.
DATA TYPES
Data type determines the type of the data that the variable holds. The
variable is used to store the different type of data value such as integer,
fractional number, character, string, etc. The basic types of data are:
1. Basic/ Primary /Fundamental data types
2. User-defined data type
3. Derived data type
4. Empty data type (void data type)
1. Primary Data type (int, char, float, double)
These are in built data types. They are:
i. Integer Data type:
 This allows a variable to store numeric values.
 ―int‖ is a keyword used to refer integer data type.
 Its size is 2 or 4 or 8 bytes.
 Its size varies depends upon the processor.
 For 16 bit processor, 2 byte (16 bit) of memory will be allocated.
 Likewise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte
(64 bit) of memory for 64 bit processor.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to
+2,147,483,647.
 If you want to use the integer value that crosses the above limit,
you can go for ―long int‖ and ―long long int‖ for which the limits
are very high.
 %d is used to represent the int value in scanf and printf.
ii. Float Data type:
Floating point data type consists of 2 types. They are,
a. float b. double
a. float
 Float data type allows a variable to store decimal values.
 Size is 4 bytes. This also varies depend upon the processor in the
CPU as ―int‖ data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float
data type.
 %f is used to represent the float value in scanf and printf.
b. double
 It is also same as float data type.
 It allows up-to 10 digits after decimal.
 The range is from 1E–37 to 1E+37.
 %lf is used to represent the double value in scanf and printf.
iii. Character Data type:
 A single character can be defined as a character (char) data type.
 %c is used to represent character value in printf and scanf.
 We can use two kind of character variable:
Signed character- default character variable
Unsigned character
The entire list of data types in C available for use is given below:
Size
C Basic Data Types (in Range
bytes)
int 2 -32,768 to 32,767
signed int 2 -32,768 to 32,767
unsigned int 2 0 to 65535
short int 1 -128 to 127
signed short int 1 -128 to 127
Integer Data
unsigned short int 1 0 to 255
Types
long int 4 -2,147,483,648 to
2,147,483,647
signed long int 4 -2,147,483,648 to
2,147,483,647
unsigned long int 4 0 to 4,294,967,295

Floating float 4 3.4E-38 to 3.4E+38

Point Data double 8 1.7E-308 to 1.7E+308

Types long double 10 3.4E-4932 to 1.1E+4932

char 1 -128 to 127


Character
signed char 1 -128 to 127
Data Types
unsigned char 1 0 to 255

2. User-defined data type


You can declare your own data type by using ‗typedef‘ and ‗enum‘
i. typedef (Type definition):
―type definition‖ allows user to provide an altenative name to the existing
data type.
Syntax: typedef data-type identifier;

Here the ‗data-type‘ refers to basic data-type and ‗identifier‘ is the name
given by the user.
Eg: typedef int marks;
main()
{
marks sub1, sub2, sub3;
……………………………
……………………………
}
ii. enum (Enumerated Data-type):
 It is another type of user-defined data type.
 Enumeration data type consists of named integer constants as a list.
 It start with 0 (zero) by default and value is incremented by 1 for the
sequential identifiers in the list.
Syntax: enum identifier {value-1, value-2, value-3, ….. , value-
n};
The values inside the closing brace are known as enumeration
constant.
Eg enum weekdays {sun=1, mon, tue, wed};
Here sun has assigned the value 1,mon assigned the value 2, tue has
assigned the value 3, and wed has assigned the value 4.
3. Derived data type
Array, pointer, structure and union are called derived data types.
4. Void data type
void is an empty data type that has no value.This can be used in
functions and pointers.
Syntax : void variable_name;
Eg void add();
void *a;
DEFINING SYMBOLIC CONSTANTS
 A symbolic constant is name that substitutes for a sequence of
character that cannot be changed.
 The character represents a numeric constant, a character constant, or
a string.
 When the program is compiled, each occurrence of a symbolic
constant is replaced by its corresponding character sequence.
 They are usually defined at the beginning of the program.
Syntax: #define symbolic_name constant_value
Eg #define TOTAL_MARKS 100
Following are the rules used to define the symbolic constant:
1. Symbolic name is similar to variable but it is not variable.
2. The preprocessor statements begin with a #symbol, and are not end
with a semicolon.
3. No blank space allows between ‗#‘ and ‗define‘ word.
4. A blank space is required between ‗#define‘ and ‗symbolic_name‘ &
between ‗symbolic_name‘ and ‗constant_value‘
5. You cannot put assignment operator ‗=‘ between ‗symbolic_name‘ and
constant value.
6. You can put anywhere in program but before it is used in the
program.
Example
#include <stdio.h>
#include <conio.h>
#define PI 3.14 //symbolic constant
float area;
void main()
{
float r;
printf("Enter the radius of the circle\n");
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}
OPERATORS
Operator is a symbol that tells computer to perform certain mathematical
and logical operations. C operators are classified into a number of
categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
1. Arithmetic Operators
These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
Arithmetic Operators/Operation Example
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
i. Integer Arithmetic
When both the operands in a single arithmetic expression are
integers, the expression is called an integer expression, and the
operation is called integer arithmetic. The result of the integer
arithmetic is always the integer.
Eg Where a= 12 and b=3 the result is,
Expression Result
a+b 15
a-b 9
a*b 36
a/b 4
ii. Real Arithmetic
An arithmetic operation involving only real operands is called real
arithmetic. The operator %( modulo) cannot be used with real
operands.
Eg Where a= 12.4 and b=3.1 the result is,
Expression Result
a+b 15.5
a-b 9.3
a*b 38.44
a/b 4.0
iii. Mixed-mode Arithmetic
When one of the operands is real and the other is integer, the
expression is called a mixed-mode arithmetic expression and its result
is always a real number.
Eg Where a= 12and b=2.5 the result is,
Expression Result
a+b 14.5
a-b 9.5
a*b 30.0
a/b 4.8
2. Relational Operators
Relational operators are used to find the relation between two
variables. i.e. to compare the values of two variables.

Operators Example/Description
> x > y (x is greater than y)
< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
3. Logical operators:
 These operators are used to perform logical operations on the
given expressions.
 There are 3 logical operators in C language.
 They are, logical AND (&&), logical OR (||) and logical NOT (!).

Operators Example/Description
&& (x>5)&&(y<5)
(logical AND) It returns true when both conditions are true
|| (x>=10)||(y>=10)
(logical OR) It returns true when at-least one of the condition is true
!((x>5)&&(y<5))
! It reverses the state of the operand ―((x>5) && y<5))‖
(logical NOT) If ―((x>5) && (y<5))‖ is true, logical NOT operator makes it
false
4. Assignment Operators
Assignment operators are used to assign some values to the variables.
There is only one assignment operator that is ‗=‘.
Eg a = 30;
In addition, C has a set of „shorthand‟ assignment operators of the
form,
v op = exp;
Eg x +=y+1; this is same as the statement x=x+(y+1);
Simple Expression Shorthand Operators
a=a+1 a += 1
a = a –23 a -= 23
a=a*4 a*=4
a=a/5 a /= 5
a = a % 10 a %= 10
The advantages of shorthand operators are:
 It is easy to write since we have not to write the operand twice.
 It is easy to read
 It is more efficient
5. Increment and Decrement Operators
Increment operators are used to increase the value of the variable by one
and decrement operators are used to decrease the value of the variable
by one.
Syntax:
Increment operator: pre increment : ++var_name; (or) post increment:
var_name++;
Decrement operator: pre decrement: – -var_name; (or) post decrement:
var_name – -;
Eg : post-increment
i=10;
a= i++;
printf(―i = %d \t a = %d\n‖,i,a);
This statement print the Output: i = 11 a = 10
Eg : pre-increment
i=10;
a= ++i;
printf(―i = %d \t a = %d\n‖,i,a);
This statement print the Output: i = 11 a = 11
Same thing is true for the decrement operator.
6. Conditional Operator
Conditional operators return one value if condition is true and returns
another value is condition is false. A ternary operator pair ―?:‖ is also
known as conditional operator.
Syntax: exp1 ? exp2 : exp3;
Here exp1 is evaluated first. If it is true then the exp2 is evaluated and
becomes the value of the expression. If exp1 is false then exp3 is
evaluated.
It‘s similar to if(exp1)
exp2;
else
exp3;
7. Bitwise Operators
 These operators are used to perform bit operations.
 Decimal values are converted into binary values.
 These operators are used for testing the bits, or shifting them right
or left.
 These operators can‘t be used with the float or double.
Below are the bit-wise operators and their name in c language.
 & – Bitwise AND
 | – Bitwise OR
 ~ – Bitwise NOT
 ^ – XOR
 << – Left Shift
 >> – Right Shift
Truth table for bit wise operation & bit wise operators:

8. Special Operators
C supports some special operators such as
1. Comma operator
2. Size of operator
3. Pointer operators(& and *) and
4. Member selection operators(. and ->)
The Comma Operator: Comma operator is used to link the
expression together and entire expression is evaluated from left to
right.
Eg: value = (x = 10, y = 5, x + y);
This statement first assigns the value 10 to x, then assigns 5 to y,
and finally assigns 15(i.e, 10+5) to value.
The sizeof Operator: The sizeof is a compile time operator and, it
gives the bytes occupied by the operand in memory.
Eg:
m = sizeof(sum);
n = sizeof(long int)
k = sizeof(235L)
EXPRESSIONS
An expressions is a combination of operands (both variables and constants),
operators arranged as per the syntax of the language.
Example: i=i * 2 + (m +1)/2
Type of Expressions
1. Constant expressions
2. integral expressions
3. Float expression
4. Pointer expression
5. Relational expression
6. Logical expression
7. Bitwise expression
1. Constant Expressions: It consists of only constant values.
Example: 13 12+5/2.0 ‗a‘
2. Integral Expressions: An integral expression produces integer results
after implementing all the automatic and explicit type conversions.
Example: m m*n-5 m*‘x‘ 5+int(2.3)
3. Float Expressions: Float expressions produces floating point results
after implementing all the automatic and explicit type conversions.
Example: m m*n-5 m*‘x‘ 5+float(2)
4. Pointer Expressions: Pointer expressions produce address values.
Example: &m Ptr+1 ―xyz‖
5. Relational Expressions or Boolean Expressions: A relational
expression consists of two or more expressions whose values are
compared to determine their relationships and produces bool results.
(ie. true or false).
Example: a<2*b–7 c != -1
6. Logical Expressions: Logical expressions combine two or more
relational expressions and produces bool results.
Example: a>b && x==10 x==10 || y==5
7. Bitwise Expressions: Bitwise expressions are used to manipulate
data at bit levels. They are basically used for testing or shifting bits.
Example: x<<3//Shift 3 bit position to left
y>>1 //Shift 1 bit position to right
8. Special Assignment Expressions
i. Chained Assignment
x=(y=10) Or x=y=10
ii. Embedded Assignment
x=(y=10)+30 Is identically equal to
y=10
x=y+30
iii. Compound Assignment
x=x+10 is written as x+=10
The operator += is known as compound assignment operator or
short hand assignment operator.
General form Variable2 op=variable2;
EVALUATION OF EXPRESSIONS
Expressions are evaluated using an assignment statement of the form
variable = expression;
Eg:
1) x = a * b – c;
2) y = b / c * a;
Precedence of Operators and Associativity
In the ‗C‘ the operators having same precedence are evaluated from left to
right or right to left depend upon the level of which these operators belong.
· For arithmetic operators,

OPERATORS PRECEDENCE ASSOCIATIVITY


*/% FIRST PRIOTIY LEFT TO RIGHT
+- SECOND PRIORITY LEFT TO RIGHT
OPERATORS ASSOCIATIVITY
( ) [ ] -> : : Left to right
! ~ ++ -- + - * sizeof Right to left
*/% Left to right
+- Left to right
<<>> Left to right
<<=>>= Left to right
== != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
?: Left to right
= += *= -= %= ^= != <<= >>= Right to left
, Left to right

Let us consider following example:


Assume a=6 , b=4 and c=9
For the statement z = b-c *a;
Will be evaluated as z = 4-9 *6
z=4-54= -50
In the above expression – and * are two operators. The * operator has
higher priority means precedence than – operator, so as c * a will be
evaluated first, then + will be evaluated.
5 -3 * 4 +6 /4 will be evaluated as 3*4 first, then 6/4,then – operation
and at last + will be evaluated.
5 -3 *4 + 6 / 4
5 – 12 + 6 / 4
5 – 12 + 1
-7 + 1
-6
In an expression we can use the parenthesis to change the order of
evaluation of sub expressions
4 * (3+6) – (4+3) the order of evaluation will be first (3+6), then (4+3)
then 4 * result of (3+6) and finally the – operator will be done.so the
answer will be 29.
TYPE CONVERSION
When variables and constants of different types are combined in an
expression then they are converted to same data type. The process of
converting one predefined type into another is called type conversion. This
can be achieved in 2 ways.
 Implicit Type Conversion
 Explicit Type Conversion
1. Implicit Type Conversion
When the type conversion is performed automatically by the compiler
without developer intervention, such type of conversion is known as
implicit type conversion or type promotion. The compiler converts all
operands into the data type of the largest operand.
Eg:
int i=5;
float f;
f=i;
Here the lower type i automatically converted to the higher type f.
Following rules are applied during type conversion:
1. If one of the operand is long double then other operands will be
converted into long double and result is long double.
2. Else if one of the operand is double, the other will be converted into
double and the result is double.
3. Else if one of the operand is float, the other will converted to float and
the result will be float.
4. Else if one of the operand is unsigned long int, the other will be
converted to unsigned long int and the result will be unsigned long
int.
5. Else if one of the operand is long int and the other is unsigned int
then
a. If unsigned int can be converted to long int, the unsigned int
operand will be converted to long int and the result is long int.
b. Else both operands will be converted to unsigned long int and the
result will be unsigned long int.
6. Else if one of the operands is long int, the other will be converted to
long int and the result will be long int.
7. Else if one of the operand is unsigned int, the other will be converted
to unsigned int and the result will be unsigned int.
Following rules are applied during the assigning the right side value
to left side.
1. When the float value is assigned to int, the fractional part is
truncated.
2. When the double value is assigned to float, rounding of digit is
performed.
3. When long int is assigned to the int, the excess bits are dropped
(Deleted).
2. Explicit Type Conversion
In this method, we can explicitly convert the value of one type to
another. The casting operator is used here. The explicit type
conversion is also known as type casting.
Syntax: (type-name) expression;
Eg:
x=(float)(5+6); explicitly converts the value to float.
The following rules have to be followed while converting the expression
from one type to another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
MATHEMATICAL FUNCTIONS
We should include the header file #include<math.h> in the beginning
of the program for using these mathematical functions.
Function Meaning
Trignometric
acos(x) Arc cosine of x
asin(x) Arc sine of x
atan(x) Arc tangent of x
atan2(x,y) Arc tangent of x/y
cos(x) cosine of x
sin(x) sine of x
tan(x) tangent of x
Hyperbolic
cosh(x) Hyperbolic cosine of x
sinh(x) Hyperbolic sine of x
tanh(x) Hyperbolic tangent of x
Other functions
ceil(x) x rounded up to the nearest integer
exp(x) e to the power x
fabs(x) absolute value of x
floor(x) x rounded down to the nearest integer
fmod(x,y) remainder of x/y
log(x) natural log of x, x>0
log10(x) base 10 log of x.x>0
pow(x,y) x to the power y
sqrt(x) square root of x,x>=0

MANAGING INPUT AND OUTPUT OPERATIONS


All input/Output operations are carried out through functions printf and
scanf. These functions are collectively known as standard i/o library
functions and comes under the header file #include<stdio.h>
Reading a Character: Reading a single character can be done by using the
function getchar ().
Syntax: variable_name = getchar();
Eg: char name;
name=getchar();
Program
/*Reading a character from terminal*/
#include <stdio.h>
int main ()
{
char c;
printf("Enter character: ");
c = getchar();
printf("Character entered: ");
putchar(c);
return(0);
}
Output
Enter character: a
Character entered: a
Writing a Character: The function putchar is for writing character one at a
time to the terminal. It takes the form as shown below:
Synatx: putchar (variable_name);
Eg: answer=‘y‘;
putchar(answer);
will display the character y on the screen. The statement
putchar(„\n‟);would cause the cursor on the screen to move to the
beginning of the next line.
Program /*Writing a character to the screen*/
#include <stdio.h>
int main ()
{
char c;
printf("Enter character: ");
c = getchar();
printf("Character entered: ");
putchar(c);
return(0);
}
Output
Enter character: a
Character entered: a
Formatted Input
The formatted data can be read with the help of scanf function.
Syntax: scanf(“control string”,arg1,arg2….argn);
 control string specifies the field format in which the data is to be
entered
 arguments arg1,arg2...argn specifies the address of locations
where the data are stored
 Control strings and arguments are separated by commas.
Inputting integer numbers:
The field specification for reading an integer number is: %wd
Eg: scanf(“%2d %5d”,&num1, &num2);
Program
#include<stdio.h>
int main()
{
int c;
printf("Enter a number\n");
scanf("%d",&c);
printf("Number=%d",c);
return 0;
}
Output
Enter a number 4
Number = 4
Inputting Real Numbers:
scanf reads real numbers using simple specification:%f
Eg: scanf(“%f %f %f”, &x, &y, &z);
And for double type, the specification should be %lf instead of simple %f.
Program
#include<stdio.h>
int main()
{
float a;
printf("Enter value: ");
scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d
return 0;
}
Output
Enter value: 23.45
Value=23
Inputting Character Strings:
Following are the specifications for reading character strings:
%ws or %wc
Reading Mixed Data Types:
It is possible to use one scanf statement to input all types of data.
Eg: scanf(“%d %c %f %s”,&count, &code, &ratio, &name);
Scanf Format Codes
Code Meaning
%c Read a single character
%d Read a decimal integer
%e Read a floating point value
%f Read a floating point value
%g Read a floating point value
%h Read a short integer
%i Read a decimal, hexadecimal, or octal
%o integer
%s Read an octal integer
%u Read a string
%x Read an unsigned decimal integer
%[..] Read a hexa decimal integer
Read a string of word(s)

Formatted Output
The formatted data can be written with the help of printf function.
Syntax: printf(―control string‖,arg1, arg2…argn);
Control string consists of three types of items:
 Characters that will be printed on the screen as they appear.
 Format specifications that define the Output format for display of
each item.
 Escape sequence characters such as \n, \t and \b
Output of integer Numbers:
The format specification for printing an integer number is%wd
Output of Real Numbers:
The Output of real numbers may be displayed in decimal notation using the
following format specification:%w.p f
We can also display real numbers in exponential notation by:%w.p e
Printing of Single Character:
A single character can be displayed in a desired position using the format:
%wc
Printing of Strings:
The format specification for Outputting strings is of the form%w.ps
Mixed Data Output:
It is permitted to mix data types in one printf statements.
Eg:printf(“%d %f %s %c”,a, b, c, d);
UNIT-II
DECISION MAKING AND BRANCHING
To change the flow based on the certain conditions, we are using the
Decision Making statement or control statement. ‗C‘ supports the following
control statement or decision-making statement:
1. „if‟ statement
2. „switch‟ statement
3. Conditional Operator statement
4. „goto‟ statement
1. „if‟ Statement: -It has following forms:
 simple if
 if..else
 nested if..else
 if..else..if
simple „if‟ Statement: -
Syntax :
if(test condition)
{
Block Statement-1
}
Statement-2
If the condition is true ‗Block Statement-1‘ will be executed and it
follows ‗Statement-2‘ execution. If condition is false directly
‗Statement-2‘ will be executed.
Ex
int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
Output: m and n are equal

„if...else‟ Statement: - It is extension of the ‗if‘ statement. Its format


is:
if(test condition)
{
Block Statement-1
}
else
{
Block Statement-2
}
Statement-3
If the condition is true then computer execute the ‗Block Statement-1‘.
If condition is false then computer will execute ‗Block Statement-2‘.
After executing either ‗Block Statement-1‘ or ‗Block Statement-2‘ it will
execute the ‗Statement-3‘.
Example
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output m and n are not equal
Nested „if...else‟ Statement: -‗if...else‘ statement with in another
‗if...else‘ statement is said to be nested ‗if...else‘ statement.
Syntax
if(test condition-1)
{
if(test condition-2)
{
Block Statement-1
}
else
{
Block Statement-2
}
}
else
{
Block Statement-3
}
Statement-4
If the condition is true then it checks another ‗test condition-2‘. If ‗test
condition-2‘ is true then it will execute ‗Block Statement-1‘ otherwise
execute the ‗Block Statement-2‘.
If ‗test-condition1‘ is false then it will execute ‗Block Statement-3‘.
After completing the nested ‗if...else‘ statement execution computer
will execute ‗Statemetn-4‘.

Example
#include <stdio.h>
int main()
{
int m=40, n=20;
if (m != n)
{
printf("m is not equal to n\n");
if (m > n)
{
printf("m is greater than n\n");
}
else
{
printf("m is greater than n\n");
}
}
else
{
printf("m is equal to n\n");
}
return 0;
}
Output m is greater than n
„if...else if‟ Statement
It is used to make multipath decisions. Multipath decision involves chain
of ‗if‘ with ‗else if‘. The format of this statement is:
if(test condition-1)
{
Block Statement-1
}
else if(test condition-2)
{
Block Statement-2
}
else if(test condition-3)
{
Block Statement-3
}
else
{
Block Statement-4
}
Statement-5
If the condition is true then computer will execute ‗Block Statement-1‘
otherwise it will check the ‗test condition-2‘.If the condition is true then
computer will execute ‗Block Statement-2‘ otherwise it will check the ‗test
condition-3‘.
If condition is true then it will execute ‗Block Statement-3‘ otherwise it
will execute ‗Block Statement-4‘.
Flowchart

False
test
condition-1
True

test False
condition-2
True

False
Block Statement-1 test
condition-3
True

Block Statement-2

Block Statement-3

Block Statement-4

Statement-5

Example:
#include <stdio.h>
int main()
{
int percentage;
printf(―Enter percentage=‖);
scanf‖(―%d‖,&percentage);
if(percentage >=70)
{
printf(―Distinction\n‖);
}
else if(percentage >= 60)
{
printf(―First Class\n‖);
}
else if(percentage >= 50)
{
printf(―Second Class\n‖);
}
else if(percentage >=40)
{
printf(―Pass Class\n‖);
}
else
{
printf(―Fail\n‖);
}
}
Output
Enter percentage= 80
Distinction

2. „switch‟ Statement
Switch case statements are used to execute only specific case statements
based on the switch expression. This is a multiple or multi-way branching
decision making statement.
Rules for declaring switch case:
 The case label should be integer or character constant.
 Each compound statement of a switch case should contain break
statement to exit from case.
 Case labels must end with (:) colon.
Advantages of using switch case:
 Easy to use and to find out errors.
 Debugging is made easy in switch case.
 Complexity of a program is minimized.
The general form is:
switch(variablename)
{
case v1 :Block Statement-1
break;
case v2 :Block Statement-2
break;
case v3 :Block Statement-3
break;
default :Block Statement-4
break;
}Statement-5
Here if the value of variable= = v1 then ‗Block Statement-1‘ will be executed.
If variable= = v2 then ‗Block Statement-2‘ will be executed. If at last no
match found for the variable then default statement is executed. Here we
have to put the ‗break‘ statement to complete the execution of ‗switch‘.

variable
for match

= =V1 = =V2 = =V3 default

Block Block Block Block


Statement- Statement- Statement- Statement-
1 2 3 4

Statement-5

Example:
#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(―Value is 1 \n‖ );
break;
case 2:
printf(―Value is 2 \n‖ );
break;
case 3:
printf(―Value is 3 \n‖ );
break;
case 4:
printf(―Value is 4 \n‖ );
break;
default :
printf(―Value is other than 1,2,3,4 \n‖ );
}
return 0;
}
Output: Value is 3
3. Conditional Operator OR ?: Operator
‗C‘ provides the facility of the operator to check the condition by using the
conditional operator having three operands.
Syntax: (Condition)? Statement1 : Statement2
If condition is true then statement1 will be executed otherwise
statement2 will be executed. Here you can also represent the
condition for assignment operation:
variable = (Condition)? Value1 : Value2
Example:
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}
Output:
Enter the Number: 4
Even
The advantage of the conditional operator is that you can represent the
condition in shorter form.
4. „goto‟ Statement
 goto statements is used to transfer the normal flow of a program to
the specified label in the program.
 In ‗goto‘ statement label is used to indicate at which position you
have to make the jump. Label ends with the colon (:).
 Whenever you have to make the jump you have to write statement
goto Label.
 There are two kind of jump performed by goto:
 Forward jump: Here the jump is made to the next following
statements. If label is after the ‗goto‘ statement then this kind of
situation is arise.
goto LABEL;
………………
………………
LABEL :
 Backward jump: Here the jump is made to the previous statements.
When label is before the ‗goto‘ statement then this kind of situation is
arise. The syntax of backward jump is,
LABEL :
………………
………………
………………
goto LABEL;
Consider the following example to understand ‗goto‘ statement,
int main()
{
int age;
Vote:
printf("You are eligible for voting");
NoVote:
printf("You are not eligible to vote");
printf("Enter you age:");
scanf("%d", &age);
if(age>=18)
goto Vote;
else
goto NoVote;
return 0;
}
Output:
Enter you age: 20
You are eligible for voting
Disadvantages of goto:
1. Some compiler generates less efficient code if you are using ‗goto‘
statement.
2. Your program becomes unreadable.
3. Program logic becomes complicated and program becomes less
understandable.
DECISION MAKING AND LOOPING
Loop is used to execute the certain block of code repeatedly until some
conditions are satisfied, i.e., loops are used in performing repetitive work in
programming.
Suppose you want to execute some code/s 100 times. You can perform it by
writing that code/s only one time and repeat the execution 100 times using
loop.There are mainly two kinds of loops:
Entry-controlled loop
In entry-controlled loop, the test condition is checked first before the loop is
executed. If the condition is false then the body of loop is not executed.
Some common examples of this looping statement are:
 while loop
 for loop
Exit-controlled loop
In exit-controlled loop, the loop is executed first and then the condition is
checked. Here the loop is executed at least one time compulsorily. Some
common example of this looping statement is:
 do-while loop
i. for Loop
 This is an entry controlled looping statement.
 In this loop structure, more than one variable can be initialized.
 One of the most important features of this loop is that the three
actions can be taken at a time like
 variable initialization,
 condition checking and
 increment/decrement
Syntax:
for(initialization; test expression; increment/ decrement)
{ Body of the loop; }

Example:
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}
Output: 0123456789

Nested For Loops


Nesting of loops is also possible. In the below example we have nested for
loop inside another for loop, this is called nesting of loops. Such type of
nesting is often used for handling multidimensional arrays.
Example
main()
{
for (int i=0; i<=10; i++)
{
for (int j=0; j<=10; j++)
{
printf("%d, %d",i ,j);
}
}
}
ii. while loop:
 This is an entry controlled looping statement.
 It is used to repeat a block of statements until condition
becomes true.
Syntax:
while (test expression)
{
statements to be executed.
}
In above syntax, the condition is checked first. If it is true, then it
executes the block of statements associated with it. This process
continues until test condition satisfies.
Flowchart:

Example:
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
}
Output: 3456789
iii. do...while loop
 This is an exit controlled looping statement.
 In this, block of statements are executed first and then condition is
checked.
Syntax:
do
{
statements;
} while (test expression);
In above syntax, first the block of statements is executed, at the end of loop,
while statement is executed. If the resultant condition is true then the body
of a loop will be executed once again. This process continues till the
condition becomes true. When it becomes false, then the loop terminates.

Example
#include <stdio.h>
int main()
{
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);
}
Output
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4

S.no while do while


1 Loop is executed only Loop is executed for first time
when condition is true. irrespective of the condition. After
executing while loop for first time,
then condition is checked.
2 Entry controlled loop Exit controlled loop
break Statement:
It is used to terminate the loop immediately after it is encountered. The
break statement can be used in terminating all three loops for, while and
do...while loops.
Syntax: break;

Example
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(―\nComing out of for loop when i = 5″);
break;
}
printf(―%d ―,i);
}
}
Output: 01234
Coming out of for loop when i = 5
Continue Statement:
It is sometimes desirable to skip some statements inside the loop. In such
cases, continue statements are used. Just like break, continue is also used
with conditional if statement.
Syntax: continue;
Example: #include <stdio.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
}
printf("%d ", j);
}
Output: 0123567

ARRAYS
An array is a collection of elements of the same data type.
Eg: List of employees in an organization
List offruits in a basket
Types
 One-dimensional arrays
 Two-dimensional arrays
 Multidimensional arrays
One Dimensional Array: An array with a single subscript is known as one
dimensional array.
Declaration of one-dimensional array: data_type array_name[array_size];
For Example: int age[5];
Here, the name of array is age. The size of array is 5.All elements in an
array are of the same type (int, in this case).
Array elements:
Size of array defines the number of elements in an array. Each element of
array can be accessed and used by user according to the need of program.

Initialization of one-dimensional array: Arrays can be initialized at


declaration time in this source code as: int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during initialization.
int age[]={2,4,34,3,4};

Accessing array elements: In C programming, arrays can be accessed and


treated like variables.
For Example:
scanf("%d",&age[2]);- statement to insert value in the 3rd element of
array age[].
scanf("%d",&age[i]); - Statement to insert value in (i+1)th element of
array age[].
printf("%d",age[0]); -statement to print first element of an array.
printf("%d",age[i]); -statement to print (i+1)th element of an array.
Example:
#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
for (i=0;i<5;i++)
{
printf(―value of arr[%d] is %d \n‖, i, arr[i]);
}
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Two-dimensional arrays: Array with two subscripts is called as two-
dimensional array. It can be declared as follows
type array- name[row_size][column_size];
Example:
#include<stdio.h>
int main()
{
int i,j; // declaring and Initializing array
int arr[2][2] = {10,20,30,40};
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
printf(―value of arr[%d] [%d] : %d\n‖,i,j,arr[i][j]); // Accessing
variables
}
}
}
Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40
Multidimensional arrays: C programming language allows creating arrays
of arrays known as multidimensional arrays.
For Example: float a[2][6];
Here, a is an array of two dimension, which is an example of
multidimensional array. This array has 2 rows and 6 columns

Initialization of Multidimensional Arrays: In C, multidimensional arrays


can be initialized in different number of ways.
int c[2][3]={{1,3,0}, {-1,5,9}}; or int c[][3]={{1,3,0}, {-1,5,9}};
or
int c[2][3]={1,3,0,-1,5,9};
Eg: Initialization Of three-dimensional Array:
double cprogram[3][2][4]={
{ {-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2} },
{ {0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1} },
{ {8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0} }
};
Example: Write a C program to find sum of two matrix of order 2*2
#include<stdio.h>
void main()
{
int a[2][2],b[2][2],c[2][2],i,j;
clrscr();
printf("Enter the value of First 2 x 2 Matrix : ");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the value of Second 2 x 2 Matrix : ");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("Sum of Two Matrix : %d\n",c[i][j]);
}
}
getch();
}
Output:
Enter the value of First 2 x 2 Matrix : 2 2 2 2
Enter the value of Second 2 x 2 Matrix : 3 3 3 3
Sum of Two Matrix :
5 5
5 5
Dynamic and Static Arrays
The process of allocating memory at compile time is known as static memory
allocation and the arrays that receive static memory allocation are called
static arrays.
The process of allocating memory at run time is known as dynamic memory
allocation and the arrays that receive dynamic memory allocation are called
dynamic arrays.
Dynamic arrays are created using what are known as pointer variables and
memory management functions malloc, calloc and realloc. These functions
are included in the header file <stdlib.h>.
CHARACTER ARRAYS AND STRINGS
An array of characters enclosed within double quotes (― ―) are called strings.
A string is terminated by null character \0.
For Example: " c string tutorial "
Here, "c string tutorial" is a string. When, compiler encounters strings,
it appends null character at the end of string.

The common operations performed on character strings are:


1. Reading and writing strings
2. Combining strings together
3. Copying one string to another
4. Comparing strings for equality
5. Extracting a portion of the string
Declaring and Initializing String
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is
that, strings are of char type.
Syntax: char string_name[size];
Eg: char s[5];

Strings can also be declared using pointer.


Eg char *p
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd"; OR,
char c[5]="abcd"; OR,
char c[]={'a','b','c','d','\0'}; OR;
char c[5]={'a','b','c','d','\0'};

String can also be initialized using pointers aschar *c="abcd";


Writing/printing String to Screen
i. Using printf function
To print the string we are using same ‗printf‘ function but we have to specify
the Output format as „%s‟
printf(―%s‖, string_name);
Eg
char name[20] = ―indian‖;
printf(―%s\n‖, name);
Above statement print the string ‗name‘. Output is ―indian‖.
We can also format the Output of string as under: %w.ps
Here ‗w‘ indicates the total width, ‗p‘ indicates no. of characters you want to
print, and ‗s‘ indicate we are printing string value.
Eg
char str[100]=‖indian‖;
printf(―%10.4s‖, str);
Here in Output we are getting total width=10 but the Output character is
only 3 that is ―ind‖ since we have ‗p‘ value =3.
ii. Using putchar and puts functions
We can also use ‗puts‘ function to print the string.
puts(string_name);
Eg puts(name);
It will print the value of variable ‗name‘ with new line at end.
iii.putchar takes the general form:
It will print the value of variable ‗ch‘.
char ch=‘a‘;
putchar(ch);
Reading String from terminal
i . Using scanf function
To read we can use same ‗scanf‘ function: scanf(“%s”, string_name);
But here we need not put ‗&‘ operator because string variable automatically
determine its address.
ii. Using getchar and gets function
1. We have to read the entire string character by character in loop up to
we is not entering new line character. At the end of string we have to
explicitly put the null character to indicate the end of string.
char c, name[100];
int i=0;
do
{
c=getchar( ) ;
name[i] = c;
i++;
} while (c != ‗\n‘);
name[i] = ‗\0‘;
2. We have to use ‗gets‘ function which read the string up to new line.
char name[100];
gets( name ) ; // this will read the string up to new line
Reading a line of text
We can use same scanf function with formatting to read the string.
scanf(“%[^\n]”, name);
Here we have used %[^character] format. It means your computer read the
strings up to you are not entering the new line character.
„atoi( )‟ function: -
This function is used to convert string into number. The format of this
function is:
int atoi(string);
We have to pass the string as argument and function returns integer
equivalent to string.
Eg int a;
a = atoi(―123‖);
Here after executing above statement variable ‗a‘ contains number 123.
int a;
a = atoi(―123H45‖);
If you insert any non digit character in between your number string the
conversion is truncated when your computer encounter non digit character.
Here value of ‗a‘ is123 only.
int a;
a = atoi(―F123‖);
If your string contains first character as non-digit character then the return
value is zero. Here the Output of ‗a‘ is 0.
STRING HANDLING FUNCTION
In C, we cann‘t assign one string value into another directly by using
assignment operator. Also we cannot compare two strings with using equal
to operator (==). Similarly the joining of two strings cannot possible by using
simple addition operator (+). For that purpose C provides some special
function. These all functions are included into <string.h> header file.
The more commonly-used string functions are:
 strcat - concatenate two strings
 strcmp - compare two strings
 strcpy - copy a string
 strlen - get string length
 strrev- reverses a string
1. strcat( ) function
strcat( ) function concatenates two given strings. It concatenates source
string at the end of destination string.
Syntax :
strcat(str2,str1);- str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char s1[ ] = " jass" ;
char s2[ ]= " ritha" ;
printf ( "\ns1 = %s", s1 ) ;
printf ( "\ns2 = %s", s2 ) ;
strcat ( s1, s2 ) ;
printf ( "\nAfter concatenation strcat( ) = %s", s1 ) ;
}
Output:
s1=jass
s2=ritha
After concatenation strcat( )=jassritha
2. strlen( ) function
strlen() function counts the number of characters in the given string and
returns the length of the string as integer value. The format of the function
is:
int n=strlen(string);
Eg
#include <stdio.h>
#include <string.h>
int main( )
{
int n;
char name[]=‖kavi‖;
n = strlen(name); // Gives the length of string
printf(―Length of string = %d\n‖, n);
}
Output: Length of string =4
3. strcpy( ) function
This function is used to copy or assign the value of one string into another
string. This function contains two arguments and returns nothing.
void strcpy(string1, string2);
Eg
#include <stdio.h>
#include <string.h>
int main( )
{
char s1[100] = ―jass‖;
char s2[100];
strcpy(s2,s1); // Copy the value of str1 into str2
printf(―Copied string=%s‖,s2);
}
Output: Copied string= jass
4. strcmp( ) function
 strcmp() function is used to compare two strings.
 strcmp() function does a case sensitive comparison between two
strings.
 If the two strings are equal it returns 0 else returns non-zero
value.
The format of function is: int n= strcmp ( string1, string2);
Example:
#include <stdio.h>
#include <string.h>
int main( )
{
char s1[ ] = " jass" ;
char s2[ ] = "joss " ;
int i;
printf ( "\ns1 = %s", s1 ) ;
printf ( "\ns2 = %s", s2 ) ;
i= strcmp ( s1, s2 ) ;
if(i==0)
printf(―strings are equal‖);
else
printf(―strings are unequal‖);
}
Output: strings are unequal
5. strrev( ) function
This function is used to reverse the given string. The format of function is:
strrev ( string);
Example
#include<stdio.h>
#include<string.h>
void main()
{
char str[10];
gets(str);
printf(―Reverse string=%s‖, strrev(str));
}
Output: kavi
Reverse string=ivak
Some other String Handling Functions:
 strncpy ( ) copies given number of characters of one string to
another
 strncat ( ) appends a portion of string to another
 strrstr ( ) Returns pointer to last occurrence of str2 in str1.
 strlwr ( ) converts string to lowercase
 strupr ( ) converts string to uppercase
UNIT III

Definition: OOPs:-
Oops is an Object Oriented Programming which is a way to modularize
programs by creating partitioned memory area for both data and functions.

FEATURES OF OOPs:
• Emphasis is on data rather than procedure.
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the
data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.
Organization of data and function in oops:
PROCEDURE-ORIENTED PROGRAMMING (POP)
In the procedure oriented approach, the problem is viewed as the
sequence of things to be done such as reading, calculating and printing
such as Cobol, Fortran and C.

FEATURES OF POPs:
• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as
functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design.

OBJECT ORIENTED Vs PROCEDURE ORIENTED


S.No Object oriented Procedure Oriented
programming programming
1. The program is written as a The program is written as a
collection of objects which logical structure.
communicate with each
other.
2. The basic entity is object. The flow of the execution of the
Each computation is object is dependent on the
performed using objects structure of the program.
only.
3. Data is given more Code is given more importance.
importance.
4. Can handle very complex Can handle up to moderately
programs. complex programs.
5. More data security. Less data security.
6. More code reusability. Less code reusability.
7. Flexibility is more. Flexibility is less.
8. Abstraction is more. Abstraction is less.
9. This is a bottom up This is a top down approach.
approach.
BASIC CONCEPTS OF OOPS:

The basic concepts of oops are:


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

1. OBJECTS:
 Objects are the basic run time entities.
 It has certain properties and method.
 It may represent a person, a place, a bank account, a table of data or
any item that the program has to handle.
 It may also represent user-defined data such as vectors, time and
lists.
 Objects take up space in the memory and have an associated address.
 Each class can have a number of objects.
Example:
Object :
Employee
Data:
Name
Address
Salary
Functions:
Working time
Total salary
Pending

2. CLASS:
 A class is a collection of objects of similar types.
 Objects are the variable of the type class.
 Class is a user defined data type.
 Once a class has been defined, we can create any number of
objects to that class.
 Each object is associated with the data of type class.
 For examples, Mango, Apple and orange are members of class
fruit.
 Classes are user-defined types that behave like built-in types. If
fruit has been defined as a class, then the statement
fruit mango;

will create an object mango belonging to the class fruit.

 Class is similar to structure in c.

3. DATA ABSTRACTION:
 Abstraction refers to the act of representing essential features
without including the background details or explanation.
 The attributes are sometimes called as data members.
 The functions that operate on these data are called as methods
or member function.
 The classes which use the concept of data abstraction are
known as Abstract Data Types (ADT).
Example: Flight which is invented based on the fly of birds.

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 object‘s data
and the program.
 This insulation of the data from direct access by the program is
called data hiding or information hiding.
5. POLYMORPHISM:
 Polymorphism is a Greek term.
 Polymorphism means the ability to take more than one form.
 It allows us to have more than one function with the same name
in a program.
 A single function name can perform the several task is called
function overloading.
 The process of making operator to exhibit different behaviours
in different instance is called operator overloading.
Example:
6. INHERITANCE:
 Inheritance is the process by which objects of one class acquire
the properties of objects of another classes.
 It supports the concept of hierarchical classification.
 In OOP, the concept of inheritance provides the idea of
reusability.
 This means that we can add additional features to an existing
class without modifying it.

7. DYNAMIC BINDING:

 Binding refers to the linking of a procedure call to the code to


be executed in response to the call.
 Dynamic binding or Late binding means that the code
associated with a given procedure call is not known until the
time of the call at run time.
 Static binding or Early binding means that the code
associated with a given procedure call is known at the time of
call at compile time.
 It is associated with polymorphism and inheritance.
8. MESSAGE PASSING:
 Objects can communicate one another by sending and receiving
information. The steps are as follow:
1. Creating classes that define object and their
behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
 Object has a life cycle. They can be created and destroyed.
BENEFITS OF OOPs

The advantages are:


1. Through inheritance, we can eliminate redundant code extend the use
of existing classes.
2. We can build programs from the standard working modules that
communicate with one another that lead to saving of development
time and higher productivity.
3. The principle of data hiding helps the programmer to build secure
program.
4. It is possible to have multiple instances of an object to co-exist
without any interference.
5. It is possible to map object in the problem domain to those in the
program.
6. It is easy to partition the work in a project based on objects.
7. The data-centered design approach enables us to capture more detail
of a model can implemental form.
8. Object-oriented system can be easily upgraded from small to large
system.
9. Message passing techniques for communication between objects
makes to interface descriptions with external systems much simpler.
10. Software complexity can be easily managed.
APPLICATIONS OF OOPS
The applications of OOPs include:
• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems
PRINCIPLES OF OOP
The principles that make language Object Oriented are
 Encapsulation,
 Data Abstraction,
 Polymorphism and
 Inheritance.
OBJECT ORIENTED LANGUAGE
Based on the features, they can be classified into the following two
categories:
1. Object-based programming languages, and
2. Object-oriented programming languages.
Object-based programming is the style of programming that primarily
supports encapsulation and object identity. Major feature that are required
for object based programming are:
• Data encapsulation
• Data hiding and access mechanisms
• Automatic initialization and clear-up of objects
• Operator overloading
Languages that support programming with objects are said to the objects-
based programming languages. They do not support inheritance and
dynamic binding. Ada is a typical object-based programming language.
Object-oriented programming language incorporates all of object-based
programming features along with two additional features, namely,
inheritance and dynamic binding. Object-oriented programming can
therefore be characterized by the following statements:
Object-based features + inheritance + dynamic binding
Introduction of C++
 C++ is an object-oriented programming language.
 It was developed by Bjarne Stroustrup at AT&T Bell
Laboratories in Murray Hill, New Jersey, USA, in the early
1980‘s.
 C+ + is a superset of C.
 The most important facilities that C++ adds on to C are
classes, inheritance, function overloading and operator
overloading.
Application of C++
C++ is a versatile language for handling very large programs; it is suitable
for virtually any programming task including development of editors,
compilers, databases, communication systems and any complex real life
applications systems.
 C++ allows us to create hierarchy related objects.
 C++ is able to map the real-world problem properly
 C++ programs are easily maintainable and expandable.
FUNCTION

 Functions are reusable code segment that perform specific task.


 Functions are the basic building blocks of C++.
 Functions provide modular structure to a program.
 Functions help to divide a larger program into number of
smaller units which is the basis of top down approach.
Advantages of Functions
 Functions provides Reusability
 Reduce the size of program
 Functions give modular structure to a program
 Writing functions make programming easy

Need for a Function


 A larger program becomes difficult to understand.
 For this reason functions are used.
 Reduction in program size is another reason for using functions.
 The functions code is stored in only one place in memory, even
though it may be executed as many times as a user needs.
The main function:
 The main( ) function is the starting point for the execution of a
program.
 The definition of main( ) is
main( )
{
main program statements
}
 In C++, the main( ) returns a value of int to the operating system.
 The functions that have a return value should use the return
statement for termination.
 The main( ) function in C++ is defined as,
int main( )
{
………
………
return 0;
}
Function Prototype:

 Function Prototype is a declaration statement in the calling


program.
 It gives the details such as number, type of argument & its
return type.
 When a function is called, compiler ensures that proper
argument & return type is returned correctly.

Syntax: type fun-name(argument list);

Example: float volume(int, float h, float r);

The function can be called using the syntax fun-name(argument


values);

Example: volume(10, 12.5, 25.5)


Function definition as the following general form.
Syntax: type function name (argument list)
{
function body
}
Example: float volume(int a, float b,float c)
{
float v=a*b*c;
return;
}
INLINE FUNCTION
An inline function is a function that is expanded in a line when it is
invoked.
Syntax:
inline function - header
{
function body
}
Example:
inline double cube(double a)
{
return (a*a*a);
}
This inline function can be invoked as c= cube (3.0);
d= cube (2.5+1.5);
 All inline function must be defined before they called.
 The inline keyword sends a request not a command to the
compiler.
 The compiler may ignore the request if the function definition in
too complicated and compiler treat it as normal function.

The inline function does not work for the following situations:
 For functions returning values and having a loop or a switch or a
goto statement.
 For functions that do not return value and having a return
statement.
 For functions having static variable(s).
 If the inline functions are recursive (i.e. a function defined in terms
of itself).

Advantage of inline function:


 Better than a macro.
 Function call overheads are eliminated.
 Program becomes more readable.
 Program executes more efficiently.
Example:
#include<iostream.h>
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{
return(x*x*x);
}
void main()
{
float a=2.0;
float b=3.0;
clrscr();
cout<<"\nMultiplication value is:"<<mul(a,b);
cout<<"\n\nCube value is :"<<cube(a)<<"\t"<<cube(b);
getch();
}
Output:
Multiplication Value is: 6.00
Cube Value is: 8.000 and 9.000
FUNCTION OVERLOADING

 Overloading refers to the use of same things for different purpose.


 Function overloading means that the use of same function name to
create a function that performs different tasks.
 A function is overloaded when same name is given to different
function. However, the two functions with the same name will differ at
least in one of the following.
 The number of parameters
 The data type of parameters
 The order of appearance
 These three together are referred to as the function signature.
Example: int add (int);
float add();
double add (int , int);
Example:
#include<iostream.h>
int add(int);
float add (int,float);
float add (int,float,float);
int main()
{
cout<<add(10)<<endl;
cout<<add(2,3.5) <<endl;
cout<<add(2,2.5,2.5) <<endl;
return 0;
}
int add (int a)
{
return (a+10);
}
float add (int a,float b)
{
return(a*b);
}
float add (int a,float b,float c()
{
return(a+b+c);
}
Output
20
5.5
7.0
CLASS AND OBJECT
What is a Class?
 Class is a collection of similar types of objects
 Class consists of Data members and methods.
 A class is an abstract data type similar to 'C' structure.
Specifying a Class

 A class is a way to bind the data and its associated functions


together. A class specification has two parts:

1. Class declaration
2. Class function definitions
 The class declaration describes the type and scope of its
members.
 The class function definitions describe how the class functions
are implemented.
 In the class declaration, member functions and variables can be
given different access restrictions:
public: access from any function,
protected: access from this class‘s and sub-class functions only,
private: access from this class‘s functions only,

The general form of a class declaration is:


class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

 The class declaration is similar to a struct declaration.


 The body of a class is enclosed within braces and terminated by
a semicolon.
 The class body contains the declaration of variables and
functions. These functions and variables are collectively called
class members.
 The class members are usually grouped under two sections
private and public. These keywords private and public are
known as visibility labels. These keywords are followed by a
colon.
 The class members that have been declared as private can be
accessed only from within the class.
 The public members can accessed from outside the class also.
 The use of the keyword private is optional.
 By default the members of a class are private.
 The variables which declared inside the class are known as
data member.
 The functions which declared inside the class are called as
member functions.
 The binding of data and functions together into a single class-
type is referred to as encapsulation.
Data Hiding of a Class

Example:
class A
{
int a,b;
pubilc:
void add()
{
int c=a+b
}
};
Creating Objects
 Once a class has been declared, we can create variables of that type
by using the class name.
 The declaration of object in C++ is similar to declaration of variables .
 To create an object; use the class name as type specifier.
Syntax: <class name> objectname ;
Example: item x;

Creates a variable x of type item. In C++, class variables are known


as objects. Therefore x is called an object of type item. It may possible to
declare more than one object in one statement.
Example: item x, y, z;
Accessing Class Members

Once an object of a class has been created, the program can reference
its public members by using the dot operator in the same way as that
structure members are accessed.

Syntax: object name . functionname(arguments);


objectname.variablename;
The class members can be accessed by using dot operator.
Example: x.getdata(100, 56.6);
x. putdata( );
MEMBER FUNCTION
The function within a class is said to be member function. The member
functions can be defined in two places:
1. Inside class definition
2. Outside class definition
Inside Class Definition:
 When a member function is defined inside a class, we do not require
placing a membership label along with the function name.
 We use only small functions inside the class definition and such
functions are known as inline functions.
Example:
class item
{
int number;
public:
void getdata(int a);
void putdata()
{
cout<<number<<endl;
}
};
Outside Class Definition:
 Member functions that are declared inside a class have to be defined
separately outside the class. Their definitions are very much like
normal functions.
Syntax
return_type class-name::function_name (argument list)
{
Function body
}
Here the operator :: is known as scope resolution operator helps in
defining the member function outside the class.
Example:
void item:: getdata(int a)
{
number=a;
}
void item:: putdata()
{
cout<<number<<‖\n‖;
}
Characteristics of member functions
 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 cannot do so.
 A member function can call another member function directly,
without using the dot operator.
Example Program Using Class and Object:
# include<iostream.h>
class test
{
int x;
pubilc:
void get() // Function defined inside class
{
cin>>x;
}
void dis();
};
void test :: dis() // Function defined outside class
{
cout<<"x="<<x;
}
int main()
{
integer obj;
cout<<"Enter a value";
obj.get();
obj.dis();
return 0;
}

Output: Enter a value 36


x=36

Making an outside function Inline


We can define a member function outside the class definition and still
make it inline by just using the qualifier inline in the header line of function
definition.
Syntax:
inline return type class name:: function name(arg)
{
function body;
}
Example:
class item
{

pubilc:
void get data(int,int); //declaration
};
inline void:: item get data (int x,int y) //definition
{
a=x;
b=y; }
ARRAY OF OBJECTS
Array of variable that are of the type class are called as array of objects.

Syntax: class_ type array_name[size];

Example:

#include<iostream.h>
class item
{
char sname[10]; // Character Array within Class
public:
void getdata();
void putdata();
};
void item::getdata()
{
cin>>sname;
}
void item::putdata()
{
cout<<sname<<"\n";
}
int main()
{
item a[5]; // Array of objects
cout<<"Enter 5 student names";
for(int i=0; i<5; i++)
a[i] .getdata();
cout<<"Entered names are";
for(int i=0; i<5; i++)
a[i].putdata();
return 0;
}
Output
Enter 5 student names
Arun
Kavi
Jaas
Sarva
Ram
Entered names are
Arun
Kavi
Jaas
Sarva
Ram
STATIC DATA MEMBERS
A data member of a class can be qualified as static.
Characteristics of Static Data Member
 It is initialized to zero when the first object of its class is created. No
other initialization is permitted.
 Only one copy of that member is created for the entire class and is
shared by all the objects of that class, no matter how many objects are
created.
 It is visible only within the class, but its lifetime is the entire program.
 Static variables are normally used to maintain values common to the
entire class.
Example
#include <iostream.h>
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number = a;
count ++;
}
void getcount(void)
{
cout << "Count: ";
cout << count <<"\n";
}
};
int item :: count;
int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout << "After reading data"<<"\n";
a.getcount();
b.getcount();
c.getcount();
return 0;
}
Output
Count: 0
Count: 0
Count: 0
After reading data
Count: 3
Count: 3
Count: 3
STATIC MEMBER FUNCTIONS
Like static member variable, we can also have static member function. A
member function that is declared static has the following properties:
• A static function can have access to only static members declared in
the class.
• A static member function can be called the class name as follows:
class-name :: function-name();
Example:
#include <iostream.h>
class test
{
static int count; //static member variable
int code;
public:
void setcode()
{
code=++count;
}
void showcode(void)
{
cout << "object number:"<<code<<‘\n‖;
}
static void showcount(void) //static member function
{
cout << ―count:‖<<count <<"\n";
}
};
int test :: count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount(); //accessing static function
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
return 0
}
Output
Count: 2
Count: 3
object number: 1
object number: 2
object number:3
FRIEND FUNCTION
 A friend function in C++ is a function that is declared outside a class
but is capable of accessing the private and protected members of the
class.
 Friend functions are declared using the friend keyword inside the
body of the class.
 The function definition does not use either keyword friend or the
scope operator ::
Syntax:
class ABC
{
.....
.....
public:
.....
.....
friend void xyz(void);
};
Special Characteristics of Friend Functions
 The function that is declared as friend will not fall in the scope of the
class it was declared.
 A friend declaration can be placed in either the private or the public
part of a class declaration
 Like a member function, a friend function is explicitly declared in the
declaration of the class of which it is a friend
 A friend function can access private data members of that class.
 A friend function will be called without the object.
 Usually friend function takes object as an argument.
Example:

include<iostream.h>
class sample
{
int a,b;
public:
void set()
{
a=10;
b=20;
}
friend int dis(sample s);
};
int dis (sample s)
{
return int(s.a+s.b);
}
int main()
{
sample x;
x.set();
cout<<"sum ="<<dis(x);
return 0;
}
OUTPUT sum =30
OVERLOADING MEMBER FUNCTIONS
To overload member functions, you must use the same function name for all
of the functions, but the parameters must be different. The parameters can
be different in the following ways:
 The number of parameters can be different.
 The types of the parameters can be different.
 The order of the parameters can be different.
For example, the following code defines two overloaded member functions
called print():
#include <iostream>
class MyClass
{
public:
void print()
{
cout << "Hello, world!" << endl;
}
void print(const string& message)
{
cout << message << endl;
}
};
int main()
{
MyClass x;
x. print(); // Prints "Hello, world!"
x.print("This is a message"); // Prints "This is a message"
return 0;
}
BIT FIELDS AND CLASSES
Bit fields are a feature of C and C++ that allow you to define variables that
occupy a specific number of bits in memory. This can be useful for saving
space, or for storing data that is only a small number of bits in size.
To declare a bit field in C++, you use the following syntax:
type : width;
For example, the following code declares a bit field called flag that occupies
1 bit of memory:
bool flag : 1;
Bit fields can be of any integral type, including char, short, int, and long.
The width of a bit field must be a positive integer, and it must not exceed the
width of the underlying type.
Bit fields can be used in classes, just like any other type of variable. For
example, the following code declares a class called MyClass that has a bit
field called flag:
class MyClass
{
public:
bool flag : 1;
};
Bit fields can be accessed and modified using the same syntax as other
variables.
 Bit fields are not objects, so they cannot be used with operators such
as new and delete.
 Bit fields cannot be used as function parameters or return values.
 Bit fields cannot be used as members of unions.
CONSTRUCTOR
 A constructor is a special member function whose name is same as
class name and its task is to initialize the object of its class.
 The constructor is invoked whenever an object of its associated class
is created.
 It is called constructor because it constructs the values of data
members of the class.
Syntax:

class A
{

public:
A(); // constructor

}
A constructor function have some special characteristics

 It should have the same name as that of the class.


 It should not have any return type.
 Constructors can take default arguments
 Constructors can be dynamically initialized.
 Constructors cannot be virtual
 It should be declared in the public section.
 Constructors are invoked automatically when the objects are
created.
 They cannot be inherited.
DESTRUCTOR
A destructor is a member function having same name as that of its class
preceded by ~(tilde) sign and which is used to destroy the objects that have
been created by a constructor.
Characteristics of destructor:
 Never takes any arguments
 Will not return any values
 Destructors cannot be overloaded
 Destructors can be made virtual.
 Can‘t be inherited
CONSTRUCTOR AND DESTRUCTOR WITH STATIC MEMBERS
Here is an example of a constructor and destructor with static members:
class MyClass
{
public:
static int count;
MyClass()
{
count++;
cout << "Object created, count = " << count << endl;
}
~MyClass()
{
count--;
cout << "Object destroyed, count = " << count <<endl;
}
};
int MyClass::count = 0;
int main()
{
MyClass a;
MyClass b;
return 0;
}
This code will print the following output:
Object created, count = 1
Object created, count = 2
Object destroyed, count = 1
Object destroyed, count = 0
 The constructor is called when each object is created, and the
destructor is called when each object is destroyed.
 The static member count is incremented each time a new object is
created, and decremented each time an object is destroyed.
UNIT IV
Operator overloading
 Operator overloading refers to the multiple definitions of an operator
and giving special meaning to an existing operator.
 The mechanism of giving special meaning to an operator is known as
operator overloading.
Almost all operators in C++ can be overloaded, except the following few
operators.
 Class member access operators ( .*)
 Scope Resolution operator ( :: )
 Size operator( sizeof)
 Conditional operator (? :)
Defining Operator Overloading

The general form of a member operator function is shown here:


return-type class-name::operator op(arg-list)
{
Function Body
}
Operator functions must be either member functions (non-static) or friend
functions.

Unary operator Binary operator

Member function No argument One Argument

Friend function One Argument Two argument

Examples:

vector operator+(vector); //vector addition

vector operator-(); //unary minus

friend vector operator+(vector, vector) //vector addition

The process of overloading involves the following steps:


 Create a class that defines the data type that is to be used in the
overloading operation

 Declare the operator function operator op( ) in the public part of


the class. It may be either a member function or a friend function

 Define the operator function to implement the required operations.

Overloaded operator functions can be invoked by expressions such as

op x or x op for unary operators and

x op y for binary operators op x (or x op) would be interpreted as

operator op(x) for friend functions and

x. operator op(y) in case of member function.

OVERLOADING UNARY OPERATORS

The unary operators operate on a single operand and following are the
examples of Unary operators.

 The increment (++) and decrement (--) operators.

 The unary minus (-) operator.

 The logical not (!) operator.

Example

#include <iostream.h>
class space
{
int x, y, z;
public:
void getdata(int a, int b, int c);
void display(void);
void operator-(); //overloaded unary minus
};
void space::getdata(int a, int b, int c)
{
x=a;
y=b;
z=c;
}
void space::display(void)
{
cout<<x<<‖\n‖;
cout<<y<<‖\n‖;
cout<z<<‖\n‖;
}
void space:: operator-()
{
x=-x;
y=-y;
z=-z;
}
int main()
{
space S;
S.getdata(10,-20, 30);
cout<<"S:";
S.display();
-S; //activates operator-() function
cout<<"S:";
S.display();
return 0;
}
Output
S: 10 -20 30
S: -10 20 -30
OVERLOADING BINARY OPERATORS
Binary operators can be overloaded just as easily as unary operators. The
same mechanism can be used to overload a binary operator. A statement
like
a = add(b, c);
can be replaced by a natural looking expression
a = b + c;
Example (Overloading + using member functions)
#include<conio.h>
class complex
{
int a, b;
public:
void getvalue()
{
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}
void display()
{
cout << a << "+" << b << "i" << "\n";
}
};
void main()
{
clrscr();
complex obj1, obj2, result;
obj1.getvalue();
obj2.getvalue();
result = obj1 + obj2;
cout << "Input Values:\n";
obj1.display();
obj2.display();
cout << "Result:";
result.display();
getch();
}
Sample Output:
Enter the value of Complex Numbers a, b
4 5
Enter the value of Complex Numbers a, b
2 2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
Example: Overloading + using friend functions
#include<conio.h>
class complex
{
int a, b;
public:
void getvalue()
{
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
}
void display()
{
cout << a << "+" << b << "i" << "\n";
}
friend complex operator +(complex,complex);
};
complex operator +(complex obj1,complex obj2)
{
complex t;
t.x=obj1.x+obj2.x;
t.y=obj1.y+obj2.y;
return t;
}
void main()
{
clrscr();
complex obj1, obj2, result;
obj1.getvalue();
obj2.getvalue();
result = obj1 + obj2;
cout << "Input Values:\n";
obj1.display();
obj2.display();
cout << "Result:";
result.display();
getch();
}
Sample Output:
Enter the value of Complex Numbers a, b
4 5
Enter the value of Complex Numbers a, b
2 2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
Rules for operator overloading
1. Only existing operator can be overloaded. New operators cannot be
created.
2. The overloaded operator must have at least one operand that is of
user defined data type.
3. We can‘t change the basic meaning of an operator
4. Overloaded operators follow the syntax rules of the original operators.
They can‘t be overridden.
5. There are some operators that can‘t be overloaded.
 Class member access operators ( .*)
 Scope Resolution operator ( :: )
 Size operator( sizeof)
 Conditional operator (? :)
6. We can‘t use friend functions to overload certain operators. However,
member functions can be used to overload them.
 Assignment operator =
 function call operator ()
 subscripting operator []
 class member access operator ->
7. Unary operators overloaded by means of member function take no
explicit arguments and return no explicit values, but, those
overloaded by means of the friend function, take one reference
argument (the object of the relevant class).
8. Binary operators overloaded through a member function, take one
explicit argument and those which are overloaded through a friend
function take two explicit arguments.
9. When using binary operators overloaded through a member function,
the left hand operand must be an object of the relevant class.
10. Binary arithmetic operators such as +,-,* and / must explicitly return
a value. They must not attempt to change their own arguments.
TYPE CONVERSIONS
Type conversion or typecasting refers to changing an entity of one data type
into another. It is used to convert one data type into another data type
automatically.

Implicit Type Conversion: Implicit type conversion is an automatic type


conversion by the compiler. The type conversions are automatic as long as
the data types involved are built-in types.

Example

int y;

float x=123.45;

y = x;

In this example the float variable x is automatically gets converted to int.


Thus the fractional part of y gets truncated.
Explicit Type Conversion: Automatic type conversion for user defined data
types is not supported by the compiler hence the conversion routines have
to be specified explicitly. Three types of situations might arise in the data
conversion between incompatible types.
 Conversion from basic type to class type.
 Conversion from class type to basic type
 Conversion from one class type to another class type.

Basic to Class Type


Basic to Class Type conversion in C++ can be done using a constructor or a
cast operator.
Example
The following program converts integer to the class type ―length‖
class length
{
int cm,m;
public:
length(int n) //Constructor
{
m=n/100;
cm=n%100;
}
};
void main()
{
int n;
cin >> n;
length obj = n; //Integer to class type
}
The constructor used for type conversions take a single argument whose
type is to be converted.

Class to Basic Type


Overloaded casting operator is used to convert data from a class type to a
basic data type.
Syntax:
operator typename()
{
statements.....
}
This function converts a class type to specified type name.
For example operator int() converts the class object to integer data type.
Conditions for a casting operator function
 It must be a class member.
 It must not specify a return type.
 It must not have any arguments.
Example
The following example cast the object of type ―time‖ to basic data types (int
and float)
class time
{
int min,sec;
public:
time(int n)
{
min = n/60;
sec=n%60;
}
operator int() //Casting Operator
{
int x;
x= min * 60 + sec;
return x;
}
operator float() //Casting Operator
{
float y;
y = min + sec/60;
return y;
}
};
void main()
{
time t1(160);
int n = t1; //Conversion
float x = t1; //Conversion
}
One Class to another Class Type
The Constructors helped us to define the conversion from a basic data type
to class type and the overloaded casting operator helped to define the
conversion from a class type to basic data type.
Now to convert from one class type to another class type these both help us
to do.
Example
The following program converts the class type length1 to type length2
class length2; //forward declaration
class length1
{
int m,cm;
public:
length1(int n)
{
m=n/100;
cm=n%100;
}
operator length2() //from length1 type to length2 type
{
int x= m*100 + cm;
length2 tempobj(x);
return tempobj;
}
};
class length2
{
int cm;
public:
length2(int n)
{
cm=n;
}
operator length1() //from length2 type to length1 type
{
length1 tempobj(cm);
return tempobj;
}
};
void main()
{
int x= 125;
length2 obj1(x);
length1 obj2= obj1;
}
INHERITANCE
The mechanism of deriving a new class from an old one is called
inheritance. The old class is referred to as the base class and new one is
called the derived class.
Different Forms of Inheritance
There are various forms of inheritance.
1. Single inheritance: A derived class with only one base class is called
single inheritance.
2. Multilevel inheritance: The mechanism of deriving a class from
another derived class is called multilevel inheritance.
3. Hierarchical inheritance: One class may be inherited by more than
one class. This process is known as hierarchical inheritance.
4. Multiple inheritance: A derived class with several base classes is
called multiple inheritance.
5. Hybrid inheritance: It is a combination of hierarchical and multiple
inheritance.
Defining Derived Class
A derived class is defined by specifying its relationship with the base class
using visibility mode.
The general form of defining a derived class is:
class derived_class : visibility_mode base_class
{
// members of derived class
};
The colon indicates that the derived_class is derived (inherits some property)
from base_class.
The visibility-mode can be either private or public or protected. If no
visibility mode is specified, then by default the visibility mode is considered
as private.

Single Inheritance: A derived class with only one base class is known as
Single Inheritance.

Example:
class A
{
public:
void showA()
{
cout<<‖Base Class‖;
}
};
class B: public A
{
public:
void showB()
{
cout<<‖\nDerived Class‖;
}
};
int main()
{
B b;
b.showA();
b.showB();
return 0;
}
Output:
Base Class
Derived Class
Multilevel Inheritance: Multilevel Inheritance is a method where a
derived class is derived from another derived class.

The class A serves as base class for the derived class B which in turn serves
as a base class for derived class C. The class B is known as intermediate
base class. The chain ABC is known as inheritance path.

Example:

#include <iostream.h>
class A
{
public:
void showA()
{
cout<<‖Base Class‖;
}
};
class B: public A
{
public:
void showB()
{
cout<<‖\nIntermediate Base Class‖;
}
};
class C: public B
{
public:
void showC()
{
cout<<‖\nDerived Class‖;
}
};
int main()
{
C c;
c.showA();
c.showB();
c.showC();
return 0;
}
Output:
Base Class
Intermediate Base Class
Derived Class
Multiple Inheritance: Multiple Inheritance is a method by which a class is
derived from more than one base class. It allows to combine the features of
several existing classes for defining new classes.
Syntax for derived a class with multiple base classes:
class D: visibility B-1, visibility B-2…
{
Body of D
}
where visibility may be either public or private. The base classes are
separated by commas.

Example Program:

#include <iostream.h>
class M
{
int m;
public:
void getm ()
{
m=10;
}
};
class N
{
int n;
public:
void getn(int)
{
n=20;
}
};
class P: public M, public N
{
public:
void display( );
};
void P :: display(void)
{
cout<<‖m=‖<<m<<‖\n;
cout<<‖n=‖<<n<<‖\n;
cout<<‖m*n=‖<<m*n<<‖\n;
}
int main ()
{
P p;
p.display( );
return 0;
}
Output
m=10
n=20
m*n=200
Hierarchical Inheritance: Hierarchical Inheritance is a method of
inheritance where one or more derived classes is derived from common base
class.

Hierarchical classification of students

Example:

#include <iostream.h>
class A
{
public:
void showA()
{
cout<<‖DEPARTMENT OF BCA\n‖;
}
};
class B: public A
{
public:
void showB()
{
cout<<‖III BCA‖;
}
};
class C: public A
{
public:
void showC()
{
cout<<‖II BCA‖;
}
};
class D: public A
{
public:
void showD()
{
cout<<‖I BCA‖;
}
};
int main ()
{
B b;
b. showB();
C c;
c. showC();
D d;
d.showD();
return 0;
}
Output:
Department of BCA
III BCA
Department of BCA
II BCA
Department of BCA
I BCA
In the above example the three derived classes B, C, D uses a single base
class A. Thus three classes are inherited from a single class.
Hybrid Inheritance: "Hybrid Inheritance" is a method where one or more
types of inheritance are combined together and used.

Example:
#include<iostream>
int a,b,c,d,e;
class A
{
public:
void getab()
{
cout<<"\nEnter a and b value:";
cin>>a>>b;
}
};
class B:public A
{
public:
void getc()
{
cout<<"Enter c value:";
cin>>c;
}
};

class C
{
public:
void getd()
{
cout<<"Enter d value:";
cin>>d;
}
};
class D:public B,public C
{
public:
void result()
{
getab();
getc();
getd();
e=a+b+c+d;
cout<<"\n Addition is :"<<e;
}
};
int main()
{
D d1;
d1.result();
return 0;
}
Output
Enter a and b value: 5 10
Enter c value: 15
Enter d value: 20
Addition is :50
Multipath Inheritance
Multipath Inheritance in C++ is derivation of a class from other derived
classes, which are derived from the same base class.This type of inheritance
involves other inheritance like multiple, multilevel, hierarchical etc.

 Here class D is derived from class B and C.

 Class B and C are child of class A.

 From the above two points, we can say class D is indirectly derived
from class A.

Example

#include<iostream>
#include<conio.h>

class base

public:

int a;

};

class D1:public base

public:

int b;

};

class D2:public base

public:

int c;

};

class D3:public D1,public D2

public:

int total;

};

int main()

D3 ob;

ob.a=10; // error

//this is ambiguous , which a? from D1 or D2 as

// D3 inherits from both D1 and D2

ob.b=20;
ob.c=30;

ob.total=ob.a+ob.b+ob.c;

cout<<"total "<<ob.total<<endl;

return(0);

}
VIRTUAL BASE CLASS
 A virtual base class in C++ is a base class that is declared with the
virtual keyword.

 When a base class is declared as virtual, only one copy of its data
members is created, regardless of how many times it is inherited.

 Virtual base classes are used to prevent multiple inheritance from


creating multiple copies of the same data members.

Example:

class A
{
public:
int i;
};
class B : virtual public A
{
public:
int j;
};
class C: virtual public A
{
public:
int k;
};
class D: public B, public C
{
public:
int sum;
};
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is
inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << ―Value of i is : ‖<< ob.i<<‖\n‖;
cout << ―Value of j is : ‖<< ob.j<<‖\n‖;
cout << ―Value of k is :‖<< ob.k<<‖\n‖;
cout << ―Sum is : ‖<< ob.sum <<‖\n‖;
return 0;
}
ABSTRACT BASE CLASSES
 An abstract class in C++ is a class that cannot be instantiated.
 This is because it contains at least one pure virtual function, which is
a function that has no definition.
 Pure virtual functions must be overridden by any class that inherits
from the abstract class.
Example of an abstract class:

class AbstractClass

public:

virtual void doSomething() = 0; // pure virtual function

};

The = 0 syntax indicates that the function is pure virtual. You cannot define
the body of a pure virtual function.
Any class that inherits from an abstract class must override all of the pure
virtual functions in the base class. For example:
class ConcreteClass : public AbstractClass
{
public:
void doSomething() override {
// implementation of doSomething()
}
};
If a class does not override all of the pure virtual functions in its base class,
then the class is also abstract.
UNIT V
POINTER
A pointer is a variable whose value is the address of another variable.
Like any variable or constant, we must declare a pointer before we can work
with it.
General form of a pointer variable declaration:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and
var-name is the name of the pointer variable.
Example:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Example program:
#include <iostream.h>
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
cout << "Address stored in ip variable: ";
cout << ip << endl;
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Output:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Pointer to class and object
 A pointer to class in C++ is a variable that stores the address of an
object of a class type.
 Pointers to classes are used to access the members of a class object
indirectly.
 To declare a pointer to class, you use the * operator.
 For example, the following declaration declares a pointer to a Person
class object:
Person* p;
#include <iostream>
class Person
{
public:
string name;
int age;
Person(string name, int age)
{
this->name = name;
this->age = age;
}
void print()
{
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main()
{
// Create a pointer to a Person object
Person* p = new Person("John Doe", 30);
// Print the name and age of the person pointed to by p
p->print();
// Delete the person pointed to by p
delete p;
return 0;
}
This program creates a new Person object and stores the address of the
object in the p pointer. The p pointer is then used to print the name and age
of the person. Finally, the p pointer is used to delete the person object.
this Pointer
 C++ uses a unique keyword called this to represent an object
that invokes a member function.

 this is a pointer that points to that object for which this


function was called.

 this pointer is automatically passed to a member function when


it is called.

Example program:
#include<iostream>
class This_Pointer
{
int a;
public:
void setData(int a)
{
this->a = a;
}
void printData()
{
cout<<"The value of a is"<<a<<endl;
}
};
int main()
{
This_Pointer tp;
tp.setData(10);
tp.printData();
return 0;
}
Output:-
The value of a is 10
Explanation of the program
In this program, the 'a' is a private member of the class This_Pointer. Also,
the arguments received by the member function printData() is also a. Hence,
if we do not use this pointer explicitly both the 'a' will be considered as data
members.
POINTERS TO DERIVED CLASSES AND BASE CLASSES
 A pointer to a base class can point to an object of a derived class.
 This is called upcasting.
 When a base class pointer points to a derived class object, only the
members of the base class are accessible through the pointer.
 The members of the derived class are not accessible through the
pointer.
For example, the following code defines a base class Animal and a derived
class Dog.
The following code creates a Dog object and creates a Animal pointer to it.
Dog* dog = new Dog();
Animal* animal = dog;
The animal pointer can be used to call the speak() method of the Dog object,
but it cannot be used to call the bark() method.
animal->speak(); // Prints "I am an animal"
animal->bark(); // Error: `bark()` is not a member of `Animal`
It is possible to cast the animal pointer to a Dog* pointer in order to call the
bark() method.
Dog* dog = (Dog*)animal;
dog->bark(); // Prints "Woof!"
Here are some of the advantages of using pointers to derived classes:
 Pointers to derived classes can be used to create generic code that can
work with objects of any derived class.
 Pointers to derived classes can be used to dynamically allocate
memory for objects of derived classes.
 Pointers to derived classes can be used to create polymorphism.

ARRAY OF CLASSES
An array of classes is a data structure that stores a collection of objects of
the same class. The elements of an array of classes are accessed using their
index, which is an integer. The size of an array of classes is fixed at compile
time.
Here are some of the characteristics of an array of classes:
Elements of the same type: All the elements of an array of classes must be
of the same class.
Fixed size: The size of an array of classes is fixed at compile time.
Sequential access: Elements of an array of classes are accessed in
sequence, using their index.
Memory usage: An array of classes occupies contiguous memory.
Speed: Accessing elements of an array of classes is fast.
Here are some of the advantages of using an array of classes:
Efficient storage: An array of classes stores all the elements of the same
class in contiguous memory, which makes it efficient to store and access the
data.
Fast access: Elements of an array of classes can be accessed quickly using
their index.
Ease of use: Arrays of classes are easy to use and understand.
Here are some of the disadvantages of using an array of classes:
Fixed size: The size of an array of classes is fixed at compile time, which
means that it cannot be resized after it is created.
Limited flexibility: Arrays of classes are not as flexible as other data
structures, such as linked lists.
Memory usage: Arrays of classes can use a lot of memory, especially if they
are large.
C++ STREAM
 A stream is a sequence of bytes.
 It represents a device on which input and output operations are
performed.
 It can be represented as a source or destination of characters of
indefinite length.
 It is generally associated to a physical source or destination of
characters like a disk file, keyboard or console.
 C++ provides standard iostream library to operate with streams.
 Input Stream: The source stream that extracts data from input device
and provides that to the program.
 Output Stream: The destination stream that receives output from the
program and can be sent to the output device.

C++ STREAM CLASSES


The C++ I/O system contains a hierarchy of classes that are used to
define various streams to deal with both the console and disk files. The
classes are called stream classes.
 ios acts as a base class for istream, ostream, streambuf.
 streambuf is a pointer and istream ,ostream acts as a base
class for the derived class iostream.
 Here iostream can inherit the attributes of ios through istream
and ostream.
 To avoid the duplication ios must be declared as virtual base
class assign and iostream_withassign adds the assignment
operator function to these classes.
Sequential Input and Output operations
The file stream classes support a number of member function for
performing the input and output operations on file.

Function
 put() and get() are designing for handling a single character at a
time.
 write() and read() are designed to write and read blocks of binary
data.
I/O operations on character
put() and get() functions:
put(): The function put() writes a single character to the stream.
get(): The function get() reads a single character from the stream.
Example Program
#include<iostream.h>
#include<fstream.h>
#include<string.h>
int main()
{
char str[20];
cout<‖Enter the string \n‖;
cin>>str;
int len=strlen(str);
fstream file;
file.open(―TEXT‖, ios::in | ios::out);
for(int i=0;i<len;i++)
file.put(string[i]);
file.seekg(0);
charch;
while(file)
{
file.get(ch);
cout<<ch;
}
return 0;
}
write() and read() function
The write() and read() function to handle the data in binary form .This
means that the values are stored in the disk file in the same format in which
they are stored in the internal memory.

The binary input and output functions takes the following form

Syntax:

infile.read((char*) & v, sizeof ((v));

outfile.write((char*) & v, sizeof ((v));

This function takes two arguments. The first is to address of the variable v
and the second is the length of that variable in bytes.

Example:

#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
const char *filename=‖BINARY‖;
int main()
{
float height[4]={123.7,123.7,167.5,176.49};
ofstreamoutfile;
outfile.open(filename);
outfile.write((char *) & height, sizeof(height));
outfile.close();
for(int i=0;i<4;i++)
height[i]=0;
ifstreaminfile;
infile.open(filename);
infile.read((char*)&height,sizeof(height));
for(i=0;i<4;i++)
{
cout.setf(ios::showpoint);
cout<<setw(10)<<setprecision(2)<<height[i];
}
infile.close();
return 0;
}
Reading and writing a class object:

 The binary input and output function read() and write() are designed
to read & write the values.
 The function write() copies a class object from memory byte with no
conversion.
 The length of object is obtained using the size of operator
Program:
class inventory
{
char name[10];
int code;
float cost;
public:
void readdata(void);
void writedata(void0;
};
void inventory::readdata(void)
{
cout<<‖Enter the name‖;
cin>>name;
cout<<‖Enter the code‖;
cin>>code;
cout<<‖Enter the cost‖;
cin>>cost
}
void inventory::writedata(void)
{
cout<<name<<code<<cost;
}
int main()
{
inventory item[3];
fstream file;
file.open(―stock.DATA‖,ios::in|ios::out);
cout<<‖Enter the values for 3 items:‖);
for(i=0;i<3;i++)
{
item[i].readdata();
file.write((char*)&item[i].sizeof(item[i]));
file.seekg(0);
for(i=0;i<=3;i++)
{
file.read((char*)&item[i]sizeof(item[i]));
item[i].writedata();
}
file.close();
return 0;
}
File pointers and their Manipulations
 The C++ I/O system supports function for setting a file pointer to any
desired position inside the file or to get the file pointer.
 These allow the programmer to have control over a pointer in the file
where read or write operation takes place.
 These functions are listed below:
Function Member of class Action performed
seekg() ifstream Moves get file pointer to a specific location
seekp() ofstream Moves put file pointer to a specific
location
tellg() ifstream Returns the current position of the get
pointer
tellp() ofstream Returns the current position of the put
pointer

 The seekp() and tellp() are member function of ofstream.


 The seekg() or tellg() are member function of ifstream.
 The class fstream deals with file in both input and output modes.
 Each file has two associated pointers known as the file pointers.
 Input pointer (or get pointer)
 Output pointer (or put pointer)
If we want to open an existing file to add more data, the file is opened in
‗append‘ mode. This moves the output pointer to the end of the file.
Specifying the offset
o The seek() function can be used to move a file pointer to a desire
location.
o The seek() functions seekg() and seekp() can also be used with
two arguments

Syntax:
seekg (offset, refposition);

seekg (offset, refposition);

The parameter offset represents the number of bytes the file pointer to be
moved from the location specified by the parameter refposition.

The refposition takes one of the following three constants defined in the ios
class

 ios::beg //start of the file


 ios::cur //current position of the pointer
 ios::end //end of the file
Ex:
fout.seekg(0,ios::beg);
fout.seekg(m,ios::beg);
fout,seekg(m+1,ios::end);
Updating a file: Random Access
Updating is a routine task in the maintenance of any data file. The updating
would include one or more following tasks
 Displaying the contents of a file
 Modifying an existing file
 Adding a new item
 Deleting an existing item
This can be easily implemented if a file contains a collection of items/objects
of equal lengths.It can be done by the following statement

int object_length = sizeof(object);


The location of the desired object,say the mth object

int location = m * object_length;

We can also find out the total number of objects in a file using the
object_length as follows

int n = file_size/object_length;

Random Access of File Using File Pointer Manipulation


#include<iostream.h>
#include<fstream.h>
int main()
{
fstream fp;
char buf[100];
int pos;
// open a file in write mode with 'ate' flag
fp.open("random.txt", ios :: out | ios :: ate);
cout << "\nWriting to a file ... " << endl;
fp << "This is a line" << endl; // write a line to a file
fp << "This is a another line" << endl; // write another file
pos = fp.tellp();
cout << "Current position of put pointer : " << pos << endl;
fp.seekp(-10, ios :: cur); // move the pointer 10 bytes
backward from current position
fp << endl << "Writing at a random location ";
fp.seekp(7, ios :: beg); // move the pointer 7 bytes forward
from beginning of the file
fp << " Hello World ";
fp.close(); // file write complete
cout << "Writing Complete ... " << endl;
fp.open("random.txt", ios :: in | ios :: ate); // open a file in
read mode with 'ate' flag
cout << "\nReading from the file ... " << endl;
fp.seekg(0); // move the get pointer to the beginning of the
file
// read all contents till the end of file
while (!fp.eof()) {
fp.getline(buf, 100);
cout << buf << endl;
}
pos = fp.tellg();
cout << "\nCurrent Position of get pointer : " << pos << endl;
return 0;
}
Output
Writing to a file …
Current Position of put pointer : 40
Writing Complete …
Reading from the file …
This is Hello World is a anot
Writing at random location
Current Position of get pointer : -1
TEMPLATES
 Generic programming is an approach where generic types are used as
parameters in algorithms so that they work for a variety of suitable data
types and data structure.
 A template is a blue print or formula for creating a generic
class or function.
 A template can be used to create a family of classes or functions.
 A template can be considered as a kind of macro.
 A template is defined with a parameter that would be replaced by
a specified data type at the time of actual use of class or
function, the templates are sometimes called as parametrized
classes or functions.

TYPES: The two types of templates are


1. class template.
2. function template
Class Templates
 Class template is used to create family of classes with same
member function but different types of data.
 The process of creating a specific class from a class template is
called instantiation.
General form:
Template <class T>
class tagname
{

};
Syntax for declaring an object:
tagname <type> object –name;
Example:
#include<iostream.h>
template<class T>
class max
{
T a,b;
public:
max(T first, T second)
{
a=first;
b=second;
}
T getmax()
{
T result;
result = a>b?a:b;
return result;
}
};
A single template to support all data types:
The class created from a class template is called template class.
Syntax: classname <type> objectname(arglist);
Example:
#include<iostream.h>
#include<conio.h>
template <class T>
class data
{
public:
data(T c)
{
cout<<‖c= ―<<c<<‖size in bytes:‖<<sizeof(c);
}
};
int main()
{
clrscr();
data <char> h(‗A‘);
data <int> i(20);
data <float> j(2.3);
return 0;
}
Output:
c = A size in bytes : 1
c = 20 size in bytes: 2
c = 2.3 size in bytes: 4
Class templates with multiple parameters
The class template may contain one or more parameters of generic
data type. The arguments are separated by comma with template
declaration.
General form:
template <class T1, class T2,…>
class classname
{
---
Body of the class
---
};
Syntax for declaring an object :
tagname <type ,type 1 ,type 2 ,…..> object name;
Example:
#include<iostream.h>
template <class T1, class T2>
class data
{
public:
data (T1 a, T2 b)
{
cout<<‖\n a=―<<a<<‖b= ―<<b;
}
};
int main()
{
clrscr();
data <int,float>h(2,2.5);
data <int,char> i(3,‘C‘);
data <float,int> j(7.5,20);
return 0;
}
Output
a=2 b=2.5
a=3 b=C
a=7.5 b=20
When objects are created, constructor functions automatically called &
values are received by template argument.
Function templates
Function template is used to create a family of functions with different
arguments type.
Syntax:

template <class t>


returntype functionname(argument of type T)
{
//body of function
}
The function template is similar to that of the class template except that we
are defining functions instead of classes.
Example:

#include<iostream.h>
template <class T>
void swap(T &x,T &y)
{
T temp = x;
x = y;
y = temp;
}
void fun(int m,int n,float a,float b)
{
cout<<‖m and n before swap:‖<<‖m=‖<<m<<‖n=‖<<n<<‖\n‖;
swap(m,n);
cout<<‖m and n after swap:‖<<‖m=‖<<m<<‖n=‖<<n<<‖\n‖;
cout<<‖a and b before swap:‖<<‖a=‖<<a<<‖b=‖<<b<‖\n‖;
swap(a,b);
cout<<‖a and b after swap:‖<<‖a=‖<<a<<‖b=‖b<<b<‖\n‖;
}
int main()
{
fun(10,20,11.5,12.5);
return 0;
}
Output
m and n before swap: m=10 n=20
m and n after swap: m=20 n=10
a and b before swap: m=11.5 n=12.5
a and b after swap: m=12.5 n=11.5
Bubble sort using template functions
#include<iostream.h>
template<class T>
void bubble(T a[],int n)
{
for(int i=0;i<n-1;i++)
for(int j=n-1;i<j;j--)
if(a[j]<a[j-1])
{
swap(a[j]a[j-1]);
}
}
template<class X>
void swap(X &a,X &b)
{
X temp = a;
a = b;
b = temp;
}
int main()
{
int x[5] = {10,50,40,30,20};
float y[5] = {1.5,5.5,4.5,3.5,2.5};
bubble(x,5);
cout<<‖Sorted x-array:‖;
for(int i=0;i<5;i++)
cout<<x[i]<<‖ ―;
cout<<endl;
cout<<‖sorted y-array:‖;
for(int j=0;j<5;j++)
cout<<y[j]<<‖ ―;
cout<<end;‘
return 0;
}

Output
Sorted x-array: 10,20,30,40,50
Sorted y – array: 1.5,2.5,3.5,4.5,5.5
Function templates with multiple parameters
Like template class, we can use more than one generic data type in function
template statement, using a comma-separated list.
Syntax
template<class T1, class t2,….>
returntype functionname(arguments of types T1,T2,…)
{
---
Body of the function
---
}
Example
#includeiostream.h>
#include<string>
template<class T1,class T2>
void display(T1 X,T2 y)
{
cout<<x<<‖ ―<<y<‖\n‖;
}
int main()
{
cout<<‖int and character string…\n‖;
display(2000,‖EDF‖);
cout<<‖float and integer….\n‖;
display(9.4,1235);
return 0;
}
Output
int and character string
2000 EDF
float and integer
9.4 1235
EXCEPTION HANDLING

Introduction
The two most common types of bugs are logic error and syntactic error.
 The logic error occurs due to poor understanding of the problem and
solution procedure.
Eg: To return average of 2 numbers. Return a+b/2 causes
logical error.
The correct statement is return (a+b) /2;
 The syntactic error arises due to poor understanding of language
itself.
Eg: To print hello , we must use
printf(―hello‖);
and printf(hello) results in syntactic error.
Exception
 Exceptions are run time anomalies or unusual conditions that a
program may encounter while executing.
 Anomalies might include conditions such as
 division by zero,
 access to any array outside of its bounds.
 running out of memory or disk space
 Exception handling provides a type-safe, integrated approach, for
copying with the unusual predictable problem.

Basics of Exception Handling


Exceptions are of two types, namely
 Synchronous exception
 Asynchronous exception
Synchronous Exception: Error such as ―out-of-range index‖, and
―overflow‖.
Asynchronous Exception: Error that is caused by events beyond the
control of the program.
Purpose of Exception handling
The purpose of exception handling mechanism is to provide means to detect
and report an ―exceptional circumstances‖.
 Find the problem(hit the exception)
 Inform that an error has occurred(Throw the exception)
 Receive the error information(Catch the exception)
 Take corrective actions(Handle the exception)
The error handling code consists of two segments
1. To detect error and to throw exception
2. To catch the exception and to take appropriate actions
Exception handling mechanism:
It basically has three keywords, namely
 try
 catch
 throw
try
 It is used to preface a block of statements which may generate
exceptions.
 This block of statements is known as try blocks.
Example
try
{
if(x!=0)
{
cout<<a/x;
}
else
{
throw(x);
}
}
throw
 When an exception is detected, it is thrown using a throw statement
in the try block.
catch
 Catch block catches the exception thrown by the throw statement in
the try block and handles in accordingly.
 Always catch block must follow try block that throws the exception

The block throwing exception


Example:

#include<iostream.h>
int main()
{
int a,b;
cout<<‖Enter value for a and b‖;
cin>>a>>b;
int x = a-b;
try
{
if(x!=0)
{
cout<<a/x<<‖\n‖;
}
else
{
throw(x);
}
}
catch(int i)
{
cout<<‖Exception occurred:divide by zero\n‖;
}
cout<<‖END‖;
return 0;
}
Function invoked by try block throwing exception
 Exceptions are thrown by functions that are invoked from within the
try blocks.
 The point at which the throw is executed is called the throw point.
 Once an exception is thrown to the catch block, control return to the
throw point.
Function invoked by try block throwing exception
General Format

Example
#include<iostream.h>
void divide(int x, int y, int z)
{
cout<<‖\n Inside the function \n‖;
if((x-y)!=0)
{
int R = z/(x-y);
cout<<‖Result = ―<< R << ―\n‖;
}
else
{
throw(x-y);
}
}
int main()
{
try
{
cout<<‖Inside the try block \n‖;
divide(10,20,30);
divide(10,10,30);
}
catch(int i)
{
cout<<‖caught the exception \n‖;
}
return 0;
}
Output
Inside the try block
Inside the function
Result = -3
Inside the function
Caught the exception
Throwing Mechanism
When an exception is detected, it is thrown using the throw statement

throw(exception);

throw exception;

throw; //used for re-throwing an exception

The operand object exception may be of any type, including constants.


Catching Mechanism
The code for handling exceptions is included in catch blocks.

catch (type arg)


{
//statements for managing exceptions
}
 The type indicates the type of exception that catch block handles.
 The parameter arg is an optional parameter name.
 The catch statement catches an exception whose type matches with
the type of catch argument.
 The catch block is simply skipped if the catch statement does not
catch an exception.

Multiple catch statements


 It is possible that a program can have more than one condition to
throw an exception.
 We can associate more than one catch statement with a try.
Syntax
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}
----
----
catch(typeN arg)
{
//catch blockN
}
 When an exception is thrown the exception handlers are searched in
order for an exact match.
 After executing the handler, a control goes to the first statement after
the last catch block for that try.
 When no match is found, the program is terminated.
Example

#include<iostream.h>
void test(int x)
{
try
{
if(x == 1) throw x;
else if(x==0) throw ‗x‘;
else if(x==-1) throw 1.0;
cout<<‖End of try block \n‖;
}
catch(char c)
{
cout<<‖caught a character \n‖;
}
catch(int m)
{
cout<<‖caught an integer \n‖;
}
catch(double d)
{
cout<<‖caught a double \n‖;
}
cout<<‖End of try catch system \n‖;
}
int main()
{
cout<<‖Testing multiple catches \n‖;
cout<<‖x==1 \n‖;
test(1);
cout<<‖x==0 \n‖;
test(0);
cout<<‖x==-1 \n‖;
test(-1);
cout<<‖x==2 \n‖;
test(2);
return 0;
}
Output
Testing multiple catches
x==1
caught an integer
End of try catch system

x==0
caught a character
End of try catch system

x==-1
caught a double
End of try catch system

x==2
End of try block
End of try catch system
Catch all Exceptions
 We can force a catch statement to catch all exceptions instead of a
certain type alone.
 This could be achieved by defining the catch statement using ellipse.

Syntax
catch(…)
{
//statements for processing
//all exceptions
}
Example
#include<iostream.h>
void test(int x)
{
try
{
if(x==0) throw x;
if(x==-1) throw ‗x‘;
if(x ==1 ) throw 1.0;
}
catch(…)
{
cout<<‖caught an exception \n‖;
}
int main()
{
test(-1);
test(0);
test(1);
return 0;
}
Output
caught an exception
caught an exception
caught an exception
Remember catch(...) should always be placed last in the list of handlers.
Placing it before other catch blocks, would prevent those blocks from
catching exceptions.
Re-throwing Exception
A handler may decide to throw the exception caught without processing it.
In such situation we may simply invoke throw without only argument.
Syntax: throw;
Example
#include<iostream.h>
void divide(double x, double y)
{
cout<<‖Inside function‖;
try
{
if(y==0.0)
throw y;
else
cout<<‖Division=‖<<x/y;
}
catch(double)
{
cout<<‖caught double inside function‖;
throw;
}
cout<<‖End of function‖;
}
int main()
{
cout<<‖Inside main‖;
try
{
divide(10.5,3.0);
divide(20.0,0.0);
}
catch(double)
{
cout<‖caught double inside main‖;
}
cout<<‖End of main‖;
return 0;
}
Output
Inside main
Inside function
Division = 5.25
End of Function

Inside function
Caught double inside function
Caught double inside main
End of main
When an exception is re-thrown, it will not be caught by the same catch
statement or any other catch in that group. Rather, it will be caught by an
appropriate catch in the outer try/ catch sequence only.
Miscellaneous functions
Miscellaneous functions in C++ are a collection of functions that perform
various tasks that are not related to any specific area of programming. They
are typically used for tasks such as:
 Getting and setting environment variables

 Handling errors

 Generating random numbers

 Timing operations

 Manipulating strings

 Reading and writing files


Some of the most common miscellaneous functions in C++ include:
 getenv(): This function gets the current value of an environment variable.

 setenv(): This function sets the value of an environment variable.

 perror(): This function displays the most recent error that occurred during a
library function call.

 rand(): This function generates a random number.

 time(): This function returns the current time.

 srand(): This function seeds the random number generator.

 exit(): This function terminates the program.

 assert(): This function checks if a condition is true.

 getchar(): This function reads a character from the keyboard.

 putchar(): This function prints a character to the console.

*************************************************************************************
Question Bank
Unit I

MCQS

1. C Language was developed in the year.


a)1972 b)1975 c)1980 d)1985
2. C language was developed by .
a) Dennis Rechard b) Dennis M. Ritchie
c)Bjarne Stroustrup d)Anders Hejlsberg
3. C language is a successor to which language?
a) Basic b) Cobol c) C++ d) B
4. C language is a .
a) Procedural oriented programming language
b) General purpose programming language
c) Structured programming
d) All of the above
5. To develop which operating, C language was invented?
a) Linux b) Unix c) Android d) Mac
6. Almost every C program begins with the statement .
a) main () b) printf() c) include<stdio.h> d) scanf ( )
7. Which of the following is not a valid C variable name?
a) int number; b) float rate;
c) int variable_count; d) int $main;
8. Which one is not a reserve keyword in C Language?
a) auto b) main c) case d) register
9. How many keywords are there in C language?
a) 32 b) 33 c) 64 d) 18
10. Which is not a valid keyword in C language?
a) For b) while c) do-while d) switch
11. A C variable name can start with a
a) Number b) PlusSign (+) c)Underscore( _ ) d) Asterisk (*)
12. All keywords in C are in
a) LowerCase letters b) UpperCase letters
c) CamelCase letters d) None of the mentioned
13. The C-preprocessors are specified with symbol.
a) # b) $ c) ‖ ‖ d) &
14. scanf() is a predefined function in header file.
a) stdlib. h b) ctype. h c) stdio. h d) stdarg. h
15. White spaces are used to
a) Separatewords b)connect words
c)ignore words d) none of the above
16. Each and every individual unit in C program is known as
a) tokens b)groups c)unit d)classes
17. Key words means .

a) fixed meanings b) normal meaning


c) meaningless words d) changing names
18. Which are the fundamental data types in C?
a) char b) int c) float d) All of the above
19. How many byte(s) does a char type take in C?
a) 1 b) 2 c) 3 d) 4
20. For which type, the format specifier "%i" is used?
a) int b) char c) float d) double
21. What is the difference between float and double in C?
a) both are used for the same purpose
b) double can store just double value as compare to float value
c) double is an enhanced version of float and was introduced in C99
d) double is more precise than float and can store 64 bits
22. A variable is .
a) Datatype b) identifier c) keyword d) none of the above
23. Variable is used .
a) store a data value b) delete a value
c)assigning value d) calculate the value
24. What are the classes of integer storage in given below?
a) short int b) long int c) signed and unsigned d) all of the above
25. What is the value of signed char?
a) -128 to 127 b) -126 to 127 c) -125 to 127 d) -124 to 127
26. Floating point numbers are defined by the keyword
a) float b) integer c) double d) decimal
27. A double data type numbers uses bits.
a) 64 bits b) 32 bits c)16 bits d) 8 bits
28. Void data type used to .
a) Return a value b) does not return any value
c) passing a value d) copy a value
29. Characters are usually stored in bits.
a) 4bits b) 8 bits c) 8 bytes d) 8 megabytes
30. Unsigned chars have values.
a) 0 and 266 b) 0 and 255 c) 0 and 277 d) 0 and 288
31. Typedef cannot create .
a) new type b) new data c)new value d) new memory
32. What will be the output of the following code snippet?
#include <stdio.h>
int main() {
int a = 3, b = 5;
int t = a;
a = b;
b = t;
printf("%d %d", a, b);
return 0;
}
a) 3 5 b) 3 3 c) 5 5 d) 5 3
33. How many main( ) function we can have in our program?
a) 1 b) 2 c) No Limit d) Depends on Compiler
34. Which is the correct format specifier for double type value in C?
a) %d b) %f c) %lf d) %LF
35. C support a rich set of operator.
a) builtin b) user defined c) derived d) mixed
36. Operators are used in program to manipulate ?
a)variable b) data c) data and variable d)constants
37. An expression is sequence of .
b) operands b)operators c)data d)variables
38. What is the arithmetic operator in given below list?
a) + b)- c) * d) all of theabove
39. operator cannot be used on floating point data
c) division b)modulo division c)multiplication d) unary addition
40. Which operator is used to find the remainder of two numbers in C?
a) / b)\ c) % d) //
41. Increment (++) and decrement (--) are the operators in C?
a) Unary b) Binary c) Ternary d)None of the above
42. A Single arithmetic integer expression a+b is called
a) float expression b)arithmetic expression
c)integer expression d) none
43. An Arithmetic operation involving only real operands is called
a) real arithmetic b)floatarithmetic
c) integerarithmetic d)expression
44. Which operator cannot be used with real operands
a)/ b)* c) % d)::?
45. What is the result of real operation?
a) real b)integer c)float d)string
46. We may compare the age of two persons so what operation performed
that?
a) arithmetic b)relational c)comparison d)logical
47. The comparison can be done with the help of operator
a) relational b)logical c)arithmetic d)assignment
48. The value of a relational expression is .
a) one b)two c) one or zero d)three
49. What type of operators are used when we want to test more than one
condition and makedecision
a) relational b)logical c)assignment d)conditional
50. The statement a>b && x= = 10 is what type of expression
a) logical b)conditional c) binary d)ternary
51. Assignment operator is used for .
a) assign a value b) deleteavalue c) referavalue d) calculate
avalue
52. In given below what symbol is performed during assigning avalue
a) + b) = c) * d)/
53. The operator op= is called
a) briefinformation b)shorthand c)abbreviatedform d)abstract
54. The statement of using assignment operator is more
d) difficult b)easy c) efficient d) hard
55. Which is the correct form of declaring assignment operator?
a) a+=a; b)a=a*a c)c*=a d) all of the above
56. We want to add the values during declaration of the program so what
type of operator used
a) decrement b)arithmetic c) increment d)assignment
57. M- - meaning of this symbolis----------
a) decrement b)increment
c)assigningvalue d) comparing thevalue
58. What is the conditional operator?
b) exp1;exp2;exp3 b) exp1?exp2?exp3? c)exp1?exp2:exp3
d)exp1?exp2;exp3?
59. Which is the C expression?
a)(m+n) (x+y) b)3x2+2x+1 c)a*b-c d)(x/y)-k

60. How we evaluated arithmetic expression without parenthesis


c) right b) left to right c) right to left d)left
61. What is the result of logical or relational expression in C?
a) True or False
b) 0 or 1
c) 0 if an expression is false and any positive number if an expression is true
d) None of the mentioned
62. When two or more operators of the same precedence level appear
evaluated?
a) Associatively rule b) decision making rule c)evaluation rule
d) none of the above
63. A single character input from the keyboard can be obtained by using
thefunction .
a) prinf() b) getchar( ) c) putchar() d) scanf ( )
64. The function scanf ( ) reads .
a) a single charcter b) characters and strings
c) any possible variable type d) any possible number
65. The math library is setup for the user by the file .
a) float.h b) limit.h c) math.h d) time.h
66. The single character input/output functions are
a) scanf( ) and printf() b) getchar( ) and printf ()
c) scanf ( ) and putchar( ) d) getchar ( ) and putchar()
67. Formatted input refers to an data.
a) input b) ouput c) memory d) bit
68. Control string also known as
a) input string b)output string c) format string d) character
string
69. what is the syntax of reading an integer number?
a) %w ds b) %wsd c) %w cd d) %wdc
70. Identify the wrong statement
a) putchar(65) b)putchar('x') c)putchar("x") d)putchar('')
71. What will be the output main()
{

int i;

i = 10;

printf("%d\t",5,6);

printf("%d", i , i++);

(a) 5 11 (b)6 10 (c)6 11 (d) 510


72. C programs are converted into machine language with the help of
a) Editor b) Compiler c) operating system c) None of the above
5 MARKS
1. Write note on Overview of C.
2. What is constant? Explain its types.
3. Write note on variables.
4. Explain the rules apply to a #define statement which define a
symbolic constant.
5. Explain about expression.
6. Describe the logical operators available in C.
9 MARKS
1. Explain the various data types in C.
2. Explain about C-tokens.
3. Explain various operators available in C with example.
4. Explain about types-conversion.
5. Explain the various formatted Input/ Output statements available in
C with example.
Unit II
MCQS

1. Which of the following is branching statement of C language?


a) if statement b) if…else statement
c) switch statement d) All of these
2. The two statements that can be used to change the flow of control are
.
a) if and switch b) if and while
c) switch and dowhile d) break and continue
3. In simple if statement with no else what happens if the condition
following the if is false?
a) the program searches for the last else intheprogram
b)nothing
c) control falls through to the statement following if
d) the body of the statement is executed
4. The statement following else in an if-else construct are executed when
.
a) the conditional statement following the if is false
b) the conditional statement following the if is true
c) the conditional statement following the else is false
d) the conditional statement following else is true
5. If, switch, conditional and goto statements are called .
a) decision making b)condition making
c) flow of execution d) normal statement
6. The statements control the flow of execution is called .
a) looping b) control structure
c) decision making d) un conditional
7. Which is a powerful decision making statements?
a) for b) if c) while d) do-while
8. What is the syntax of if statements?
a) if(testexpression) b) if(―body of the loop‖)
c) if(=?) d) if(statements)
9. In given below which one is the family of if statement?
a) if-else b)nested if c) else if ladder d) all of the above
10. We may have to use more than one if else statement is
called .
a) simpleif b) nested if c) if-else d) else if ladder
11. If we have to make decision based on multiple choices, which of the
following is best suited?
a) if b) if-else c) if-else-if d) All of the above
12. Which of the following is an invalid if-else statement?
a) if (if (a ==1)){} b) if(a){} c) if ((char)a){} d) if (func1 (a)){}
13. is the built in multiway decision statement in C.
a) for b) switch c) if d) while
14. Switch statement accepts.
a) int b)char c)long d) All of theabove
15. In switch statement case label end with symbol
a) ; b) = c) : d) :=
16. The default is an case
a) conditional b) unconditional c) loop d) optional
17. The switch expression must be an type
a) float b) double c) void d) integral
18. must be constant or constant expression

a) case label b) default c) break d) values


19. Case label values must be .
a) unique b) different c) same d) optional
20. The statement transfer the control out of the switch statement
a) label b) break c) default d) switch
21. The goto statement to branch from one point to another
in the program?
a) conditionally b)unconditionally
c) valid values d) none of the above
22. The goto requires a in order to identify the place where
branch is to be made
a) statement b) test condition c) label d) for
23. What is the use of break keyword?
a) halt execution of program
b) b) restart execution of program
c) exit from loop and switch statement
d) not a switchstatement
24. In switch statement, each case instance value must be ?
a) constant b) variable c) special symbol d) identifier
25. A switch statement is used to
a) To use switching variable
b) Switch between function in a program char
c) Switch from one variable to another variable
d) To choose from multiple possibilities which may arise due to
different values of a single variable
26. A sequence of statements are executed until some condition terminated
a) loop b) if-else c) goto d) switch
27. Which one of the following sentences is true?
a) the body of the while loop is executed at least once
b) the body of a do…while loop is executed at least once
c) the body of do….while loop is executed zero or more times
d) a for loop can never be used in place of while loop

28. The control conditions are tested before the start of the loop execution is
called .
a) exit control b)entry control c) flow control d) test control
29. The test condition is performed at the end of the loop is .
a) exit control b) entry control c) flow control d) test
control
30. One for statement within another statement is .
a) for b) goto c)switch d) nested for
31. If c is a variable initialized to 1, how many times will the following loop
be executed?
while ((c > 0) && (c < 60))
{
loop body
c ++;
}
a) 60 b) 59 c) 61 d) None of these
32. The following loop
for( i=1, j=10; i<6; ++i, --j )
printf ("%d %d", i, j );
prints
a) 1 10 2 9 3 8 4 7 5 6 b) 1 2 3 4 5 10 9 8 7 6
c) 1 1 1 1 1 1 9 9 9 9 9 d) none of above
33. Which loop is faster in C Language, for, while or Do While?
a) for b) while c) do while d) All work at same speed

34. Which loop is guaranteed to execute at least one time?


a) for b) while c) do while d) None of the above
35. Which among the following is a unconditional controlstructure
a) do-while b)if-else c)goto d)for
36. Array elements are always stored in memory location.
a) sequential b)random c) sequential and random d) list
37. Array can be considered as set of elements stored in consecutive
memory locations but having .
a) Same data type b) Different datatype c) Same scope d) None
of these
38. Array is an example of type memory allocation.
a) Compile time b) Run time c) Both A and B d) None of the above
39. The process of allocating memory at compile time is known
as allocation
a) static memory b) dynamic memory c) storage
memory d) temporary memory
40. The arrays created memory space at run time called
a) dynamic array b) static array
c) one dimension array d) two dimension array
41. A string is a sequence of .
a) integer b)character c)string d)float
42. A group of character enclosed with double quotes iscalled .
a) string b)character c)integer d)number
43. What is a String in C Language?
a) String is a new Data Type in C
b) String is an array of Characters with null character as the last
element of array
c) String is an array of Characters with null character as the first element of
array
d) String is an array of Integers with 0 as the last element of array

44. In given below which one is example of string


a) („hello‟?) b)(“welcome”) c) (?welcome?) d)(*welcome*)
45. What operations are performed character string?
a) reading & writing b)combining c) copying d) all of the above
46. What is Character-Array?
a) array of alphabets b) array of well-defined characters
c) array of characters d) array of characters terminated by \0

47. C does not support string as a type


a) datatype b)charactertype c)integraltype d) variabletype
48. C allows us to represent string as character ?
a) array b)data type c)identifier d)keyword
49. The general form of declaration of string variable is
a) charstring-name[size]; b)char array-name[size];
c) int var-name[size]; d) none of the above
50. The compiler assigns a character string to a ?
a) array b)character array c)string array d) one dimensional array
51. The compiler automatically supplies a character at the end
of the string
a) zero b)not null c)null d) any value
52. C also permits us to initialize a character array without specifying
the .
a) no elements b)variable elements
c) array elements d) number of elements
53. Which function will you choose to join two words?
a) strcpy() b) strcat() c) strncon() d) memcon()
54. What will strcmp() function do?
a) Compares the first n characters of the object
b) undefined function
c) copies the string
d) compares the string
55. function counts the number of characters in the given string.
a) strcpy() b) strcat() c) strlen() d) strcmp()
56. Which function is used to copy or assign the value of one string into
another string?
a) strcpy() b) strcat() c) strlen() d) strcmp()
57. Which function is used to reverse the given string?
a) strrev() b) strreverse() c) strev() d) reverse()

5 MARKS
1. With an example, explain the switch case construct in ‗C‘
2. Compare while with do-while statement.
3. Write a ‗C‘ program to check whether the given number is PRIME or
not using while loop.
4. How to use the break and continue statements in ‗C‘? Give an
example.
5. How two dimensional arrays are declared in C? Explain with an
example.
6. How to read the string from terminal and write the string to screen?
9 MARKS
1. Explain different types of if statement with an example.
2. Explain control statement or decision making statement.
3. Explain the looping statement with example.
4. Explain the types of arrays with example.
5. Write a C program to perform matrix multiplication using array.
6. Explain string handling function.
Unit III
1. Who invented C++?
a) Dennis Ritchie b) Ken Thompson c) Brian Kernighan d) Bjarne
Stroustrup
2. What is C++?
a) C++ is an object oriented programming language
b) C++ is a procedural programming language
c) C++ supports both procedural and object oriented programming
language
d) C++ is a functional programming language
3. Which of the following is used for comments in C++?
a) /* comment */ b) // comment */
c) // comment d) both // comment or /* comment */
4. Which of the following user-defined header file extension used in c++?
a) hg b) cpp c) h d) hf
5. Which of the following is a correct identifier in C++?
a) VAR_1234 b) $var_name c) 7VARNAME d) 7var_name
6. Wrapping data and its related functionality into a single entity is
known as
a) Abstraction b) Encapsulation c) Polymorphism d) Modularity
7. How structures and classes in C++ differ?
a) In Structures, members are public by default whereas, in Classes,
they are private by default
b) In Structures, members are private by default whereas, in Classes,
they are public by default
c) Structures by default hide every member whereas classes do not
d) Structures cannot have private members whereas classes can have
8. What does polymorphism in OOPs mean?
a) Concept of allowing overriding of functions
b) Concept of hiding data
c) Concept of keeping things in different modules/files
d) Concept of wrapping things into a single unit
9. Which concept allows you to reuse the written code?
a) Encapsulation b) Abstraction c) Inheritance d)
Polymorphism
10. Which of the following explains Polymorphism?
a) int func(int, int); float func1(float, float);
b) int func(int); int func(int);
c) int func(float); float func(int, int, char);
d) int func(); int new_func();
11. C++ is
a) procedural programming language
b) object oriented programming language
c) functional programming language
d) both procedural and object oriented programming language
12. What does modularity mean?
a) Hiding part of program
b) Subdividing program into small independent parts
c) Overriding parts of program
d) Wrapping things into single unit
13. How many types of polymorphism are there in C++?
a) 1 b) 2 c) 3 d) 4
14. How run-time polymorphisms are implemented in C++?
a) Using Inheritance b) Using Virtual functions
c) Using Templates d) Using Inheritance and Virtual functions
15.How compile-time polymorphisms are implemented in C++?
a) Using Inheritance b) Using Virtual functions
c) Using Templates d) Using Inheritance and Virtual functions
16. Which concept means the addition of new components to a program
as it runs?
a) Data hiding b) Dynamic binding c) Dynamic loading d) Dynamic
typing
17. Which of the following approach is used by C++?
a) Top-down b) Bottom-up c) Left-right d) Right-left
18. Which of the following explains the overloading of functions?
a) Virtual polymorphism b) Transient polymorphism
c) Ad-hoc polymorphism d) Pseudo polymorphism
19. Which operator is overloaded for a cout object?
a) >> b) << c) < d) >
20. Which concept is used to implement late binding?
a) Virtual functions b) Operator functions
c) Constant functions d) Static functions
21.C++ was developed by ----------- --.
a. Dennis richiese b. James gosling c. Bjarne Stroustrup d. None
of The Above
22. Object oriented programming employs programming
approach.
a.Top down b. bottom up c. procedural d. all the
above
23. In CPP, cin and cout are the predefined stream .
a. Object b. function c. operator d. data types
24. Which is an Objects example.
a. place b. data c. name d. all of the above
25. Class is an data type.
a. primitive b. user definedc. derived d. All the above
26.Constant variables can be created in CPP by using .
a.enum b. const c. #define d. all of these
27. The wrapping up of data and function into a single unit is known as---

a. encapsulation b. abstraction c. inheritance d. All the above


28.Which is the pillar of OOP?
a. encapsulation b. abstraction c. inheritance d. polymorphism
29 --------------- is refers to important feature without background details.
a. polymorphism b. inheritance c. abstraction d.
none of these
30.--------------is the mechanism of deriving a new class from existing
(old) class.
a. polymorphism b. inheritance c. abstraction d.
none of these
31. New class is also called
a. Sub class b. base c. parent d. all of these
32. Old class is also called -----------
a. derived b. parent c. super d. both b and c
33. The initial name of c++ is------------
a. C with classes b. c with cpp c. c within class d. none of these
34.C++ introduces a new comment symbol ---------- --.
b. /(slash) b. //(double slash) c. .(dot) d.
+(plus)
35. The smallest individual units in a program are known as ---------------
a. function b. member c. tokens d. symbols
36.Identifiers allows only ----------- symbol.
c. underscore b. slash c. Both a and b d. plus
34.Which one of the following is not correct identifier.
d. sum5 b. sum7_ c. 5sum- d. none of these
35.identifier or variable name can starts with
e. symbols b. letters c. special char d. None of the above
36. is a derived data type.
f. structure b. class c. union d. array
37. Array is a collection of ------------- data items that share a common
name.
g. different b. homogeneous c. seperate d. All the
above
38. fuctions are .
h. read b. perform task c. display d. none of these
39.cin statement used to ---------- --.
i. display b. calculate c. read d. All the above
40.What is the operator used cout statement?
a. >> b. << c. == d. <=
41. Input operator is also called---------------
a. extraction b. insertion c. pointer d. all
42. are used to format the data display.
a. keywords b. manipulators c. operators d. variables
43.endl is used to feed to output
j. newline b. nextline c. both a and b d. delete
43.The switch statement is a --------------- branching statement
a. One way b. multi way c. two way d. none of
these
44. perform repetitive tasks within a program
a. if b. switch c. loop d. else if
45 ------------ is a exit controlled loop.
b. Do while b. while c.for d. all
46.Which is valid for loop statement---------------
a. for (i=0 ;1<100 ;i=i+2) b. for (i=0 ;i<100 ;i=i++)
c. for (i=1 ;i<100 ;i=i+2) d. for (i=0 ;i<100 ;i=1)

5 Marks
1. What are the advantages of object oriented programming?
2. Write note on Function.
3. What is Inline function? Explain.
4. Write note on Function Overloading.
5. Discuss about array of objects.
6. Write note on Overloading member functions.
9 Marks
1. Explain the basic concepts of object oriented programming.
2. Explain about Member Function in detail.
3. Discuss about static data members.
4. Discuss about static member function with example.
5. Explain about friend function with an example.
6. Explain about constructor and destructor.
Unit IV

MCQs

1. 1. What is a binary operator?


a) Operator that performs its action on a single operand
b) Operator that performs its action on two operand
c) Operator that performs its action on three operand
d) Operator that performs its action on any number of operands
2. 2. Which is the correct example of a binary operator?
a) ++ b) — c) Dereferencing operator(*) d) +
3. 3. Which is the correct example of a unary operator?
a) & b) == c) - - d) /
4. Which is called ternary operator?
a) ?: b) && c) ||| d) ===
5. Pick the incorrect statements out of the following.
a) Operator overloading does not disturbs the precedence of operators
b) Arity of operators can be changed using operator overloading
c) No new operators can be created
d) All of the mentioned
6. What is the return type of the conversion operator?
a) void b) int c) float d) no return type
7. How many parameters does a conversion operator may take?
a) 0 b) 1 c) 2 d) as many as possible
8. How are types therein user-defined conversion?
a) 1 b) 2 c) 3 d) 4
9. Pick out the correct syntax of operator conversion.
a) operator float()const b) operator float()
c) operator const d) operator const()
10. Which among the following best describes the Inheritance?
a) Copying the code already written
b) Using the code already written once
c) Using already defined functions in programming language
d) Using the data and functions into derived segment
11. How many basic types of inheritance are provided as OOP
feature?
a) 4 b) 3 c) 2 d) 1
12. Which among the following best defines single level inheritance?
a) A class inheriting a derived class
b) A class inheriting a base class
c) A class inheriting a nested class
d) A class which gets inherited by 2 classes
13. Which programming language doesn‘t support multiple
inheritance?
a) C++ and Java b) C and C++
c) Java and SmallTalk d) Java
14. Which type of inheritance leads to diamond problem?
a) Single level b) Multi-level
c) Multiple d) Hierarchical
15. Which access type data gets derived as private member in
derived class?
a) Private b) Public
c) Protected d) Protected and Private
16. Members which are not intended to be inherited are declared as

a) Public members b) Protected members


c) Private members d) Private or Protected members
17. While inheriting a class, if no access mode is specified, then
which among the following is true? (in C++)
a) It gets inherited publicly by default
b) It gets inherited protected by default
c) It gets inherited privately by default
d) It is not possible
18. If a derived class object is created, which constructor is called
first?
a) Base class constructor b) Derived class constructor
c) Depends on how we call the object d) Not possible
19. A virtual function is a member function of which of the following
class?
(A). Derived class (B). Parent class
(c). base class (D). Both A and B
20. A virtual function is redefined in which of the following class?
(A). Derived class (B). Parent class
(c). base class (D). Both A and B
21. The virtual function is used to tell the compiler to perform ?
(A). static linkage (B). dynamic linkage
(c). late binding (D). Both B and C
22. Which of the following best describes the virtual function?
(A). Function overriding
(B). write a function in the child class that is already present in the
parent class
(c). Run time polymorphism
(D). All of these
23. In late binding, function call is resolved during?
(A). runtime (B). Compile time
(c). Infinite time (D). None of these
24. What is an abstract class in C++?
a) Class specifically used as a base class with atleast one virtual functions
b) Class specifically used as a base class with atleast one pure virtual
functions
c) Class from which any class is derived
d) Any Class in C++ is an abstract class
25. What is a pure virtual function in C++?
a) A virtual function defined in a base class
b) A virtual function declared in a base class
c) Any function in a class
d) A function without definition in a base class
26. Which is the correct syntax of defining a pure virtual function?
a) pure virtual return_type func();
b) virtual return_type func() pure;
c) virtual return_type func() = 0;
d) virtual return_type func();

27. Which is the correct statement about pure virtual functions?


a) They should be defined inside a base class
b) Pure keyword should be used to declare a pure virtual function
c) Pure virtual function is implemented in derived classes
d) Pure virtual function cannot implemented in derived classes

28. Which among the following best defines multilevel inheritance?


a) A class derived from another derived class
b) Classes being derived from other derived classes
c) Continuing single level inheritance
d) Class which have more than one parent

29. If there are 5 classes, E is derived from D, D from C, C from B and B


from A. Which class constructor will be called first if the object of E or D is
created?
a) A b) B c) C d) A and B

30. If there are 3 classes. Class C is derived from class B and B is derived
from A, Which class destructor will be called at last if object of C is
destroyed.
a) A b) B c) C d) All together
5 Marks

1. What is operator overloading? Write its rules.


2. Explain unary operator overloading.
3. What is inheritance? Write about single inheritance.
4. Give a note on virtual base class with example.
5. Write about abstract base class.
9 Marks

1. Explain binary operator overloading with example.


2. Explain type conversion.
3. Explain about multiple and hierarchical inheritance.
4. Discuss about multipath inheritance.
5. Discuss about hybrid inheritance.
Unit V

MCQs
1. What does the following statement mean?
int (*fp)(char*)
a) pointer to a pointer
b) pointer to an array of chars
c) pointer to function taking a char* argument and returns an int
d) function taking a char* argument and returning a pointer to int
2. The operator used for dereferencing or indirection is
a) * b) & c) -> d) –>>
3. Choose the right option.
string* x, y;
a) x is a pointer to a string, y is a string
b) y is a pointer to a string, x is a string
c) both x and y are pointers to string types
d) y is a pointer to a string
4. Which one of the following is not a possible state for a pointer.
a) hold the address of the specific object
b) point one past the end of an object
c) zero
d) point to a type
5. Which of the following is illegal?
a) int *ip; b) string s, *sp = 0;
c) int i; double* dp = &i; d) int *pi = 0;

6. Which header file is required to use file I/O operations?


a) <ifstream> b) <ostream> c) <fstream> d) <iostream>

7. Which stream class is to only write on files?


a) ofstream b) ifstream c) iostream d) fstream

8. Which of the following is used to create a stream that performs both input
and output operations?
a) ofstream b) ifstream c) iostream d) fstream

9. Which of the following is not used as a file opening mode?


a) ios::trunc b) ios::binary c) ios::in d) ios::ate
10. By default, all the files in C++ are opened in mode.
a) Text b) Binary c) ISCII d) VTC

11. What is the use of ios::trunc mode?


a) To open a file in input mode
b) To open a file in output mode
c) To truncate an existing file to half
d) To truncate an existing file to zero

12. Which of the following is the default mode of the opening using the
ofstream class?
a) ios::in b) ios::out c) ios::app d) ios::trunc

13. What is the return type open() method?


a) int b) char c) bool d) float

14. What is an exception in C++ program?


a) A problem that arises during the execution of a program
b) A problem that arises during compilation
c) Also known as the syntax error
d) Also known as semantic error

15. By default, what a program does when it detects an exception?


a) Continue running
b) Results in the termination of the program
c) Calls other functions of the program
d) Removes the exception and tells the programmer about an exception

16. Why do we need to handle exceptions?


a) To avoid unexpected behaviour of a program during run-time
b) To let compiler remove all exceptions by itself
c) To successfully compile the program
d) To get correct output
17. How Exception handling is implemented in the C++ program?
a) Using Exception keyword
b) Using try-catch block
c) Using Exception block
d) Using Error handling schedules

18. Which of the following is an exception in C++?


a) Divide by zero
b) Semicolon not written
c) Variable not declared
d) An expression is wrongly written

19. What is an error in C++?


a) Violation of syntactic and semantic rules of a languages
b) Missing of Semicolon
c) Missing of double quotes
d) Violation of program interface

20. What is the difference between error and exception?


a) Both are the same
b) Errors can be handled at the run-time but the exceptions cannot
c) Exceptions can be handled at the run-time but the errors cannot
d) Both can be handled during run-time

21. What are the different types of exceptions?


a) 1 b) 2 c) 3 d) 4

22. Which keyword is used to throw an exception?


a) try b) throw c) throws d) except
23. What is Re-throwing an exception means in C++?
a) An exception that is thrown again as it is not handled by that catching
block
b) An exception that is caught twice
c) An exception that is not handled in one caught hence thrown again
d) All of the mentioned
24. What is meant by the template parameter?
a) It can be used to pass a type as an argument
b) It can be used to evaluate a type
c) It can of no return type
d) It can be used to delete a type
25. Which keyword can be used in template?
a) class b) typename
c) both class & typename d) function
26. What is the validity of template parameters?
a) inside that block only b) inside the class
c) whole program d) inside the main class
27. Why we use :: template-template parameter?
a) binding b) rebinding
c) both binding & rebinding d) reusing
28. Which parameter is legal for non-type template?
a) pointer to member b) object c) class d) baseclass
29. Which of the things does not require instantiation?
a) functions b) non virtual member function
c) member class d) all of the mentioned
30. How Exception handling is implemented in the C++ program?
A. Using try-catch block B. Using Exception block
C. Using Exception keyword D. Using Error handling schedules
5 Marks
1. Write note on pointer.
2. Explain about pointer to class and object.
3. Write note on pointer to derived classes and base classes.
4. Write note on array of classes.
5. Write note on Miscellaneous functions.
9 Marks
1. What is this pointer? Explain with example.
2. Explain about C++ stream classes in detail.
3. Explain about file pointers and their manipulators.
4. Define Template. Explain it briefly.
5. What is exception handling? Explain it.

*************************************************

You might also like