Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views97 pages

Microsoft Word - Rahul Notes C++

C++ is a statically typed, compiled, general-purpose programming language that supports object-oriented programming and combines features of high-level and low-level languages. It includes various components such as tokens, data types, operators, and a structured program layout, making it versatile for applications like GUI, game development, and software systems. C++ offers advantages like performance, platform compatibility, dynamic memory management, and scalability, along with a rich set of operators for mathematical and logical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views97 pages

Microsoft Word - Rahul Notes C++

C++ is a statically typed, compiled, general-purpose programming language that supports object-oriented programming and combines features of high-level and low-level languages. It includes various components such as tokens, data types, operators, and a structured program layout, making it versatile for applications like GUI, game development, and software systems. C++ offers advantages like performance, platform compatibility, dynamic memory management, and scalability, along with a rich set of operators for mathematical and logical operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

C++ Language

 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.

 C++ is regarding as middle level language as its comprise a combination of both


high level and low level programming language features.
 C++ was develop ed by Branje stroustrup in 1979 as bells lab I Murrey hills.
 C++ supports the superset of C language.

High
Hj level language Compiler Machine language

 Compiler :- A compiler is a special Program that process statements


Written in particular programming language. It converts a high level language
into a 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

Keyword Operator Constant Variable


s s
i. Keyword :- Every keyword serve as a Basic building blocks for program statement.
 All keywords have fixed meaning cannot be changed.
 All keyboard must be written in lower case.
 There are 64 keywords in C++.

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 :-

1) Primary or Built-in or Basic data type


2) Derived data types
3) User-defined data types

C++ Data Types

Primitive/ Derived data User defined


Basic data types data types
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’.

iv. Character:- This data type is used for storing characters.


 The keyword or the data type used to define character is ‘char’.
 Structure of c++ :-

Documentation Section - /* comments */


Preprocessor directive - #include, #define…etc
Global declaration
Class
Main Program section
{
Local variables or statements;
}
Local part, executable part
Subprogram section
Function 1;
Function 2;

i.) Documentation section :- It includes the comments that


improves the readability of the program. A program is a non-executable
statements that helps to read and understand a program. A comment is a
message that exists only for the programmer and is ignored by the
compilers.
Types of comments :-

a.) Single line comment :- // Addition of two numbers . A single line is


enclosed within delimiter (//).

b.) Multi- line comment :- /* Addition of two numbers*/ In this first


line of Comment starts with forward slash (/*) and the last with (*/).

ii.) Pre-processor directive system: It includes various pre-


processor directives. All the preprocessor directives start with #sign which
distinguish them from other item in a c++ program. There is no Semi-column
or special mark at the end of directive. A pre-processor directive is the
massage to a compiler to do something before compiling the code and it is
handled by a part of Compiler Known as preprocessor directive.
Some of the most important preprocessor directive are :-
#include:- The #include directive provides a way to reuse previously
written code in the c++ program. It tells the preprocessor to include
specified file in the source file. In place of the directive before
compilation.
#define :- The symbolic constants can be specified using #delfine.
The symbolic constant allow the programmer to define the name for
constant and use the name throughout the program.
Syntax:- # define PI 3.14

 Rules of directive are:-

i.) All the pre-processor directive must begin with #sign


ii.) Preprocessor directive should not end with semi-column,
because they are not c++ statement.
iii.) Only one pore-processor directive can occur in a line.
iv.) There should be no space between the # sign and the directive.

iii.) Global declaration section :- It is used to declare global


variables. They are called so because they are accessible to any part of the
program. Those variables are visible throughout the program.

iv.) Class :- It describes the information present in the program.


Syntax :-

class car
{
class declaration or definition
Class function definition
};
Int main()
{
class_name object_name;
statements;
}

v.) Main () program section :- The execution of the program


always start from this part of the program. This part begins with a function
name [ main() ]. The body of a function is enclosed in curly braces { }. The
statement with in main function can be divided into two parts :-
a. Local declaration part :- It includes the statements that helps
to declare variable that can only be accessed with in main().
b. Executable part :- It consist pf statements that are executed in a
given order.

vi.) Sub-program section :- It includes various user defined


functions. These user-define functions are not a part of any class.

 Advantages of C++ :-

1.) Performance :- Since c++ is a compiler based programming language, it is


comparatively faster, during the program execution. There is no install special
runtime.
2.) Platform compatibility :- c++ is completely platform
independent so developers need not to be worried about platform compatibility.
While using a single code base, the programs can run on multiple operating
system.
3.) Memory Management :- C++ support the function of Dynamic
memory allocation. It eliminates the usage of Garbage collector. Hence the
management of the memory completely lies on the programmer. The users are
allowed or reallocate memory as per the required.
4.) Scalability:- If there is any application that is resource intensive, c++
scales them up accordingly i.e. the program may need to handle multiple Tasks
simultaneously: This includes both small scale and large scale data.
5.) Object-Oriented Programming :- C++ is an object-oriented
programming language, which includes concepts like classes, inheritance,
polymorphism, data abstraction, and encapsulation. This allows for code
reusability and makes programs very maintainable.
6.) Low-Level Control and Efficiency:- C++ provides
developers with fine control of memory usage and performs close to the
hardware limitations. Its combination of high performance and object-oriented
features makes C++ the go-to language where efficiency is concerned.
 C++ 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. An
operator operates the operands.
 For e.g. :- int c=a+b; Here, ‘+’ is the addition operator ‘a’ and ‘b’ are the
operands that are being added.
 Operators in C++ can be classified as :-
1. Arithmetic operator
2. Relational/comparison operator
3. Assignment operator
4. Logical operator
5. Bitwise operator

1) Arithmetic operator:- These operators are used to perform arithmetic or


mathematical operations on the operands. Such as addition, subtraction, multiplication,
division and modulus etc.
 It is read from left to right.
 Some examples are :- operator

a+b
a-b a + b
a*b
operand
a/b
a%b

 WAP OF ADDITION OF TWO NUMBER AT RUN TIME AND COMPIPLE.

 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;
}

 WAP TO PERFORM ALL ARITHMETIC OPERATION ON TWO


NUMBERS.
#include<iostream>
using namespace std;
int main()
{
int a,b,c,d,e,f,g;
cout<<"Enter the value of a and b";
cin>>a>>b;
c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=a%b;
cout<<"Result are "<<c<<" "<<d<<" "<<e<<" "<<f<<" "<<g;
return 0;
}

2) Assignment operator :- These operators are used to assign value to a variable.


The left operand of the assignment operator is a variable and the rightside operand of the
assignment operator is a value.
 The value on the right side must be of the same data type as the variable on
the left side otherwise, compiler will raise an error.
 Some of the Assignment operators are :-
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Moduls and assign

 Some example of assignment operator :-

 WAP TO COPY THE VALUE OF A TO B


#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter the value of a ";
cin>>a;
b=a;
cout<<"Value of b is "<<b;
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;
}

3) Comparison/Relational operator :- These are used to create a


relationship and compare the values of two operands.

 Some of the comparison operator are :-


== is equal to
> Greater than
>= Greater than equal to
< Less than
<= Less than equal to
!= Not equal to

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 :- Control statement change the sequential order of


execution by using selection, iteration and transfer statement.

Control
statement

Decision making Loping Jumping


statements Statement statements

If for goto

If-else while break

If-else if – else do-while continue

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;
}

b.) if-else statement:- An if-else statement operates on an either/or basis.


One statement is executed if the condition is true; another is executed if the statement is
fslse.
Syntax:-
If(condition)
{
// Statements 1;
}
else
{
// Statements 2;
}

Programs of if else statement


 WAP TO FIND LARGEST OF TWO NUMBERS.

#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;
}

 WAP TO FIND WHEATHER A PERSON IS ELEGIBLE FOR


VOTING OR NOT.
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter value of age";
cin>>age;
if(age>=18)
{
cout<<"Person is elegible for voting ";
}
else
{
cout<<"Person is not elegible for voting";
}
return 0;
}

 WAP TO PRINT NUMBER IS EVEN OR NOT.

#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;
}

Programs of if-else if statement


 WAP TO FIND WEATHER NUMBER IS POSITIVE, NEGATIVE
OR ZERO.

#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;
}

 WAP TO PRINT LARGEST OF THREE NUMBERS.


#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Enter the value of a,b and c";
cin>>a>>b;
if((a>b)&&(a>c))
{
cout<<"A is largest";
}
else if((b>a)&&(b>c))
{
cout<<"B is largest";
}
else if((c>a)&&(c>b))
{
cout<<"C is largest";
}
else
{
cout<<"All are equal";
}
return 0;
}

d.) Switch statement:- It is a multi-way decision making statement which


selects several alternatives based on the values of integer, variable or expressions.
 It is mainly used to replace multiple if else-if statements.
Syntax:-
switch(expressions)
{
case 1:
statement 1;
break;
case 2:
statement 2;
break;
.
.
.
.
default:
statement n;
break;
}

Programs of switch statement

 WAP TO PRINT WEEK DAYS USING SWITCH STATEMENT.


#include<iostream>
using namespace std;
int main()
{
int day;
cout<<"Enter the value of day";
cin>>day;
switch(day)
{
case 1:
cout<<"Monday";
break;
case 2:
cout<<"Tuesday";
break;
case 3:
cout<<"Wednesday";
break;
case 4:
cout<<"Thursday";
break;
case 5:
cout<<"Friday";
break;
case 6:
cout<<"Saturday";
break;
case 7:
cout<<"Sunday";
break;
default:
cout<<"Invalid day";
break;
}
return 0;
}

 WAP TO PERFORM ARITHMETIC OPERATION.

#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;
}

 WAP TO PRINT LARGEST OF TWO NUMBERS ,EVEN OR


ODD, POSITIVE OR NEGATIVE.

#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;
}

Programs of while loop

 WAP TO PRINT HELLO 5 TIMES.

#include<iostream>
using namespace std;
int main()
{
int i;
while(i<=5)
{
cout<<"HELLO"<<endl;
i++;
}
return 0;
}

 WAP TO PRINT N NATURAL NUMBERS.


#include<iostream>
using namespace std;
int main()
{
int i,n;
cout<<"Enter the value of n";
cin>>n;
i=1;
while(i<=n)
{
cout<<i<<endl;
i++;
}
return 0;
}

 WAP TO PRINT REVERSE COUNTING 50 TO 25.


#include<iostream>
using namespace std;
int main()
{
int i;
i=50;
while(i>=25)
{
cout<<i<<endl;
i--;
}
return 0;
}

 WAP TO FIND SUM OF N NATURAL NUMBERS.

#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;
}

 WAP TO FIND REVERSE OF A NUMBER.

#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;
}

 WAP TO CHECK WEATHER NUMBER IS PALINDROME OR


NOT .

#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;
}

 WAP TO CHECK WHETHER NUMBER IS ARMSTRONG OR


NOT.

#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;
}

 WAP TO FIND PRODUCT OF A DIGIT.

#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;
}

 WAP TO FIND HCF OF TWO NUMBER.

#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;
}

 WAP TO FIND LCM OF TWO NUMBER.

#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 ;
}

Programs of for loop

 WAP TO PRINT YOUR NAME 15 TIMES.


#include<iostream>
using namespace std;
int main()
{
int i; for(i=1; i<=15; i++)
{
cout<<"Rahul Saini"<<endl;
}
return 0;
}

 WAP TO PRINT 1 TO 15 NATURAL NUMBER.


#include<iostream>
using namespace std;
int main()
{
int i;
for(i=1; i<=15; i++)
{
cout<<i<<endl;
}
return 0;
}

 WAP TO PRINT REVERSE COUNTING 50


TO 25.
#include<iostream>
using namespace std;
int main()
{
int i;
for(i=50; i>=25; i--)
{
cout<<i<<endl;
}
return 0;
}

 WAP TO PRINT SUM OF N NATURAL NUMBERS.

#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;
}

 WAP TO PRINT SUM OF EVEN NUMBER.


#include<iostream>
using namespace std;
int main()
{
int i,even=0,n;
cout<<"Enter value of n";
cin>>n;
for(i=1; i<=n; i++)
{
if(i%2==0)
{
even=even+i;
}
}
cout<<"Sum of even number is "<<even;
return 0;
}

 WAP TO PRINT TABLE OF A NUMBER.


#include<iostream>
using namespace std;
int main()
{

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;
}

 WAP TO PRINT FACTORIAL OF A NUMBER.

#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;
}

 WAP TO PRINT FIBONACCI SERIES.

#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;
}

 WAP TO PRINT OUTPUT.


#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
{
cout<<"*";
}
cout<<endl;
}
return 0;
}

 WAP TO PRINT OUTPUT.


#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
{
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}

 WAP TO PRINT OUTPUT.

#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;
}

 WAP TO PRINT OUTPUT.


#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=5; i>=1; i--)
{
for(j=1; j<=i; j++)
{
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}

 WAP TO PRINT OUTPUT


#include<iostream>
using namespace std;
int main()
{
int i,j,k;
for(i=1; i<=5; i++)
{
for(j=1; j<=5-i; j++)
{
cout<<" ";
}
for(k=1; k<=2*i-1; k++)
{
cout<<"*";
}
cout<<endl;
}
return 0;
}

 WAP TO PRINT OUTPUT.

#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;
}

 WAP TO PRINT OUTPUT.


#include<iostream>
using namespace std;
int main()
{
int i,j,k;
for(i=1; i<=5; i++)
{
for(j=1; j<=5-i; j++)
{
cout<<" ";
}
for(k=1; k<=2*i-1; k++)
{
cout<<"*";
}
cout<<endl;
}
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;
}

 WAP TO PRINT OUTPUT.

#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;
}

C. Jumping statements:- These statements are used to manipulate the flow of


the program if the some condition are met. It is used to terminate or continue the loop
inside a program or to stop the execution of a function.
 Like:- Break,continue and goto statements.

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 ;

Programs of break statement

#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 ;

Programs of continue statement


 THIS EXAMPLES SKIPS THE VALUE OF 4.

#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;
... .. ...

Programs of Goto statement

 WAP TO CHECK WEATHER NUMBER IS EVEN OR NOT


USING GOTO 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

 Types of array:- There are mainly 3 types of array


1.) One-dimensional array
2.) Two-dimensional array
3.) Multi-dimensional array

1.) One-dimensional array:- In this type of array, it stores element in a single


dimensions. In this array, a single specification is required to describe elements of the
array.
Syntax:- (0,0) (0,1) (0,2)
data_type array_name[size];
(1,0) (1,1) (1,3)
for e.g. arr[5];
(2,0) (2,1) (2,2)

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

Declaration of 2-D array data type Row 2

array_name [row] [column]; Row 3


3.) Multi-dimensional array:- The simplest example of multi-dimensional array is a 2-
d array. A two dimensional array also falls under the category of multi-dimensional array.
This array can have many number of dimensions.
Syntax:-
data_type array_name [size 1] [size 2]………[size n];

for example:- int array [5] [3] [9];

Programs of Array

 WAP TO PRINT ARRAY ELEMENTS.


#include<iostream>
using namespace std;
int main()
{
int a[5],i;
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;
}
return 0;
}

 WAP TO FIND ADDITION OF ARRAY ELEMENTS.

#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;
}

 WAP TO FIND ADDITION OF EVEN ELEMENTS AND


ODD ELEMENTS USING ARRAY.

#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;
}

 WAP TO FIND MAX ELEMENT OF AN ARRAY.

#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;
}

 WAP TO FIND MIN ELEMENT OF AN ARRAY.


#include<iostream>
using namespace std;
int main()
{
int a[5],i,min;
cout<<"Enter array elements";
for(i=0; i<=4; i++)
{
cin>>a[i];
}
min=a[0];
for(i=1; i<=4; i++)
{
if(min>a[i])
{
min=a[i];
}
}
cout<<"Smallest element of array is "<<min;
return 0;
}

 WAP TO PRINT ARRAY IN ASSENDING ORDER.


#include<iostream>
using namespace std;
int main()
{
int a[5],i,j,k;
cout<<"Enter the elements of array"<<endl;
for(i=0; i<=4; i++)
{
cin>>a[i];
}
for(i=0; i<=4; i++)
{
for(j=i+1; j<=4; j++)
{
if(a[i]>a[j])
{
k=a[i];
a[i]=a[j];
a[j]=k;
}
}
}
cout<<"Array elements in assending order"<<endl;
for(i=0; i<=4; i++)
{
cout<<a[i]<<endl;
}
return 0;
}

 WAP TO PRINT ARRAY IN DESENDING ORDER


#include<iostream>
using namespace std;
int main()
{
int a[5],i,j,k;
cout<<"Enter the elements of array"<<endl;
for(i=0; i<=4; i++)
{
cin>>a[i];
}
for(i=0; i<=4; i++)
{
for(j=i+1; j<=4; j++)
{
if(a[i]<a[j])
{
k=a[i];
a[i]=a[j];
a[j]=k;
}
}
}
cout<<"Array elements in desending order"<<endl;
for(i=0; i<=4; i++)
{
cout<<a[i]<<endl;
}
return 0;
}

 WAP TO PRINT ARRAY ELMENTS IN MATRIX FORM.

#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;
}

 WAP TO PRINT TRANSPOSE OF A MATRIX.

#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;
}

 WAP TO MULTIPLICATION OF TWO MATRIX.


#include<iostream>
using namespace std;
int main()
{
int a[2][2],b[2][2],c[2][2],i,j,k;
cout<<"Enter elements for matrix A"<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cin>>a[i][j];
}
}
cout<<endl;
cout<<"Matrix A: "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
cout<<"Enter elements for matrix B"<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cin>>b[i][j];
}
}
cout<<endl;
cout<<"Matrix B: "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<b[i][j]<<" ";
}
cout<<endl;
}
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
c[i][j]=0;
for(k=0; k<=1; k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
cout<<endl;
cout<<"Multiplication ="<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}

 WAP TO SUM OF TWO MATRIX.


#include<iostream>
using namespace std;
int main()
{
int a[2][2],b[2][2],c[2][2],i,j,k;
cout<<"Enter elements for matrix A"<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cin>>a[i][j];
}
}
cout<<endl;
cout<<"Matrix A: "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
cout<<"Enter elements for matrix B"<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cin>>b[i][j];
}
}
cout<<endl;
cout<<"Matrix B: "<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<b[i][j]<<" ";
}
cout<<endl;
}
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
c[i][j]=0;
for(k=0; k<=1; k++)
{
c[i][j]+=a[i][k]+b[k][j];
}
}
}
cout<<endl;
cout<<"Addition ="<<endl;
for(i=0; i<=1; i++)
{
for(j=0; j<=1; j++)
{
cout<<c[i][j]<<" ";
}
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.

 Strings are actually one-dimensional array of characters


terminated by a null character. Thus a null terminated string
contains the characters that comprise the string followed by a
null.
 The following declaration and initialization create a string
consisting of the word “Hello”. To hold the null character at the
end of the array, the size of the character array containing the
string is one more than the number of characters in the word
“Hello”.
Actually, you don’t place the null character at the end of a
string constant. The c++ compiler automatically places the ‘\0’ at
the end of the string when initializes the array.

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)

 puts():- The function used to display single character on the screen.


 gets():- To extract value from keyboard.

 WAP TO REVERSE THE STRING


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50];
cout<<"Enter any string "<<endl;
gets(s1);
strrev(s1);
cout<<"Reverse of string "<<endl;
puts(s1);
return 0;
}

 WAP TO LOWER THE STRING


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50];
cout<<"Enter any string "<<endl;
gets(s1);
strlwr(s1);
cout<<"Lower the string "<<endl;
puts(s1);
return 0;
}

 WAP TO UPPER THE STRING.


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50];
cout<<"Enter any string "<<endl;
gets(s1);
strupr(s1);
cout<<"Upper the string "<<endl;
puts(s1);
return 0;
}

 WAP TO FIND LENGTH OF THE STRING


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50];
cout<<"Enter any string "<<endl;
gets(s1);
int z= strlen(s1);
cout<<"Length of the string "<<z;
return 0;
}

 WAP OF CONCATINATION OF TWO 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<<"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;
}

 WAP OF COMPARISION OF TWO STRING


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50],s2[20];
int a;
cout<<"Enter string S1"<<endl;
gets(s1);
cout<<"Enter string S2"<<endl;
gets(s2);
a=strcmp(s1,s2);
if(a==0)
{
cout<<"String is equal";
}
else
{
cout<<"String is not equal";
}
return 0;
}

 WAP TO CHECK WEATHER STRING IS PALIDROME OR


NOT.
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s1[50],s2[20];
int a;
cout<<"Enter string S1"<<endl;
gets(s1);
strcpy(s2,s1);
strrev(s2);
a=strcmp(s1,s2);
if(a==0)
{
cout<<"String is Palidrome";
}
else
{
cout<<"String is not palidrome";
}
return 0;
}
POINTERS

 Pointers are most powerful features available in c++. The use


of pointers offers a great degree of flexibility for manipulating
data in the programs and making the programs quicker and
memory efficient. Although programming can be done without
the use of pointers but in some situations, pointers show its
real power such as:-
 Management of objects allocated memory dynamically.
 Passing arrays, string to function more efficiently.
 To pass function arguments that will be changed by the function.
 To return more than one value from the function.
 Optimize the program to execute faster or use less memory.

 What is Pointer ?
A pointer is a variable that contains the address of another
variable in memory.

 Pointer variable is also known as address


variable as it always store address of some
other variable.

 Declaring Pointer Variable :- A pointer variable is declared in the same way as


that of normal variable except that the name of the pointer variable must be preceded by
asterik (*) .
Syntax:-
data_type *pointer_variable

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

 C++ Provided two operators to work specially with pointers:-


a) Address/reference operator (&)
b) Indirection/dereference operator (*)

a.) Address/reference operator (&) :- We can initialize the pointer


variable by assigning the address of some other variable. The address of the
variable can be obtained by preceding the name of the variable with the address
operator.
 This operator returns the address of 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

b.) Indirection/dereference operator (*) :- Once the pointer variable


store the address of some variable. It can be used to indirectly access the
variables whose address is stored in it.
 This operator returns the value of variable pointed by the pointer
variable.
 Advantages of pointers :-

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

 WAP A PROGRAM TO FIND SUM OF TWO VARIABLES.

#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;
}

 WAP TO FIND SIMPLE INTERERST USING POINTERS.


#include<iostream>
using namespace std;
int main()
{
int p,r,t,si,*x,*y,*z;
cout<<"Enter the value of p";
cin>>p;
cout<<"Enter the value of r";
cin>>r;
cout<<"Enter the value of t";
cin>>t;
x=&p;
y=&r;
z=&t;
si=((*x)*(*y)*(*z)/100);
cout<<"Simple interest = "<<si;
return 0;
}

 WAP TO FIND AREA OF SQUARE USING POINTER.

#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;
}

 WAP TO FIND AREA OF TRIANGLE USING POINTER.

#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;
}

 WAP TO CHECK LEAP YEAR OR NOT.


#include<iostream>
using namespace std;
int main()
{
int year,*x;
cout<<"Enter the year";
cin>>year;
x=&year;
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 Leap year";
}
return 0;
}

 WAP TO PRINT SWAPPING WITH USING THIRD


VARIABLE USING POINTERS.

#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;
}

 WAP TO PRINT SWAPPING WITHOUT USING THIRD


VARIABLE.

#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.

 A function groups a number of repeated statements in a program into a single unit


and is identified by a name known as function name.
 A program can contain one or more function but the main() function must be the
part of every program.
 Like c++ programs also contains at least one function, which is main(), from where
the program execution always begains.
 After the function has performed the intended task the control is return back to the
calling function and continue with the rest of statement of its body.

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.

 Types of function:- There are mainly two type of functions


1) Library functions
2) User-defined functions

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.

2.) User-defined function :- In some situations, while designing complex


programs, a user may require to perform. some specific task repeatedly and there is
no library function available for performing that task. Hence to solve this problem,
the programmer writes his own function(s) as per the requirements in the program.
These functions which are defined specifically by the user to meet his requirements
are called user-defined functions.
 Every C+ program contains at least one function. The function
which is present in every C+ program is main() which is a user-
defined function. This is the function from where the program's
execution begins. The library functions and user-defined
functions are normally used in the main () function.

 Argument passing techniques :- It is the process of transferring


data between the calling function and the called function. In c++ there are three ways by
which arguments can be passed.
i. Pass by value / call by value
ii. Pass by address / call by pointer
iii. Pass by reference / call by reference

i.) Pass by value / call by value :- It is a mechanism for


argument passing when an argument(s) is passed by value, then a copy of
arguments is made and passed to the corresponding formal arguments(s) in
the called function. Since the formal arguments contains a copy of the value of
the actual argument, which is stored in the separate memory location. So any
changes made to these are not reflected back to the formal arguments. The
changes made in the formal arguments are local to the block which are lost
once the control is returned back to the calling function.

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.

 The address of arguments is passed by preceding by the address


operator (&) with the name of variable. Whose value you want
to modify. The corresponding formal arguments are preceded
with asterisk (*) sign. Which act as a pointer variable to store the
address of the actual argument.

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;
}

iii.) Pass by reference / call by reference :- The pass by


reference is very easy and simple technique of programming which is only
available in c++ not in c.
In this any modification in the formal arguments in the called function are
reflected back to the actual arguments in the calling function. This method of
argument passing which allows the modifications back to the actual arguments
is similar to the pass by pointer technique of arguments passing but without
using the complex syntax of pointers.

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

 WAP TO PRINT ADDITION OF TWO NUMBER USING


FUNCTION.

#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;
}

 WAP TO FIND SIMPLE INTEREST USING FUNCTION.

#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";
}
}

 WAP TO FIND AREA OF SQUARE USING FUNCTION.

#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

 Basic concepts of object oriented programming


language :- The term object oriented means that we organize a problem as a
collection of discrete objects contain data and functions that operate on that data. It is a
powerful way to approach the task of programming.

class Inheritance

Basic concepts
object of object Polymorphism
oriented
programming
Abstraction language Dynamic binding

Encapsulation Message passing

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.

Difference between object and class :-

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.

iii.) Encapsulation :- It is a mechanism that binds together data and functions


that manipulate that data into a single logical unit. It keeps the data safe from an
external interface and misuse. Encapsulation is a wrapping of data and related
function in an single unit called class.
 Data hiding :- It can be defined as a mechanism of hiding data of a class from
outside world (other classes). So that any access to it either intentionally or
unintentionally cannot modify that data. Data hiding can be achieved by making
data of class private.

iv.) Abstraction :- It is essential elements of object oriented programming. It is a


process that involves the internal details. In oops complexity is managed by using
this concept of abstraction. Classes that use the concept of abstraction are known as
abstract data types.
v.) Inheritance :- It is a process of driving a new class from an existing class
without modifying it. The new class is called the derived class, subclass or child class
and the existing class is called the base class, super-class or parent class. It follows
the concept of class hierarchy. It also work as a tree structure.

vi.) Polymorphism :- It is very powerful concept. The word polymorphism is


divided from two Greek words ‘poly’ which means ‘many’ and ‘morphos’ which
means ‘forms’. So, polymorphism means the ability to take many forms. It can be
defined as the ability to use the same name for two or more related but technically
different task.

Class shape
draw()
data function

draw() draw() draw()


class circle class square class rectangle

 Polymorphism can also be defined as ability of different class to respond to the


same request in its own way. The main advantage of polymorphism is that, it
reduces complexity by allowing same name to perform different related task. In
c++ polymorphism can be implemented by using function overloading and
operator overloading.

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

 Definition :- Inheritance is one of the key concept that enables you to


organize classes in a hierarchical form. Just like a child inherits the characteristics of
his own. In similar way a new class can inherits the data members and members
function of existing class and can also add members of its own.

 This process of creating a new class from an existing class is known as


inheritance.
 The existing class that is being inherited is called the base class and the new
class that inherits the functionality is called the derived class.
 The main advantage of inheritance is the reusability of the code.

 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;
}

2.) Multi-level inheritance :- It is also possible to derive a class from an


existing derived class. This form of inheritance is known as multi-level inheritance. It is
implementing by defining at least three class. Each derived class must have a kind of
relationship with its immediate base class.

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;
}

3.) Hierarchical inheritance :- Inheritance represents hierarchical


arrangement of classes in which a single base class can be used to derive multiple classes.
This form of inheritance in which more than one classes are derived from single base class
is known as hierarchical inheritance.
These derived classes can further act as a base class for lower level multiple derived
classes and this process continue and hance represents the hierarchy of classes.
Animal
base class

Cat Dog
Child class Child class

 WAP OF HIERARCHIAL 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 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

 WAP OF MULTIPLE INHERITANCE.


#include<iostream>
using namespace std;
class car
{
public:
void car1()
{
cout<<"This is a 4 wheeler"<<endl;
}
};
class bike
{
public:
void bike1()
{
cout<<"This a two wheeler"<<endl;
}
};
class vehcile : public car, public bike
{
public:
void vehcile1()
{
cout<<"This is a vehcile"<<endl;
}
};
int main()
{
vehcile v;
v.car1();
v.bike1();
v.vehcile1();
return 0;
}

 Ambiguity in multiple inheritance :- In multiple inheritance, there


may be a possibility that a class may inherits member functions with the same name from
two or more base classes and the derived class may not have function with the same name
ass those of its base classes. If the object of the derived class need to access one of the same
named member function of the base classes then it results in ambiguity as it is not clear to
the compiler which base class member function should be invoked.

 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();

5.) Hybrid inheritance :- In some situations, it is essential to design a program


using two or more forms of inheritance. This method of combining two or more forms of
inheritance to design a program is Known as Hybrid inheritance. Such form of inheritance
represents complex hierarchy.

Vehicle

Car Racing

Ferrari

 WAP OF HYBRID INHERITANCE.

#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
}

 Outside the class


class_name :: class_name ()
{
//constructor's Body
}

For example :-

 CONSTRUCTOR INSIDE THE CLASS.

#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;
}

 There are two type of constructors in c++ :-


1) Default constructor
2) Parameterized constructor

1.) Default constructor :- A constructor which has no arguments is known as


the default constructor. It is invoked at the time of creating object.

For example :-

#include<iostream>
using namespace std;
class employee
{
public :
employee()
{
cout<<"Default constructor invoked "<<endl;
}
};
int main()
{
employee e1;
employee e2;
return 0;
}

2.) Parametrized constructor :- A constructor which has parameters is


called as parameter constructor. It is used to provide different values to distinct objects.

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;
}

 Destructor :- It is a special member function like a constructor. Destructor destroys


the class objects created by constructor. It has same name as class name but, it is prefixed with a
tilde (~) symbol.

 It neither requires any argument nor return any value.


Syntax :-

 inside the class


~ class_name ()
{
//Destructor's Body
}
 Outside the class
class_name :: ~ class_name ()
{
//destructor's Body
}
For example:-

#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 :- t is very powerful concept. The word polymorphism is divided from


two Greek words ‘poly’ which means ‘many’ and ‘morphos’ which means ‘forms’. So,
polymorphism means the ability to take many forms. It can be defined as the ability to use the
same name for two or more related but technically different task.
 Polymorphism can also be defined as ability of different class to respond to the
same request in its own way. The main advantage of polymorphism is that, it
reduces complexity by allowing same name to perform different related task. In
c++ polymorphism can be implemented by using function overloading and
operator overloading.

Polymorphism

Compile time Run time

Function Operator Function Virtual


overloading overloading overriding function
 Function overloading :- When two or more functions can share the same name
that performs similar operations but have different parameters list. Such a situation, the function
that share the same name are said to be overloaded and the process is known as function
overloading.
 It allows a family of functions to share a common name that
performs multiple related activity.
 When an overloaded function is invoked it is the responsibility of
the number of arguments passed. If the number of arguments
are same than depending upon the type of arguments passed.

 WAP OF ADDITION OF TWO NUMBERS WITH


DIFFERENT DATA TYPES.
#include<iostream>
using namespace std;
void sum(int,int);
void sum(double,double);
void sum(char,char);
int main()
{
int a=5,b=8;
double c=7.52,d=8.14;
char e='A',f='B';
sum(a,b);
sum(c,d);
sum(e,f);
return 0;
}
void sum(int x,int y)
{
cout<<"Sum of two integers = "<<x+y<<endl;
}
void sum(double x, double y)
{
cout<<"Sum of two floating point integers = "<<x+y<<endl;
}
void sum(char x, char y)
{
cout<<"Sum of two characters = "<<x+y;
}

 WAP TO SHOW THE CONCEPT OF FUNCTION


OVERLOADING TO CALCULATE THE AREA WHERE
SAME FUNCTIONS DIFFERS IN NUMBERS OF
PARAMETERS.

#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;
}

 Advantages of function overloading :-


1.) We need to remember a single name instead of multiple names of the
functions that perform similar type of operation.
2.) Overloaded functions that performs similar tasks can make complex
program more readable, understandable and easy to debug.
3.) Maintainability of the program become easier.
4.) Overloaded functions are extensively used for handling class objects.

 Function overriding :- It is a features that allows us to have a same function in the


child class which is already present in the parent class. A child class inherits the data members
and function members of parent class, but when you want to override a functionality in the child
class then you can use function overriding .

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;
}

 Virtual base class :- It is used in Virtual inheritance in a way of preventing


multiple "instances" of a given class appearing in an inheritance hierarchy when using
multiple inheritances.
 Need for vistual base class :- Consider the situation where we have one
class A. This class A is inherited by two other classes B an C. Both these classes
are inherited into another in a new class D.

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.

 How to resolve the issue :- To resolve tis ambiguity when class A is


inherited in both class B and C it is declared as virtual base class.

Syntax :- Two ways to write virtual base class syntax

Class B : virtual public A class C : public virtual A


{ {
Statements ; statements ;
} }

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
}

 Types of operator overloading :- There are mainly two types of operator


overloading :-
a.) Unary operator overloading.
b.) Binary operator overloading.

a.) Unary operator overloading :- The unary operator work only on a


single operands. Some common unary operator includes :- unary plus (+), unary
minus (-),++,-- and ! etc.

 WAP TO OVERLOAD UNARY INCREMENT OPERATOR.

#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.

 Overloading Arithmetic operators :- The arithmetic operators +,-


,*,/ and % can be overloaded.
For example :-

#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;
}

 Overloading relational operator :- The relational operator are :-


>,<,<=,>=,== etc. These operators compares the data values of the operands. In
addition to comparing the operands of built in data types, the relational operators
can also be used to compare user-defined data types using the concept of operator
overloading.

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);
}

 The main objective of using a friend function in a program are as follow :-


o It acts as a bridge between two classes.
o A friend function can be used to overload operators.

 Program to demonstrate how a friend function acts


as a bridge between two classes.

#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.

#include <iostream >


using namespace std;
enum year { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
int main()
{
int i;
for (i = Jan; i <= Dec; i++)
cout << i << " ";
return 0;
}

 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

 PROGRAM OF PRINT STUDENT DETAILS IN COMPILE


TIME.
#include<iostream>
using namespace std;
struct student
{
int rollno;
char name[50];
float marks;
};
int main()
{
struct student s={4,"Rahul",86.5};
cout<<"Student details is - "<<endl;
cout<<"Rollno is - "<<s.rollno<<endl;
cout<<"Name - "<<s.name<<endl;
cout<<"Marks - "<<s.marks;
return 0;
}

 PROGRAM OF PRINT STUDENT DETAILS IN RUN TIME.

#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;
}

You might also like