Fundamentals of Programming
Fundamentals of Programming
(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]
Fundamentals of Programming
Unit I
Unit II
Unit III
Unit IV
Unit V
Text Book(s)
Reference Books
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.
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
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
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,
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
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
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
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
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.
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.
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;
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:
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).
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,
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;
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.
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.
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
Examples:
The unary operators operate on a single operand and following are the
examples of Unary operators.
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.
Example
int y;
float x=123.45;
y = x;
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.
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.
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;
};
public:
int b;
};
public:
int c;
};
public:
int total;
};
int main()
D3 ob;
ob.a=10; // error
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.
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:
};
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.
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.
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:
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
Syntax:
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
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;
};
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:
#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.
#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;
#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
Timing operations
Manipulating strings
perror(): This function displays the most recent error that occurred during a
library function call.
*************************************************************************************
Question Bank
Unit I
MCQS
int i;
i = 10;
printf("%d\t",5,6);
printf("%d", i , i++);
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
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---
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
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
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;
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
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
*************************************************