Microsoft Word - Rahul Notes C++
Microsoft Word - Rahul Notes C++
Introduction to C++ :-
C++ is a statically typed, compiled, general purpose,
case-sensitive, free from programming language that supports the concepts of object-
oriented programming language.
High
Hj level language Compiler Machine language
Application of C ++ :-
GUI (Graphical user interface) application.
Image editing.
Software, Web browsers.
Compiler.
Different operating systems.
Game development.
C++ Tokens :- In a c++ program the smallest individual unit are known as tokens. C++
programs are written using these tokens.
C++ Tokens
Identifier
Strings
ii. Identifiers :- Identifiers refers to the names of variable, function, array, c lasses, etc.
These are user defined names consist of a of sequence of letters and digits with a letter as a
first character.
Rules for identifiers :-
First tractor must be an alphabet or underscore.
It consists of only letters, digits or underscore.
Cannot use a keyword.
Must not contain white spaces.
iii. Constants :- Constant refers to a fixedvalue that does not change during execution of
program.
123 // decimal integer
12.34 // float point integer
0.37 // octal integer
0x2 // Hexadecimal constant
“C++” // String Constant
‘A’ // Character constant
‘ab’ // Wide Character constant
iv. Strings:- It is always represented as an array of characters. Strings are enclosed within
single quotes.
The size of string is a number of characters that the string contains. For e.g.:-
“ABC”…..etc.
v. Operators:- It is a special symbol use to perform the function. The operator is a symbol
that tells the compiler to perform specific mathematical or logical manipulation.
C++ has may operators like Arithmetic, logical, comparison, assignment and
bitwise operators.
operator
A ++ B
Operand
vi. Variables :- A variable is a data name that may be used to store data value . Unlike
constants that remains unchanged during the execution of a program, a variable may take
different values at different times during execution.
Rules for constructing variables :-
First character in the variable must be an alphabet or underscore. For e.g :- int x,
_temp;
The length of variable can be long as specified b It’s cool suckle suck. ut the
compiler only recognize the first eight characters. For e.g. :- file manager;
(system recognizes the first 8 characters i.e. file_man)
No commas or blanks are allowed with in a variable name. for e.g int h1; (valid)
int h,1; (not valid)
No special symbol other than underscore can be used in a variable name.
C++ Data Types :- All variables use data type during declaration to restrict the type
of data to be stored. Therefore, we can say that data types are used to tell the variables the type
of data they can store. Whenever a variable is defined in C++, the compiler allocates some
memory for that variable based on the data type with which it is declared. Every data type
requires a different amount of memory.
C++ supports the following data types :-
Union
Integer Array
Structure
Function
Float/Real
Class
Pointer
Void
Enumeration
Character
Primary or Built-in or Basic data type:- These data types are built-in or
predefined data types and can be used directly by the user to declare variables. example: int,
char, float, void, etc. Primitive data types available in C++ are:
i. Integer:- This data type is used to define the variables taking integer value with or
without constant values given to them.
The keyword or the data type used to define integer is ‘int’. There are other data
types like integer ‘short’ and ‘long’ used to define integer value but they have
different ranges.
ii. Float:- This data type is used to define the variables taking decimal values.
The keyword or the data type used to define float is ‘float’. There are other data
types like ‘double’ and ‘long double’ used to define decimal values but they have
different ranges.
iii. Void:- The void data type has no values. The type of function is said to be void when it
doesn’t return any value to the calling function.
The keyword or the data type used to define void is ‘void’.
class car
{
class declaration or definition
Class function definition
};
Int main()
{
class_name object_name;
statements;
}
Advantages of C++ :-
a+b
a-b a + b
a*b
operand
a/b
a%b
Compile time
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
a=10;
b=20;
c=a+b;
cout<<"Result is "<<c;
return 0;
}
Run time
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter the value of a and b";
cin>>a>>b;
c=a+b;
cout<<"Result is "<<c;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter the value of a ";
cin>>a;
a/=4;
cout<<"Value of a is "<<a;
return 0;
}
4) Logical operator:- These operators are used to combine two or more conditions.
These are mainly of three types :-
a. AND (&&)
b. OR (||)
c. NOT (!)
a.) And operator:- The ‘&&’ operator returns true when both the conditions under
consideration are satisfied otherwise it returns false. For example :- a and b returns true
when both a and b are true (i.e. non zero ).
A Y=A*B
AND
B
GATE
b.) OR operator :- The “||” operator returns true even if one ( or both ) of the conditions
under consideration is satisfied. Otherwise, it returns false. For example :- a//b returns true
if one of a or b or both true (i.e. non-zero) of course, it returns true when both a and b are
true.
c.) Not operator :- The ‘!’ operator returns true the condition under consideration is not
satisfied, otherwise it returns false. For example :- !a returns true if a is false i.e. when a=0.
5) Bitwise operator:- It is a type of operator that operates on bit arrays, bit strings
and binary values with individuals bits at the bit level. In simple words we can say that is used
to manipulate values in computer.
C++ provides following operators for bit manipulation :-
a.) & Bitwise AND
b.) | Bitwise OR
c.) ^ Bitwise Exclusive OR
d.) << Shift left
e.) >> Shift right
a.) Bitwise AND (&) :- The bitwise AND operator in a single ampersand (&). It is just a
representation of AND which does it works on the bits of the operands rather than the
truth value of the operands.
For example :-
1 1 0 0 1 0 0 0
& 1 1 0 0 1 0 0 0
1 0 0 0 1 0 0 0
b.) Bitwise OR (|) :- The bitwise OR operator perform logical disjunction at the bit level.
Its result is 1 if either of the bit is 1and 0. Only and when both bits are 0. Its symbol is ‘1’
which can be called a pipe.
For example :-
1 1 0 0 1 0 0 0
| 1 0 1 1 1 0 0 0
1 1 1 1 1 0 0 0
c.) Bitwise Exclusive OR (^) :- It sets each bits in the result to 1 if the corresponding
bits in two operands are different. It is frequently used to set a bit to 1 (ON) or 0 (OFF).
For example :-
1 1 0 0 1 0 0 0
^ 1 0 1 1 1 0 0 0
0 1 1 1 0 0 0 0
d.) Shift Left (<<) :- It Shifts each bits in its left hand operand to the left by number of
positions indicated by right hand operand.
For example :- If the variables ch contains the bit pattern 11100101 then ch<<1 will
produce 11001010 .
e.) Shift right (>>) :- It Shifts each bits in its right hand operand to the right by number of
positions indicated by left hand operand.
For example :- ch>>1 in the above example we have 01110010 .
Control
statement
If for goto
switch
A. Decision making statement:- These statement are also known as
conditional operator. We can use these condition to perform different action for different
decisions. Like :- If, if-else, if-else if-else and switch statements.
a.) if statement:- It is used to decide wheather a certain statement or block of
statement will be executed or not . i.e. if the certain condition is true than a block of
statement is executed otherwise not.
Syntax:-
If(condition)
{
// Statements;
}
Programs of if statement
WAP TO PRINT YOUR NAME IF A=15.
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter value of a";
cin>>a;
if(a==15)
{
cout<<"Rahul";
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter value of a and b";
cin>>a>>b;
if(a>b)
{
cout<<"A is greater than B";
}
else
{
cout<<"B is greater than A";
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter value of a";
cin>>a;
if(a%2==0)
{
cout<<"Number is even";
}
else
{
cout<<"Number is odd";
}
return 0;
}
c.) if-else if statement:- This statement chooses one of the statements available
depending on the condition. If no condition are true then the else statement at the end is
executed.
Syntax:-
If(condition)
{
// Statements 1;
}
else If(condition)
{
// Statements 2;
}
else If(condition)
{
// Statements 3;
}
.
.
.
.
else
{
// Statements 3;
}
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter value of a";
cin>>a;
if(a>0)
{
cout<<"Number is positive";
}
else if(a<0)
{
cout<<"Number is negative";
}
else
{
cout<<"Number is zero";
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b,c,ch;
cout<<"Enter the value of a and b";
cin>>a>>b;
cout<<"Enter the choice";
cin>>ch;
switch(ch)
{
case 1:
c=a+b;
cout<<"Addition"<<c;
break;
case 2:
c=a-b;
cout<<"Subtraction"<<c;
break;
case 3:
c=a*b;
cout<<"Multiplication"<<c;
break;
case 4:
c=a/b;
cout<<"Division"<<c;
break;
case 5:
c=a%b;
cout<<"modulus"<<c;
break;
default:
cout<<"Wrong choice";
break;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b,x,ch;
cout<<"Enter the choice";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter value of a and b";
cin>>a>>b;
if(a>b)
{
cout<<"A is greater ";
}
else if (b>a)
{
cout<<"B is greater";
}
else
{
cout<<"Both are equal";
}
break;
case 2:
cout<<"Enter the number";
cin>>x;
if(x>0)
{
cout<<"Positive number";
}
else if(x<0)
{
cout<<"Negative number";
}
else
{
cout<<"Number is zero";
}
break;
case 3:
cout<<"Enter number";
cin>>x;
if(x%2==0)
{
cout<<"Even number";
}
else
{
cout<<" Odd number";
}
break;
default:
cout<<"Wrong choice";
break;
}
return 0;
}
B. Looping statements:- A set of statements are executing using repetitive
structure. These statements are executed many times while these statements appear once in
the program.
There are two types pf loops:-
I.) Entry controlled loop:- The condition is tested before entering loop
body.
Like :- for loop, while loop.
II.) Exit controlled loop:-Test condition is tested/evaluated at the end of
loop body. Therefore, loop body will execute at least once, irrespective
of weather the test condition is true/false.
Like :- do-while loop.
a.) While loop :- The while loop is often used when the numbers of times the
loop has to be executed is known in advance.
Syntax :-
While(condition)
{
Statement;
Increment/decrement;
}
#include<iostream>
using namespace std;
int main()
{
int i;
while(i<=5)
{
cout<<"HELLO"<<endl;
i++;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int i,n,sum=0;
cout<<"Enter value of n";
cin>>n;
while(i<=n)
{
sum=sum+i;
i++;
}
cout<<"Sum is "<<sum;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int rem,rev=0,num;
cout<<"Enter number";
cin>>num;
while(num !=0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
cout<<"Reverse of a number is"<<rev;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int n,rem,rev=0,num;
cout<<"Enter number";
cin>>num;
n=num;
while(num>0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
if(n==rev)
{
cout<<"Palindrome";
}
else
{
cout<<"Not palindrome";
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int n,rem,sum=0,num;
cout<<"Enter number";
cin>>num;
n=num;
while(num>0)
{
rem=num%10;
sum=sum+rem*rem*rem;
num=num/10;
}
if(n==sum)
{
cout<<"Armstrong number";
}
else
{
cout<<"Not armstrong";
}
return 0;
}
WAP TO FIND SUM OF A DIGIT.
#include<iostream>
using namespace std;
int main()
{
int rem,sum=0,num;
cout<<"Enter number";
cin>>num;
while(num>0)
{
rem=num%10;
sum=sum+rem;
num=num/10;
}
cout<<"Sum of digit"<<sum;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int rem,pro=1,num;
cout<<"Enter number";
cin>>num;
while(num>0)
{
rem=num%10;
pro=pro*rem;
num=num/10;
}
cout<<"Product of digit"<<pro;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b,rem;
cout<<"Enter the value of a and b";
cin>>a>>b;
rem=a%b;
while(rem!=0)
{
a=b;
b=rem;
rem=a%b;
}
cout<<"HCF is "<<b;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b,c,rem,lcm;
cout<<"Enter the value of a and b";
cin>>a>>b;
c=a*b;
rem=a%b;
while(rem!=0)
{
a=b;
b=rem;
rem=a%b;
}
lcm=c/b;
cout<<"LCM is "<<lcm;
return 0;
}
b.) For loop :- There are situations where you want to have a statement or a
group of statements, to be execute number of times and the number of repetition
doesn’t depend on the condition.
But it is simply a repetition up-to a certain number.
This loop helps us to perform ‘n’ number of steps together in one line.
Syntax:-
For(initialization ; condition; increment/decrement)
{
Statement ;
}
#include<iostream>
using namespace std;
int main()
{
int i,sum=0,n;
cout<<"Enter value of n";
cin>>n;
for(i=1; i<=n; i++)
{
sum=sum+i;
}
cout<<"Sum is "<<sum;
return 0;
}
int i,t,n;
cout<<"Enter value of n";
cin>>n;
for(i=1; i<=10; i++)
{
t=n*i;
cout<<"Table of a number is "<<t<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int i,f=1,n;
cout<<"Enter value of n";
cin>>n;
for(i=1; i<=n; i++)
{
f=f*i;
}
cout<<"Factorial of a number is "<<f<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a=0,b=1,i,n,c;
cout<<"Enter value of n";
cin>>n;
for(i=1; i<=n; i++)
{
c=a+b;
cout<<c<<endl;
a=b;
b=c;
}
return 0;
}
c.) Do-While loop:- In while loop, condition is evaluated first. Therefore, the
body of the loop may not be executed at all if the condition is not satisfied at the
first attempt. But in do-while loop condition is evaluated at the end.
Syntax:-
Initialization ;
do
{
statement ;
Increment/decrement;
}
while(condition);
PATTERNS
WAP TO PRINT OUTPUT.
#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=1; i<=5; i++)
{
for(j=1; j<=5; j++)
{
cout<<"*";
}
cout<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
{
cout<<i<<" ";
}
cout<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int i,j,k;
for(i=5; i>=1; i--)
{
for(j=1; j<=5-i; j++)
{
cout<<" ";
}
for(k=1; k<=2*i-1; k++)
{
cout<<"*";
}
cout<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=5; i>=1; i--)
{
for(j=i; j>=1; j--)
{
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}
a.) Break statement:- This statement is used to move out from switch block if you
don’t write break statement in any case that are given in choice, than in that situation
all the cases below to given choice will be executed till the break statement is not found.
We can also use break statement with if statement
Sytntax:-
break ;
#include<iostream>
using namespace std;
int main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==5)
break;
cout<<i<<endl;
}
return 0;
}
b.) Continue statement:- The continue statement breaks one iteration (in the
loop) if a satisfied conditions occurs, and continus with the next iteration in the loop.
Syntax:-
continue ;
#include<iostream>
using namespace std;
int main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==4)
continue;
cout<<i<<endl;
}
return 0;
}
c.) Goto statement:- The C++ goto statement is used to jump directly to that part
of the program to which it is being called. Every goto statement is associated with the
label which takes them to part of the program for which they are called. The label
statements can be written anywhere in the program it is not necessary to use them
before or after the goto statement.
Syntax:-
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter any number";
cin>>n;
if (n % 2 == 0)
goto label1;
else
goto label2;
label1:
cout << "Even" << endl;
return 0;
label2:
cout << "Odd" << endl;
}
Array
Array:- Array is a collection of similar data type. Array are used to store multiple value
in a single variable, instead of declaring separate variable of each value.
Followed by square bracket
Declaration of arrays:-
Int arr [5]
Data type Array name Array size
2.) Two-dimensional array:- In this type of array, two index describe each elements,
the first index represent a row and the second index represents a column.
Syntax:-
data_type array_name[size 1] [size 2];
Column 0 column 1 column 2
Row 1
Programs of Array
#include<iostream>
using namespace std;
int main()
{
int a[5],i,sum=0;
cout<<"Enter the elements of array";
for(i=0; i<=4; i++)
{
cin>>a[i];
}
for(i=0; i<=4; i++)
{
cout<<"elements of array are "<<a[i]<<endl;
}
for(i=0; i<=4; i++)
{
sum=sum+a[i];
}
cout<<"sum is = "<<sum;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a[5],i,even=0,odd=0;
cout<<"Enter array elements";
for(i=0;i<=4;i++)
{
cin>>a[i];
}
for(i=0; i<=4; i++)
{
if(a[i]%2==0)
{
even=even+a[i];
}
else
{
odd=odd+a[i];
}
}
cout<<"Addition of even number ="<<even<<endl;
cout<<"Addition of odd number ="<<odd;
}
#include<iostream>
using namespace std;
int main()
{
int a[5],i,max;
cout<<"Enter array elements";
for(i=0; i<=4; i++)
{
cin>>a[i];
}
max=a[0];
for(i=1; i<=4; i++)
{
if(max<a[i])
{
max=a[i];
}
}
cout<<"Biggest element of array is "<<max;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a[2][2],i,j;
cout<<"Enter array elements "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cin>>a[i][j];
}
}
cout<<"Array Elements in matrix "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a[2][2],i,j;
cout<<"Enter array elements "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cin>>a[i][j];
}
}
cout<<"Array Elements in matrix "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"Transpose of matrix "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<a[j][i]<<" ";
}
cout<<endl;
}
return 0;
}
Strings
String:- A string consist of number of characters enclosed with double quotes. A string
may also known as an array of characters.
Syntax:
Char str [50]
String
Char String Size
data name
type
String function :-
i.) strrev (String reverse)
ii.) strlwr (String lower)
iii.) strupr (String upper)
iv.) strcmp (String compare)
v.) strcat (String catenation)
vi.) strlen (String length)
vii.) strcpy (String copy)
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50],s2[20];
cout<<"Enter string S1"<<endl;
gets(s1);
cout<<"Enter string S2"<<endl;
gets(s2);
cout<<"String concatination ";
strcat(s1,s2);
puts(s1);
return 0;
}
WAP OF COPY THE STRING.
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50],s2[20];
cout<<"Enter string S1"<<endl;
gets(s1);
cout<<"Enter string S2"<<endl;
gets(s2);
cout<<"Copy of string= ";
strcpy(s1,s2);
puts(s1);
return 0;
}
What is Pointer ?
A pointer is a variable that contains the address of another
variable in memory.
For example:-
Int * ptr ;
Data type to which pointer
variable will be pointing to Name of the pointer
variable
Tells the
compiler
that it is a
pointer
variable
For example:-
int i=5;
int *ptr=&i;
In the second statement, pointer variable ptr is initialized with address
of
variable i as shown
1.) Pointers reduce the code and improve performance. They are used to retrieve string, trees,
array, structures, and functions.
2.) Pointers allown us ton return multiple values from function.
3.) In addition to this, the pointer allow us to access a memory location in the computer’s
memory.
Programs of Pointers
#include<iostream>
using namespace std;
int main()
{
int a,b,c,*x,*y;
cout<<"Enter the value of a and b"<<endl;
cin>>a>>b;
x=&a;
y=&b;
c=(*x)+(*y);
cout<<"Sum = "<<c;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,area,*x;
cout<<"Enter the side of square";
cin>>a;
x=&a;
area=(*x)*(*x);
cout<<"Area of square = "<<area;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int b,h,area,*x,*y;
cout<<"Enter the base of triangle";
cin>>b;
cout<<"Enter the height of triangle";
cin>>h;
x=&b;
y=&h;
area=0.5*(*x)*(*y);
cout<<"Area of triangle = "<<area;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b,c,*x,*y;
cout<<"Enter the value of a";
cin>>a;
cout<<"Enter the value of b";
cin>>b;
x=&a;
y=&b;
cout<<"Before swapping"<<endl;
cout<<"Value of *x ="<<*x<<endl;
cout<<"Value of *y ="<<*y<<endl;
c=*x;
*x=*y;
*y=c;
cout<<"After swapping"<<endl;
cout<<"Value of a"<<*x<<endl;
cout<<"value of b"<<*y<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a,b,*x,*y;
cout<<"Enter the value of a";
cin>>a;
cout<<"Enter the value of b";
cin>>b;
x=&a;
y=&b;
cout<<"Before swapping"<<endl;
cout<<"Value of *x ="<<*x<<endl;
cout<<"Value of *y ="<<*y<<endl;
*x=*x+*y;
*y=*x-*y;
*x=*x-*y;
cout<<"After swapping"<<endl;
cout<<"Value of a"<<*x<<endl;
cout<<"value of b"<<*y<<endl;
return 0;
}
FUNCTION
Functions:- A function is a self contain block of statements enclosed between the
braces {} that perform the specific task.
Syntax:-
Function_name()
{
statement (1);
statement (2);
}
Advantages of function :-
1) Function supports modular programming in which a large program is divided into
self-contained path, each of which has an unique purpose.
2) Function result in reducing the overall size of the program as repetitive set of
instruction are written, only once in a function.
3) Function promote portability since written are independent of system dependent
features.
4) Designing large and complex program become very easily and fast using function.
This is because different person can be involved in making different function
which can later combined to make a complete program.
5) In c++ a function can call itself again and again is known as recursion.
1) Library function :- These are those function which are pre-defined in the
compiler. These type of function are group into a library file. These files are also called as
header file. The header file contains the information about library function and the
actual coding is available in the object code from the library file.
There are numbers of library functions in c++:-
a) Library function that carry out standard input/output formatting. For
example :- setw(), setfill(), setbase() etc. They are included in iomanip.h
b) Library function that performs mathematical operations. For example :-
sqrt(), sin(), pow(), abs(), exp() etc. They are included in <math.h
header> file.
c) Library functions that performs operations on strings. For example :-
strcpy(), strlen(), strcm(), strlwr() etc. They are included oin <string.h>
header file.
For example :-
#include<iostream>
using namespace std;
int main()
{
int a,b;
void swap(int,int);
cout<<"Enter the value of a and b"<<endl;
cin>>a>>b;
cout<<"Before calling in main"<<endl;
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
swap(a,b);
cout<<"After calling in main"<<endl;
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
return 0;
}
void swap(int x, int y)
{
int z;
z=x;
x=y;
y=z;
cout<<"After modification in function x = "<<x<<" "<<"y = "<<y<<endl;
}
ii.) Pass by address / call by pointer :- It is a mechanism of
passing arguments to a function. Unlike pass by value method where a copy of
arguments is passed, In passed by address method the address of arguments is
passed to the called function. If any modification are made to the formal
arguments than those are reflected back to the actual arguments.
For example:-
#include<iostream>
using namespace std;
int main()
{
int a,b;
void swap(int*,int*);
cout<<"Enter the value of a and
b"<<endl;
cin>>a>>b;
cout<<"Before calling in
main"<<endl;
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
swap(&a,&b);
cout<<"After calling in main"<<endl;
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
return 0;
}
void swap(int *x, int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
cout<<"After modification in function x = "<<*x<<" "<<"y = "<<*y<<endl;
}
For example :-
#include<iostream>
using namespace std;
int main()
{
int a,b;
void swap(int &,int &);
cout<<"Enter the value of a and b"<<endl;
cin>>a>>b;
cout<<"Before calling in main"<<endl;
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
swap(a,b);
cout<<"After calling in main"<<endl;
cout<<"Value of a = "<<a<<endl;
cout<<"Value of b = "<<b<<endl;
return 0;
}
void swap(int &x, int &y)
{
int z;
z=x;
x=y;
y=z;
cout<<"After modification in function x = "<<x<<" "<<"y = "<<y<<endl;
}
Programs of Functions
#include<iostream>
using namespace std;
int sum(int,int);
int main()
{
int a,b;
cout<<"Enter the value of a and b";
cin>>a>>b;
sum(a,b);
return 0;
}
int sum(int x,int y)
{
int z;
z=x+y;
cout<<"Result is = "<<z;
}
#include<iostream>
using namespace std;
int si(int,int,int);
int main()
{
int p,r,t;
cout<<"Enter the value of p,r and t";
cin>>p>>r>>t;
si(p,r,t);
return 0;
}
int si(int x,int y,int z)
{
int a;
a=(x*y*z)/100;
cout<<"Simple interest is = "<<a;
}
WAP TO CHECK YEAR IS LEAP OR NOT USING
FUNCTION.
#include<iostream>
using namespace std;
int leap(int);
int main()
{
int year;
cout<<"Enter the value of year";
cin>>year;
leap(year);
return 0;
}
int leap(int x)
{
if(x%400==0)
{
cout<<"Leap year";
}
else if(x%100==0)
{
cout<<"Leap year";
}
else if(x%4==0)
{
cout<<"Leap year";
}
else
{
cout<<"Not a leap year";
}
}
#include<iostream>
using namespace std;
int area(int);
int main()
{
int num;
cout<<"Enter the value of number";
cin>>num;
area(num);
return 0;
}
int area(int x)
{
int z;
z=x*x;
cout<<"Area of square is "<<z;
}
Recursion :- It is a process in which function call itself again and again until certain
condition is satisfied.
When a called function in turns calls another function a process
of chaining occurs. Recursion is a special case of this process,
where a function call itself. For recursion there is two basic
requirement :-
i. The function must call itself again and again.
ii. It must have an exit condition.
WAP TO CALCULATE FACTORIAL OF A NUMBER
USING RECURSION.
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int x,fact;
cout<<"Enter the number";
cin>>x;
fact=factorial(x);
cout<<"Factorial of a number = "<<fact;
return 0;
}
int factorial(int a)
{
int n,b;
if(a==1)
{
return (1);
}
else
{
b=a*factorial(a-1);
}
}
Advantages of recursion :-
1.) Recursion function are written in less number of statements.
2.) Recursion is useful for branching process.
3.) Recursion reducing the programming codes as recursion requires less
coding.
4.) Recursion is a powerful tool in mathematical definations.
5.) Recursion function is more concise and more readable.
6.) In certain problems like tower of Hanoi , recursion may be the only
solution.
Disadvantages of recursion :-
1) It consumes large space because the recursive calls along with automatic
variable are stored on the stack. If recursive cells are not checked
properly than system may go out of memory for example :- infinite
recursion.
2) Recursion requires good programming skills because a little careless may
result into infinite recursive loop.
3) It is not more efficient in terms of speed of execution.
OOPS
class Inheritance
Basic concepts
object of object Polymorphism
oriented
programming
Abstraction language Dynamic binding
i.) Object:- It is often used to represent an entity in the real world that can be
easily identified. An object can be a person, place, or anything you can see in the real
world.
Some common examples of an object are car, book, apple etc. Every object is
described by there attributes and behavior. The data describing the object are
referred to as attributes of an object. The behavior of an object is implemented using
functions.
When a program is executed, the objects interacts by sending messages to one
another.
ii.) Classes :- We just mentioned that objects containing data and code to
manipulate that data. The entire set of data and code of an object can be made a
user defined data type with the help of a class. In fact, objects are variables of the
type class. Once a class has been defined we can create any number of objects
belonging to that class. Each object is associated with the data of type class with
which they created.
A class is thus a collection of objects of similar type. For
example:- mango, apple and orange are the members of the class fruit.
Classes are user-defined data types and behaves like built in types of a programming
language.
Object Class
i.) Data and function that operates on i.) A collection of objects with same
that are bended together to form an attributes and common behavior is
object. called a class.
ii.) Objects are real world entities. ii.) Class is just a specification or a
logical entity to create objects.
iii.) Object occupies some space in iii ) Class doesn’t consume space in
memory. memory.
iv.) Object is an instance of a class. iv.) Class is static entity or the attributes
of a class are fix before during and after the
execution of the program.
v.) An object is a dynamic entity that v.) Class is astatic entity or the
has limited life spam. attributes of a class are fix before during
and after the execution of the program.
vi.) Example :- Table ,chair. vi.) Example :- Furniture, suits.
Class shape
draw()
data function
vii.) Dynamic binding :- Binding refers to the linking of function call to the
code of the function to be executed in response to the function call. It is of two
types:-
a) Static binding :- In static binding, the binding is perform at compile time. It
makes the program efficient and faster but the flexibility of the program
becomes poor.
b) Dynamic binding:- This binding is perform at runtime the code of the
function to be linked with function call is unknown until it is executed. It is
associated with polymorphism and inheritance. It provides greater flexibility
used to create class libraries that can be reused and extended.
Advantages of oops :-
Oops provide reusability to the code and extend the use of existing classes.
It is easier to maintain code as there are classes and object which help in
making it easy to maintain rather than restricting.
It also helps in data hiding, keeping the data and information safe from leaking
or getting exposed.
It is easy to implement.
Inheitance
Types of inheritance :-
1.) Single inheritance.
2.) Multi-level inheritance.
3.) Hierarchical inheritance.
4.) Multiple inheritance.
5.) Hybrid inheritance.
1.) Single inheritance :- In a single inheritance a class is derived from only one
base class. This form of inheritance is implemented by defining two classes one of which is
known as base class and other is known as derived class.
Base class
Child class
WAP OF SINGLE INHERITANCE.
#include<iostream>
using namespace std;
class animal
{
public:
void eat()
{
cout<<"Eating"<<endl;
}
};
class dog : public animal
{
public:
void bark()
{
cout<<"Barking";
}
};
int main()
{
dog d;
d.eat();
d.bark();
return 0;
}
Base class A
Child class B
Child class C
WAP OF MULTI-LEVEL INHERITANCE.
#include<iostream>
using namespace std;
class animal
{
public:
void eat()
{
cout<<"Eating"<<endl;
}
};
class dog : public animal
{
public:
void bark()
{
cout<<"Barking"<<endl;
}
};
class cat : public dog
{
public:
void weep()
{
cout<<"Weeping";
}
};
int main()
{
cat c;
c.eat();
c.bark();
c.weep();
return 0;
}
Cat Dog
Child class Child class
#include<iostream>
using namespace std;
class animal
{
public:
void eat()
{
cout<<"Eating"<<endl;
}
};
class dog : public animal
{
public:
void bark()
{
cout<<"Barking"<<endl;
}
};
class cat : public animal
{
public:
void weep()
{
cout<<"Weeping"<<endl;
}
};
int main()
{
cat c;
c.eat();
c.weep();
dog d;
d.eat();
d.bark();
return 0;
}
4.) Multiple inheritance :- It is also possible to derive a class from two or more
unrelated base classes. When we derive a class from two or more base classes then this
form of inheritance is known as multiple inheritance .
It allows the new class to inherit the functionality of two or more well developed and
tested base classes. Each derived class in multiple inheritance must have a kind of
relationship with its base classes.
Car 1 Car 2
Vehicle
This ambiguity can be resolved by using the scope resolution operator to specify the class in
which the ,member function lies as given below :- d1.base :: read();
Vehicle
Car Racing
Ferrari
#include<iostream>
using namespace std;
class vehicle
{
public :
void vehicle1()
{
cout<<"This is a vehcile"<<endl;
}
};
class car : public vehicle
{
public :
void car1()
{
cout<<"This is a car"<<endl;
}
};
class racing
{
public :
void racing1()
{
cout<<"This is a racing car"<<endl;
}
};
class ferrari : public car,public racing
{
public:
void ferrari1()
{
cout<<"This is a ferrari"<<endl;
}
};
int main()
{
ferrari f;
f.vehicle1();
f.car1();
f.racing1();
f.ferrari1();
return 0;
}
Constructor :- Constructor is a special method which is invoked automatically at the
time of object creation. It is used to initialize the data members of new object generally. The
constructor in c++ has the same name as that of the class or structure.
It doesn’t return any value hence they don’t have a return type.
Syntax :-
inside the class
class_name ()
{
//constructor's Body
}
For example :-
#include<iostream>
using namespace std;
class student
{
int roll_no;
char name[50];
double fees;
public :
student()
{
cout<<"Enter name of student - " ;
cin>>name;
cout<<"Enter roll number of student - ";
cin>>roll_no;
cout<<"Enter fees of the student - ";
cin>>fees;
}
void display()
{
cout<<name<<" "<<roll_no<<" "<<fees;
}
};
int main()
{
student s;
s.display();
return 0;
}
For example :-
#include<iostream>
using namespace std;
class employee
{
public :
employee()
{
cout<<"Default constructor invoked "<<endl;
}
};
int main()
{
employee e1;
employee e2;
return 0;
}
For example :-
#include<iostream>
using namespace std;
class employee
{
public :
int id;
string name;
float salary;
employee(int i, string n, float s)
{
id=i;
name=n;
salary=s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main()
{
employee e1=employee(101,"Rahul",95000);
employee e2=employee(102,"Rohit",70000);
e1.display();
e2.display();
return 0;
}
#include<iostream>
using namespace std;
class employee
{
public :
employee()
{
cout<<"Constructor invoked"<<endl;
}
~employee()
{
cout<<"Destructor invoked"<<endl;
}
};
int main()
{
employee e1;
employee e2;
return 0;
}
Polymorphism
#include<iostream>
#include<math.h>
using namespace std;
void area(int);
void area(int,int);
void area(int,int,int);
int main()
{
int side=10;
int l=5,b=6;
int a=4,br=5,c=6;
area(side);
area(l,b);
area(a,br,c);
return 0;
}
void area(int x)
{
cout<<"Area of square = "<<x*x<<endl;
}
void area(int x, int y)
{
cout<<"Area of rectangle = "<<x*y<<endl;
}
void area(int x, int y,int z)
{
float s=(x+y+z)/2;
float ar;
ar=sqrt(s*(s-x)*(s-y)*(s-z));
cout<<" Area of rectangle by heron's formula = "<<ar;
}
For example :-
#include<iostream>
using namespace std;
class parent
{
public :
void print()
{
cout<<"Base class function"<<endl;
}
};
class child : public parent
{
public :
void print()
{
cout<<"Child class function"<<endl;
}
};
int main()
{
child c;
c.print();
return 0;
}
Virtual function :- A virtual function is a member function declared in the base class
using the Keyword virtual whose functionality is redefined (same function name ) by its derived
classes.
To declare the visual function in the base class, precede its function declaration with the
Keyword visual.
Syntax.
Class base class name
{
Virtual return_type member_function_name()
{
Statements
}
};
The virtual function declared in the base class represents the Single inheritance and its
re-definition by the derived class implements operation specific to each derived class.
To implement run time polymorphism using virtual function. it must be invoked through
the base class pointer that contain the address of objects of different derived classes.
Virtual function are named so because when virtual function are used in the class
hierarchy, the programmer appears to call a function defined in the base class but may in
reality be calling a function of its derived class.
For example :-
#include<iostream>
using namespace std;
class base
{
public :
virtual void print()
{
cout<<"Print base class"<<endl;
}
void show()
{
cout<<"show base class"<<endl;
}
};
class derived : public base
{
public :
void print()
{
cout<<"Print derived class"<<endl;
}
void show()
{
cout<<"Show derived class"<<endl;
}
};
int main()
{
base *bptr;
derived d;
bptr=&d;
bptr->print();
bptr->show();
return 0;
}
Class A
Class B Class C
Class D
As we can see from the figure that data member or function of class A are inherited
twice to class D. One through class B and second though class c. Then in this case
ambiguity arises.
For example :-
#include<iostream>
using namespace std;
class grandparent
{
protected :
int gp_data;
public :
void readgp()
{
cout<<"Enter grandparent data";
cin>>gp_data;
}
};
class parent1 : virtual public grandparent
{
protected :
int p1_data;
public :
void readp1()
{
cout<<"Enter data of parent 1";
cin>>p1_data;
}
};
class parent2 : virtual public grandparent
{
protected :
int p2_data;
public :
void readp2()
{
cout<<"Enter data of parent 2";
cin>>p2_data;
}
};
class child : public parent1,public parent2
{
private :
int sum;
public :
void add()
{
sum=gp_data+p1_data+p2_data;
}
void show()
{
cout<<"Grand parent data member = "<<gp_data<<endl;
cout<<"Data members of parent 1 "<<p1_data<<endl;
cout<<"Data members of parent 2 "<<p2_data<<endl;
cout<<"Sum of all data = "<<sum;
}
};
int main()
{
child c;
c.readgp();
c.readp1();
c.readp2();
c.add();
c.show();
return 0;
}
Operator overloading :- C++ has the ability to provide the operators with a
special meaning for a data type, this ability is known as operator overloading. Operator
overloading is a compile-time polymorphism. The keyword ‘operator’ followed by the symbol for
the operator being defined. Like any other function, an overloaded operator has areturn type
and a parameter list.
For example :- we can overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +. Other example classes where arithmetic operators
may be overloaded are Complex Numbers, Fractional Numbers, Big integers, etc.
Syntax :-
Return_Type classname :: operator op(Argument list)
{
Function Body
}
#include<iostream>
using namespace std;
class score
{
private :
int val;
public :
score()
{
val=0;
}
score operator ++()
{
score temp;
val=val+1;
temp.val=val;
return temp;
}
int show()
{
return (val);
}
};
int main()
{
score s1,s2;
cout<<"Initial value of s1 obj = "<<s1.show()<<endl;
cout<<"Initial value of s2 obj = "<<s2.show()<<endl;
++s1;
s2=++s1;
cout<<"Final value of s1 obj = "<<s1.show()<<endl;
cout<<"Final value of s2 obj = "<<s2.show();
return 0;
}
b.) Binary operator :- Binary operators works on two operands. Just like unary
operators, the concept of operator overloading also applies to binary operators.
Some of the binary operators that can be overloaded are +,-,<,>,==,+=.!= etc.
#include<iostream>
using namespace std;
class complex
{
private :
double real,img;
public :
complex ()
{
real=img=0.0;
}
void read()
{
cout<<"Enter real part = ";
cin>>real;
cout<<"Enter imaginary part = ";
cin>>img;
}
complex operator +(complex ccz)
{
complex temp;
temp.real = real + ccz.real;
temp.img = img + ccz.img;
return (temp);
}
void show()
{
if(img>0)
cout<<real<<"+"<<img<<"i"<<endl;
else
cout<<real<<img<<"i"<<endl;
}
};
int main()
{
complex c1,c2,c3;
cout<<"Enter complex number c1 - "<<endl;
c1.read();
cout<<"Enter complex number c2 - "<<endl;
c2.read();
c3=c1+c2;
c3.show();
return 0;
}
For example :-
#include<iostream>
using namespace std;
class dob
{
private :
int dd,mm,yyyy;
public :
dob(int d,int m,int y)
{
dd=d; mm=m; yyyy=y;
}
void show ()
{
cout<<"Dob - "<<dd<<"-"<<mm<<"-"<<yyyy<<endl;
}
int operator==(dob);
};
int dob :: operator==(dob dd2)
{
if((yyyy==dd2.yyyy)&&(mm=dd2.mm)&&(dd==dd2.dd))
return (1);
else
return (0);
}
int main()
{
dob d1(15,10,2002);
dob d2(12,10,2005);
d1.show();
d2.show();
if(d1==d2)
cout<<"d1 and d2 have same dob";
else
cout<<"d1 and d2 have different dob";
return 0;
}
Friend function :- A class encapsulates data and function that operates on that data.
Data members are usually made private so, that it can not be accessed from non-member
function of the class. However, in certain situations there is need to access the private data
members of the class by a function which is not the member of that class. It can be achieved by
making non member function as a friend function.
A friend function is a non-member function that has been granted access to all
the private members of a class.
The declaration of friend function can be placed anywhere in the class
specification irrespective of access specifiers. The definition of friend function is
specified outside the class body and is not treated as the part of the class.
The major difference between a member function of a class and a friend
function is that the member function is access through the object while friend
function requires objects to be passed by value or reference.
Disadvantage :- Since the friend function can access the private members of
a class. So, it violates the rules of encapsulation, therefore it should be used less
frequently.
Syntax :-
class class_name
{
friend return_type function_name(arguments);
}
#include<iostream>
using namespace std;
class employee
{
private :
friend void salary();
};
void salary()
{
int salary=40000;
cout<<"Salary - "<<salary;
}
int main()
{
employee e;
salary();
return 0;
}
Friend classes :- In this case, the private members of the class will be
accessible to the friend class.
For example :-
#include<iostream>
using namespace std;
class aaa
{
private :
int a,b;
public :
aaa(int aa,int bb)
{
a=aa;
b=bb;
}
friend class bbb;
};
class bbb
{
public :
void f1(aaa obja)
{
cout<<"a = "<<obja.a<<endl;
}
void f2(aaa objb)
{
cout<<"b = "<<objb.b;
}
};
int main()
{
aaa ob1(10,15);
bbb ob2;
ob2.f1(ob1);
ob2.f2(ob1);
return 0;
}
Enumeration :- It is also known as Enum. It is a user defined data type which can
be assigned some limited values. These values are defined by the programmer at the time of
declaring the enumerated type.
If we assign a float value in a character value, then the compiler generates an
error. In the same way if we try to assign any other value to the enumerated data
types compiler generates an error. Enumerator types of values are also known as
enumerators. It is also assigned by zero, the same way as the array. It can also be
used with switch statements.
For example :- If a gender variable is created with value male or female. If any
other value is assigned other than male and female then it is not appropriate. In
this situation, one can declare the enumerated type in which only male and
female values are assigned.
Program of Enumeration.
Structure :- So far, we have been dealing with variables that can hold one value at time
and arrays that can hold a number of values of same data type (group of homogeneous data
items). But there are some situations where, we want to store data items of different types as a
single unit using a single name. In such a case, we can neither use simple variables nor an array.
For instance, if we want to store information of student(s) in a class that include their rollno (int
type), name (sting type), marks (float type) and so on. Such type of related data items of
different types cannot be grouped together using an array. In order to group such related data
items of different type, C+ provides a data type known as structure.
A structure is a collection of related data items which can be of different types held
together in a single unit. The data items enclosed within a structure are known as its
members which can be either of int, float, char etc. types. As a structure may
contain items of different types so it can be viewed as a collection of heterogeneous
data items.
The variables of structure type can be created through which we can manipulate its
members. This property help us to organize complex data items efficiently in a
program.
Syntax :-
struct struct_name
{
data_type member1;
data_type member2; Structure
…………………………….. members
data_type membern;
};
Programs of Structure
#include<iostream>
using namespace std;
struct student
{
int rollno;
char name[50];
float marks;
};
int main()
{
struct student s;
cout<<"Enter roll number of student - ";
cin>>s.rollno;
cout<<"Enter name of student - ";
cin>>s.name;
cout<<"Enter marks of student - ";
cin>>s.marks;
cout<<"Student details is - "<<endl;
cout<<"Rollno is - "<<s.rollno<<endl;
cout<<"Name - "<<s.name<<endl;
cout<<"Marks - "<<s.marks;
return 0;
}