C & C++
C & C++
CONTENTS
1. Introduction.......................................................................................................3
i. Simple If Statement...............................................................................4
3. Looping.............................................................................................................17
i. While Statement...................................................................................18
4. Arrays................................................................................................................39
6. Functions...........................................................................................................52
7. Pointers.............................................................................................................57
8.
62
9. Unions................................................................................................................67
C++ LANGUAGE
CONTENTS
1. Introduction......................................................................................................74
1
2. Class And Object..............................................................................................76
3. Function............................................................................................................89
4. Function Overloading......................................................................................93
5. Inline Function.................................................................................................95
6. Friend Functions..............................................................................................97
7. Virtual Function..............................................................................................100
8. Inheritance.......................................................................................................105
i. Single Inheritance...............................................................................105
10. Files...................................................................................................................119
INTRODUCTION
C programs are divided into modules or functions. Some functions are written by users like us
and many others are stored in the C Library.
Library functions are grouped category wise and stored in different files known as header files.
Before 1960 à ALGOL language.
1970’s à BCPL (BASIC COMBINED PROGRAMMING LANGUAGE) AND “B” Language.
ALGOL + BCPL + B = “C” Language – 1972 Dennis Ritchie.
Programming written in C is efficient and fast.
There are 32 keywords and its strength lies it’s built in functions.
2
C is highly portable. This means that C programs written for one computer can be run on another
with little or no modification.
Another important feature of C is its ability to extend itself.
FUNCTION: It includes one or more statements that are designed to perform a specific task.
In a C program the smallest individual units are known as C tokens.
TOKEN: In a passage of text, individual words and punctuation marks are called tokens.
C TOKEN
INTERGER REAL
2. Character Constant
Reading data
scanf(“control strings”,var,&var2,….);
int --- %d
char --- %c
string --- %s
float --- %f
int a=40
3
Writing data
printf(“control strings”, var1,var2….);
1. int a,b,c….
2. int a;
3. float b;
4. char d;
1. /*print the message */--------document section
2. link section---------head files #include<stdio.h>
3. document section
main()
{
declaration part;
execution part;
}
C language possesses such decision making capabilities and supports the following statements
known as control or decision making statements.
1. If statement
2. Switch statement
3. Conditional operator statement
4. Go to statement
i. Simple If Statement:
Syntax:
if (test expression)
{
4
Statement-block;
}
Statement-x;
Exercise 1
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,big;
clrscr();
printf(“Enter Two Value:”);
scanf(“%d”,&a,&b);
big = b;
if(a>big)
{
big =a;
}
printf(“The Biggest Value is%d”,big);
}
if (test expression)
{
True Statement-block;
}
else
{
False Statement-block;
}
Exercise 1
/* Find Out Odd or Even */
#include<stdio.h>
#include<conio.h>
5
void main()
{
int n;
clrscr();
printf(“Enter any value:”);
scanf(“%d”,&n);
if(n%2==0)
{
printf(“%d is even number”,n);
}
else
{
printf(“%d is odd number”,n);
}
getch();
}
Exercise 2
/* Find the Pos or Neg Number */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter any number:”);
scanf(“%d”, &n);
if(n>0)
{
printf(“%d is positive number”,n);
}
else
{
printf(“%d is negative number”, n);
}
getch();
}
6
Exercise 3
/* Find the biggest number*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
clrscr();
printf(“Enter the A & B Values:\n”);
scanf(“%d %d”, &a, &b);
if(a>b)
{
printf(“%d is biggest number”,a);
}
else
{
printf(“%d is biggest number”, b);
}
getch();
}
if (condition 1)
{
Statement 1-block;
}
else if(condition 2)
{
Statement 2-block;
}
else
{
Statement-block;
}
/* Invoice Bill Creation */
#include<stdio.h>
7
void main()
{
char item[30];
int icode,qty;
float rate,amt,dis,netamt;
clrscr();
printf(“Enter the product name:\n”);
scanf(“%s”, item);
printf(“Enter the Item Code Number:\n”);
scanf(“%d”, &icode);
printf(“Enter the quantity number:\n”);
scanf(“%d”, &qty);
printf(“Enter product rate:\n”);
scanf(“%f”, &rate);
amt =qty * rate;
printf(“****************************\n”);
printf(“INVOICE BILL DETAILS \n”);
printf(“****************************\n”);
printf(“ITEM NAME :%s\n” ,item);
printf(“ITEM CODE :%d\n”,icode);
printf(“No.of Qty :%d\n”,qty);
printf(“PRODUCT RATE :%f\n”,rate);
printf(“AMOUNT :%f\n”,amt);
if(amt<5000)
{
dis= amt * 10/100;
netamt=amt-dis;
}
else if(amt>=5000 && amt<10000)
{
dis= amt * 15/100;
netamt = amt – dis;
}
else if(amt>=10000 && amt<20000)
{
dis = amt * 20/100;
netamt = amt –dis;
8
}
else
{
dis =amt * 25/100;
netamt=amt – dis;
}
printf(“DISCOUNT AMOUNT :%f\n”,dis);
printf(“NET AMOUNT :%f\n”,netamt);
printf(“******************************\n”);
printf(“THANK YOU COME AGAIN\n”);
printf(“******************************\n”);
getch();
}
9
iv. Nested If:-
if (condition 1)
{
if (condition 2)
{
Statement 1-block;
}
else if(condition 2)
{
Statement 2-block;
}
else
{
Statement 3-block;
}
}
else
{
Statement-block;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b,c;
clrscr();
printf("Enter the values:\n");
scanf("%d %d %d", &a, &b, &c);
if(a>b && a>c)
{
printf("A value %d is biggest ",a);
}
else if(b>c && b>a)
{
printf("B value %d is biggest",b);
10
}
else
{
printf("C value %d is biggest",c);
}
getch();
}
/* Leap Year */
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("Enter any year:\n");
scanf("%d", &year);
if(year%100==0)
{
if(year%400==0)
{
printf("%d is leap year",year);
}
else
{
printf("%d is not leap year",year);
}
}
else if(year%4==0)
{
printf("%d is leap year",year);
}
else
{
printf("%d is not a leap year",year);
}
getch();
11
}
v. Switch Statement:-
Exercise 2
/* SWITCH */
#include<stdio.h>
main()
{
int ch, r,area,h,vol,a,n;
clrscr();
printf("Enter your choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
13
printf("Enter the radius value:\n");
scanf("%d",&r);
area=3.14*r*r;
printf("Area of the circle is......%d",area);
break;
case 2:
printf("Enter the radius value:\n");
scanf("%d",&r);
printf("Enter the height value:\n");
scanf("%d",&h);
vol=3.14 * r * r* h;
printf("Volume of the cube is....%d",vol);
break;
case 3:
printf("Enter the side value:\n");
scanf("%d",&a);
area=a * a;
printf("Area of the square......%d",area);
break;
case 4:
printf("Enter the number:\n");
scanf("%d", &n);
if(n>0)
printf("%d is positive number",n);
else
printf("%d is negative number",n);
break;
default:
printf("Your choice is wrong");
break;
}
getch();
}
Exercise 3
/* Find the Key */
#include<stdio.h>
#include<ctype.h>
14
main()
{
int ch;
char c;
clrscr();
printf("Enter your choice:\n");
scanf("%d", &ch);
printf("Enter any character:\n");
scanf("%c",&c);
c=getchar();
switch(ch)
{
case 1:
if(islower(c))
printf("%c is lower case",c);
else if(isupper(c))
printf("%c is upper case",c);
else if(isdigit(c))
printf("%c is digit",c);
else
printf("Special character");
break;
case 2:
if(islower(c))
putchar(toupper(c));
else if(isupper(c))
putchar(tolower(c));
else
printf("None");
break;
case 3:
if(isalpha(c))
printf("%c is alphabet",c);
else if(isdigit(c))
printf("%c is digit",c);
else
printf("%c is not alphanumeric ",c);
15
break;
default:
printf("Your choice is wrong");
break;
}
getch();
}
Exercise 4
/* Processing In Different Number Operation */
#include<stdio.h>
main()
{
int n,year,ch;
clrscr();
printf("1. POSITIVE / NEGATIVE NUMBER\n");
printf("2. LEAP YEAR\n");
printf("3. ODD/ EVEN NUMBER\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter any number:\n");
scanf("%d",&n);
if(n>0)
printf("%d is positive number",n);
else
printf("%d is negative number",n);
break;
case 2:
printf("Enter any year:\n");
scanf("%d", &year);
if(year%4==0)
printf("%d is leap year",year);
else
printf("%d is not a leap year",year);
break;
16
case 3:
printf("enter any number\n");
scanf("%d",&n);
if(n%2==0)
printf("%d is even number",n);
else
printf("%d is odd number",n);
break;
default:
printf("Your choice is Error Please check your choice ");
break;
}
getch();
}
LOOPING
In some situations there is a need to repeat a set of instructions specified number of times or
until a particular condition is satisfied. This repetitive operations are done through a loop control
structure is called looping.
A program loop consists of two segments, one known as the body of the loop and the other
known as the control statement. The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Generally a looping process would include the following four steps:
1. Setting and initialization of a counter
2. Execution of the statements in the loop
3. Test for a specified condition for execution of the loop
4. Incrementing the counter
The C language provides three loop constructs for performing loop operations. They are
1. While Statement
2. Do-While Statement
3. For Statement
i. While Statement:-
The simplest of all the looping structures in C is the while statement.
The basic format of while statement is
while (test condition)
{
17
body of the loop
}
The while is an entry controlled loop statement. The test condition is evaluated and if the condition is
true, then the body of the loop is executed. After execution of the body, the test condition is once again
evaluated and if it is true, the body is executed once again. This process of repeated execution of the
body continues until the test-condition is false
Exercise 1
/*Addition of numbers 1..........n */
#include<stdio.h>
main()
{
int i=1,sum=0,n;
clrscr();
printf("Enter the no.of terms:");
scanf("%d",&n); 5
while(i<=n)
{
sum=sum+i;0+1
printf("%d\n",sum);
i++;
}
printf("The sum of numbers upto....n %d\t", sum);
getch();
}
Exercise 2
/* Multiplication Table */
#include<stdio.h>
main()
{
int i=1,n, t,c;
clrscr();
printf("Enter the table number:\n");
scanf("%d",&t);
printf("Enter the no.of terms:\n");
scanf("%d",&n);
while(i<=n)
18
{
c = i * t;
printf("%d * %d = %d\n", i,t,c);
i++;
}
getch();
}
Exercise 3
/* Factorial Value */
#include<stdio.h>
main()
{
int i=1,n,fact=1;
clrscr();
printf("Enter the no.of terms:\n");
scanf("%d",&n);
while(i<=n)
{
fact=fact * i;
printf("%d\n\n", fact);
i++;
}
printf("Total factorial value is....%d\n", fact);
getch();
}
Exercise 4
/* 1/2+2/3+3/4.......n/n+1 */
#include<stdio.h>
main()
{
int i=1,n;
float s=0;
clrscr();
printf("Enter the n value:");
19
scanf("%d",&n);
while(i<=n)
{
s=(float)i/(i+1);
printf(" value is...%f\n",s);
i++;
}
printf("The sum of the series value is...%f",s);
getch();
}
Exercise 5
/* Power value */
#include<stdio.h>
#include<math.h>
main()
{
int p=1,s=0,x,n;
clrscr();
printf("Enter the X & No.of terms Values:\n");
scanf("%d %d",&x,&n);
while(p<=n)
{
s=pow(x,p);
printf("%d\n",s);
p++;
}
printf("Power Value is.......%d",s);
getch();
}
Exercise 6
/* Printing Number Style */
#include<stdio.h>
main()
{
int i=1,count,n;
clrscr();
20
printf("Enter the no.of terms:\n");
scanf("%d",&n);
while(i<=n)
{
count=1;
while(count<=i)
{
printf("%d\t",count);
count++;
}
printf("\n");
i++;
}
getch();
}
Exercise 7
/* Printing Stars Formats */
#include<stdio.h>
main()
{
int i=1,count,n;
clrscr();
printf("Enter the no.opf terms:");
scanf("%d",&n);
while(i<=n)
{
count=1;
while(count<=i)
{
printf(" *\t");
count++;
}
printf("\n");
i++;
}
getch();
}
21
Exercise 8
/* Converted Upper Case to Lower Case */
#include<stdio.h>
main()
{
int i=0;
char str[30];
clrscr();
printf("Enter any string:\n");
scanf("%s",str);
while(str[i]!='\0')
{
if(str[i]>='A' && str[i]<='Z')
str[i]=str[i]+32;
i++;
}
printf("The converted in lowercase is....%s", str);
getch();
}
Exercise 9
/* Find the sum of given digits */
#include<stdio.h>
main()
{
int n, r,sum=0;
clrscr();
printf("Enter any number:");
scanf("%d",&n);
while(n>0)
{
r=n % 10;
sum=sum+r;
n=n/10;
}
printf("Sum of digit %d",sum);
getch();
}
22
Exercise 10
/* Armstrong Number */
#include<stdio.h>
main()
{
int a,b,c=0,d=0,z;
clrscr();
printf("enter any number:\n");
scanf("%d",&a);
z=a;
while(a>0)
{
b=a%10;
c=b*b*b;
a=a/10;
d=c+d;
}
if(z==d)
{
printf("Armstrong Number");
}
else
{
printf("Not Amstrong Number");
}
getch();
}
Exercise 11
/* Reversing an Integer */
#include<stdio.h>
main()
{
int a, b, c=0;
clrscr();
printf("Enter a numberal:\n");
scanf("%d",&a);
while(a>0)
23
{
b =a % 10;
a=a/10;
c=b + c * 10;
}
printf("Reversed Numeral is %d", c);
getch();
}
ii. Do-While Statement:-
In some occasions, there is a necessity to execute the body of the loop before the test is
performed. Such situations can be handled with the help of do statement.
This takes the format:
do
{
body of the loop;
} while (test condition);
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At
the end of the loop, the test condition in the while statement is evaluated. If the condition is true, the
program continues to evaluate the body of the loop once again. This process continues as long as the
condition is true. When the condition becomes false, the loop will be terminated and the control goes
to the statement that appears immediately after the while statement. Note the semicolon at the end of
while statement.
Since the test condition is evaluated at the bottom of the loop that do….while construct
provides on exit controlled loop and therefore the body of the loop is always executed at least once
Exercise 1
/* Print the Reverse Order by Using Do...While */
#include<stdio.h>
main()
{
int i=100,n;
clrscr();
printf("Enter the value of N:");
scanf("%d",&n);
do
{
printf("%d\n",i);
24
i=i-n;
}while(i>=n);
getch();
}
Exercise 2
/* Find the Power Value by Using Do...While */
#include<stdio.h>
#include<math.h>
main()
{
int n,x,i=1,sum=1;
clrscr();
printf("Enter the value of X:");
scanf("%d",&x);
printf("enter the value of N:");
scanf("%d",&n);
do
{
sum=sum+pow(x,i);
printf("%d\n",sum);
i++;
}while(i<=n);
printf("The sum of power series is...%d",sum);
getch();
}
Exercise 3
/* Find the Sum of the 1+3+5+7…Series */
#include<stdio.h>
main()
{
int sum=0,n,i=1;
clrscr();
printf("Enter the value of N:");
scanf("%d",&n);
do
{
25
sum=sum+i;
printf("%d\n", sum);
i=i+2;
}while(i<=n);
printf("The sum Of the series in 1+3+5+7...%d",sum);
getch();
}
Exercise 4
/* Find the Divisor Numbers */
#include<stdio.h>
main()
{
int a,r,n;
clrscr();
printf("Enter the N Value:");
scanf("%d",&n);
a=2;
do
{
r=n%a;
if(r==0)
printf("%d\t",a);
a++;
}while(a<=n/2);
getch();
}
Exercise 5
/*Factorial */
#include<stdio.h>
main()
{
int i=1,fact=i,n;
clrscr();
printf("Enter the N Value:");
scanf("%d",&n);
do
26
{
fact=fact*i;
i++;
}while(i<=n);
printf("The factorial value is.........%d",fact);
getch();
}
27
…………..
…………..
}
do
{
………….
….………
if (condition)
break;
……………
……………
while (condition);
}
Continue statement:
In some situations we want to take the control to the beginning of the loop, by passing the
statements inside the loop which have not yet been executed, for this purpose the continue is used.
When the statements continue is encountered inside any ‘c’ loop control automatically passes to the
beginning of the loop
Exercise 1
/* Sum of the Value In Given Number */
#include<stdio.h>
main()
{
int i,sum=0,n;
28
clrscr();
printf("Enter the no.of vaues:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
printf("%d\n",sum);
}
printf("The sum of last values are:%d\n",sum);
getch();
}
Exercise 2
/* Find the Total & Average Values */
#include<stdio.h>
main()
{
char name[30];
int reg,i, m,n,sum=0,avg;
clrscr();
printf("Enter the student name:\n");
scanf("%s",name);
printf("Enter the register number:\n");
scanf("%d",®);
printf("Enter the no.of subjects:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the marks:");
scanf("%d",&m);
sum=sum+m;
avg=sum/n;
}
printf("Student Name : %s\n",name);
printf("Register Number : %d\n",reg);
printf("The sum of values are : %d\n",sum);
printf("Average value is : %d",avg);
29
getch();
}
Exercise 3
/* Multiplication Table Using For.......*/
#include<stdio.h>
main()
{
int i, c, t, n;
clrscr();
printf("Enter the table number:");
scanf("%d",&t);
printf("Enter the no.of terms:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
c=i*t;
printf("%d * %d = %d\n", i,t,c);
}
getch();
}
Exercise 4
/* Fibonacci Series */
#include<stdio.h>
main()
{
int a,b,c,n,i;
clrscr();
printf("Enter the no.of terms:");
scanf("%d",&n);
a=0;
b=1;
c=a+b;
printf("%d\n",c);
for(i=1;i<=n;i++)
{
a=b;
30
b=c;
c=a+b;
printf("%d\n",c);
}
getch();
}
Exercise 5
/* Sum of the Given Positive Number */
#include<stdio.h>
main()
{
int i,n,sum=0,x;
clrscr();
printf("Enter the N value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter any number:");
scanf("%d",&x);
if(x<0)
continue;
else
sum=sum+x;
}
printf("Sum is....%d",sum);
getch();
}
Exercise 6
/*Plus Stars Print Style */
#include<stdio.h>
main()
{
int i,j,n;
clrscr();
printf("Enter the range:");
scanf("%d", &n);
31
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==(n+1)/2 || j==(n+1)/2)
{
printf(" * ");
}
else
{
printf(" ");
}
}
printf("\n");
}
getch();
}
Exercise 7
/* Star box */
#include<stdio.h>
main()
{
int i,j,n,t;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
t=n;
for(i=1;i<=n;i++)
{
if(i==1 || i==n)
{
for(j=1;j<=n;j++)
{
printf(" *");
}
}
32
else
{
for(j=1;j<=n;j++)
{
if(j==1 || j==n)
{
printf(" *");
}
else if(i==j || j==t)
{
printf(" *");
}
else
{
printf(" ");
}
}
}
t--;
printf("\n");
}
getch();
}
Exercise 8
/* Reverse String */
#include<stdio.h>
main()
{
int i, count=0;
char a[30];
clrscr();
printf("Enter the text:");
scanf("%s",a);
for(i=0;a[i]!='\0';i++)
{
count++;
33
printf("\n \t %c",a[i]);
}
printf("\n %d",count);
for(a[i]!='\0';i>=0;i--)
{
printf("\n %c",a[i]);
}
getch();
}
Exercise 9
/*Find the No. Of Even & Odd */
#include<stdio.h>
main()
{
int n, a[20],i,ecount=0, ocount=0;
clrscr();
printf("enter the term:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the number:");
scanf("%d",&a[i]);
if(a[i]%2==0)
{
ecount++;
}
Else
{
ocount++;
}
}
printf("No.of terms in odd number : %d\n", ocount);
printf("No.of terms in even number :%d", ecount);
getch();
}
Exercise 10
34
/*Display the prime number series in given no*/
#include<stdio.h>
main()
{
int n,i,j,t;
clrscr();
printf("Enter the number:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
t=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
t++;
}
if(t==2)
printf("%d\n",i);
}
getch();
}
Exercise 11
/* Different angle of star prints */
#include<stdio.h>
main()
{
int i,j,k,x;
clrscr();
printf("Enter the X Value:");
scanf("%d",&x);
for(i=1;i<=10;i++)
{
for(j=1;j<=x;j++)
printf(" ");
for(k=1;k<=i;k++)
printf(" * ");
35
x--;
printf("\n");
}
getch();
}
Exercise 12
/* Print the number style */
#include<stdio.h>
main()
{
int i,j,n;
clrscr();
printf("Enter the no.of terms:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t", j);
}
printf("\n");
}
getch();
}
Exercise 13
/* Reverse string */
#include<stdio.h>
#include<string.h>
main()
{
char word[40],reverse[40];
int i,j,k;
clrscr();
printf("Enter any string:");
gets(word);
for(i=0;word[i]!='\0';i++)
36
{
for(j=i,k=0;j>=0;j--,k++)
{
reverse[k]=word[j];
}
reverse[k]='\0';
printf("The reverse string is %s", reverse);
}
getch();
}
Exercise 14
/* Print the Alphabets */
#include<stdio.h>
main()
{
char n;
clrscr();
printf("\n\n");
for(n=65;n<=122;n++)
{
if(n>90 && n<97)
continue;
printf("|| %4d -%c",n,n);
}
printf("\n");
getch();
}
Exercise 15
/* Text Model Printing */
#include<stdio.h>
main()
{
int c,d;
char string[]="CPROGRAMMING";
clrscr();
printf("\n");
37
for(c=0;c<=11;c++)
{
d=c+1;
printf("| %-12.*s |\n",d,string);
}
printf("--------------------\n");
for(c=11;c>=0;c--)
{
d=c+1;
printf("| %-12.*s |\n",d,string);
}
printf("----------------------\n");
getch();
}
ARRAYS
Array is a collection of similar data items that are stored under a common name. A value in
an array is identified by index or subscript enclosed in brackets with array name. The number of
subscripts determines the dimension of the array.
One Dimensional Arrays: A list of items can be given one variable name using only one subscript
and such a variable is called a single-subscripted variable or a one-dimensional array
Array Declaration: Like variables, the array must be declared before they are used.
Syntax:
data_type array_variable [size or subscript of the array];
Array Initialization: The values can be initialized to an array when they are declared like ordinary
variables.
Syntax:
data_type array_name [sizes]={list of variables};
Exercise 1
/* Count the Number of Spaces in A Given Text */
#include<stdio.h>
main()
{
char a[30];
int i,c=0;
clrscr();
printf("Enter any text:\n");
38
for(i=0;(a[i]=getche())!=13;i++)
a[i]='\0';
for(i=0;a[i]!='\0';i++)
if(a[i]==32)
c++;
printf("%d is the no.of spaces in the text",c);
getch();
}
Exercise 2
/* ASCENDING ORDER */
#include<stdio.h>
main()
{
int a[10],temp=0,i,j,n;
clrscr();
printf("Enter the limit:\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
for(j=i;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
printf("The sorted order is\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
39
}
getch();
}
Exercise 3
/* Print the Alphabets */
#include<stdio.h>
main()
{
int i, asc=65;
char alpha[30];
clrscr();
for(i=0;i<26;i++)
{
alpha[i]=asc;
asc=asc+1;
}
alpha[i]='\0';
printf("The alphabets are\n");
printf("%s\t",alpha);
getch();
}
Exercise 4
/* Biggest Number */
#include<stdio.h>
main()
{
int i,n,big=0,a[10];
clrscr();
printf("Enter the terms");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
printf("Enter the value");
scanf("%d", &a[i]);
}
for(i=0;i<=n;i++)
40
{
if(big<a[i])
big=a[i];
}
printf("Biggest number is %d", big);
getch();
}
Exercise 5
/* Find Out the No. Of Vowels */
#include<stdio.h>
main()
{
int a=0,e=0,i=0,u=0,o=0,other=0;
int count=0;
char str[30];
clrscr();
printf("Enter any string\n");
scanf("%s",str);
do
{
switch(str[count])
{
case 'a':
case 'A':
a++;
break;
case 'e':
case 'E':
e++;
break;
case 'i':
case 'I':
i++;
break;
case 'o':
case 'O':
41
o++;
break;
case 'u':
case 'U':
u++;
break;
default:
other++;
break;
}
count++;
}while(str[count]!='\0');
printf("Number of A Vowels %d\n",a);
printf("E Vowels %d\n",e);
printf("I Vowels %d\n",i);
printf("O Vowels %d\n",o);
printf("U Vowels %d\n",u);
printf("Others %d\n",other);
getch();
}
Exercise 6
/* Counting the Number of Occurrence of A Character in A String */
#include<stdio.h>
#define MAX_NUMBER 50
main()
{
char string[MAX_NUMBER],a;
int x=0,y=0;
clrscr();
printf("Enter the string:\n");
gets(string);
printf("\n Enter the character to be searched:");
scanf("%c",&a);
while(string[x]!='\0')
{
if(a==string[x])
42
y++;
x++;
}
printf("\n The character appears %d Times",y);
getch();
}
Exercise 7
/*Sort the Names in Alphabetical Order */
#include<stdio.h>
main()
{
char name[20][20],temp[20];
int i,j,n;
clrscr();
printf("Enter the limit:");
scanf("%d",&n);
printf("Enter the names one by one\n");
for(i=0;i<n;i++)
{
scanf("%s", name[i]);
}
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
printf("the sorted order is \n");
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
43
getch();
}
Exercise 8
/* Replace the Character */
#include<stdio.h>
main()
{
int i=0;
char text[50],search,rep;
clrscr();
puts("Enter any text\n");
gets(text);
printf("Enter the searching letter\n");
scanf("%c", &search);
flushall();
printf("Enter the Replaceing letter:\n");
scanf("%c",&rep);
while(text[i]!='\0')
{
if(text[i]==search)
text[i]=rep;
i++;
}
printf("The replaced character of the given text is....");
puts(text);
getch();
}
Exercise 9
/* New Palindrome */
#include<stdio.h>
#include<string.h>
main()
{
char str1[30],str2[30];
clrscr();
44
printf("Enter any string:");
scanf("%s", str1);
strcpy(str2,str1);
if(strcmp(str2,strrev(str1))==0)
printf("Palindrome");
else
printf("Not a Palindrome");
getch();
}
Two Dimensional Arrays: We have looked at arrays with only one dimension. It is also possible for
arrays to have two or more dimension. The two dimensional array is called a matrix.
Two dimensional arrays are used in situation where a table of values needs to be stored in an array.
These can be defined in same fashion as in one-dimensional arrays, except a separate pair of square
brackets is required each subscript.
Syntax:
Data type_array_name [row size][column size];
Exercise 1
/* Write A Program to Addition of Two Matrices */
#include<stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j;
clrscr();
printf("Enter the first matrix value\n:");
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
scanf("%d",&a[i][j]);
printf("Enter the second matrix value\n:");
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
scanf("%d", &b[i][j]);
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
c[i][j]=a[i][j]+b[i][j];
clrscr();
printf("\n The first matrix is...\n");
45
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d",a[i][j]);
printf("\t");
}
printf("\n");
}
printf("\n The second matrix is....\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d", b[i][j]);
printf("\t");
}
printf("\n");
}
printf("\n The addition of two matrices are....\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf("%d", c[i][j]);
printf("\t");
}
printf("\n");
}
getch();
}
Exercise 2
/* Find the Diagonal of the Given Matrix and To Find the Sum of the Diagonal Elements */
#include<stdio.h>
int a[5][5],i,j,p,q,m,n,sum=0;
main()
46
{
clrscr();
input();
value();
real();
sum=0;
maindiagonal();
printf("\n\n Sum of the main diagonal = %d\n\n",sum);
sum=0;
subdiagonal();
printf("\n\n Sum of the sub diagonal = %d\n\n",sum);
getch();
}
input()
{
printf("\n\n Enter the order of the matrix \n");
scanf("%d %d", &m,&n);
printf("\n %d x %d",m,n);
getch();
}
value()
{
int i,j,k;
printf("\n\n Enter the values of the matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
}
real()
{
int i,j;
printf("\n\nThe real matrix is as below\n");
for(i=0;i<m;i++)
47
{
for(j=0;j<n;j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
getch();
}
maindiagonal()
{
int i,j;
printf("\n\nThe Diagnoal of the matrix is as below\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
printf("%d\t",a[i][j]);
sum=sum+a[i][j];
}
}
}
}
subdiagonal()
{
for(i=0,j=m-1;i<n;i++,j--)
{
printf("%d\t",a[i][j]);
sum=sum+a[i][j];
}
getch();
}
48
STRING HANDLING FUNCTIONS
A string is an array of characters. Any group of characters (except double quote sign) defined
between double quotations marks is a constant string.
C library supports a large number of string handling functions that can be used to carryout
many of the string manipulations
The following the most commonly used string-handling functions
Exercise 1
/* STRING COPY PROGRAM */
#include<stdio.h>
main()
{
char str1[20],str2[20];
clrscr();
printf("Enter the first string:\n");
scanf("%s", str1);
printf("Enter the second string:\n");
scanf("%s", str2);
strcpy(str1,str2);
printf("The first string is.......%s", str1);
getch();
}
Exercise 2
/* Find the Length of the String Programs */
#include<stdio.h>
main()
{
char str[30];
int n;
clrscr();
printf("Enter any string:\n");
49
scanf("%s", str);
n=strlen(str);
printf("Entering string length is....%d",n);
getch();
}
Exercise 2
/*String Compare To Another */
#include<stdio.h>
main()
{
char str1[30],str2[30];
int x;
clrscr();
printf("Enter the first string:\n");
scanf("%s", str1);
printf("Enter the second string:\n");
scanf("%s", str2);
x=strcmp(str1,str2);
if(x==0)
{
printf("Entering strings are equal");
}
else
{
printf("Entering strings are not equal");
}
getch();
}
Exercise 3
/*Merge the 2 Strings*/
#include<stdio.h>
main()
{
char str1[20],str2[20];
clrscr();
printf("Enter the first string:\n");
50
scanf("%s", str1);
printf("enter the second string:\n");
scanf("%s",str2);
strcat(str1,str2);
printf("The merged string is.................%s", str1);
getch();
}
FUNCTIONS
Function: A function is a set of instructions that perform a specified task which repeatedly occurs in
the main program
Functions are classified into 2 types as shown below:
FUNCTION
Pre-Defined Function: The ‘C’ language has a number of pre-defined or library functions that carry
out various commonly used operations or calculations
Example:
printf(), scanf(), sin(), sqrt()….etc
User-Defined Function: These are written by the programmer to perform a particular task, that is
repeatedly used in main program or to broken down a large program into a number to smaller
functions
Advantage of User-Defined Functions:
The length of the source program can be reduced by dividing it into the functions.
Easy to locate and debug an error.
The user-defined function can be used in many other source programs, whenever necessary.
Functions avoid need for repeated programming of the similar instructions.
Functions enable a programmer to build a customized library of repeatedly used routines.
Functions facilitate top-down programming approach.
Syntax:
Data type function_name (parameters list)
parameters declaration;
{
local variables declaration;
51
……………..
……….…….
body of the function
……………
……………
return (expression);
}
Category of Functions: The functions are classified into the following types depending on whether
the arguments are present or not and whether a value is returning or not. Theses are also called
function prototypes. The arguments are also called as parameters.
1. Functions With No Arguments And No Return Values
2. Functions With Arguments And No Return Values
3. Functions With Arguments And Return Values
4. Functions With No Arguments And Return Values
Exercise 1
/* Factorial Using Functions*/
#include<stdio.h>
int factorial(int);
main()
{
int n,res;
clrscr();
printf("Enter any value:\n");
scanf("%d", &n);
res=factorial(n);
printf("Factorial value is............%d\n", res);
res=factorial(10);
printf("Factorial value is............%d\n", res);
getch();
}
int factorial(int x)5
{
int fact=1,i;
for(i=1;i<=x;i++)
fact=fact*i;
52
return(fact);120
}
Exercise 2
/* With No Arguments No Return Values */
#include<stdio.h>
main()
{
void add(void); /* tells that this function add()does not return value*/
add();
}
void add()
{
int a,b,c;
clrscr();
printf("Enter two numbers:\n");
scanf("%d %d", &a,&b);
c=a+b;
printf("the addition of two numbers area............%d", c);
getch();
}
Exercise 3
/* With Arguments and No Return Value */
#include<stdio.h>
main()
{
void add(int,int);
int a,b;
clrscr();
printf("Enter the A Value:\n");
scanf("%d", &a);
printf("Enter the B Value:\n");
scanf("%d", &b);
add(a,b);
}
void add( int x, int y)
{
53
int z;
clrscr();
z=x * y;
printf("The multiplication of two numbers are..........%d",z);
getch();
}
Exercise 4
/*With Arguments and Return Value*/
#include<stdio.h>
main()
{
int add();
int a,b,c;
clrscr();
printf("enter the A Values:\n");
scanf("%d", &a);
printf("Enter the B Value:\n");
scanf("%d", &b);
c=add(a,b);
printf("Result of sum is..........%d",c);
getch();
}
int add( int x, int y)
{
int z;
z=x+y;
return(z);
}
Exercise 5
/* Call By Value Program */
#include<stdio.h>
void swap(int, int);
main()
{
int i,j;
clrscr();
54
printf("Enter the i & j Values:\n");
scanf("%d %d", &i, &j);
printf("Before swapping \n i= %d \t j= %d\n",i,j);
swap(i,j);
printf("After swapping \n i= %d \t j= %d",i,j);
getch();
}
void swap(int i, int j)
{
int t;
t=i;
i=j;
j=t;
}
Exercise 6
/* Call By Value */
#include<stdio.h>
void swap(int*, int*);
main()
{
int i, j;
clrscr();
printf("Enter the i & j Values:\n");
scanf("%d %d", &i,&j);
printf("Before swapping in i= %d \t j= %d\n",i,j);
swap(&i,&j);
printf("After swapping in i = %d \t j= %d",i,j);
getch();
}
void swap(int *a, int *b)
{
int t;
t=*a;
a=*b;
*b=t;
}
55
POINTERS
Pointer is a variable which contains the address of another variable. It is an important and
powerful feature in C language and it is handy to use once it is measured.
Why need pointers?
1. Pointers enable us to access a variable that is defined outside the function
2. Pointers are very useful in handling data tables
3. Pointers reduce the length and complexity of the program
4. Pointers increase execution speed
5. Pointers save the memory space
6. Pointers are closely associated with arrays
Accessing the Address of a Variable: We are not able to know the address of a variable since the
actual location of a variable in the memory is system dependent. But we can determine the address of
a variable using the “&” (address of) operator as seen in scanf function.
Declaring and Initializing Pointer: In C, every variable must be declared before use. Since pointer
variables contain addresses that belong to a separate data type, they must be declared as pointers
before we use them
Syntax:
Data_type *pname
This tells the compiler three things about the variable pname
1. The * (asterisk) tells that the variable pname is a pointer variable
2. pname needs a memory location
3. pname points to a variable of data type
Accessing Variable Through Pointers: Once pointer has been assigned the address of a variable, the
question remains as to how to access the value of the variable using the pointer. This is done by *
(asterisk) operator, usually known as “indirection operator” or “value of address operator”
Exercise 1
/* Access the address of variables */
#include<stdio.h>
main()
{
int a,b=25;
char k,o='p';
float m,z=58.365;
a=100;
k='g';
m=12.65;
56
clrscr();
printf("%d is stored at address of %u\n",a,&a);
printf("%d is stored at address of %u\n",b, &b);
printf("%c is stored at address of %u\n",k,&k);
printf("%c is stored at address of %u\n",o,&o);
printf("%f is stored at address of %u\n",m,&m);
printf("%f is stored at address of %u\n",z,&z);
getch();
}
Exercise 2
/*Access a variable through pointers */
#include<stdio.h>
main()
{
int i=5;
int *j;
j=&i;
clrscr();
printf("Address of i = %u\n", &i);
printf("Address of i = %u\n", j);
printf("Address of j = %u\n", &j);
printf("\n");
printf("Value of i = %d\n", i);
printf("Value of i = %d\n",*(&i));
printf("Value of i = %d\n", *j);
getch();
}
Exercise 3
/* Return the length of the string using pointers */
#include<stdio.h>
#include<string.h>
main()
{
int n=0;
char *ptr;
clrscr();
57
puts("Enter any string\n");
gets(ptr);
for(;*ptr!='\0';ptr++)
n++;
printf("The length of the string is %d\n",n);
getch();
}
Exercise 4
/*POINTER INCREMENTS AND SCALE FACTOR */
#include<stdio.h>
main()
{
int i=4, *x;
char c='m',*y;
float j=1.50,*z;
clrscr();
printf("\n");
printf("Value of i = %d\n",i);
printf("Value of c = %c\n",c);
printf("Value of j = %f\n",j);
printf("\n\n");
x=&i;
y=&c;
z=&j;
printf("Original address of X is = %u\n",x);
printf("Original address of Y is = %u\n",y);
printf("Original address of Z is = %u\n",z);
printf("\n\n");
x++;
y++;
z++;
printf("New address of X is = %u\n",x);
printf("New address of Y is = %u\n",y);
printf("New address of Z is = %u\n",z);
getch();
}
58
Exercise 5
/*Pointers and arrays */
#include<stdio.h>
main()
{
int *p,sum,i;
static int x[5]={5,9,7,3,6};
i=0;
p=x;
sum=0;
clrscr();
printf("Element\tvalue\taddress \n");
while(i<5)
{
printf("x[%d] \t %d\t %u\n",i,*p,p);
sum=sum + *p;
i++;
p++;
}
printf("\n sum=%d\n",sum);
getch();
}
Exercise 6
/*Pointer and Character string*/
#include<stdio.h>
main()
{
char name[]="chennai";
int length;
char *cp=name;
clrscr();
printf("%s\n",name);
while(*cp!='\0')
{
printf("%c is stored at address %u\n",*cp,cp);
cp++;
}
59
length=cp-name;
printf("The length of the string is........%d\n",length);
getch();
}
Exercise 7
/*Pointer Function */
#include<stdio.h>
main()
{
int x=100,y=200;
clrscr();
printf("Before exchange value of x= %d\t y = %d\n",x,y);
exchange(&x,&y);
printf("After exchange value of x= %d\t y= %d\n",x,y);
getch();
}
exchange( int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
return;
}
Exercise 8
/*Pointer return values */
#include<stdio.h>
main()
{
int a,b;
int *p;
int *larger(int *, int *);
clrscr();
printf("Enter A & B values\n");
scanf("%d %d", &a, &b);
p=larger(&a,&b);
60
printf("\n");
printf("The largest value is..............%d", *p);
getch();
}
int *larger(int *x, int *y)
{
if(*x > *y)
return(x);
else
return(y);
}
STRUCTURES
We have seen that arrays can be used to represent a group of data item that belong to the same
type. Such as int or float. However if we want to represent a collection of data items of different types
using a single name, then we cannot use an array. Fortunately, C supports a constructed data type
known as structure, which is a method for packing data of different types.
Structures help to organize complex data in a more meaningful way. It is a powerful concept
that we may often need to use in our program design
Declaring Structure:
Syntax:
struct structure name
{
structure_element 1;
structure_element 2;
…………………..
……..…………....
structure_element n;
};
struct structure_name v1,v2,v3……vn;
where v1, v2, v3………vn are structure variables
Rules for declaring a structure:
A structure must end with a semicolon
A structure appears at the top of the source programs
Each structure element must be terminated and is declared independently for its name and type
in a separate statement
Giving Values to Members:
61
We can assign values to the members of a structure in a number of ways, As mentioned earlier,
the members themselves are not variables, They should be linked to the structure, variables in order to
make them meaningful members. The link between the structure and a variable is established using the
member operator (.) also known as dot operator or period operator
Exercise 1
/* EX: 1 structure elements in memory */
#include<stdio.h>
main()
{
struct book
{
char name[30];
int pages;
float price;
};
static struct book b1={ 'C',200, 95.00};
clrscr();
printf("Address of name = %c\n",b1.name);
printf("Address of pages =%d\n",b1.pages);
printf("Address of price = %f\n", b1.price);
getch();
}
Exercise 2
/*Student Information Using Structure*/
#include<stdio.h>
struct student
{
char name[30];
int reg, m1,m2,m3,tot;
float avg;
};
void main()
{
struct student s[10];
int treg,i=0,ch,j,x;
char tname[30];
do
62
{
clrscr();
printf("1. add new student\n");
printf("2.search by reg no \n");
printf("3. search by name\n");
printf("type ur choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
i++;
printf("Enter student name:\n");
scanf("%s", s[i].name);
printf("Enter register number:\n");
scanf("%d",&s[i].reg);
printf("Enter 3 marks:\n");
scanf("%d %d %d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
break;
}
case 2:
{
printf("enter temp reg");
scanf("%d",&treg);
for(j=1;j<=i;j++)
{
if(treg==s[j].reg)
{
printf("Student name : %s\n", s[j].name);
printf("Register number : %d\n", s[j].reg);
printf("Total marks : %d\n", s[j].tot);
printf("Average marks : %f\n", s[j].avg);
}
}
63
break;
}
case 3:
{
printf("enter search name");
scanf("%s",tname);
for(j=1;j<=i;j++)
{
if((strcmp(tname,s[j].name))==0)
{
printf("Student name : %s\n", s[j].name);
printf("Register number : %d\n", s[j].reg);
printf("Total marks : %d\n", s[j].tot);
printf("Average marks : %f\n", s[j].avg);
}
}
break;
}
}
printf("do u want to continue press 1: ");
scanf("%d",&x);
}
while(x==1);
getch();
}
}Exercise 3
/* Array of structure */
#include<stdio.h>
struct marks
{
int sub1, sub2,sub3, total;
};
main()
{
int i;
static struct marks student[3]={{55,71,67},{60,63,74},{50,43,71}};
64
static struct marks gtotal;
clrscr();
for(i=0;i<=2;i++)
{
student[i].total=student[i].sub1+student[i].sub2+ student[i].sub3;
gtotal.sub1=gtotal.sub1+student[i].sub1;
gtotal.sub2=gtotal.sub2+student[i].sub2;
gtotal.sub3=gtotal.sub3+student[i].sub3;
gtotal.total=gtotal.total+student[i].total;
}
printf("Student\t Total\n\n");
for(i=0;i<=2;i++)
printf("Student[%d]\t%d\n",i+1,student[i].total);
printf("\nSUBJECT\t TOTAL\n\n");
printf(" Subject[1]\t %d\n Subject[2]\t %d\n Subject[3]\t
%d\n",gtotal.sub1,gtotal.sub2,gtotal.sub3);
printf("\n Grand Total \t %d\n", gtotal.total);
getch();
}
Exercise 4
/* Nested structures */
#include<stdio.h>
main()
{
struct address
{
char phone[10];
char city[30];
int pin;
};
struct emp
{
char name[30];
struct address a;
};
static struct emp e={" Saran", "12345", "Pondy",13};
clrscr();
65
printf("Name = %s\nPhone = %s\n",e.name,e.a.phone);
printf("City = %s\nPin = %d", e.a.city, e.a.pin);
getch();
}
Exercise 5
/*Passing structure elements to functions*/
#include<stdio.h>
struct std
{
int no;
float avg;
};
void fun(struct std p);
void main()
{
struct std a;
clrscr();
a.no=30;
a.avg=90.75;
fun(a);
}
void fun(struct std p)
{
printf("Number is %d\n", p.no);
printf("Average is %f\n", p.avg);
getch();
}
Exercise 6
/*Write a program using nested structure to access and print */
#include<stdio.h>
main()
{
struct hostel_detail
{
int hostel_room_number;
char food;
66
int deposit_amount;
};
struct student
{
char name[20];
int number;
char branch[5];
struct hostel_detail hostel;
};
static struct student student1={"RAJU",101,"CT",10,'V',2000};
clrscr();
printf("%s %d %s %d %c%d",
student1.name,student1.number,student1.branch,student1.hostel.hostel_room_number,student1
.hostel.food,student1.hostel.deposit_amount);
getch();
}
UNIONS
Unions are derived data types they are declared like structure. The difference between the
union and the structure is in terms of storage. In structure each member has its own-storage location,
whereas all the members of union use the same location. Although a union may contain many
members of different types when we use union the compiler allocates a piece of storage that is large
enough to hold.
Syntax:
union union_name
{
union_member 1;
union_member 2;
union_member 2;
……….
……….
union_member n;
};
union union_variable;
Exercise 1
/* Union Accessing Different Values */
67
#include<stdio.h>
union name
{
int a;
char b[2];
};
main()
{
union name e;
clrscr();
e.a=298;
printf("e.a Value is--------------%d\n", e.a);
printf("e.b[0] value is-----------%d\n",e.b[0]);
printf("e.b[1] value is-----------%d\n",e.b[1]);
getch();
}
Exercise 2
/* BOOK DETAILS */
#include<stdio.h>
main()
{
union book
{
float price;
int pages;
};
static union book b1;
b1.price=25.120;
b1.pages=50;
clrscr();
printf("PRICE=%f\n",b1.price);
printf("PAGES=%d\n",b1.pages);
getch();
}
File Management in C
68
Until now, we have been using the functions such as scanf and printf to read and write data.
These are console oriented I/O functions which always use the terminal (keyboard and screen) the
target place. This works fine as long as the data is small. However, many real-life problem involve
volumes of data and in such situations, the console oriented I/O operations pose two major problems
C supports a number of functions that have the ability to perform basic file operations which
include:
1. Naming file
2. Opening file
3. Reading data from a file
4. Writing data to a file and
5. Closing a file
Exercise 1
/* Read & Write the Data's */
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("DATA INPUT\n");
f1=fopen("input","w");
while((c=getchar())!=’$’)
putc(c,f1);
fclose(f1);
printf("\n DATA OUTPUT\n");
f1=fopen("input","r");
while((c=getc(f1))!=EOF)
printf("%c",c);
getch();
fclose(f1);
}
Exercise 2
69
/* MARK LIST DETAILS */
#include<stdio.h>
main()
{
FILE *fp;
int m1,m2,m3,total;
float avg;
char name[20];
clrscr();
fp=fopen("mark.txt","r");
printf("Enter student name");
scanf("%s",name);
printf("Enter 3 subjects");
scanf("%d %d %d",&m1,&m2,&m3);
total=m1+m2+m3;
avg=total/3;
fprintf(fp,"%s %d %d %d %d %f", name,&m1,&m2,&m3,&total,&avg);
fclose(fp);
fp=fopen("mark.txt","w");
fscanf(fp,"%s %d %d %d %d %f", name,m1,m2,m3,total,avg);
printf("\n name=%s \n m1=%d\nm2=%d\nm3=%d\ntotal=%d\navg=%f\n",name,m1,m2,
m3,total,avg);
fclose(fp);
getch();
}
Exercise 3
/*Handling Of Files with Mixed Data Types */
#include<stdio.h>
main()
{
FILE *fp;
int number, quantity,i;
float price, value;
char item[10],filename[10];
clrscr();
printf("INPUT FILE NAME:");
70
scanf("%s",filename);
fp=fopen(filename,"w");
printf("Input inventory data\n\n");
printf("Item name Number Price Quantity\n");
for(i=1;i<=3;i++)
{
fscanf(stdin,"%s %d %f %d",item, &number,&price, &quantity);
fprintf(fp, "%s %d %f %d",item,number,price, quantity);
}
fclose(fp);
fprintf(stdout,"\n");
fp=fopen(filename,"r");
printf("Item name Number Price Quantity Value\n");
for(i=1;i<=3;i++)
{
fscanf(fp,"%s %d %f %d",item, &number,&price,&quantity);
value=price * quantity;
fprintf(stdout,"%s %d %f %d %f\n",item,number,price,quantity,value);
}
fclose(fp);
getch();
}
/*Data is read using the function fscanf from the file stdin*/
/*The data from the file, along with the item values are written to the file stdout */
Exercise 4
/* Handling Of Integer Data Files */
#include<stdio.h>
main()
{
FILE *f1,*f2,*f3;
int number,i;
clrscr();
printf("Contents of DATA file \n");
f1=fopen("DATA","w"); /* create DATA file*/
for(i=1;i<=10;i++)
{
71
scanf("%d",&number);
if(number==-1) break;
putw(number,f1);
}
fclose(f1);
f1=fopen("DATA","r");
f2=fopen("ODD","w");
f3=fopen("EVEN","w");
while((number =getw(f1))!=EOF) /* Read from DATA file */
{
if(number %2 ==0)
putw(number ,f3); /* Write to EVEN file */
else
putw(number,f2); /* Write to ODD file */
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen("ODD","r");
f3= fopen("EVEN","r");
printf("\n Contents of ODD file\n");
while((number=getw(f2))!=EOF)
printf("\t%d",number);
printf("\n Contents of EVEN file \n");
while((number=getw(f3))!=EOF)
printf("\t%d",number);
fclose(f2);
fclose(f3);
getch();
}
72
C++ LANGUAGE
INTRODUCTION
OBJECT-ORIENTED LANGUAGE
Object – Oriented Programming is not the right of any particular language. Like structured
programming. OOP concept Can be implemented using languages such as C and Pascal. However,
programming becomes clumsy and may generate confusion when the programs grow large. A
language that is specially designed to support the oop concepts makes it easier to implement them.
The languages should support several of the oop concepts to claim that they are Object
Oriented. Depending upon the features they support, they can be classified into the following two
categories.
1. Object based programming languages
2. Object oriented programming languages
Program features:
1. // ---Comment line
a. E.g: sum of two numbers
2. Output operator
73
a. cout<< “prompt message”;
3. Input operator
a. cin>>a;
The operator >> is known as extraction or get from operator. It extracts (or takes) the value from the
keyboard and assigns it to the variable on the right. The corresponds to the familiar scanf() operation.`
Output operator:
The only output statement. E.g. cout<<”Welcome to all”;
Causes the string in quotation marks to be displayed on the screen. This statement introduces two new
C++ features, cout and <<. The identifier cout is a predefined object that represents the standard
output stream in C ++
The operator << is called the insertion or put to operator. It inserts (or sends) the contents of
the variable on its right.
Structure of C++ Program
Include Files
Class Declaration
74
CLASS AND OBJECT
Class:
A class is a way to bind the data and its associated functions together. It allows the data and
functions to be hidden.
A class specification has two types:
Class declarations---describes the type and scope of its members.
Class function definitions---describes how the class functions are implemented.
Syntax:
Class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
The class declaration is similar to a struct declaration. The keyword class specifies, that what
follows in an abstruct data type of class name.
The class body contains the declaration of variables and functions. These functions and
variables are collectively called class members. They are usually grouped under sections, namely
private, public and protect.
The class members that have been declared as private can be accessed only from within the
class. On the other hand public can be accessed from outside the class also.
Object:
The fundamental idea behind an oops is to combine both data and the functions that operate on
the data into a single unit, such unit is called a object.
//Example Of Class and Object
#include<iostream.h>
#include<conio.h>
class student
{
private:
75
char sname[20];
int reg, m1,m2,m3;
int tot;
float avg;
public:
void getdata();
void caldata();
void dispdata();
};
void student:: getdata()
{
cout<<"Enter the student name:"<<endl;
cin>>sname;
cout<<"Enter the register number:"<<endl;
cin>>reg;
cout<<"Enter the first mark:"<<endl;
cin>>m1;
cout<<"Enter the second mark:"<<endl;
cin>>m2;
cout<<"Enter the third mark:"<<endl;
cin>>m3;
}
void student::caldata()
{
tot=m1+m2+m3;
avg=tot/3;
}
void student::dispdata()
{
cout<<"Student name...."<<sname<<endl;
cout<<"Register Number...."<<reg<<endl;
cout<<"First mark....."<<m1<<endl;
cout<<"Second mark......"<<m2<<endl;
cout<<"Third mark............"<<m3<<endl;
cout<<"Total mark........."<<tot<<endl;
cout<<"Average mark..............."<<avg<<endl;
}
76
void main()
{
student s;
clrscr();
s.getdata();
s.caldata();
s.dispdata();
getch();
}
77
cout<<"Sum of two numbers are.."<<c<<endl;
}
void main()
{
sum s;
clrscr();
s.getdata();
s.caldata();
s.printdata();
getch();
}
78
da=salary*5/100;
hra=salary*8/100;
pf=salary*12/100;
lic=salary*2/100;
loan=salary*1/100;
gp=salary+da+hra;
ded=pf+lic+loan;
netpay=gp-ded;
}
void emp::printdata()
{
cout<<"**************************************************"<<endl;
cout<<"EMPLOYEE PAYSLIP FOR THE MONTH OF APR-09"<<endl;
cout<<"**************************************************"<<endl;
cout<<"EMPLOYEE NAME :"<<ename<<endl;
cout<<"EMPLOYEE ID NUMBER :"<<eid<<endl;
cout<<"BASIC SALARY :"<<salary<<endl;
cout<<"DA :"<<da<<endl;
cout<<"HRA :"<<hra<<endl;
cout<<"PF :"<<pf<<endl;
cout<<"LIC :"<<lic<<endl;
cout<<"LOAN :"<<loan<<endl;
cout<<"GROSS PAY :"<<gp<<endl;
cout<<"DEDUCTION :"<<ded<<endl;
cout<<"NET PAY :"<<netpay<<endl;
cout<<"**************************************************"<<endl;
}
void main()
{
emp e;
clrscr();
e.getdata();
e.caldata();
e.printdata();
getch();
}
79
// Employee Details
//Employee Information
#include<iostream.h>
#include<conio.h>
class emp
{
private:
char ename[40];
int eid;
void getinfo();
public:
int salary;
void getdata();
void putdata();
};
void emp::getinfo()
{
cout<<"Enter employee name:\n";
cin>>ename;
cout<<"Emter employee id number:\n";
cin>>eid;
}
void emp::getdata()
{
cout<<"Enter employee salary:\n";
cin>>salary;
getinfo();
}
void emp::putdata()
{
cout<<"Name :"<<ename<<endl;
cout<<"Eid :"<<eid<<endl;
cout<<"Salary :"<<salary<<endl;
}
void main()
{
emp p;
80
clrscr();
p.getdata();
p.putdata();
getch();
}
//Palindrome
#include<iostream.h>
#include<conio.h>
#include<string.h>
class palin
{
private:
char str1[30],str2[30];
public:
void getdata();
void checkdata();
};
void palin::getdata()
{
cout<<"Emter any string:"<<endl;
cin>>str1;
}
void palin::checkdata()
{
strcpy(str2,str1);
if(strcmp(str2,strrev(str1))==0)
cout<<"This string is palindrome"<<endl;
else
cout<<"This string is not a palindrome:"<<endl;
}
void main()
{
palin p;
clrscr();
p.getdata();
p.checkdata();
81
getch();
}
82
void replace::disp()
{
cout<<"Replaced text is...."<<text;
}
void main()
{
replace r;
clrscr();
r.getdata();
r.checkdata();
r.disp();
getch();
}
83
int i=0;
clrscr();
cout<<"Enter any text:";
cin>>text;
cout<<"Enter the searching letter:";
cin>>search;
cout<<"Enter the replace letter:";
cin>>rep;
while(text[i]!='\0')
{
if(text[i]==search)
text[i]=rep;
i++;
}
cout<<"The replaceing word is "<<endl;
cout<<"\t"<<text;
getch();
}
// Using Structure
#include<iostream.h>
#include<conio.h>
struct studrec
{
char sname[20];
int regno,age;
void getdata();
void printdata();
};
void studrec::getdata()
{
cout<<"Enter the Student Name:"<<endl;
cin>>sname;
cout<<"Enter the Register Number:"<<endl;
cin>>regno;
cout<<"Enter the Student Age:"<<endl;
cin>>age;
84
}
void studrec::printdata()
{
cout<<"Student name :"<<sname<<endl;
cout<<"Register number :"<<regno<<endl;
cout<<"Student Age :"<<age<<endl;
}
void main()
{
studrec s;
clrscr();
s.getdata();
s.printdata();
s.age=15;
s.regno=789;
s.printdata();
getch();
}
#include<iostream.h>
#include<conio.h>
struct mat
{
public:
int a[3][3], i,j;
void getdata();
void printdata();
};
void mat::getdata()
{
cout<<"Enter the value:\n";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>a[i][j];
}
85
}
}
void mat::printdata()
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<"\t"<<a[i][j];
}
cout<<"\n";
}
}
void main()
{
mat m;
clrscr();
m.getdata();
m.printdata();
getch();
}
86
cin>>n;
cout<<"Enter the values\n";
for(i=0;i<n;i++)
cin>>a[i];
}
void ascen::shownum()
{
cout<<"From the given numbers:\n";
cout<<"Second smallest number:"<<a[1]<<endl;
cout<<"Second biggest number:"<<a[n-2]<<endl;
}
void ascen::proce()
{
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
k=a[i];
a[i]=a[j];
a[j]=k;
}
}
void main()
{
ascen as;
clrscr();
as.getnum();
as.proce();
as.shownum();
getch();
}
FUNCTION
Function is defined as a named group of statement. A function can be called from any point in
a program. If a problem can be divided into small modules. Then each module can be represented as a
function.
There are two types of functions in C++, they are
87
1. Library function
2. User defined function
All c++ programs consist of one or more functions. Out of this one function should be main. This
function shows from where the program execution begins.
Function definition:
A function should be defined before it is used. A function has two parts:
(i) Function Header
(ii) Statement body
Syntax:
Header-Function-type function-name (list of arguments with declaration)
{
Local variable declaration;
Executable statement;
Statement body…………
…………
Return (expression)
}
88
#include<conio.h>
void main()
{
sum();
}
sum()
{
int i, j,x;
cin>>i>>j;
x=i+j;
cout<<”Sum”<<x;
return;
}
Function with argument and no return value:
Syntax:
void main()
{
int a,b;
…………
…………
message(a,b);
……….
……….
}
void message(int x, in y)
{
……………..
……………..
}
Exercise:
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j;
cout<<”Enter the values:”;
cin>>i>>j;
89
sum(i,j);
}
void sum(int x, int y)
{
int z;
z=x+y;
cout<<”Sum”<<z;
}
Exercise:
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,value;
cin>>i>>j;
value=sum(I,j);
cout<<”Sum”<<value;
}
int sum(int x, int y)
90
{
int z;
z=x+y;
return(z);
}
FUNCTION OVERLOADING
91
We can use the same function name to create function that performs a variety of different
tasks. This is known as function overloading or function polymorphism in Oops.
The function would perform different operations depending on the argument list in the function
call.
For example:
int add(int a , int b);
int add(int a, int b, int c);
double add(double x, double y);
double add(double p , int y);
// function overloading
#include<iostream.h>
#include<conio.h>
void sum_avg(int, int);
void sum_avg(int);
void sum_avg(int, int, int);
void main()
{
int a,b,c;
clrscr();
cout<<"Enter the A & B Values:"<<endl;
cin>>a>>b;
sum_avg(a,b);
sum_avg(100);
cout<<"Enter the A, B & C Values:"<<endl;
cin>>a>>b>>c;
sum_avg(a,b,c);
getch();
}
void sum_avg(int a, int b)
{
int sum;
float avg;
sum=a+b;
avg=sum/2;
cout<<"Sum of two numbers are."<<sum<<endl;
cout<<"Average value is."<<avg<<endl;
}
92
void sum_avg(int x)
{
x=a;
Cout<<”a=”<<x;
}
void sum_avg(int a, int b , int c)
{
int sum;
float avg;
sum=a+b+c;
avg=sum/3;
cout<<"Sum of three numbers are: "<<sum<<endl;
cout<<"Average value is :"<<avg<<endl;
}
#include<iostream.h>
#include<conio.h>
int volume(int);
int volume(int, int);
double volume(double, double, double);
void main()
{
clrscr();
cout<<"Volume of cube"<<volume(4)<<endl;
cout<<"Volume of the cylinder"<<volume(2,3)<<endl;
cout<<"Volume of the rectangle"<<volume(2,6,8)<<endl;
getch();
}
int volume(int a)
{
return(a*a*a);
}
int volume(int r,int h)
{
return(3.14*r*r*h);
}
double volume(double l, double b, double h)
93
{
return(l*b*h);
}
INLINE FUNCTION
Inline functions are functions where the call is made to online functions. The actual code than
gets placed in the calling program.
The inline function takes the format as a normal function but when it is complied it is compiled
as inline code.
The function is placed separately as inline function, thus adding readability to the source
program.
When the program is compiled the code present in function body is replaced in the place of
function call
Syntax:
inline data type function name(arguments)
94
clrscr();
cout<<"Enter the Values :\n";
cin>>x>>y;
cout<<"Sum ="<<add(x,y)<<endl;
cout<<"Multiplication = "<<mul(x,y)<<endl;
cout<<"Division = "<<div(x,y)<<endl;
getch();
}
// Find The Biggest Number Using Inline Function
#include<iostream.h>
#include<conio.h>
inline int max(int x, int y)
{
if(x>y)
{
return x;
}
else
{
return y;
}
}
void main()
{
int x, y, z;
clrscr();
cout<<"Enter X & Y Value:\n";
cin>>x>>y;
z=max(x,y);
cout<<"Biggest number is............"<<z<<endl;
getch();
}
FRIEND FUNCTIONS
class_class name
{
95
…………….
…………….
public:
…………….
…………….
friend void xyz(void);
};
The functions that are declared with the keyword friend are known as friend functions. Friends
function although not a member function has full access rights to the private members of the class.
Friend functions possess certain characteristics:
1. It can be invoked like a normal function without the help of any object.
2. Unlike member functions, it cannot access the member names directly and has to use an object
name and dot membership operator with each member name.
3. It can be declared either in public or in private.
4. Usually, it has the objects as arguments.
96
int tot;
tot=e.a+e.b;
cout<<"Total value is.........."<<tot<<endl;
}
void main()
{
sum s1;
clrscr();
s1.getdata();
s1.printdata();
add(s1);
getch();
}
// Calling Two Classes Using Friend Function
#include<iostream.h>
#include<conio.h>
class mark;
class info
{
private:
char name[30];
int reg;
public:
void getdata()
{
cout<<"Enter the name:\n";
cin>>name;
cout<<"Enter the register:\n";
cin>>reg;
}
friend void print(info f, mark k);
};
class mark
{
private:
int m1,m2,m3;
public:
97
void getdata()
{
cout<<"Enter the marks:\n";
cin>>m1>>m2>>m3;
}
friend void print(info f, mark k);
};
void print(info f, mark k)
{
cout<<"Name :"<<f.name<<endl;
cout<<"Register number :"<<f.reg<<endl;
cout<<"Mark 1 :"<<k.m1<<endl;
cout<<"Mark 2 :"<<k.m2<<endl;
cout<<"Mark 3 :"<<k.m3<<endl;
cout<<"Total Mark :"<<k.m1+k.m2+k.m3<<endl;
if(k.m1>=40 && k.m2>=40 && k.m3>=40)
cout<<"Result is pass"<<endl;
else
cout<<"Result is fail"<<endl;
}
void main()
{
info f1;
mark k1;
clrscr();
f1.getdata();
k1.getdata();
print(f1,k1);
getch();
}
VIRTUAL FUNCTION
It is basically introduced to handle some specific tasks related to class and objects.
STUDENT
When virtual functions are created for implementing late binding.
TEST SPORTS
98
RESULT
Compiler requirements:
1. The virtual functions must be members of some class
2. They cannot be static member
3. They are accessed by using objects pointers
4. A virtual functions can be a friend of another class
A virtual function in a base class must be defined even though it may not be used.
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int roll_number;
public:
void get_number()
{
cout<<"Enter the roll_number:\n";
cin>>roll_number;
}
void put_number()
{
cout<<"Roll number :"<<roll_number<<endl;
}
};
class test:virtual public student
{
protected:
int m1,m2,m3;
public:
void get_marks()
{
cout<<"Enter the makrs details:\n";
cin>>m1>>m2>>m3;
99
}
void put_marks()
{
cout<<"First mark :"<<m1<<endl;
cout<<"Second mark :"<<m2<<endl;
cout<<"Third mark :"<<m3<<endl;
}
};
class sports:virtual public student
{
protected:
int score;
public:
void get_score()
{
cout<<"Enter your score:\n";
cin>>score;
}
void put_score()
{
cout<<"My score is :"<<score<<endl;
}
};
class result:virtual public test, public sports
{
protected:
int total;
public:
void display()
{
total=m1+m2+m3+score;
put_number();
put_marks();
put_score();
cout<<"Total value details :"<<total<<endl;
}
};
100
void main()
{
result r;
clrscr();
r.get_number();
r.get_marks();
r.get_score();
r.display();
getch();
}
Exercise 2
#include<iostream.h>
#include<conio.h>
class emp
{
protected:
char name[30];
int eid;
public:
void get_name()
{
cout<<"Enter your name:\n";
cin>>name;
cout<<"Enter the id number:";
cin>>eid;
}
void put_name()
{
cout<<"Employee name :"<<name<<endl;
cout<<"Employee idnumber:"<<eid<<endl;
}
};
class salary:virtual public emp
{
protected:
long int salary;
101
public:
void get_salary()
{
cout<<"Enter the salary:\n";
cin>>salary;
}
void put_salary()
{
cout<<"Salary :"<<salary<<endl;
}
};
class bonus:virtual public emp
{
protected:
int bonus;
public:
void get_bonus()
{
cout<<"Enter the bonus amount:\n";
cin>>bonus;
}
void put_bonus()
{
cout<<"Bonus amount is :"<<bonus<<endl;
}
};
class netsalary:virtual public salary,public bonus
{
protected:
long int netsal;
public:
void get_netsal()
{
netsal=salary+bonus;
put_salary();
put_bonus();
cout<<"Net salary amount is "<<netsal<<endl;
102
}
};
void main()
{
netsalary n;
clrscr();
n.get_name();
n.get_salary();
n.get_bonus();
n.get_netsal();
getch();
}
INHERITANCE
The idea of classes leads to the idea of inheritance. We use the concept of classes being divided
into subclass. The principle in this soft of division is that each sub class shares characteristics with the
class from which it is derived. Each sub-class also has its own particular characters.
The c++ classes can be reused in several ways. Once a class has been written and tested, it can
be adapted by other programmers to suit their requirements. This is basically done by creating new
classes, reusing the properties of the existing ones. The mechanism of deriving a new class from an
old one is called inheritance or derivation
Single Inheritance:-
A derived class with only one base class is called as single inheritance.
Where derived_class is the name of the derived class and base_class is the name of the class on which
it is based. The member Access Specifier may be public, protected or private. This access specifier
describes the access level for the members that are inherited from the base class.
Member Access How Members of the Base Class Appear in the Derived Class
Specifier
Private Private members of the base class are inaccessible to the derived class.
103
Protected members of the base class become private members of the derived
class.
Public members of the base class become private members of the derived class.
Protected Private members of the base class are inaccessible to the derived class.
Protected members of the base class become protected members of the derived
class.
Public members of the base class become protected members of the derived class.
Public Private members of the base class are inaccessible to the derived class.
Protected members of the base class become protected members of the derived
class.
Public members of the base class become public members of the derived class.
In principle, a derived class inherits every member of a base class except constructor and destructor. It
means private members are also become members of derived class. But they are inaccessible by the members of derived class.
Exercise 1
#include<iostream.h>
#include<conio.h>
class student
{
protected:
char name[40];
int reg, n,m[20],i;
public:
void getdata();
void putdata();
};
void student::getdata()
{
cout<<"Enter the student name:\n";
cin>>name;
cout<<"Enter the register number:\n";
cin>>reg;
cout<<"Enter the no.of subjects:\n";
cin>>n;
for(i=0;i<n;i++)
{
cin>>m[i];
}
}
Void hai()
104
{
}
void student::putdata()
{
cout<<"Student name :"<<name<<endl;
cout<<"Register number :"<<reg<<endl;
}
class result:public student
{
int total;
public:
void cal();
void disp();
};
Void hai()
{
}
void result::cal()
{
total=0;
for(i=0;i<n;i++)
{
total=total+m[i];
}
}
void result::disp()
{
cout<<"Total marks :"<<total<<endl;
}
void main()
{
result r;
clrscr();
r.getdata();
r.putdata();
r.cal();
r.disp();
105
getch();
}
Exercise 2
#include<iostream.h>
#include<conio.h>
class base
{
protected:
int a;
public:
void get_a();
void put_a();
};
void base::get_a()
{
cout<<"Enter the A Value:\n";
cin>>a;
}
void base::put_a()
{
cout<<"A = "<<a<<endl;
}
class derived:public base
{
private:
int b;
public:
int c;
void get_b();
void cal();
void disp();
};
void derived::get_b()
{
cout<<"Enter the B Value:\n";
106
cin>>b;
}
void derived::cal()
{
c=a*b;
}
void derived::disp()
{
cout<<"B ="<<b<<endl;
cout<<"Multiplication of two numbers are:"<<c<<endl;
}
void main()
{
derived d;
clrscr();
d.get_a();
d.put_a();
d.get_b();
d.cal();
d.disp();
getch();
}
Exercise
#include<iostream.h>
#include<conio.h>
107
class emp
{
protected:
char ename[40];
int eid;
public:
void get_emp()
{
cout<<"Enter the employee name:";
cin>>ename;
cout<<"Enter the employee id number:";
cin>>eid;
}
void put_emp()
{
cout<<"Employee name :"<<ename<<endl;
cout<<"Employee id number:"<<eid<<endl;
}
};
class salary:public emp
{
protected:
int sal;
int age;
public:
void get_salary()
{
cout<<"Enter the salary amount:"<<endl;
cin>>sal;
cout<<"Enter the age:"<<endl;
cin>>age;
}
void put_salary()
{
put_emp();
cout<<"Salary :"<<sal<<endl;
cout<<"Age :"<<age<<endl;
108
}
};
class bonus:public salary
{
protected:
int bon;
public:
void get_cal()
{
bon=salary*5/100;
}
void put_cal()
{
cout<<"Bonus amount :"<<bon<<endl;
}
};
void main()
{
bonus b;
clrscr();
b.get_emp();
b.get_salary();
b.get_cal();
b.put_cal();
getch();
}
109
Multiple Inheritance:-
A derived class with several base class is called Multiple Inheritance.
A B
Exercise 1
#include<iostream.h>
#include<conio.h>
class info
{
protected:
char name[40];
int reg;
public:
void get_info()
{
cout<<"Enter the student name:";
cin>>name;
cout<<"Enter the register number:";
cin>>reg;
}
void put_info()
{
cout<<"Student name :"<<name<<endl;
cout<<"Register number :"<<reg<<endl;
}
};
class details
{
protected:
int m1,m2,m3;
public:
void get_details()
110
{
cout<<"Enter the 3 marks:";
cin>>m1>>m2>>m3;
}
void put_details()
{
cout<<"First mark :"<<m1<<endl;
cout<<"Second mark :"<<m2<<endl;
cout<<"Third mark :"<<m3<<endl;
}
};
class result:public info, public details
{
protected:
int total;
public:
void get_result()
{
total=m1+m2+m3;
}
void put_result()
{
put_info();
put_details();
if(m1>=40 && m2>=40 && m3>=40)
{
cout<<"Result is pass\n";
}
else
{
cout<<"Result is fail\n";
}
cout<<"Total mark :"<<total<<endl;
}
};
void main()
{
111
result r;
clrscr();
r.get_info();
r.get_details();
r.get_result();
r.put_result();
getch();
}
//body of function
To extend the meaning of an operator, an operator function is defined with a keyword operator followed by the
operator symbol.
Category Operators
Airthmetic +,–,*,/,%
112
Relational < , > , == , != , <= , >=
Logical || , && , !
Assignment =
Unary ++ , —
Subscripting []
Deference *
Function call ()
Address of &
Comma ,
Note : If increment/decrement operators are used before variable, they are called prefix operators i.e ++x. And if
increment/decrement operators are used after variable, they are called postfix operators i.e x++.
#include <iostream>
113
using namespace std;
class check_count
{
public:
int count_plus;
int count_minus;
check_count()
{
count_plus = 0;
count_minus = 2;
};
void operator ++()
{
count_plus= count_plus*1;
}
// count increment
//before increment/decrement
cout << "x =" << x.count_plus<<"\n";
cout <<"y =" << y.count_minus<<"\n";
++x;
--y;
//after increment/decrement
cout<<"\nAfter increment/decrement\n";
cout<<"x ="<<x.count_plus<<"\n";
cout<<"y ="<<y.count_minus<<"\n";
return 0;
}
Output
114
Example: C++ program to illustrate binary operator overloading
#include<iostream>
class complex
private:
int real,imag;
public:
void getvalue()
cin>>real;
cin>>imag;
complex temp;
temp.real=real+obj.real;
temp.imag=imag+obj.imag;
return(temp);
115
complex temp;
temp.real=real-obj.real;
temp.imag=imag-obj.imag;
return(temp);
void display()
cout<<real<<"+"<<"("<<imag<<")"<<"i"<<"\n";
};
int main()
complex c1,c2,c3,c4;
c1.getvalue();
c2.getvalue();
c3 = c1+c2;
c4 = c1-c2;
cout<<"Result is:\n";
c3.display();
c4.display();
116
return 0;
Output
Constructor:
A constructor is a special member function whose task is to initialize the objects of its class.
It is special because its name is the same as the class name. The constructor is invoked
whenever an object of its associated class is created. It is called constructor because it constructs the
values of data members of the class.
Destructor:
A destructor as the name implies is used to destroy the objects that have been created a
constructor. Like a constructor, the destructor is a member function whose name is the same as the
class name but is preceded by a tilde.
// Constructor and Destructor
#include<iostream.h>
117
#include<conio.h>
class tcps
{
int x,y;
public:
tcps()
{
x=0;
y=0;
}
tcps(int a)
{
x=a;
y=0;
}
tcps(int a, int b)
{
x=a;
y=b;
}
void disp()
{
cout<<"X Value:"<<x<<endl;
cout<<"Y Value:"<<y<<endl;
}
~tcps()
{
cout<<"\n Destructor:";
}
};
void main()
{
tcps t1;
tcps t2(10);
tcps t3(10,20);
clrscr();
cout<<" First Object\n";
118
t1.disp();
cout<<" Second Object\n";
t2.disp();
cout<<" Third Object\n";
t3.disp();
getch();
}
119
alpha a6;
}
cout<<"\n reenter";
getch();
}
120
cout<<"\n enter the withdraw amount :";
cin>>wamt;
if(wamt>=bamt)
{
cout<<"\n invalid operation , your balance is below the withdraw amt";
wamt=0;
}
bamt=bamt-wamt;
}
void showbalance()
{
cout<<"\n balance amount "<<bamt;
}
};
void main()
{
bank c;
char ch;
do
{
clrscr();
cout<<"choose any of the option ";
cout<<"\n\t 1.customer entry ";
cout<<"\n\t 2.deposit ";
cout<<"\n\t 3.withdraw ";
cout<<"\n\t 4.balance report ";
cout<<"\n\t 5.exit";
int n;
cin>>n;
switch(n)
{
case 1:
c.getdata();
break;
case 2:
c.deposit();
break;
121
case 3:
c.withdraw();
break;
case 4:
c.showbalance();
break;
case 5:
exit(0);
}
cout<<"\n do you want to continue the process :";
cin>>ch;
}
while(tolower(ch)=='y');
}
In C++, polymorphism causes a member function to behave differently based on the object that
calls/invokes it. Polymorphism is a Greek word that means to have many forms. It occurs when you
have a hierarchy of classes related through inheritance.
For example, suppose we have the function makeSound(). When a cat calls this function, it will
produce the meow sound. When a cow invokes the same function, it will provide the moow sound.
Though we have one function, it behaves differently under different circumstances. The function has
many forms; hence, we have achieved polymorphism.
Types of Polymorphism
You invoke the overloaded functions by matching the number and type of arguments. The information
is present during compile-time. This means the C++ compiler will select the right function at compile
time.
Function overloading occurs when we have many functions with similar names but different
arguments. The arguments may differ in terms of number or type.
Example 1:
#include <iostream>
using namespace std;
void test(int i) {
cout << " The int is " << i << endl;
}
void test(double f) {
cout << " The float is " << f << endl;
}
void test(char const *ch) {
cout << " The char* is " << ch << endl;
}
int main() {
test(5);
test(5.5);
test("five");
return 0;
}
Operator Overloading
In Operator Overloading, we define a new meaning for a C++ operator. It also changes how the
operator works. For example, we can define the + operator to concatenate two strings. We know it as
the addition operator for adding numerical values. After our definition, when placed between integers,
it will add them. When placed between strings, it will concatenate them.
Example 2:
#include<iostream>
class ComplexNum {
private:
int real, over;
public:
ComplexNum(int rl = 0, int ov = 0) {
real = rl;
over = ov;
}
Runtime Polymorphism
This happens when an object's method is invoked/called during runtime rather than during compile
time. Runtime polymorphism is achieved through function overriding. The function to be
called/invoked is established during runtime.
Function Overriding
Function overriding occurs when a function of the base class is given a new definition in a derived
class. At that time, we can say the base function has been overridden.
For example:
#include <iostream>
using namespace std;
class Mammal {
public:
void eat() {
};
public:
void eat() {
Cow c = Cow();
c.eat();
return 0;
124
C++ Virtual Function
If a virtual function class is inherited, the virtual class redefines the virtual function to suit its needs.
For example:
#include <iostream>
using namespace std;
class ClassA {
public:
virtual void show() {
cout << "The show() function in base class invoked..." << endl;
}
};
class ClassB :public ClassA {
public:
void show() {
cout << "The show() function in derived class invoked...";
}
};
int main() {
ClassA* a;
ClassB b;
a = &b;
a->show();
}
It's also called early binding or static It's also called late/dynamic binding or
polymorphism dynamic polymorphism
125
discovery is done during compile time discoverer is done during runtime.
FILES
C++ uses file streams as an interface between the programs and the files. The stream that
supplies data to the program is known as input stream
The stream that receives data from the program is known as output stream. Input stream
extracts data from the file and the output stream inserts data the file.
The I/O system of c++ contains a set of classes that define the file handling methods. These
include if stream, ofstream and fstream
Ifstream to read a stream of object from a specified file
Ofstream to write a stream of object on a specified file
Fstream both to read and write a stream of objects on a specified file
127