GD INFOTECH Complete C++ Language Notes Website
This webpage is arranged topic-wise so teaching becomes easy. Each topic opens separately, which helps explain theory, syntax, programs, and exercises one by one in class.
It is structured from your uploaded C++ notes into a classroom-friendly teaching site.
1. Introduction & History
Begin with the origin of C++ and how it developed from C.
History of C++ Language
Teaching tip
Start by showing that C++ is an extension of C. Then explain inventor, year, and lab.
C++ LANGUAGE EXTENSION OF C SIMULA 67 C C++ MADE AT and T-BELL LABS 1980 BJARNE STROUSTRUP
COMMENT SINGLE LINE COMMENT // MULTIPLE LINE COMENT /*……………….. …………………*/
2. Basic Programs & Data Types
Introduce syntax, first program, variables and validation rules.
First Program of C++
FIRST PROGRAM OF C++
// This programe will display introduction to c++
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Cout<<”introduction to c++”;
getch();
}
Data Types in C++
Data type in c++ Char- store alphabets Int- storing only integer value and occupied 2bytes on hard disk Float- all storing decimal values 4bytes in memory
Validation Rules
Validation- Validation name rules- Can be any number of character Should start with alphabet or under case Should not be a keyword Should not allowed comma , blank space or any special symbol Only under score is allowed Like- Int 5a //wrong Int basic salary //wrong
Program 2, 3 and 4
Programe 2
//sum of two given numbers
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Int num1=25,num2=35,num3;
Clrscr();
Num3=num1+num2;
Cout<<”sum is”<<num3;
getch();
}
In the above programe first line will reserve the space for three
Memory
Num1 num2 num3
25 35 -
With statement
Num3=num1+num2;
Num1 num2 num3
25 35 60
Programe 3
//use of character variable
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Char alphavar;
Char numvar=’7’;
Clrscr();
Alphavar=’A’;
Cout<<”value of alphavar is”<<alphavar<<endl;
Cout<<”value of numvar is”<<numvar<<endl;
Numvar=’B’;
Cout<<”value of number after changing “<<numvar<<endl;
getch();
}
Programe 4
//float variables in c++
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Float numvar1=11.57;
Float numvar2=2.5;
Clrscr();
Cout<<”value of numvar1 is”<<numvar1<<endl;
Cout<<”value of numvar2 is”<<numvar2<<endl;
getch();
}
3. Operators & Input Output
Teach cin, cout, arithmetic operators and assignment operators.
Introduction of User Input
Introduction of user input
Cin>>variable name
Programe5
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Int num1,num2,num3;
Clrscr();
Cout<<”enter the first number”;
Cin>>num1;
Cout<<”enter the second number”;
Cin>>num2;
Num3=num1+num2;
Cout<<”sum is”<<num3;
getch();
}
Mathematical Operators
Mathematical operater in c++ + plus _ monus * multiply % modulus
Programe6
//programming using mathematical operaters
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Int num1,num2,num3,num4,num5;
Num1=2;
Num2=num1+2;
Num3=num1*num2;
Num4=num3/num2;
Num5=5%2;
Cout<<”value of num1 is”<<num1<<endl;
Cout<<”value of num2 is”<<num2<<endl;
Cout<<”value of num3 is”<<num3<<endl;
Cout<<”value of num4 is”<<num4<<endl;
Cout<<”value of num5 is”<<num5;
getch();
}
Output—
Value of num1 is 2
Value of num2 is 4
Value of num3 is 8
Value of num4 is 2
Value of num5 is 1
Assignment Operators
Mathematical assignment operaters + = suppose a + =5 a=a+5 - = “ a - =5 a=a-5 * = “ a * =5 a=a*5 / = “ a / =5 a=a/5
Programe7
//programe to show mathematical assignment operaters
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Int num1=2,num2=3,num3=4,num4=8;
Clrscr();
num1 + = 2;
num2 * = 2;
num3 - = 1;
num4 / = 2;
Cout<<”value of num1 is”<<num1<<endl;
Cout<<”value of num2 is”<<num2<<endl;
Cout<<”value of num3 is”<<num3<<endl;
Cout<<”value of num4 is”<<num4<<endl;
getch();
}
Output---
Value of num1 is 4
Value of num2 is 6
Value of num3 is 3
Value of num4 is 4
Exercises
EXERCISES:- 1. WAP to input principal, rate and time from keyboard.calculate simple interest Hint………….. si = p*r*t / 100; Float p,r,t,si; 2. WAP to input basic salary, da,hra from the keyboard program to calculate the gross salary. Hint……….. Gs=bs+da+hra; 3. WAP to input only the basic salary from keyboard only. Da is 30% of basic salary ta is 40% of basic salary And gs=bs+da+ta 4. The distance between two cities ( in km ) are input through the keyboard WAP to convert and print distance in meters , feet, inches and centimeters. M=km * 1000; Cm=m* 100; Inch=cm/2.54; Ft=inch/12; 5. two number are input through the keyboard into the the location of c and d WAP to interchange the contents.
4. Decision Making
Teach if, else, nested if and switch case with classroom examples.
Decision Making & Relational Operators
LESSON 2
DESION MAKING
WHEN ONE STATEMENT OR MORE STATEMENTS ARE EXECUTED ON THE BASIS OF THE TRUTH OF CONDITION THEN WE USE……………
if ___________________
if _________________else
if____elseif________else
RELATIONAL OPERATERS
In the above statement relational operaters are used……
> greater
< less than
= = equal to
! = not equal to
> = greater than or equal to
< = less than and equal to
if Statement
//PROGRAM USING IF STATEMENT ONLY
# Include<iostream.h>
# Include<conio.h>
Void main()
{
Int num1,num2;
Clrscr();
Cout<<”enter the value of num1”;
Cin>>num1;
Cout<<”enter the value of num2”;
Cin>>num2;
If(num1>num2)
{
Cout<<”num1 is greater than num2”;
}
getch();
}if...else and nested if
If____________else
If you are required to execute one out of two statement than you have to use if__else
//PROGRAM TO USE IF---------ELSE
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int a,b;
clrscr();
cout<<”enter the value of a”;
cin>>a;
cout<<”enter the value of b”;
cin<<b;
if(a>b)
cout<<”a is greater”;
else
cout<<”b is greater”;
getch();
}
NESTED IN BLOCKS
IF ALTERNATE ARE MORE THAN ONE
//PROGRAMING USING IF_____ELSE IF_____ELSE
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int marks;
clrscr();
cout<<”enter the marks”;
cin>>marks;
if(marks>=85)
cout<<”merit”;
else
{
if(marks>=60)
cout<<”first division”:
else
{
if(marks>=50)
cout<<”second division”;
else
{
If(marks>=40)
Cout<<”third division”;
else
cout<<”fail”;
}
}
}
getch();
}
//one more programe of nested if’s
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int day;
clrscr();
cout<<”enter week day”;
cin>>day;
if(day= =1)
cout<<”Sunday”;
else
{
if(day= =2)
cout<<”monday”;
else
{
if(day= =3)
cout<<”tuesday”;
else
{
if(day= =4)
cout<<”wednesday”;
else
{
if(day= =5)
cout<<”thursday”;
else
{
if(day= =6)
cout<<”friday”;
else
{
if(day= =7)
cout<<”Saturday”;
else
cout<<”invalid day”;
}
}
}
}
}
}
getch();
}Switch Case & Exercises
SWITCH CASE
also use when we have to choose one out of many switch()
//PROGRAM TO IMPLEMENT SWITCH CASE
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int day;
clrscr();
cout<<”enter week day”;
cin>>day;
switch(day)
{
case1:
cout<<”Sunday”;
break;
case2:
cout<<”monday”;
break;
case3:
cout<<”tuesday”;
break;
case4:
cout<<”wednesday”;
break;
case5:
cout<<”thursday”;
break;
case6:
cout<<”friday”;
break;
case7:
cout<<”saturday”;
break;
default:
cout<<”invalid day”;
break;
}
getch();
}
EXERCISE
1) WAP TO INPUT THE AGE OF PERSON THROUGH KEYBOARD IF AGE > =18 THAN OUTPUT SHOULD BE PERSON IS ELIGIBLE FOR VOTE ELSE PRRSON IS NOT ELIGIBLE FOR VATE.
2) WAP TO INPUT YEAR FROM KEYBOARD OUTPUT SHOULD BE WHETHER THE YEAR IS LEEP YEAR OR NOT.
3) WAP TO INPUT THE NUMBER FROM KEYBOARD AND OUTPUT SHOULD BE WHETHER THE NUMBER IS EVEN OR ODD.
4) WAP TO INPUT THE NO. OF CALLS THROUGH PROGRAM TO CALCULATE THE TELEPHONE BILL RATE’S ARE AS FOLLOW:-------
ON FIRST 100 CALLS .80P PER CALL
NEXT 100 CALLS 1.00 PER CALL
NEXT 200 Calls 1.50 PER CALL
AND NEXT 2 PER CALL
SUPPOSE WE INPUT 350 CALLS THE BILL SHOULD BE
FIRST 100 100*.80 80
NEXT 100 100*1 100
NEXT 150 150*1.50 225
4505. Loops
Explain repetition, nested loops, while loop, do while loop and conditional operator.
Loop Basics and for Loop
LOOPS
When one or more statements are to be executed again & again till certain condition then we use loop
Loop types………….
for loop
While loop
do while loop
for loop
for( initial value ; condition ; increment/decrement)
{
Statement
}
//WAP to print 1 to 20 through for loop
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int i ;
clrscr();
for(i=1;i<=20;i++)
{
Cout<<i;
}
getch();
}
//print number 20 to 1
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int i;
clrscr();
i >=1
for(i=20;i>=1;i--)
cout<<i;
getch();
}
//print number 1 to 100 divisible by 2
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int i;
clrscr();
for(i=2;i<=100;i=i+2)
cout<<i<<endl;
getch();
}Logical Operators, Nested Loop and Exercises
Logical operaters
&& AND
! NOT
|| OR
//PRINT NUMBER 1 TO 100 DIVISIBLE BY 3 AND 5
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int i;
clrscr();
for(i=1;i<=100;i++)
{
If(i%3= =0 && i%5= =0)
}
Cout<<i<<endl;
getch();
}
EXCERCISE 1) WAP to print the number from 1 to 100 which are divisible by 5 2) WAP to calculate the sum of natural number. 3) WAP to input number from keyboard and through for loop calculate the factorial of such number
NESTED LOOP OR INNER LOOP
Loop with in another loop is called nested loop
Like……..
For( )
{
For( ) //nested
}
//WAP to display the output of program as follows……..
1
12
123
1234
12345
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
cout<<j;
cout<<endl;
}
getch();
}
EXERCISE 4
1) SHOW THE OUT PUT AS FOLLOW
1
22
333
4444
55555
HINT:-
for(i=1;i<=5;i++)
{
for(j=1;j<+i;j++)
cout<<i;
cout<<endl;
2)SHOW THE OUTPUT AS FOLLOW…………
55555
4444
333
22
1
HINT:-
for(i=5;i>=1;i--)
{
for(j=1;j<+i;j++)
cout<<i;
cout<<endl;
}
}
3)SHOW THE OUTPUT AS FOLLOW……..
12345
1234
123
12
1
HINT:-
for(i=5;i>=1;i--)
{
for(j=1;j<+i;j++)
cout<<j;
cout<<endl;
}While, Do While and Conditional Operator
WHILE LOOP
While(condition)
{
……………..statement…………..
…………………………………..
}
//PRINT 1 TO 20 THROUGH WHILE LOOP
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int i=1;
clrscr();
while(i<=20)
{
cout<<i;
i++;
}
getch();
}
EXERCISE=5
ATTEMPT ALL THE QUESTIONS OF FOR LOOP THROUGH WHILE LOOP.
HINT:------
1 55555
22 4444
333 333
4444 22
55555 1
int i=1,j; int i=5;
clrscr(); clrscr();
while(i=5) while(i>=1)
{ {
j=1; j=1;
while(j<=i) while(j<=i)
{ {
Cout<<i; cout<<i;
j++; j++;
} }
Cout<<endl; i--;
i++;
}
DO WHILE LOOP
//PRINT 1 TO 20 THROUGH DO WHILE LOOP
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int i=1;
clrscr();
do{
cout<<i;
i++;
}
While(i<=20);
getch();
}
ATTEMPT ALL THE QUESTIONS OF FOR LOOP THRUGH DO WHILE LOOP
CONDITIONAL OPERATORS
these are also called as ternary operators because it has three expressions_...........
EXPRESSION 1 ? EXPRESSION 2 : EXPRESSION 3
TRUE
FALSE
//EVEN AND ODD THROUGH CONDITION OPERATORS
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
clrscr();
cout<<”enter the number”;
cin>>a;
a%5= =0?cout<<”even number”:cout<<”odd number”;
getch();
}
//ANOTHER PROGRAM OF USING CONDITIONAL OPERATOR
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,greater;
clrscr();
cout<<”enter the first number”;
cin>>a;
cout<<”enter the second number”;
cin>>b;
greater=(a>b)?a:b;
cout<<”the greater value is”<<greater<<endl;
getch();
}6. Arrays
Teach one dimensional and two dimensional arrays, sorting and matrix programs.
One Dimensional Array
ARRAY
Similar set of elements are called array.
ONE DIMESIONAL ARRAY
ARRAY DECLARATION
int marks[5]
marks[0] marks[4]
INITIALISATION OF ARRAY
int marks[5]={10,11,25,30,35}
marks[0] marks[4]
10 11 25 30 35
//SIMPLE ARRAY PROGRAM
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int arr[7]={11,12,13,14,15.16,17};
int I;
clrscr();
cout<<”contents of array”<<endl;
for(i=0;i<7;i++)
{
Cout<<arr[i]<<’/t’;
}
getch();
}
//INPUT IN ARRAY THROUGH KEYBOARD
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int arr[7],i;
clrscr();
cout<<”enter 7 array;
for(i=0;i<7;i++)
cin>>arr[i];
cout<<”the output of 7 array are”<<endl;
for(i=0;i<7;i++)
cout<<arr[i]<<’/t’;
getch();
}
//LARGEST NUMBER OF AN ARRAY
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int arr[10],I,n,lar;
clrscr();
cout<<”enter 10 values”<<endl;
for(i=0;i<10;i++)
cin>>arr[i];
lar=arr[0];
for(i=0;i<10;i++)
{
If(lar<arr[i])
lar=arr[i];
}
cout<<”largest value=”<<lar;
getch();
}
/* SORT READ NUMBER FROM INPUT DEVICE AND SORT THEM IN ASSENDING ORDER */
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int arr[10];
int i,j,n,temp;
clrscr();
for(i=0;i<10;i++)
cin>>a[i];
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for(i=0;i<10;i++)
cout<<arr[i]<<’/t’;
getch();
}Two Dimensional Array
TWO DIMESIONAL ARRAY
The array which have two dimesions first for row and other from column is called two dimesional array.
DECLARATION:------
int aee[3][3];
MEMORY PICTURE
0 1 2
0
1
2 0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
INITIALISATION OF ARRAY
int arr[3][3]={ 45, 47,50
70,80,90
100,120,130}
MEMORY PICTURE
0 1 2
0
1
2 45 47 50
70 80 90
100 120 130
//SIMPLE PROGRAM OF 2D ARRAY
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int arr[3][3]={ 45, 47,50
70,80,90
100,120,130}
Clrscr();
Cout<<”contents of arrat are”<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout<<arr[i][j];
cout<<endl;
}
getch();
}
//SUM OF MARIX 3*3
# Include<iostream.h>
# Include<conio.h>
Void main()
{
int arr[3][3],arr1[3][3],add[3][3];
int i,j;
clrscr();
cout<<”enter the contest of first array”
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cin<<arr[i][j];
}
cout<<”enter the contest of second array”
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cin<<arr[i][j];
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cin<<arr[i][j];
add[i][j]=arr[i][j]+arr1[i][j];
}
cout<<”addition of 3*3 matrix is”<<endl;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout<<arr[i][j];
cout<<endl;
}
getch();
}7. Strings
Explain character arrays and string handling functions in C++ notes style.
Introduction to Strings
STRING
Character arrays are called string.
Declaration:----------
Char arr[5]=”sunil”
s
u
n
i
l
arr[0] arr[4]
but the above statement will be wrong because there is no space for ‘/0’ which must be at the end.
Char arr[6] =”sunil”
s
u
n
i
l
‘/0’
arr[0] arr[5]Simple String Programs
//SIMPLE PROGRAM OF STRING
#include<iostream.h>
#include<conio.h>
Void main()
{
Char name[ ] =”cal c computer”;
Clrscr();
Cout<<”name is”<<endl;
Cout<<name;
getch();
}
//wap which read a string and then print that
#include<iostream.h>
#include<conio.h>
Void main()
{
Char str[20];
Clrscr();
Cout<<”enter string”<<endl;
Cin>>str;
Cout<<”the string is”<<str;
getch();
}String Handling Functions
STRING HANDLING FUNCTION:------------------------ Strlen() → find length of string Strcat() → append the contents of string at the end of first Strcpy() → copy the contents of second string in first Strcmp() → compare two strings Strupr() → convert lower case string to upper case Strlwr() → convert upper case string to lower case Strrev() → reverse the string
//STRLEN()
#include<iostream.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char str[50];
int n;
Clrscr();
Cout<<”enter the string”;
Cin>>str;
n=strlen(str);
Cout<<”length is”<<n;
getch();
}
//STRCAT()
#include<iostream.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char str[30],str1[15];
Clrscr();
Cout<<”enter the first string”;
Cin>>str;
Cout<<”enter the second string”;
Cin>>str1;
Strcat(str,str1);
Cout<<”string after concatenate is”<<str;
getch();
}
//STRCPY()
#include<iostream.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char str[15],str1[15];
Clrscr();
Cout<<”enter the second string”;
Cin>>str;
Strcpy(str,str1);
Cout<<”string after copy”<<str;
getch();
}
//STRCMP()
Compare two strings the result of this function is given as…..
If both are equal value given by it are 0
If str is less as per
ASCII code value is <0
If str is greater as per
ASCII code value is >0
//STRCMP()
#include<iostream.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char str[15],str1[15];
int n;
Clrscr();
Cout<<”enter the first string”;
Cin>>str; or gets(str)
Cout<<”enter the second string”;
Cin>>str1; or gets(str1)
n= strcmp(str,str1);
if(n= = 0)
cout<<”both strings are equal”;
if (n<0)
cout<<”string is lower as per ASCII code”;
if(n>0)
cout<<”string is greater as per ASCII cond”;
getch();
}
//STRUPR()
#include<iostream.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char str[15];
Clrscr();
Cout<<”enter the contents of lower case”;
Cin>>str;
Cout<<”contents in upper case are”<<endl;
Cout<<strupr(str);
getch();
}
//STRLWR()
#include<iostream.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char str[15];
Clrscr();
Cout<<”enter the contents of upper case”;
Cin>>str;
Cout<<”contents in lower case are”<<endl;
Cout<<strlwr(str);
getch();
}
//STRREV()
#include<iostream.h>
#include<conio.h>
#include<string.h>
Void main()
{
Char str[15];
Clrscr();
Cout<<”enter the string”;
Cin>>str;
Cout<<”string in reverce order is”<<endl;
Cout<<strrev(str);
getch();
}8. Functions & Recursion
Teach function types, arguments, arrays with function and recursive factorial.
Function Basics
FUNCTION
When our program become longer and complex then it converts into small parts that small parts are called function.
OR
We can define it as a set of statements that can be executed as any time by using only the function name.
FUNCTION CAN BE :---
Void:- those which does nit return any value to the main function are called void type function.
Return:-those which return same value to the main are called return type function.
With argument:-the function which have same arguments within its are called with arguments function.
Without argument:-those which hanve no arguments with its function are called without arguments.Function Programs
// SUM OF TWO NUMBERS VOID WITHOUT ARGUMENT FUNCTION
#include<iostream.h>
#include<conio.h>
Void main()
{
Clrscr();
Void add(); //function prototype
add( );
getch();
}
Void add( )
{
int a,b,s;
cout<<”enter the value of a”;
cin>>a;
cout<<”enter the value of b”;
cin>>b;
s=a+b;
cout<<”sum is”<<s;
}
//FUNCTION VOID AND WITH ARGUMENT
#include<iostream.h>
#include<conio.h>
Void main()
{
Void add(int,int); function prototype
int a,b;
clrscr();
cout<<”enter the value of a”;
cin>>a;
cout<<”enter the value of b”;
cin>>b;
add(a,b);
getch();
}
Void add(int x,int y)
{
int z;
z= x+y;
cout<<”sum of two integer no.”<<z;
]
//FOLLOWING IS THE PROGRAM WITH DIFFERENT TYPES OF ARGUMENT
#include<iostream.h>
#include<conio.h>
Void main()
{
Void display(char,int,float);
int n;
char section;
float percentage;
clrscr();
cout<<”enter section”;
cin>>section;
cout<<”enter total no. of students”;
cin>>n;
cout<<”enter percentage”;
cin>>percentage;
display(section,n,percentage);
getch();
}
void display(char s, int t, float p)
{
Cout<<”the section”<<s<<”has”<<t<<”total no. of students with”<<p<<”percentage”<<endl;
}
//example of function type with arguments
#include<iostream.h>
#include<conio.h>
void maim()
{
int sum(int,int);
int a,b,c
clrscr();
cout<<”enter the first no.”;
cin>>a;
cout<<”enter the second no.”;
cin>>b;
c=sum(a,b);
cout<<”sum is”<<c;
getch();
}
int sum(int x,int y)
{
int z;
z=x+y;
return z;
}
//ARRAY AND FUNCTION
#include<iostream.h>
#include<conio.h>
void maim()
{
void output(int a[]);
int a[10];
int I;
clrscr();
cout<<”enter the 10 array”;
for(i=0;i<10;i++)
cin>>a[i];
output(a);
getch();
}
void output(int a[])
{
int i;
for(i=0;i<10;i++)
cout<<a[i]<<endl;
}
//SUM OF ARRAY THROUGH FUNCTION AND ARRAY
#include<iostream.h>
#include<conio.h>
Void main()
{
Void sumarray (int a [] );
int a[10];
int I;
cout<<”enter 10 array”;
for(i=0;i<10;i++)
cin>>a[i];
sumarray(a);
getch();
}
Void sumarray (int x[] )
{
int value=0,i;
for(i=0;i<10;i++)
value=value+x[i];
cout<<”sum of array”<<value;Recursion
RECURSION
WHEN the function calls it self again AND AGAIN that is called recursion.
EX:_______
#INCLUDE<iostream.h>
Void main()
{
Void funct 1();
…………………………
………………………..
funct 1();
{
void funct 1()
}
funct 1():
}
//example of factorial through recurtion
#include<iostream.h>
#include<conio.h>
void main()
{
long int fact(long int);
int x,n;
clrscr();
cout<<”enter the integer no.”<<endl;
cin>>n;
x=fact(n);
cout<<”factorial is”<<x;
getch();
}
long int fact(long int n)
{
int value;
if(n= =1)
return(1);
else
value=n*fact(n-1)
return value;
}
24
value=5*fact(4) 6
→ 4*fact(3) 2
→3*fact(2) 1
→2*fact(1)
value=1209. Manipulator Functions
Teach dec, hex, oct, setbase, setw, setfill and setprecision.
Manipulator Function Notes and Programs
MANIPULATION FUNCTION to use the manipulator functionS we have to open iomanip.h file
//USING DEC,HEX,OCT MANIPULATERS
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int value;
clrscr();
cout<<”enter the number”;
cin>>value;
cout<<”decimal number”<<dec<<value<<endl;
cout<<”hexadecimal value”<<hex<<value<<endl;
cout<<”octal value”<<oct<<value<<endl;
getch();
}
//PROGRAM TO USE SETBASE FUNCTION
#include<iostream.h>
#include<conio.h>
#include<10manip.h>
void maim()
{
int value;
clrscr();
cout<<”enter number”<<endl;
cin>>value;
cout<<”decimal value”<<setbase(10)<<value<<endl;
cout<<”hexadecimal value”<<setbase(16)<<value<<endl;
cout<<”octal value”<<setbase(8)<<value<<endl;
getch();
}
//USING SETW( )
#include<iostream.h>
#include<conio.h>
#include<10manip.h>
void maim()
{
int a=10,b=20;
clrscr();
cout<<a<<setw(3)<<b;
getch();
}
//USING SETFILL
#include<iostream.h>
#include<conio.h>
#include<10manip.h>
void maim()
{
int a=10,b=20;
clrscr();
cout<<setfill(‘*’);
cout<<a<<setw(3)<<b;
getch();
}
//USING SETPRECISION
#include<iostream.h>
#include<conio.h>
#include<10manip.h>
void maim()
{
float a,b,c;
clrscr();
a=8;
b=3;
c=a/b;
cout<<setprecision(6)<<c<<endl;
cout<<setprecision(3)<<c<<endl;
cout<<setprecision(2)<<c<<endl;
cout<<seprecition(1)<<c<<endl;
getch();
}
OUTPUT:=
2.666667
2.667
2.67
2.710. Structure & Union
Explain structured data and union concepts with examples.
Structure Programs
STRUCTURE AND UNION
structure is a collection of data items which canbe of different type int, float or anything.
DECLARATION:-
structure student {
char name[10];
int roll_no;
char branch[10];
int sem;
};
//SIMPLE PROGRAM USING STRUCTURE
#include<iostream.h>
#include<conio.h>
void maim()
{
struct student {
char name[10];
int roll_no;
char branch[10];
int sem;
};
void main()
{
student std1,std2;
clrscr();
cout<<”enter the details of first student”<<endl;
cout<<”enter the name”;
cin>>std1.name;
cout<<”enter the roll_no:;
cin>>std1.roll_no;
cout<<”enter branch”;
cin<<std1.branch;
cout<<’enter semester”
cin>>std1.sem;
cout<<”enter the details of second student”;
cout<<”enter the name”;
cin>>std2.name;
cout<<”enter the roll_no:;
cin>>std2.roll_no;
cout<<”enter branch”;
cin>>std2.branch;
cout<<’enter semester”
cin>>std2.sem;
cout<<”details of first students are”<<endl;
cout<<std1.name<<std1.roll_no<<std1.branch<<std1.sem<<endl;
cout<<”details of second students are”<<endl;
cout<<std2.name<<std2.roll_no<<std2.branch<<std2.sem<<endl;
getch();
}
//SIMPLE PROGRAM USING STRUCTURE
#include <iostream,h>
#include<conio.h>
struct Person
{
char name[50];
int age;
float salary;
};
void main()
{
Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
getch();
}
/* THE FOLLOWING PRIGRAM WILL ALSO IMPLIMENTS THE STRUCTURE */
#include<iostream.h>
#include<conio.h>
struct employee
{
int emp_code;
char emp_name[20];
char designation[10];
float salary;
};
void main()
{
employee emp1,emp2;
clrscr();
cout<<”enter the details of first employee”<<endl;
cout<<”enter the employee code”;
cin<<emp1.emp_code;
cout<<”enter the employee name”;
cin>>emp1.emp_name;
cout<<”enter desidnation”;
cin>>emp1.designation;
cout<<”enter salary”;
cin>>emp1.salary;
emp2=emp1;
cout<<”employee code of second employee”<<emp2.emp_code;
cout<<”employee name of second employee”<<emp2.emp_name;
cout<<”employee designation”<<emp2.designation<<endl;
cout<<”employee salary is”<<emp2.salary;
getch();
}
//ARRAY AND STRUCTURE
#include<iostream.h>
#include<conio.h>
struct student
{
int roll_no;
char student_name[20];
char address[15];
int age;
};
void main()
{
student std[10];
int i;
clrscr();
cout<<”accept the value into array”;
for(i=1;i<10;i++)
{
cout<<”enter the details of”<<i<<”student”<<endl;
cout<<’enter roll no.”;
cin>>std[i].roll_no;
cout<<”enter student name”;
cin>>std[i].student_name;
cout<<”enter address”;
cin>>std[i].address;
cout<<”enter age”;
cin>>std[i].age;
{
cout<<”enter the records you enter are”<<endl;
for(i=1;i<10;i++)
{
cout<<endl;
cout<<”roll no.”<<std[i].roll_no<<endl;
cout<<’student name”<<std[i].student_name<<endl;
cout<<”address”<<std[i].address<<endl;
cout<<”age”<<std[i].age<<endl;
}
}
}
getch();
}Nested Structure and Union
NESTED STRUCTURE
STRUCTURE WITH IN ANOTHER STRUCTURE IS CALLED NESTED STRUCTURE.
LIKE:-
struct tag1
{
data type member_name;
………………………
……………………..
struct tag2 member_name;
};
//PROGRAM USING NESTED STRUCTURE
#include<iostream.h>
#include<conio.h>
struct account
{
int account_no;
char account_type;
float balance;
};
struct employee
{
int emp_code;
char emp_name[20];
char designation[10];
float salary;
struct account account_details;
};
Void main()
{
employee emp1;
clrscr();
cout<<”accepting values for structure employee using variable empl”<<endl;
cout<<”enter the employee code”;
cin<<emp1.emp_code;
cout<<”enter the employee name”;
cin>>emp1.emp_name;
cout<<”enter desidnation”;
cin>>emp1.designation;
cout<<”enter salary”;
cin>>emp1.salary;
cout<<”enter account no.”;
cin>>emp1.account_details.account_no”;
cout<<”enter account type”;
cin>>emp1.account_details.account_type”;
cout<<”enter account balance”;
cin>>emp1.account_details.account_balance”;
cout<<endl;
cout<<”displaying details of employee”<<endl;
cout<<”employee code is”<<emp1.emp_code<<endl;
cout<<”employee name is”<<emp1.emp_name<<endl;
cout<<”employee designation is”<<emp1.designation<<endl;
cout<<”employee salary is”<<emp1.salary<<endl;
cout<<”account is”<<emp1.account_details.account_number<<endl;
cout<<”account type is”<<emp1.account_details.account_type<<endl;
cout<<”balance is”<<emp1.account_details.account_balance<<endl;
getch();
}
UNION
LIKE STRUCTURE BUT NOT STRUCTURE HOLD ONLY THE ONE VALUE THAT IS ASSIGNED AT THE LAST.
//PROGRAM USING UNION
#include<iostream.h>
#include<conio.h>
Void main()
{
union data
{
int i;
float f;
};
data d;
clrscr();
d.f=20.5;
d.i=10;
cout<<”first number”<<d.i<<endl;
cout<<”second number”<<d.f<<endl;
d.f=20.5;
cout<<”first number”<<d.i<<endl;
cout<<”second number”<<d.f<<endl;
getch();
}11. Class, Scope Resolution, Constructors
Teach OOP basics, class members, scope resolution and constructor types.
Class Basics
CLASS
Class class_name
{
Data members;
………………………
………………………
Member function();
}
DATA MEMBER OR MEMBER FUNCTION CAN BE
PRIVATE;- can be accessed by member functions only can not be accessed the class.
PUBLIC;- Can be accessed anywhere.
//THE FOLLOWING PROGRAM CREATES A CLASS CIRCLE
#Include<iostream.h>
#Include<conio.h>
Class circle
{
Private:
Int radius;
Public:
Void accept_radius()
{
Cout<<”enter the radius of circle”;
Cin>>radius;
}
Void area_of_circle()
{
Int area;
area=3.14*radius*radius;
cout<<”area of circle is”<<area;
}
};
Void main()
{
Circle obj1;
Clrscr();
obj.accept_radius();
obj1.area_of_circle();
getch();
}
#include <iostream.h>
#Include<conio.h>
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
void main( ) {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
getch();
}Use of Scope Resolution Operator
USE OF SCOPE RESOLUTION OPERATOR
:: SCOPE RESOLUTION OPERATOR
//DEFINE OF FUNCTION OUTSIDE THE CLASS
#Include<iostream.h>
#Include<conio.h>
Class circle
{
Private:
Int radius;
Public:
Void accept_radius();
Void area_of_circle();
};
Void circle :: accept_radius()
{
Cout<<”enter the radius of circle”;
Cin>>radius;
}
Void circle :: area_of_circle()
{
Int area;
area=3.14*radius*radius;
cout<<”area of circle is”;
}
Void main()
{
Circle object1;
Clrscr();
obj1.accept_radius();
obj1.area_of_circle();
getch();
}Constructors
CONSTRUCTOR CONSTRUCTION IS A FUNCTION IN CLASS WITH THE SAME NAME AS THAT OF A CLASS AND THESE ARE THE SPECIAL FUNCTON THAT ARE EXECUTED AUTOMATICALLY WHEN EVER THE OBJECT IS CREATED. Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors iitialize values to object members after storage is allocated to the object Constructors are of three types : 1. Default Constructor 2. Parametrized Constructor 3. Copy COnstructor
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
#include<iostream.h>
#include<conio.h>
class Cube
{
Private:
int side;
public:
Cube()
{
side=10;
cout<<”side is”<<side;
}
};
Void main()
{
Cube c;
getch();
}
Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.
#include<iostream.h>
#include<conio.h>
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
cout<<”valur of x is”<<side;
}
};
void main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
getch();
}
Copy Constructor in C++
//parametrized constructor
#include<iostream.h>
#include<conio.h>
class abc
{
private:
int a;
float b;
char c;
public:
abc(int x,float y, char z); //set default value into x
abc(abc &p);// copy contructor
~abc();
void display();
};
abc::abc(int x,float y, char z)
{
a=x;
b=y;
c=z;
}
void abc::display()
{
cout<<"a= "<<a<<endl;
cout<<"b= "<<b<<endl;
cout<<"c= "<<c<<endl;
}
abc:: abc(abc &p)
{
a=p.a;
b=p.b;
c=p.c;
}
abc:: ~abc()
{
cout<<"thanks for using c++ \n";
}
void main()
{
clrscr();
abc ob1(50,450.52, 'a'); // object created and constructor fun exe.
abc ob2(ob1);
abc ob3=ob2;
cout<<"object 1 data value"<<endl;
ob1.display();
cout<<"object 2 data value"<<endl;
ob2.display();
cout<<"object 3 data value"<<endl;
ob3.display();
getch();
}
Constructor Overloading
Just like other member functions, constructors can also be overloaded. Infact when you have both default and parameterized constructors defined in your class you are having Overloaded Constructors, one with no parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};
Void main()
{
Student A(10);
Student B(11,"Ram");
getch();
}
In above case we have defined two constructors with different parameters, hence overloading the constructors.
//PROGRAM THAT CREATES A CLASS WITH CONSTRUCTION
#Include<iostream.h>
#Include<conio.h>
Class circle
{
Int radius;
Public:
Circle()
{
radius=5;
}
Void area_of_circle()
{
Int area;
area=3.14*radius*radius;
cout<<”area of circle is”<<area<<endl;
}
};
Void main()
{
Clrscr();
Circle obj1;
obj1.area_of_circle;
getch();
}
You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value.Destructors
Destructors C++ Destructor Basics Destructors are special member functions of the class required to free the memory of the object whenever it goes out of scope. Destructors are parameterless functions. Name of the Destructor should be exactly same as that of name of the class. But preceded by ‘~’ (tilde). Destructors does not have any return type. Not even void. The Destructor of class is automatically called when object goes out of scope.
C++ Destructor Program
#include<iostream.h>
#include<conio.h>
class Marks
{
public:
int maths;
int science;
//constructor
Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}
//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};
void main( )
{
{
Marks m1;
Marks m2;
}
getch();
}
Output
Inside Constructor
C++ Object created
Inside Constructor
C++ Object created
Inside Destructor
C++ Object destructed
Inside Destructor
C++ Object destructed
Explanation :
You can see destructor gets called just before the return statement of main function. You can see destructor code below –
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
C++ Destructor always have same name as that of constructor but it just identified by tilde (~) symbol before constructor name.
Below example will show you how C++ destructor gets called just before C++ object goes out of scope.
C++ Destructor Program #2 : Out of scope
#include<iostream.h>
#include<conio.h>
class Marks
{
public:
int maths;
int science;
//constructor
Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}
//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};
void main( )
{
{
Marks m1;
}
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
getch();
}
Output :
Inside Constructor
C++ Object created
Inside Destructor
C++ Object destructed
Hello World !!
Hello World !!
Hello World !!
Hello World !!
Explanation :
In this example we have defined the scope of the object as we declared object inside the curly braces i.e inside the inner block.
int main( )
{
{
Marks m1;
}
So object will be accessible only inside the curly block. Outside the curly block we cannot access the object so destructor gets called when inner curly block ends
In this example Hello World !! gets printed after the destructor. however for below example Hello World !! gets printed before constructor
C++ Destructor Program #3 : before destructor
#include<iostream.h>
#include<conio.h>
class Marks
{
public:
int maths;
int science;
//constructor
Marks() {
cout << "Inside Constructor"<<endl;
cout << "C++ Object created"<<endl;
}
//Destructor
~Marks() {
cout << "Inside Destructor"<<endl;
cout << "C++ Object destructed"<<endl;
}
};
void main( )
{
Marks m1;
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
cout<<"Hello World !!" <<endl;
getch();
Output :
Inside Constructor
C++ Object created
Hello World !!
Hello World !!
Hello World !!
Hello World !!
Inside Destructor
C++ Object destructed12. Inheritance & Polymorphism
Teach single, multiple, multilevel, hierarchical, virtual base class and polymorphism.
Inheritance Basics and Single Inheritance
INHERITENCE
Drive one class from another is called inheritance from that from which it is derived is called base class and a new created class is called derived class.
The syntax to create class from another class
Class class_name : public baseclass_name
{
Set of statements
…………………
…………………
}
//PROGRAM TO SHOW SINGLE INHERITENCE IN C++
#Include<iostream.h>
#Include<conio.h>
Class book
{
Protected :
Int no_of_pages;
Char book_title[15];
Char author_name[15];
Char publisher_name[15];
Char catagery[15];
};
Class technical_book : public book
{
Private:
Char technology[15];
Int edition;
Public:
Void accept_book_details()
{
Cout<<”enter the title of book”;
Cin>>book_title;
Cout<<”enter author name of book”;
Cin>>author_name;
Cout<<”enter no. of pages of book”;
Cin>>no_of_pages;
Cout<<”enter publisher name of the book”;
Cin>>publisher_name;
Cout<<”enter the catagory of book”;
Cin>>catagory;
Cout<<”enter technology discussed in the book”;
Cin>>technology;
Cout<<”enter the edition of book”;
Cin>>edition;
}
Void display_book_details()
{
Cout<<” Title of book is”<<book_title<<endl;
Cout<<”Author name of book is”<<author_name<<endl;
Cout<<”No. of pages of book is”<<no_of_pages<<endl;
Cout<<”Publisher name of the book is”<<publisher_name<<endl;
Cout<<”Catagory of book is”<<category<<endl;
Cout<<”Technology discussed in the book is”<<technology<<endl;
Cout<<”Edition of book is”<<edition<<endl;
}
};
Void main()
{
Clrscr();
Technical_book obj1;
Cout<<”enter the details of the books”<<endl;
obj1.accept_book_details();
cout<<endl;
cout<<”details of the books are”<<endl;
obj1.display_book.details();
getch();
}Same Function in Base and Derived Classes
ACCESSING SAME FUNCTION IN THE BASE AND DERIVED CLASSES CAN BE DONE JUST GIVING DIFFERENT OBJECTS
#include<iostream.h>
#include<conio.h>
Class base1
{
Public;
Void display()
{
Cout<<”function from base class”;
}
Class derived1:public base1
{
Void display()
{
Cout<<”function from derived class”;
}
};
Void main()
Base obj;
Cout<<”accessing function using objects of base class”;<<endl;
obj.display();
derived1 obj1;
cout<<”accessing function using objectsof base class”<<endl;
obj1.display();
getch();
}Multiple, Multilevel, Hierarchical and Virtual Base Class
MULTIPLE BASE CLASS A B C D
#include<iostream.h>
#include<conio.h>
Class bio
{
char name[20];
char semester[20];
int age;
int rn;
public:
void getbio()
{
cout<<”enter name”:
cin>>name;
cout<<’enter semester”;
cin>>semester;
cout<<’enter age”;
cin>>age;
cout<<’enter roll no.”;
cin>>rn;
}
void showbio()
{
cout<<”name”<<name<<endl;
cout<<”semester”<<semester<<endl;
cout<<”age”<<age<<endl;
cout<<”roll no.”<<rn<<endl;
}
};
class marks
{
char sub[10];
float total;
public:
void getm()
{
cout<<”enter the subject name”;
cin>>sub;
cout<<”enter marks”;
cin>>total;
}
void showm()
{
cout<<”subject name”<<sub<<endl;
cout<<”marks are”<<total<<endl;
}
};
class final : public bio,public marks
{
long int phno;
public:
void getph()
{
cout<<”enter phone no”;
cin>>phno;
}
void showph()
{
cout<<”phone no”<<phno<<endl;
}
};
void main()
{
final f;
clrscr();
f.getbio();
f.getm();
f.getph();
f.showbio();
f.showm();
f.showph();
getch();
}
MULTILEVEL INHERITENCE B B1 D2 D3
//PROGRAM TO DISPLAY MULTILWVEL INHERITENCE
#include<iostream.h>
#include<conio.h>
Class student
{
protected:
char name[20];
int rn;
public:
void getdata()
{
cout<<”enter name”;
cin>>name;
cout<<”enter roll no”;
cin>>rn;
}
void showdata()
{
cout<<”name”<<name<<endl;
cout<<”roll no”<<rn<<endl;
}
};
class marks : public student
{
protected:
float sessional1;
float sessional2;
public:
void getm()
{
cout<<”enter the marks of sessional”;
cin>>sessional1;
cout<<”enter the marks of sessional”;
cin>>sessional2;
}
void showm()
{
cout<<”sessional1=”<<sessional1<<endl;
cout<<”sessional2=”<<sessional2<<endl;
}
};
class result : public marks
{
float total;
public:
void output()
{
total=sessional1+sessional2;
cout<<”total marks are”<<total<<endl;
}
};
void main()
{
result s1;
clrscr();
s1.getdata();
s1.getm();
cout<<”the record of student is”<<endl;
s1.showdata();
s1.showm();
s1.output();
getch();
}
HIERARCHICALINHERITENCE
B
D1 D2 D3
//PROGRAM OF HIERARCHICAL INHERITENCE
#include<iostream.h>
#include<conio.h>
Class B
{
protecte:
int x,y;
public:
void assign()
{
x=10;
y=20;
}
};
class D1:public B
{
int s;
public:
void add()
{
s=x+y;
cout<<”x+y”<<s<<endl;
}
};
class D2 : public B
{
int t;
public:
void sub()
{
t=x-y;
cout<<”x-y”<<t<<endl;
}
};
class D3 : public B
{
int m;
public:
void mul()
{
m=x*y;
cout<<”x*y”<<m<<endl;
}
};
void main()
{
D1 d1;
D2 d2;
D3 d3;
clrscr();
d1.assign();
d1.add();
d2.assign();
d2.sub();
d3.assign();
d3.mul();
getch();
}
VIRTUAL BASE CLASS
B
D1 D2
C1
In The Above Situation B is base abd d1 and d2 are two derived classes and one class c1 is taken from two classes d1 and d2 Now the problem can arise only in a situation if c1 class wants to access the functions or data members of B class because C1 is the derived class of D1 and D2 if C1 will access the data member or member functions of B it will copies from both D1 and D2 resulting ambiguity and there will be an error. so by declaring virtual this problem can be solved.
//PROGRAM USING VIRTUAL BASE CLASS
#include<iostream.h>
#include<conio.h>
Class B
{
protected:
int data;
};
class D1 : virtual public B
{
};
class D2 :vitual public B
{
};
class C : public D1,public D2
{
public:
int showdata()
{
data=5;
cout<<data;
}
};
void main()
{
C obj1;
obj1.showdata();
getch();
}Polymorphism
Polymorphism in C+ Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and morphs means forms. So polymorphism means many forms. Real life example of Polymorphism in C++ Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person have different-different behaviors. Type of polymorphism Compile time polymorphism
Method Overloading in C++
Whenever same method name is exiting multiple times in the same class with different number of parameter or different order of parameters or different types of parameters is known as method overloading. In below example method "sum()" is present in Addition class with same name but with different signature or arguments.
Example of Method Overloading in C++
#include<iostream.h>
#include<conio.h>
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20);
cout<<endl;
obj.sum(10, 20, 30);
getch();
}
Method Overriding in C++
Define any method in both base class and derived class with same name, same parameters or signature, this concept is known as method overriding. In below example same method "show()" is present in both base and derived class with same name and signature.
Example of Method Overriding in C++
#include<iostream.h>
#include<conio.h>
class Base
{
public:
void show()
{
cout<<"Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"Derived Class";
}
}
int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Ocuurs
d.show();
getch();
}
Run time polymorphism
In C++ Run time polymorphism can be achieve by using virtual function.13. Pointers in C++
Teach pointer declaration, arithmetic, pointer to pointer, pointer to function and pass by address.
Pointer Basics
POINTER IN C++
Pointer is a variable which stores the address of another data type
DECLARATION OF POINTER:-
p x
2000
5
int *p;
int x;
p=&x;
x=5; 1998 2000
//SIMPLE PROGRAM OF POINTER
#include<iostream.h>
#include<conio.h>
void main()
{
int *p;
int x;
clrscr();
cout<<”enter the value”;
cin>>x;
p=&x;
cout<<”value of x”<<x<<endl;
cout<<”value of x”<<*p;
cout<<”address of x”<<&x;
cout<<”address of x”<<p;
getch();
}
POINTER TO VOID E.G:- float y; int *p; p=&y; The above will be wrong because y is a float type variable and pointer is a integer type variable which can not be because the same type of data can be stored as the data type of pointer so here y should be integer then it can be solved.
POINTER ARITHMETIC int x, *p1,*p2,*p3; p1=&x; p2=++p1; Supose in the above address of x is 1000 then 1000 will be assigned to p1 but the value of p2 will be p2=1000+2 p2=1002 because integer takes two bytes and on the basis of above increment will be…
//PROGRAM USING MANIPULATION OF VARIABLE IN POINTER
#include<iostream.h>
#include<conio.h>
void main()
{
int x=10;
int *ptr;
ptr=&x;
cout<<”value of variable x is”<<x<<endl;
*ptr=*ptr*2;
cout<<”value of variable x is”<<x;
getch();
}Pointer and Array, Pointer to Pointer, Function Pointer
POINTER AND ARRAY
//PROGRAM USING POINTER AND ARRAY
#include<iostream.h>
#include<conio.h>
void main()
{
int a[5]={5,6,7,8,9};
int i;
int *p;
clrscr();
p=&a[10];
for(i=0;i<5;i++)
{
cout<<*(p+i)
cout<<endl;
}
getch();
}
//POINTER TO POINTER
#include<iostream.h>
#include<conio.h>
void main()
{
int data;
int *p1;
int **p2;
data=15;
cout<<”data=”<<data<<endl;
p1=&data;
p2=&p1;
cout<<”data through p1=”<<*p1<<endl;
cout<<”data through p2=”<<**p2<<endl;
getch();
}
POINTER TO FUNCTION
//PROGRAM USING POINTER TO FUNCTION
#include<iostream.h>
#include<conio.h>
void main()
{
float add(float,float);
float a,b,s;
float (*p) (float,float);
p=*add;
a=20.5;
b=10.3;
s=(*p) (a,b);
cout<<”s=”<<s<<endl;
getch();
}
float add (float a1,float b1)
{
int sum;
sum=a1+b1;
return sum;
}Pointer as Argument to Function
POINTER AS AN ARGUMENT TO FUNCTION If pointer is passed as an argument to the function that is know as pass by reference, or pass by pointer . this concept is also called as call by reference. call by reference is interpreted in two ways ….. 1) pass by reference 2) pass by address
//EXAMPLE PASS BY ADDRESS
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int*,int*);
a=10;
b=20;
clrscr();
swap(&a,&b);
cout<<”a=”<<a<<”b=”<<b<<endl;
getch();
}
void swap(int *a1,int *b1)
{
int t;
t=*a1;
*a1=*b1;
*b1=t;
}14. File Handling in C++
Teach streams, fstream library, modes, file creation, read/write and tellg/tellp.
File Handling Theory
What is file handling in C++? Files store data permanently in a storage device. With file handling, the output from a program can be stored in a file. Various operations can be performed on the data while in the file. A stream is an abstraction of a device where input/output operations are performed. You can represent a stream as either a destination or a source of characters of indefinite length. This will be determined by their usage. C++ provides you with a library that comes with methods for file handling. Let us discuss it.
The fstream Library The fstream library provides C++ programmers with three classes for working with files. These classes include: • ofstre am– This class represents an output stream. It’s used for creating files and writing information to files. • ifstream– This class represents an input stream. It’s used for reading information from data files. • fstream– This class generally represents a file stream. It comes with ofstream/ifstream capabilities. This means it’s capable of creating files, writing to files, reading from data files. To use the above classes of the fstream library, you must include it in your program as a header file. Of course, you will use the #include preprocessor directive. You must also include the iostream header file.
How to Open Files Before performing any operation on a file, you must first open it. If you need to write to the file, open it using fstream or ofstream objects. If you only need to read from the file, open it using the ifstream object. The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in them. The function takes this syntax: open (file_name, mode); • The file_name parameter denotes the name of the file to open. • The mode parameter is optional. It can take any of the following values: Value Description ios:: app The Append mode. The output sent to the file is appended to it. ios::ate It opens the file for the output then moves the read and write control to file’s end. ios::in It opens the file for a read. ios::out It opens the file for a write. ios::trunc If a file exists, the file elements should be truncated prior to its opening. It is possible to use two modes at the same time. You combine them using the | (OR) operator.
File Handling Programs
FILE HANDLING IN C++
//C++ program to create a file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream file; //object of fstream class
//opening file "sample.txt" in out(write) mode
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
cout<<"File created successfully.";
//closing the file
file.close();
}
//C++ program to write and read text in/from file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
fstream file; //object of fstream class
//opening file "sample.txt" in out(write) mode
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}
cout<<"File created successfully."<<endl;
//write text into file
file<<"ABCD.";
//closing the file
file.close();
//again open file in read mode
file.open("sample.txt",ios::in);
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}
//read untill end of file is not found.
char ch; //to read single character
cout<<"File content: ";
while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}
file.close(); //close file
}
//C++ program to write and read values using variables in/from file.
#include <iostream.h>
#include <fstream.h>
using namespace std;
int main()
{
char name[30];
int age;
fstream file;
file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;
//read values from kb
cout<<"Enter your name: ";
cin.getline(name,30);
cout<<"Enter age: ";
cin>>age;
//write into file
file<<name<<" "<<age<<endl;
file.close();
cout<<"\nFile saved and closed succesfully."<<endl;
//re open file in input mode and read data
//open file
file.open("aaa.txt",ios::in);
if(!file){
cout<<"Error in opening file..";
return 0;
}
file>>name;
file>>age;
cout<<"Name: "<<name<<",Age:"<<age<<endl;
}
Output
File created successfully.
Enter your name: Mike
Enter age: 21
File saved and closed succesfully.
Name: Mike,Age:21
//C++ program to write and read object using read and write function.
#include <iostream>
#include <fstream>
using namespace std;
//class student to read and write student details
class student
{
private:
char name[30];
int age;
public:
void getData(void)
{ cout<<"Enter name:"; cin.getline(name,30);
cout<<"Enter age:"; cin>>age;
}
void showData(void)
{
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};
void main()
{
student s;
ofstream file;
//open file in write mode
file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;
//write into file
s.getData(); //read from user
file.write((char*)&s,sizeof(s)); //write into file
file.close(); //close the file
cout<<"\nFile saved and closed succesfully."<<endl;
//re open file in input mode and read data
//open file1
ifstream file1;
//again open file in read mode
file1.open("aaa.txt",ios::in);
if(!file1){
cout<<"Error in opening file..";
return 0;
}
//read data from file
file1.read((char*)&s,sizeof(s));
//display data on monitor
s.showData();
//close the file
file1.close();
}
C++ program to demonstrate example of tellg() and tellp() function tellg() and tellp() are the predefine functions which tells (returns) the position of the get and put pointers. C++ program to demonstrate example of tellg and tellp – tellg() and tellp() function example in c++ programming language. tellg() and tellp() example in c++
//C++ program to demonstrate example of tellg() and tellp() function.
#include <iostream.h>
#include <fstream.h>
using namespace std;
void main()
{
fstream file;
//open file sample.txt in and Write mode
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
//write A to Z
file<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//print the position
cout<<"Current position is: "<<file.tellp()<<endl;
file.close();
//again open file in read mode
file.open("sample.txt",ios::in);
if(!file)
{
cout<<"Error in opening file!!!";
return 0;
}
cout<<"After opening file position is: "<<file.tellg()<<endl;
//read characters untill end of file is not found
char ch;
while(!file.eof())
{
cout<<"At position : "<<file.tellg(); //current position
file>>ch; //read character from file
cout<<" Character \""<<ch<<"\""<<endl;
}
//close the file
file.close();
}