Basireddy Memorial Degree College Nandikotkur
Basireddy Memorial Degree College Nandikotkur
COLLEGE
NANDIKOTKUR
NAME : _____________________________
GROUP : _____________________________
Introduction to programming language paradigms – Problem solving methods Flowcharts and Algorithms,
Introduction to C-Structure of C, Compilation and Execution, Character set, identifiers & Keywords, variables and
constants, data types, expressions, operators in C, Input and output statements in C.
The design and development of correct, efficient and maintainable programs depend on the approach
adopted by the program to perform various activities that need to be performed during the development
process. The entire program or software development process is divided into a no. of phases. The output of
one phase provides the input for it’s subsequent phase.
Implementation:- in this phase, the designed algorithms are converted into program code using any of
the high level language. The program codes are tested by the programmers to ensure the correctness.
Testing:- In this phase, all the modules are tested together to ensure that the over all system works.
Well as a whole product. In this phase, the software is tested using a large no. of varied different inputs
to ensure that the software is working as expected by the user’s requirements that were identified in
the requirements analysis phase.
Software deployment, training and support:- After the code is tested, the program has been approved
by the user, it is installed or deployed in the production environment. After installation and
deployment of software the developers will give the training classes to the end user regarding how to
use the software.
Step 1: Start
Step 2: Read the two numbers in to a,b
Step 3: c=a+b Step
4: write/print c
Step 5: Stop.
Flow Charts
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts use
simple geometric shapes to depict processes and arrows to show relationships and process/data flow.
Advantages
1) It is a communication tool to explain the logic of a system.
2) The are also used for program documentation.
3) The act as a guide or blue print for a the programmers to code the solution in any
Programming language.
4) They can be used to debug programs that have errors.
Limitations
1) It is a laborious and time consuming activity.
2) Flow chart of a complex program becomes complex.
3) a little bit of alteration in the solution may require complete redrawing of the flowchart.
4) There are no well defined standard that limit the details that must be in corporate into a
flow chart.
Introduction to C
C is a general-purpose High Level programming language that is extremely popular, simple, and flexible
to use. It is a structured programming language that is machine-independent and extensively used to
write various applications.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
Initially, C language was developed to be used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
Source file
Source file contains the source code of the program. it
defines the main function and may be other functions.
These files will have the extension name “.C”.
Header files:
These files contain the definitions of the functions. These
files will have the extension name “.h”.
stdio.h – input – output functions.
string.h -- for string handling functions.
math.h – for mathematical functions.
alloc.h – for dynamic memory allocation.
conio.h – for clearing the screen
Object file:
Object file is generated by compiler. it contains binary code of the function definitions. linker uses this
file to produce an executable files. These files will have extension name “.obj”.
Executable file: Executable file is generated by linker. These files are directly executed. These file will
have extension name “.exe”.
USING COMMENTS
Comments are just a way of explaining what a program does. It is mainly an internal program
documentation. The compiler ignores the comments when forming the object file. This means that the
comments are non-executable statements.
C supports two types of commenting.
// is used to comment a single statement. This is known as a line comment. A line comment can be
placed anywhere on the line and it does not require to be specifically ended as the end of the line
automatically ends the line.
/* is used to comment multiple statements. A /* is ended with */ and all statements that lie within
these characters are commented.
Tokens in C language
The smallest individual units with in a program are known as a tokens. The tokens are classified as 6
types.
Keywords: All keywords have fixed meanings and these meanings cannot be changed. Keywords serve
as basic building blocks for program statements. All keywords must be written in lowercase
A list of 32 keywords in the c language is given below:
auto break case char const continue default do
Integer Constant :
An Integer constant refers to a sequence of digits. There are 3 types of integer constants
namely decimal, octal, and hexa decimal.
The decimal integers consists of a set of digits from 0-9 and preceded by an optional ‘+’ or ‘- ’ sign.
Ex : 565, -123, +676.
An octal integer consist of the combination of digits from the set 0-7 with a leading ‘0’.
Ex : 0123, 0456, 0321, etc.
A sequence of digits preceded by ‘ox’ or ‘OX’ is considered as hexa-decimal integer. It may also
include alphabets from A to F and digits from 0-9.
Ex : ox67AB, oxAB123, ox56F
Real/ Float Constants : The integer numbers are inadequate to represent quantities likes prices,
distances, heights, weights, etc. there quantities are represented by numbers containing fractional part
like 5.67, 70.62 etc., and such numbers are called real or floating point constants.
II B.Com (CA) & B.A (CA) C & C++ Page 8
Ex : -2.16, 3.34 80.318
A real no may also represents in an exponential format. Ex : The value 215.65 can be
represented in an exponential format is 2.1565E2.
Single Character Constants :
It contains a single character enclosed in a single quotation marks.
Ex : ‘5’, ‘x’, ‘+’ etc.
String Constant :
A sequence of character can be enclosed in a double quotation marks are called string
constants. Ex : “123”, “ABC”, “A123” etc.
Variables
A variable is a data name that may be used to store a data value. The variable value can change
during the program exhibition. The value of a variable is a varied from time to time.
Syntax: data type variable list;
Ex: int a; //declaring 2 variable of integer type
float b;
char c;
int a=10,b=20; //initialization 2 variable of integer type
float f=20.8;
char c='A';
Rules :
1. They must begin with an alphabet, some compilers may accept underscore(_) as the first character
also.
2. The maximum length of a variable is almost 31 characters, but the first 8 characters are treated as a
variable name by most of the compilers.
3. Upper case and lower case or significant that is the variable Total is not equal to total.
4. The variable should not be a reserved word.
5. Spaces are not allowed in between the variable.
DATA TYPES
C supports several different types of Data Types. The variety of data types available, allow the
Programmer to select the data type appropriate to the needs of the application. C supports three
Classes of data types.
1. Primary (or Fundamental) data types
2. Derived data types
3. User-defined data types
I . Primary Data Types :
Integer data type (int) : Integer are whole number with a range of values supported by a
particular machine. Generally an integer occupies 2-4 bytes of storage and the word is size varies
from machine to machine. namely short int, int and long int, in both signed and unsigned forms
Float data type :
The float numbers (real) are stored in 32 bits (4 bytes or 1 word) with 6 digits of precessions.
The floating point numbers are defined by the keyword “float”, If we specify the data types as
“double”, it uses 64 bits (8 bytes) and giving a precision of 14 digits.
Character data type :
II.Derived Data Types: Derived data type is the aggregation of fundamental data
type. Character, integer, float, and void are fundamental data types. Pointers, arrays, structures and
unions are derived data types
III.User Define Data Types: Those data types which are defined by the user as per his/her will are
called user-defined data types. Examples of such data types are structure, union and enumeration.
OPERATORS
C operators are symbols that are used to perform mathematical or logical manipulations. The C
programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions . They are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators :
‘C’ provides a few basic arithmetic operators. The operators ‘+’, ‘-’, ‘*’, etc are work in
the same way as they do in the other languages also.
Operator Meaning
+ (plus) Addition
- (unary) Subtraction
* Multiplication
/ Division
% Modules or Remainder
2. Relational Operators :
Relational operators are also known as a comparison operator, it is an operator that compares two
values. Expressions that contain relational operators are called relational expressions.
Operator Meaning
< Less than
> Greater than
<= Less than equal to
II B.Com (CA) & B.A (CA) C & C++ Page 10
>= Greater than equal to
== Equal to
!= Not equal to
3. Logical Operators :
‘C’ has three types of logical operators. They are
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
4. Assignment Operators :
The assignment operator is used to assign a value to a variable or to assign the result of
an expression to a variable. The assignment operator in ‘C’ language is “=”. They are
Variable = expression
Ex : x=5; y=a+b;
5. Increment or Decrement Operators :
‘C’ has two very useful operators, not generally found in other languages. These are the
increment(++) and decrement(--) operators. The operator ‘++’ adds “1” to the operand. While ‘- -’
subtracts “1” from the operand. Both are called unary operators.
Here ++m is equivalent to m=m+1
-- m is equivalent to m=m-1 or m=-1
++m is called pre incrementation, m++ is called post incrementation. Similarly --m is
called pre decrementation and m- - is called post decrementation.
6. Conditional Operator (Ternary) :
A ternary operator pair “?” is available in ‘C’ language to construct a conditional
expression. The syntax is
Variable=exp1 ? exp2 : exp 3;
Example : a=10, b=15
X=a>b ? a:b
In this example first it will evaluate the exp 1. If it is true the value of a (exp2) will be assigned to
x. If the condition is false, the value of b(exp3) will be assigned to x.
7. Bitwise Operators :
‘C’ has a distinction of supporting some operators called as bitwise operators and are
used for manipulation of data at bit level. These operators are used for testing the bits or shifting
them from right to left, left to right etc., They are
Operator Meaning
& Bitwise AND
| (pipe symbol) Bitwise OR
^ Bitwise x-OR (ap)
~ /S Complement (tilde)
<< Left shift
>> Right shift
8. Special Operators :
‘C’ supports some special operators, such as comma(,) operaor, “size=of” operator, point
operators (& and *), member selection operators (. and ).
OUTPUT STATEMENTS:
1. putchar()
2. printf()
3. puts()
4. putch()
i) printf()
This function is used for displaying the output on the screen i.e the data is moved from the
computer memory to the output device.
Syntax: printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They are the
general characters which will be displayed as they are .arg1, arg2 are the output data items.
Example: Demonstrating the printf function
printf(“Enter a value:”);
printf will generally examine from left to right of the string.
The characters are displayed on the screen in the manner they are encountered until it
comes across % or \.
Once it comes across the conversion specifiers it will take the first argument and print it in
the format given.
ii. putch()
this function is a counterpart of getch. Which means that it will display a single character on the screen.
The character that is displayed is returned.
Syntax: int putch(int);
putch(ch); where,
ch - the character that is to be printed.
iii. putchar
This function is the other side of getchar. A single character is displayed on the screen.
Syntax:
putchar(ch);
iv. puts():
This statement is used to print string .
Syn: Puts(s);
INPUT STATEMENTS:
1. getchar()
2. scanf()
3. gets()
4.getch()
5.getche()
i. scanf()
scanf is used when we enter data by using an input device.
Syntax: scanf (“format string”, &arg1, &arg2, …..);
scanf works totally opposite to printf. The input is read, interprets using the conversion specifier and
stores it in the given variable. The conversion specifier for scanf is the same as printf.
scanf reads the characters from the input as long as the characters match or it will terminate. The order
of the characters that are entered are not important. It requires an enter key in order to accept an
input.
ii.getch
This function is used to input a single character. The character is read instantly and it does not require
an enter key to be pressed. The character type is returned but it does not echo on the screen.
Syntax: int getch(void);
ch=getch();
where,
ch - assigned the character that is returned by getch.
iii. getche
This function is used to input a single character. The main difference between getch and getche is that
getche displays the (echoes) the character that we type on the screen.
Syntax: int getch(void);
ch=getche();
iv. getchar
This function is used to input a single character. The enter key is pressed which is followed by the
character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar;
v. gets() :
Reading a String can be done by using the function gets. The gets takes the following form.
gets (a);
Control structures – Decision making and branching, looping structures, switch-case, break and continue, goto
statement, functions – advantages, storage classes, creating user defined functions, recursion, Parameter
passing, arrays- types of arrays, arrays and functions.- Introduction to pointers-pointer declaration, pointer
operators, Dynamic memory allocation.
Decision making Statements / Control Statements
A C program is a set of statements, which are normally executed sequentially in the order in which they
appear. We have a number of situations, where we may have to change the order of execution of
Statements based on certain condition.
C conditional statements allow you to make a decision, based upon the result of a condition. These
statements are called Decision Making Statements or Conditional Statements.
C Language supports 4 Type of decision making statements.
1. Simple if Statement
2. if-else Statement
3. Nested if-else Statement
4. else-if Ladder
1. Simple IF Statement:
The ‘statement-block’ may be a single statement or a group of statements. If the test condition
is true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x.
Syntax:
if( test condition )
{
statement – block ;
}
statement –x
Example: #include<stdio.h>
void main()
{
int a = 15, b = 20;
if (b > a)
{
printf("b is greater");
}
}
2. If – else Statement:
if (a > b)
{
printf("\n a is greater than b");
}
else if (b > a)
{
printf("\n b is greater than a");
}
else
{
printf("\n Both are equal");
}
}
3. Nested if Statement:
Nested if is also a multiple decision making statement. In this statement. First Condition will be tested if
the condition is true another if condition will be execute if the condition is false false statement
execute and so on….
if( test condition1 )
{
if ( test condition2 )
{
Statementblock- 1;
}
else
{
Statementblock- 2;
}
}
else
{
Statement - block-3;
}
Statement –x;
Example: #include<stdio.h>
void main()
{
int x=20,y=30;
if(x==20)
{
if(y==30)
II B.Com (CA) & B.A (CA) C & C++ Page 16
{
printf("value of x is 20, and value of y is 30.");
}
}
}
case value 2 :
Statements ;
break;
case value 3 :
Statements ;
break;
default :
default Statements ;
break;
}
Example: #include<stdio.h>
void main()
{
int a;
printf("Please enter a no between 1 and 5: ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("You chose One");
break;
case 2:
printf("You chose Two");
break;
case 3:
printf("You chose Three");
II B.Com (CA) & B.A (CA) C & C++ Page 17
break;
case 4:
printf("You chose Four");
break;
case 5:
printf("You chose Five.");
break;
default :
printf("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
Iterative statements / Looping Statements
A computer can perform repetitive operations; like in every computer language must have features
that instruct a computer to perform such a repetitive tasks. “The process of repeatedly executing a
block of statements is known as looping”. The statements may be executed any number of times, from
zero to infinite number, if a loop continues forever, it is called infinite loop. In looping, a sequence of
statements is executed until our desired conditions are satisfied.
C Language there are three types of looping statements available they are
While Loop
Do- While loop
For loop
While Loop :
While loop is a Entry control loop. Here, the test condition is evaluated first. If the condition is true, the
body of the loop is executed. After execution of the body the controls transfers to the test condition
again the test condition is evaluated until the condition false the statements will be execute again and
again.
syntax: while ( test condition )
{
Body of the loop;
Updation;
}
Example: #include<stdio.h>
int main ()
{
int n = 1,times=5; /* local variable Initialization */
while( n <= times ) /* while loops execution */
{
printf("C while loops: %d\n", n);
n++;
}
return 0;
}
Do-While Loop :
Do-while is an exit control loop. Here in the do-while structure first the statements will be executed
and then test the condition. If it is true the same statements will be executed. After executing the
statements. Once again it will test the condition and if it is true the same statements will be executed
II B.Com (CA) & B.A (CA) C & C++ Page 18
repeatedly and so on. This process will be continued as long as the condition is true. Whenever the
condition becomes false, it comes outside the loop and executes the remaining statements in the
sequential order. The main draw back in the do-while structure is the statements will be executed at
least once even though the condition is initially false.
Syntax: do
{
Statement -1;
Statement -2;
----------
}
While (condition)
Example: #include<stdio.h>
int main ()
{
int n = 1,times=5; /* local variable Initialization */
do /* do loops execution */
{
printf("C do while loops: %d\n", n);
n = n + 1;
}while( n <= times );
return 0;
}
For –Loop: The for loop is another entry-controlled loop that provides more concise loop control
Statement. The general form of for loop is
Syntax:
Syntax: for( initialization ; test condition ; inc/dec )
{
Body of the loop;
}
Example: #include<stdio.h>
int main ()
{
int n,times=5; /* local variable Initialization */
for( n = 1; n <= times; n = n + 1 ) /* for loops execution */
{
printf("C for loops: %d\n", n);
}
return 0;
}
Initialization of the control variable is done first, using assignment statement such as I = 1 .Next the
condition will be execute. The test condition is such as I < 10 that determine when the loop will exit. If
condition is true, the body of the loop is executed; otherwise the loop is terminated and execution
When the body of the body of loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop. The control variable is updated using an test assignment
Statement such as i++, i- - . . This process is continuing the value of control variable fails to satisfy the
test condition
Jump statements
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test condition.
The number of times a loop is repeated is decided in advanced and the test condition is written to
II B.Com (CA) & B.A (CA) C & C++ Page 19
achieve this. Sometimes, when executing a loop it becomes desirable to skip a part of the loop or leave
the loop as soon as a certain condition occurs.
1. break
2. Continue
3. goto
BREAK Statement: An early exit from a loop can be accomplished (done) by using the break statement.
When the break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are nested, the
break would only exit from the loop containing it i.e. the break will exit only a single loop.
Continue Statement :
During the loop operation, it may be necessary to skip a part of the body of the loop under certain
condition. The continue, as the name implies, causes the loop to be continued with the next iteration
after skipping any statements in between. Continue statement tells to the compiler:”SKIP THE
FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.
Types of function
There are two types of function in C programming:
1) Standard library functions ( Built in Functions )
2) User-defined functions
Standard Library Functions :
Library functions are the built in function that are already defined in the C library. The prototype of
these functions is written in header files. So we need to include respective header files before using a
library function. For example scanf( ), printf( ), getchar( ),puts( ),gets( ), the prototype of math functions
like pow(),sqrt(), etc is present in math.h, String functions strrev(),Strcmp() etc is in string.h and so on.
User-Defined Functions :
Those functions that are defined by user to use them when required are called user-defined function.
Function definition is written by user. main() is an example of user-defined function.
Implementation Of User Defined Functions
A function usually has three components. They are:
1. Function Prototype/Declaration
2. Function Definition
3. Function Call
1. Function Prototype/Declaration
Function declaration is a statement that informs the compiler about
Name of the function
Type of arguments
Number of arguments
Type of Return value
Syntax for function declaration
returntype function_name ([arguments type]);
Ex:-
void sort(int []);
int product(int,int);
2. Function Definition
Function definition consists of the body of function. The body consists of block of statements that
specify what task is to be performed. When a function is called, the control is transferred to the
function definition.
Syntax for function definition
returntype function_name ([arguments])
{
For example,
int product (int x, int y)
{
int p = x*y;
return p;
}
In this function, the return type of product() is int. So it returns an integer value p to the invoking
function.
3. Function call
A function call can be made by using a call statement. A function call statement consists of
function name and required argument enclosed in round brackets.
Syntax for function call
function_name ([actual arguments]);
For example,
sort(a);
p = product(x,y);
Example for functions:
#include<stdio.h>
int addition(); /* function declaration */
int main()
{
int answer; //local variable definition
answer = addition(); //calling a function to get addition value.
printf("The addition of the two numbers is: %d\n",answer);
return 0;
}
int addition() //function returning the addition of two numbers
{
int num1 = 10, num2 = 5; // local variable definition
return num1+num2;
}
Passing Parameters to a Function
While calling a function, the arguments can be passed to a function in two ways. they are
1. call by value.
2. call by reference.
Call by value
In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the function call
in the call by value method.
Call by reference
The call by reference method of passing arguments to a function copies the address of an argument
into the formal parameter. Inside the function, the address is used to access the actual argument used
in the call. It means the changes made to the parameter affect the passed argument. Their values
remain changed outside it.
Example of call by reference:
#include <stdio.h>
void swap(int *x, int *y);
main()
{
int a,b;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Before swapping\n");
printf("a = %d\n",a);
printf("b = %d\n",b);
swap(&a,&b); // function call by Value
printf("After swapping\n");
II B.Com (CA) & B.A (CA) C & C++ Page 23
printf("a = %d\n",a);
printf("b = %d\n",b);
}
void swap(int *x, int *y) // function definition
{
int temp;
temp =x*;
x* = y*;
y* = temp;
printf("Swapping Values \n");
printf("a = %d\n",*x);
printf("b = %d\n",*y);
}
RECURSION FUNCTION
Recursion can be defined as the technique of replicating or doing again an activity in a self-similar way
calling itself again and again, and the process continues till specific condition reaches. In the world of
programming, when your program lets you call that specific function from inside that function, then
this concept of calling the function from itself can be termed as recursion, and the function in which
makes this possible is called recursive function.
Syntax of Recursive Function:
Return type recursive_func ([argument list])
{
Statements;
... ... ...
recursive_func ([actual argument]);
... ... ...
}
EXAMPLE: Finding factorial of a number using recursion.
#include<stdio.h>
int fact(int);
main()
{
int num,f;
printf("\nEnter a number: ");
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
}
int fact(int n)
{
if(n==1)
return 1;
else
return(n*fact(n-1)); /*fact Function calling again*/
}
STORAGE CLASSES IN C
Storage classes of a variable define the scope and life time of a variable and functions declared with in
a c program. C language supports four types of storage classes. They are
1) Automatic Storage Class (Auto)
II B.Com (CA) & B.A (CA) C & C++ Page 24
2) External Storage Class (Extern)
3) Register Storage Class (Register)
4) Static Storage Class (Static)
ARRAYS
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc.
It also has the capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly accessed by using
its index number.
Properties of Array
The array contains the following properties
Each element of an array is of same data type and carries the same size, i.e., int = 2 bytes.
Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Declaration of C Array
We can declare an array in the c language in the following way.
Syntax: data_type array_name [array_size];
EX: int marks[5];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.
Pointers
Pointer is a variable that can hold the address of another variable. It is a derived data type and the
pointer variables are declared from the built in data type. Therefore a pointer, is a variable that
represents the location of a data item.
Applications of a pointers / Advantages of pointers:
it is used to pass information back and forth between a function and its reference points.
Pointers are enable the programmers to return multiple data items from a function via function
arguments.
It provides an alternative way to access individual elements of the array.
Pointers are used to pass arrays and strings as function arguments.
Pointers are used to create complex data structures such as trees, linked list, linked stack, linked
queue and graphs.
Pointers are used for dynamic memory allocation of a variable.
The actual location of a variable in the memory is system dependent and therefore, the address of a
variable is not known to us immediately. We can access the address of a variable by using address
operator ‘ & ’ . The operator & immediately preceding a variable returns the address of the variable
associated with it.
e.g: x=&p;
The address operator can be used only with a simple variable or array elements.
Initializing of pointer variables:
The process of assigning the address of a variable to a pointer variable is known as initialization of
pointer
variable. Once a pointer variable has been declared we can use the assignment operator to initialize
the variable.
int quantity=10;
int *p;
p=&quantity;
Remember that is an initialization of p and not *p.
Accessing a variable through its pointer:
II B.Com (CA) & B.A (CA) C & C++ Page 29
Once a pointer has been assign the address of a variable, then we can access the variable by using
asterisk
(*) operator, usually known as the indirection operator. Another name for the indirection operator is
the
dereferencing operator. Consider following example
int num,*p,n;
num=179;
p=#
n=*p;
The first line declares num and n as integer variables and p as a pointer variable pointing to an integer.
The second line assigns the values 179 to num and the third line assigns the address of num to the
pointer variable p. The fourth line contains the indirection operator *. When the operator * is placed
before a pointer variable in an expression, the pointer returns the value of the variable of which the
pointer value is
the address. In this case, *p returns the value of the variable num, because p is the address of num. the
*
can be remembered as ‘value at address’.
Example: #include <stdio.h>
void swap(int *x, int *y);
main()
{
int a,b;
printf("Enter two numbers: ");
scanf("%d%d",&a,&b);
printf("Before swapping\n");
swap(&a,&b);
}
void swap(int *x, int *y)
{
int temp;
temp =x*;
x* = y*;
y* = temp;
printf("Swapping Values \n");
printf("a = %d\n",*x);
printf("b = %d\n",*y);
}
1. malloc()
malloc function is used to allocate space in memory during the execution of the program.
malloc function does not initialize the memory allocated during execution. It carries
garbage value.
malloc function returns null pointer if it couldn't able to allocate requested amount of
memory.
Example program for malloc() in C
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *mem_alloc; //memory allocated dynamically
mem_alloc = malloc( 15 * sizeof(char) );
if(mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_alloc,"w3schools.in");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}
2. calloc()
calloc () function and malloc () function is similar. But calloc () allocates memory for zero-initializes.
However, malloc () does not.
Example program for calloc() in C
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char *mem_alloc; //memory allocated dynamically
mem_alloc = calloc( 15, sizeof(char) );
if( mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
II B.Com (CA) & B.A (CA) C & C++ Page 31
else
{
strcpy( mem_alloc,"w3schools.in");
}
printf("Dynamically allocated memory content : %s\n", mem_alloc );
free(mem_alloc);
}
3. realloc()
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function.
In short, it changes the memory size.
Let's see the syntax of realloc() function.
ptr=realloc(ptr, new-size)
4. free()
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Let's see the syntax of free() function.
free(ptr)
2. Classes
A group of objects that share common properties for data part and some program part are
collectively called as class.
In C ++ a class is a new data type that contains member variables and member functions that
operate on the variables.
3. Data abstraction
Abstraction refers to the act of representing essential features without including the back
ground details or explanations.
Classes use the concept of abstraction and are defined as size, width and cost and functions to
operate on the attributes.
4. Encapsulation
The wrapping up of data and function into a single unit (called class) is known as encapsulation.
The data is not accessible to the outside world and only those functions which are wrapped in
the class can access it.
These functions provide the interface between the objects data and the program.
5. Inheritance
Inheritance is the process by which objects of one class acquire the properties of another class.
In the concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it.
This is possible by designing a new class will have the combined features of both the classes.
6. Polymorphism
II B.Com (CA) & B.A (CA) C & C++ Page 34
The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism.
Poly refers too many. That is a single function or an operator functioning in many ways
different upon the usage is called polymorphism.
7. Dynamic binding
Binding refers to the linking of a procedure call to the code to the executed in response to the
call.
Dynamic binding means the code associated with a given procedure call is not known until the
time of the call at run-time.
It is associated with a polymorphic reference depends upon the dynamic type of that reference.
8. Message passing
An object oriented program consists of a set of objects that communicate with each other.
A message for an object is a request for execution of a procedure and therefore will invoke a
function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function
(message) and information to be sent.
Q. Applications of OOP:
Object-Oriented programming has several advantages over procedural languages. As OOP is faster and
easier to execute it becomes more powerful than procedural languages like C++. OOPs is the most
important and flexible paradigm of modern programming. It is specifically useful in modeling real-world
problems. Below are some applications of OOPs:
Real-Time System design: Real-time system inherits complexities and makes it difficult to build
them. OOP techniques make it easier to handle those complexities.
Hypertext and Hypermedia: Hypertext is similar to regular text as it can be stored, searched,
and edited easily. Hypermedia on the other hand is a superset of hypertext. OOP also helps in
laying the framework for hypertext and hypermedia.
AI Expert System: These are computer application that is developed to solve complex problems
which are far beyond the human brain. OOP helps to develop such an AI expert System
Neural networking and parallel programming: It addresses the problem of prediction and
approximation of complex-time varying systems. OOP simplifies the entire process by simplifying
the approximation and prediction ability of the network.
Stimulation and modeling system: It is difficult to model complex systems due to varying
specifications of variables. Stimulating complex systems require modeling and understanding
interaction explicitly. OOP provides an appropriate approach for simplifying these complex
models.
Object-oriented database: The databases try to maintain a direct correspondence between the
real world and database object in order to let the object retain it identity and integrity.
This programming paradigm emphasizes on the use This programming paradigm is based on object
of functions where each function performs a oriented concept. Classes are used where
specific task. instance of objects are created
Fundamental elements used are variables and Fundamental elements used are objects and
functions. The data in the functions are immutable methods and the data used here are mutable
(cannot be changed after creation). data.
The statements in this programming paradigm does The statements in this programming paradigm
not need to follow a particular order while need to follow an order i.e., bottom up
execution. approach while execution.
No data hiding is possible. Hence, Security is not Provides data hiding. Hence, secured programs
possible. are possible.
Introduction to C++
C ++ is an object oriented programming language, C ++ was developed by Jarney Stroustrup at AT & T
Bell lab, USA in early eighties. C ++ was developed from c and simula67 language. C ++ was early called
‘C with classes’.
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network connection, etc, this
is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to main memory, this
is called as input operation.
I/O Library Header Files
Let us see the common header files used in C++ programming are:
Header File Function and Description
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision
and setw.
The cout is a predefined object of ostream class. It is connected with the standard output device, which
is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to
display the output on a consol
Let's see the simple example of standard output stream (cout):
#include <iostream>
using namespace std;
int main( ) {
II B.Com (CA) & B.A (CA) C & C++ Page 38
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
II.Derived Data Types: Derived data type is the aggregation of fundamental data
type. Character, integer, float, and void are fundamental data types. Pointers, arrays, structures and
unions are derived data types
III.User Define Data Types: Those data types which are defined by the user as per his/her will are
called user-defined data types. Examples of such data types are structure, union and enumeration.
OPERATORS
C operators are symbols that are used to perform mathematical or logical manipulations. The C
programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions . They are
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators
1. Arithmetic Operators :
‘C’ provides a few basic arithmetic operators. The operators ‘+’, ‘-’, ‘*’, etc are work in
the same way as they do in the other languages also.
Operator Meaning
+ (plus) Addition
- (unary) Subtraction
* Multiplication
/ Division
% Modules or Remainder
2. Relational Operators :
Ex : x=5; y=a+b;
5. Increment or Decrement Operators :
‘C’ has two very useful operators, not generally found in other languages. These are the
increment(++) and decrement(--) operators. The operator ‘++’ adds “1” to the operand. While ‘- -’
subtracts “1” from the operand. Both are called unary operators.
Here ++m is equivalent to m=m+1
-- m is equivalent to m=m-1 or m=-1
++m is called pre incrementation, m++ is called post incrementation. Similarly --m is
called pre decrementation and m- - is called post decrementation.
6. Conditional Operator (Ternary) :
A ternary operator pair “?” is available in ‘C’ language to construct a conditional
expression. The syntax is
Variable=exp1 ? exp2 : exp 3;
Example : a=10, b=15
X=a>b ? a:b
In this example first it will evaluate the exp 1. If it is true the value of a (exp2) will be assigned to
x. If the condition is false, the value of b(exp3) will be assigned to x.
7. Bitwise Operators :
‘C’ has a distinction of supporting some operators called as bitwise operators and are
used for manipulation of data at bit level. These operators are used for testing the bits or shifting
them from right to left, left to right etc., They are
Operator Meaning
& Bitwise AND
| (pipe symbol) Bitwise OR
^ Bitwise x-OR (ap)
~ /S Complement (tilde)
<< Left shift
II B.Com (CA) & B.A (CA) C & C++ Page 41
>> Right shift
8. Special Operators :
‘C’ supports some special operators, such as comma(,) operaor, “size=of” operator, point
operators (& and *), member selection operators (. and ).
The ‘statement-block’ may be a single statement or a group of statements. If the test condition
is true, the statement-block will be executed; otherwise the statement-block will be skipped and
the execution will jump to the statement-x.
Syntax:
if( test condition )
{
statement – block ;
}
statement –x
Example: #include <iostream>
using namespace std;
int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
2. If – else Statement:
If the test condition is true, then the True statement- block; immediately following the if statement, are
executed; otherwise, the False- statement- block are executed. In any case, either True statement-
block or False- statement- block will be executed, not both. After executing any one block of
statements, the control is transfers to the statement-x.
Syntax:
if( test condition )
{
True-statement- block;
}
else {
False- statement- block;
}
Statement –x
Example:
#include <iostream>
using namespace std;
int main () {
II B.Com (CA) & B.A (CA) C & C++ Page 42
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}
3. else-if Ladder:
If-Else Ladder or Else if Ladder is a multiple decision making statement. In this statement, First
Condition 1 Will is tested. IF the condition is true the statement1 will be execute .If the condition false
the Second condition will be tested. If the Second condition will be true the statement 2 will be
execute. if the condition 2 false condition3 will be execute and so on …..
Syntax:
If (test condition1)
{
Statement - block-1;
}
else
{if ( test condition2 )
{
Statement - block-2;
}
else
{
if ( test condition3)
{
Statement - block-3;
}
else
{
default Statement - block
} }}}
Statement –x;
Example: #include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
II B.Com (CA) & B.A (CA) C & C++ Page 43
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}
3. Nested if Statement:
Nested if is also a multiple decision making statement. In this statement. First Condition will be tested if
the condition is true another if condition will be execute if the condition is false false statement
execute and so on….
if( test condition1 )
{
if ( test condition2 )
{
Statementblock- 1;
}
else
{
Statementblock- 2;
}
}
else
{
Statement - block-3;
}
Statement –x;
Example: #include <iostream>
using namespace std;
int main () {
int a = 100;
int b = 200;
if( a == 100 ) {
if( b == 200 ) {
cout << "Value of a is 100 and b is 200" << endl;
}
}
II B.Com (CA) & B.A (CA) C & C++ Page 44
cout << "Exact value of b is : " << b << endl;
return 0;
}
case value 2 :
Statements ;
break;
case value 3 :
Statements ;
break;
default :
default Statements ;
break;
}
Example: #include <iostream>
using namespace std;
int main () {
int num;
INLINE FUNCTION:
Q. FUNCTION OVERLOADING:
Overloading refers to the use of the same thing for different purposes.
C++ also permits overloading functions .This means that we can use the same function name to
create functions that perform a variety of different tasks. This is known as function
polymorphism in oops.
Using the concepts of function overloading, a family of functions with one function name but
with different argument lists in the functions call.
The correct function to be invoked is determined by checking the number and type of the
arguments but not on the function type.
For example an overloaded add () function handles different types of data as shown below.
//Declaration
a) The compiler first tries to find an exact match in which the types of actual arguments are the same
and use that function.
b) If an exact match is not found the compiler uses the integral promotions to the actual arguments
such as:
char to int
float to double
to find a match
c) When either of them tails, the compiler tries to use the built in conversions to the actual arguments
and them uses the function whose match is unique. If the conversion is possible to have multiple
matches, then the compiler will give error message.
Example: long square (long n);
Will cause an error because int argument can be converted to either long or double .There by creating
an ambiguous situation as to which version of square ( ) should be used.
Classes and Objects: Specifying a class, defining member functions, Access control, constructors and
destructors, Friend functions – Inheritance – Class hierarchy, derived classes, types of inheritance,
Polymorphism-static binding, dynamic binding, method overloading with virtual functions, pure virtual
functions, abstract classes.
CLASS:-
Class is a group of objects that share common properties and relationships.
In C++, a class is a new data type that contains member variables and member functions that
operates on the variables.
A class is defined with the keyword class. It allows the data to be hidden, if necessary from
external use.
When we defining a class, we are creating a new abstract data type that can be treated like any
other built in data type.
Example: item x;
Creates a variables x of type item. In C++, the class variables are known as objects. Therefore x is called
an object of type item.
item x, y ,z also possible.
class item
{
-----------
-----------
-----------
}x ,y ,z;
would create the objects x ,y ,z of type item.
Q. What is a CONSTRUCTOR?
A constructor is a special member function whose task is to initialize the objects of its class. It is special
because its name is the same as the class name. The constructor is invoked whenever an object of its
associated class is created. It is called constructor because it construct the values of data members of
the class. A constructor is declared and defined as follows:
//'class with a constructor
class integer
{
int m,n;
public: integer! void); //constructor declared
------------
------------
};
integer:: integer(void)
{
m=0;
n=0;
II B.Com (CA) & B.A (CA) C & C++ Page 52
}
There are four types of constructors used in C++.
1. Default constructor
2. Dynamic constructor
3. Parameterized constructor
4. Copy constructor
1. Default constructor
A constructor that accepts no parameter is called the default constructor. The default constructor for
class A is A :: A( ). If no such constructor is defined, then the compiler supplies a default constructor.
Therefore a statement such as: - A a; //invokes the default constructor of the compiler of the compiler
to create the object "a”;
The constructor functions have some characteristics:-
They should be declared in the public section.
They are invoked automatically when the objects are created.
They don't have return types, not even void and therefore. They cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
Like other C++ function , they can have default arguments,
Constructor can't be virtual.
An object with a constructor can't be used as a member of union.
3. COPY CONSTRUCTOR:
A copy constructor is used to declare and initialize an object from another object.
Example: - the statement
integer 12(11);
Would define the object 12 and at the same time initialize it to the values of 11.
Another form of this statement is : integer 12=11;
The process of initialization through a copy constructor is known as copy initialization.
Example:-
#include<iostream.h>
class code
{
int id;
public code ( ) {} //constructor
code (int a) { id=a; } //constructor
code(code &x)
{
Id=x.id;
}
void display( )
{
cout<<id;
}
};
int main( )
{
4. DYNAMIC CONSTRUCTOR:-
The constructors can also be used to allocate memory while creating objects. This will enable the
system to allocate the right amount of memory for each object when the objects are not of the same
size, thus resulting in the saving of memory. Allocate of memory to objects at the time of their
construction is known as dynamic constructors of objects. The memory is allocated with the help of
new operator.
Example:-
#include <iostream.h>
#include<conio.h>
class string
{
char *name;
int length;
public:
string ( )
{
length=0;
name= new char [length+1]; /* one extra for \0 */
}
string( char *s) //constructor 2
{
length=strlen(s);
name=new char [length+1];
strcpy(name,s);
}
void display(void)
{
Cout<<name<<endl;
}
void join(string &a .string &b)
{
length=a. length +b . length;
delete name;
name=new char[length+l]; /* dynamic allocation */
strcpy(name,a.name);
II B.Com (CA) & B.A (CA) C & C++ Page 55
strcat(name,b.name);
}
};
int main( )
{
char * first = “Joseph” ;
string name1(first),name2(“louis”),naine3( “LaGrange”),sl,s2;
sl.join(name1,name2);
s2.join(s1,name3);
namel.display( );
name2.display( );
name3.display( );
s1.display( );
s2.display( );
}
output :- Joseph
Louis
Language
Joseph Louis
Joseph Louis Language
A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the
compiler upon exit from the program to clean up storage that is no longer accessible. It is a good
practice to declare destructor in a program since it releases memory space for future use.
Delete is used to free memory which is created by new.
Example:- matrix : : ~ matrix( )
{
for(int i=0; i<11;i++)
delete p[i];
delete p;
}
Example of destructor:
#include <iostream.h>
#include <conio.h>
using namespace std;
class Hello {
public:
//Constructor
Hello () {
cout<< "Constructor function is called" <<endl;
}
//Destructor
II B.Com (CA) & B.A (CA) C & C++ Page 56
~Hello () {
cout << "Destructor function is called" <<endl;
}
//Member function
void display() {
cout <<"Hello World!" <<endl;
}
};
int main(){
//Object created
Hello obj;
//Member function called
obj.display();
return 0;
}
Q. Friend function
A friend function of a class is defined outside that class' scope but it has the right to access all
private and protected members of the class. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.
Declaration of friend function in C++
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
Characteristics of a Friend function:
The function is not in the scope of the class to which it has been declared as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
It can be declared either in the private or the public part.
Q. Inheritance
Reaccessability is yet another feature of OOP's. C++ strongly supports the concept of reusability. The
C++ classes can be used again in several ways. Once a class has been written and tested, it can be
adopted by another programmer. This is basically created by defining the new classes, reusing the
properties of existing ones. The mechanism of deriving a new class from an old one is called
'INHERTTENCE'. This is often referred to as IS-A' relationship because very object of the class being
defined "is" also an object of inherited class. The old class is called 'BASE' class and the new one is
called 'DERIEVED' class.
Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
Modes of Inheritance
1.Public mode: If we derive a sub class from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in derived class.
2.Protected mode: If we derive a sub class from a Protected base class. Then both public member
and protected members of the base class will become protected in derived class.
3.Private mode: If we derive a sub class from a Private base class. Then both public member and
protected members of the base class will become Private in derived class.
Types of Inheritance
Single inheritance
Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited from the only one
base class.
Example:
#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Multilevel Inheritance:
When the inheritance is such that, the class A serves as a base class for a derived class B which in turn
serves as a base class for the derived class C. This type of inheritance is called ‘MULTILEVEL
INHERITENCE’.
Example:
#include<iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
// first sub_class derived from class vehicle
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
II B.Com (CA) & B.A (CA) C & C++ Page 59
cout << "Objects with 4 wheels are vehicles\n";
}
};
// sub class derived from the derived base class fourWheeler
class Car: public fourWheeler {
public:
Car()
{
cout << "Car has 4 Wheels\n";
}
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Hierarchical Inheritance:
In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than
one derived class is created from a single base class.
Example:
#include<iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
};
// second sub class
class Bus: public Vehicle
{
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Multiple Inheritance:
Multiple Inheritances is a feature of C++ where a class can inherit from more than one classes. i.e
one sub class is inherited from more than one base classes.
Examples:
#include<iostream>
using namespace std;
// first base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
// second base class
class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};
// sub class derived from two base classes
class Car : public Vehicle, public FourWheeler {
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}
Hybrid Inheritance
There could be situations where we need to apply two or more types of inheritance to design a
program. Basically Hybrid Inheritance is the combination of one or more types of the inheritance.
Examples:
#include<iostream>
using namespace std;
// base class
class Vehicle
{
public:
II B.Com (CA) & B.A (CA) C & C++ Page 61
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
//base class
class Fare
{
public:
Fare()
{
cout << "Fare of Vehicle\n";
}
};
// first sub class
class Car : public Vehicle
{
};
// second sub class
class Bus : public Vehicle, public Fare
{
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base class.
Bus obj2;
return 0;
}
Polymorphism
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a
hierarchy of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function will cause a different function to be
executed depending on the type of object that invokes the function.
Compile time polymorphism: The overloaded functions are invoked by matching the type and
number of arguments. This information is available at the compile time and, therefore, compiler
selects the appropriate function at the compile time. It is achieved by function overloading and
operator overloading which is also known as static binding or early binding. Now, let's consider the
case where function name and prototype is same.
II B.Com (CA) & B.A (CA) C & C++ Page 62
Run time polymorphism: Run time polymorphism is achieved when the object's method is
invoked at the run time instead of compile time. It is achieved by method overriding which is also
known as dynamic binding or late binding.
Q. Operators Overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to
provide the special meaning to the user-defined data type.
Operator overloading is used to overload or redefines most of the operators available in C++. It
is used to perform the operation on the user-defined data type.
For example, C++ provides the ability to add the variables of the user-defined data type that is
applied to the built-in data types.
Operator overloading provides a flexible option for the creation of new definations for most of
the C++ operators.
We can overload all the C++ operators except the following:
Scope operator (::)
Sizeof
member selector(.)
member pointer selector(*)
ternary operator(?:)
Although the semantics of an operator can be extended, we can't change its syntax, the
grammatical rules that govern its use such as the no of operands precedence and associatively.
For example the multiplication operator will enjoy higher precedence than the addition
operator.
When an operator is overloaded, its original meaning is not lost.
For example, the operator +, which has been overloaded to add two vectors, can still be used
to add two integers.
DEFINING OPERATOR OVERLOADING
return-type class-name::operator op(arg-list)
{
function body
}
Where return type is the type of value returned by the specified operation and op is the
operator being overloaded.
The op is preceded by the keyword operator, operator op is the function name.
Rules for Operator Overloading
Existing operators can only be overloaded, but the new operators cannot be overloaded.
The overloaded operator contains at least one operand of the user-defined data type.
We cannot use friend function to overload certain operators. However, the member function
can be used to overload those operators.
Q. this pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member functions. Therefore,
inside a member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class. Only
member functions have a this pointer.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
Q. Exception Handling
An exception is a problem that arises during the execution of a program.
A C++ exception is a response to an exceptional circumstance that arises while a program is
running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the catching
of an exception.
try − A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks.
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try
{
z = division(x, y);
cout << z << endl;
}
catch (const char* msg)
{
II B.Com (CA) & B.A (CA) C & C++ Page 68
cerr << msg << endl;
}
return 0;
}