0% found this document useful (0 votes)
238 views134 pages

Class 12th IP Project

An array is a collection of elements of the same data type stored in contiguous memory locations that can be accessed using an index. There are two types of arrays: single/one-dimensional arrays that use one index and multi-dimensional arrays that use two or more indices. Arrays must be declared before use with the syntax type[] and can be initialized at compile-time or run-time. Common operations on arrays include traversing elements, inserting/deleting elements, and searching for elements using linear search.

Uploaded by

Vidhi Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
238 views134 pages

Class 12th IP Project

An array is a collection of elements of the same data type stored in contiguous memory locations that can be accessed using an index. There are two types of arrays: single/one-dimensional arrays that use one index and multi-dimensional arrays that use two or more indices. Arrays must be declared before use with the syntax type[] and can be initialized at compile-time or run-time. Common operations on arrays include traversing elements, inserting/deleting elements, and searching for elements using linear search.

Uploaded by

Vidhi Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 134

Array

An array is defined as finite ordered collection of


homogenous data elements which are stored in
contiguous memory locations.

Here the words,

Finite means data range must be defined.

Ordered means data must be stored in continuous


memory locations.

Homogenous means data must be of similar data type.

Array are of two types-

1.Single or one dimensional array

2.Multi dimensional array

~1~
Single or One dimensional array
A list of items can be given one variable name
using only one subscript and such a variable is
called single sub-scripted variable or single or one
dimensional array.

First element last


element

Numbers[0] Numbers[1] Numbers[2] Numbers[3] ………….

Declaration of one dimensional array:


Like any other variable arrays must be declared
before they are used so that the compiler can
allocate space for them in the memory. The syntax
form of array declaration is:

Type variable-name[size];

Example-

float height[50];

int group[10];

char name[10];

~2~
Initialization of Single or One Dimensional
Array:
After an array is declared, it’s elements must be
initialized. In C programming an array can be
initialized at either of the following stages :

-At compile time

-At run time

Compile Time Initialization :


Array can be
initialized when it is declared. The general form of
initialization of array is :

Type array-name[size]={list of values};

The values in the list are separated by commas.

For example :Int number[3] = {0,5,4};

Run Time Initialization : An Array can also be


explicitly initialized at run time. For eg.,
consider the following segment of a C program :

For(i=0;i<10;i++)

Scanf(“%d”,&x[i]);

~3~
Example program of One Dimensional Array :
/*Program to enter 5 values in
an array and print them*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;//Declaration of variables
clrscr();
printf("Enter 5 values in the array:\n");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printf("Elements in the array:\n");
printf("Elements stored at:\n");
for(i=0;i<5;i++)
printf("a[%d]=%d\n",i,a[i]);
getch();
}
Output:

Enter any 5 values in the array:

Elements in the array:

Elements stored at:

a[0]=1

a[1]=2

a[2]=3

a[3]=4

a[4]=5

~4~
Multi or Two Dimensional Array
Array of an array is known as Multi Dimensional
Array. Multi dimensional array is like a table which
can have two or more dimensions.

Column Column Column Column


1 2 3 4

Row 1 x[0][0] x[0][1] x[0][2] x[0][3]


Declaration of Multi
Row 2 x[1][1]
Dimensional Array:
x[1][0] x[1][2] x[1][3]

The general form of a


Row 3 x[2][0] x[2][1] x[2][2] x[2][3] multi dimensional array
declaration-

type name[size 1][size 2]…[size N];

For example: int x[3][4];

Initialization of Two Dimensional(2D)Array:


Like the one dimensional array, 2D arrays can be
initialized in two way:

-The compile time initialization

-The run time initialization

~5~
Compile Time initialization : We can initialize
the elements of the 2D array in the same way as the
ordinary variables are declared. The best form to
initialize 2D array is by using the matrix form.For
example:

int table[2][3]={

{0,2,5}

{1,3,0}

};

Run Time Initialization: Similarly like 1D


array ,2D array are initialized by using the looping
structure. To initialize the 2D array by this way,
the nested loop structure will be use; outer loop for
the rows (first sub-script) and the inner for loop
for the columns (second sub-script) of the 2D array.
For example –

for(i=0;i<3;i++)

for(j=0;j<3;j++)

scanf(“%d”,&ar1[i][j]);

Example programs of Two Dimensional Array :


/*Program to enter values in 2D array
and print them*/
#include<stdio.h>
#include<conio.h>
void main()

~6~
{
int a[2][2],i,j;//Declaring variables
clrscr();
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf("Enter values for a[%d][%d]=",i,j);
scanf("%d",&a[i][j]);
}
}
printf("Array elements are:\n");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch();
}

Output:

Enter values for a[0][0]=1

enter values for a[0][1]=2

Enter values for a[1][0]=3

Enter values for a[1][1]=4

Array elements are:

1 2

3 4

Basic Operations on Array


Follwing operations can be performed on array

(a) Traverse - access all the array elements


one by one.

~7~
(b) Insertion - Adds an element at the given
index.
(c) Deletion - Deletes an element at the given
index.
(d) Search - Searches an element using the
given index or by the value.
(e) Update - Updates an element at the given
index.

Traverse: Traversing means accessing the each


and every element of array exactly once.
Following is the algorithm for traversing a
linear array-

Here A is a linear array with lower bound LB and


upper bound UB. This algorithm traverses array A
and applies the operation PROCESS to each
element of the array.
1. Repeat for I=LB to UB
2. Apply PROCESS to A[I]
[END OF FOR LOOP]
3. EXIT

Program to show traversing:

#include<stdio.h>

#include<conio.h>

~8~
void main()

int i;

clrscr();

printf(“My name is Vidhi Singh”);

scanf(“%d”,&i);

getch();

OUTPUT:

My name is Vidhi Singh

Insertion: Insert operation is to insert one or


more data elements into an array. Based on the
requirement, a new element can be added at the
beginning, end, or any given index of array.
Following is the algorithm for Insertion an
element in to a linear array.

~9~
Algorithm: Let LA be a Linear Array (unordered)
with N elements and K is a positive integer such
that K<=N. Following is the algorithm where ITEM
is inserted into the Kth position of LA-
1. Start
2. Set J=N
3. Set N=N+1
4. Repeat steps 5 and 6 while J>=K
5. Set LA[J+1]=LA[J]
6. Set J=J-1
7. Set LA[K]=ITEM
8. Stop

Program to show insertion:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,3,5,7,8};

~ 10 ~
int item=10, k=3, n=5;
int i=0,j=n;
clrscr();
printf("The original array elements are:-\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
n=n+1;
while(j>=k)
{
a[j+1]=a[j];
j=j-1;
}
a[k]=item;
printf("\nThe array elements after insertion:-\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
getch();
}

OUTPUT:
The original array elements are:-
a[0]=1
a[1]=3
a[2]=5
a[3]=7
a[4]=8

The array elements after insertion:-


a[0]=1
a[1]=3
a[2]=5
a[3]=10
a[4]=7
a[5]=8

Deletion: Deletion refers to removing an


existing element from the array and re-
organizing all elements of an array. Following
is the algorithm for Deletion an element from a
linear array.

~ 11 ~
Consider LA is a linear array with N elements and
K is a positive integer such that K<=N.

Following is the algorithm to delete an element


available at the Kth position of LA.
1. Start
2. Set J=K
3. Repeat steps 4 and 5 while J<N
4. Set LA[J-1]=LA[J]
5. Set J=J+1
6. Set N=N-1
7. Stop

Program to show deletion:

#include<stdio.h>
#include<conio.h>
void main()
{

~ 12 ~
int a[]={1,3,5,7,8};
int k=3, n=5;
int i,j;
clrscr();
printf("The original array elements are:-\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
j=k;
while(j<n)
{
a[j-1]=a[j];
j=j+1;
}
n=n-1;
printf("\nThe array elements after deletion:-\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
getch();
}

OUTPUT:
The original array elements are:-
a[0]=1
a[1]=3
a[2]=5
a[3]=7
a[4]=8

The array elements after deletion:-


a[0]=1
a[1]=3
a[2]=7
a[3]=8
Search: Searching refers the finding out an
element using the given index or by the value.
There are two types of searching in linear array
1.Linear Search
2.Binary Search

~ 13 ~
Linear Search:
A linear search is the basic and simple search
algorithm. A linear search searches an element
or value from an array till the desired element
or value is not found. It searches in a sequence
order. It compares the element with all the
other elements given in the list and if the
element is matched it returns the value index
else it return-1. Linear Search is applied on
the unsorted or unordered list when there are
fewer elements in a list.

Consider LA is a linear array with N elements and


K is a positive integer such that K<=N. Following
is the algorithm to find an element with a value
of ITEM using sequential search-

1. Start
2. Set J=0
3. Repeat steps 4 and 5 while J<N
4. If LA[J]=ITEM then go to step 6
5. Set J=J+1
6. Print J, ITEM
7. Stop

~ 14 ~
Program to show linear search:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,3,5,7,8};
int item=5 ,n=5;
int i=0, j=0;
clrscr();
printf("The original array elements are:-\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
while(j<n)
{
if(a[j]==item)
{
break;
}
j=j+1;
}
printf("\nFound element %d at position :-%d\
n",item,j);
getch();
}

OUTPUT:
The original array elements are:-
a[0]=1
a[1]=3
a[2]=5
a[3]=7
a[4]=8

Found element 5 at position :-2

Binary Search:

~ 15 ~
Binary Search is applied on the sorted array or
list. In binary search, we first compare the
value with the elements in the middle position
of the array. If the value is matched, then we
return the value. If the value is less than the
middle element, then it must lie in the lower
half of the array and if it's greater than the
element then it must lie in the upper half of
the array. We repeat this procedure on the lower
(or upper) half of the array. Binary Search is
useful when there are large numbers of elements
in an array.

We basically ignore half of the elements just


after one comparison. Compare x with the middle
element.
If x matches with middle element, we return the
mid index.
Else If x is greater than the mid element, then
x can only lie in right half sub array after the
mid element. So we recur for right half.
Else (x is smaller) recur for the left half.

~ 16 ~
Program to show binary search:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10]={1,2,3,9,11,13,17,25,57,90};
int mid, lower=0, upper=9, num, flag=1;
clrscr();
printf("Enter number to search:-");
scanf("%d",&num);
for(mid=(lower=upper)/
2;lower<upper;mid=(lower+upper)/2);
{
if(a[mid]==num)
{
printf("\nThe number is at position [%d] in the
array",mid);
flag=0;
}
if(a[mid>num])
upper=mid-1;
else
lower=mid+1;
}
if(flag)
printf("\nElement is not present in the array");
getch();
}

OUTPUT:

Enter number to search:-11

The number is at position [4] in the array

Update: Update operation refers to updating an

~ 17 ~
existing element from the array at given index.

Consider LA is a linear array with N elements and


K is a positive integer such that K<=N. Following
is the algorithm to update an element available
at the Kth position of LA.

1. Start
2. Set LA[K-1]=ITEM
3. Stop

Program to show updation:

~ 18 ~
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={1,3,5,7,8};
int k=3, n=5, item=10;
int i,j;
clrscr();
printf("The original array elements are:-\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
a[k-1]=item;
printf("\nThe array elements after updation:-\n");
for(i=0;i<n;i++)
{
printf("a[%d]=%d\n",i,a[i]);
}
getch();
}

OUTPUT:

The original array elements are:-


a[0]=1
a[1]=3
a[2]=5
a[3]=7
a[4]=8

The array elements after updation:-


a[0]=1
a[1]=3
a[2]=10
a[3]=7
a[4]=8

Character String in C:

~ 19 ~
Strings are actually one-dimensional array of
characters terminated by a null character '\0'.
Thus a null-terminated string contains the
characters that comprise the string followed by a
null.

The following declaration and initialization


create a string consisting of the word "Hello".
To hold the null character at the end of the
array, the size of the character array containing
the string is one more than the number of
characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o','\0'};

If we follow the rule of array initialization then


we can write the above statement as follows-

char greeting[]= "Hello";

~ 20 ~
Static and Dynamic Memory Allocation:
Dynamic memory allocation is at runtime. Static
memory allocation is before run time, but the
values of variables may be change at run time.
Static memory allocation saves running time, but
can't be possible in all cases.
Dynamic memory allocation stores it's memory on
heap, and the static memory allocation stores it's
data in the "data segment" of the memory.

Pointers in 'C': A pointer is a variable whose


value is the address of another variable, i.e.,
direct address of the memory location. Like any
variable or constant, you must declare a pointer
before using it to store any variable address.
The general form of a pointer variable
declaration is-
type *var-name;

NULL Pointers:
It is always a good practice to assign a NULL
value to a pointer variable in case you do not
have an exact address to be assigned. This is
done at the time of variable declaration. A
pointer that is assigned NULL is called a null
pointer.

Recursion in 'C': Recursion is the process of


repeating items in a self-similar way. In
programming languages, if a program allows you
to call a function inside the same function,
then it is called a recursive call of the
function. Or in other words, when a function is
calling to itself is known as recursive
function.

~ 21 ~
Conditions for recursive function:

1. Every function must have a Base Criteria


(Termination condition) and for that it should not
call to itself.
2. Whenever a function is calling to itself, it
must be closer to the Base Criteria.

Following are some examples of recursions-

1. Fibonacci series
2. Binomial coefficient
3. GCD

~ 22 ~
Program for Fibonacci series:

#include<stdio.h>
#include<conio.h>
int fibonacci(int term);
void main()
{
int terms,i;
clrscr();
printf("Enter number of terms in fibonacci
series:-");
scanf("%d",&terms);
printf("Fibonacci series till %d terms\n",terms);
for(i=0;i<terms;i++)
{
printf("%d",fibonacci(i));
}
getch();
}
int fibonacci(int term)
{
if(term<2)
return term;
return fibonacci(term-1)+fibonacci(term-2);
}

OUTPUT:

Enter number of terms in fiboncci series:5


Fibonacci series till 5 terms
01123

~ 23 ~
Program for binomial coefficient:

#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n,r,f;
clrscr();
printf("Enter value for n & r\n");
scanf("%d%d",&n,&r);
if(n<r)
printf("Invalid output");
else f=fact(n)/(fact(n-r)*fact(r));
printf("\nBinomial coefficient=%d",f);
getch();
}
int fact(int x)
{
if(x>1)
return x*fact(x-1);
else
return 1;
}

~ 24 ~
Program for GCD:

#include<stdio.h>
#include<conio.h>
int gcd(int a, int b);
void main()
{
int num1, num2, hcf;
clrscr();
printf("Enter any two numbers to find gcd:-");
scanf("%d%d",&num1,&num2);
hcf=gcd(num1, num2);
printf("GCD of %d and %d=%d\n",num1,num2,hcf);
getch();
}
int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}

OUTPUT:
Enter any two numbers to find GCD:12

30

GCD of 12 and 30= 6

~ 25 ~
Sorting
Sorting:
Sorting algorithm specifices the way to arrange
data in a particular order. Most common orders are in
numerical or lexicographical order.

Bubble sort:
Bubble sort is a simple sorting algorithm. This
sorting algorithm is comparison-based algorithm in
which each pair of adjacent elements is compared and
the elements are swapped if they are not in order.
This algorithm is not suitable for large data sets as
its average and worst case complexity are of O(n2)
where n is the number of items.

~ 26 ~
How bubble sort works:
We take an unsorted array for our example. Bubble sort takes O(n2) time so
we’re keeping it short and precise.

14 33 27 35 10

Bubble sort starts with very first two elements, comparing them to
check which one is greater.

14 33 27 35 10

In this case, value 33 is greater than 14, so it is already in sorted


locations. Next, we compare 33 with 27.

14 33 27 35 10

We find that 27 is smaller than 33 and these two values must be


swapped.

14 33 27 35 10

The new array should look like this-

14 27 33 35 10

Next we compare 33 and 35. We find that both are in already sorted
positions.

14 27 33 35 10

~ 27 ~
Then we move to the next two values, 35 and 10.

14 27 33 35 10

We know then that 10 is smaller to 35. Hence they are not sorted.

14 27 33 35 10

We swap these values. We find that we have reached the end of the array.
After one iteration, the array should look like this-

14 27 33 10 35

To be precise, we are now showing how an array should look like after each
iteration. After the second iteration, it should look like this-

14 27 10 33 35

Notice that after each iteration, at least one value moves at the end.

14 10 27 33 35

And when there’s no swap required, bubble sort learns that an array is
completely sorted.

10 14 27 33 35

Algorithm:

~ 28 ~
We assume list is an array of n elements. We further
assume that swap function swaps the values of the
given array elements.

begin BubbleSort(list)

for all elements of list

if list[i]>list[i+1]

swap(list[i], list[i+1])

end if

end for

return list

end BubbleSort

Program for bubble sort:


#include<stdio.h>

#include<conio.h>

void main()

int a[5],i,j,temp;

clrscr();

printf(“Enter the array elements:-\n”);

for(i=0;i<5;i++)

scanf(“%d”,&a[i]);

printf(“Array elements before sorting:-\n”);

for(i=0;i<5;i++)

~ 29 ~
{

printf(“%d\n”,a[i]);

for(i=0;i<5-1;i++)

for(j=0;j<5-1-i;j++)

if(a[j]>a[j+1])

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

printf(“Array elements after sorting:-\n”);

for(i=0;i<5;i++)

printf(“%d\t”,a[i]);

getch();

OUTPUT:

~ 30 ~
Enter the array elements:-

55

34

Array elements before sorting:-

55

34

Array elements after sorting:-

34

55

Selection sort:

~ 31 ~
Selection sort is a simple sorting
algorithm. This sorting algorithm is an in-place
comparison-based algorithm in which the list is
divided into two parts, the sorted part at the left
end and the unsorted part at the right end.
Initially, the sorted part is empty and the unsorted
part is the entire list. The smallest element is
selected from the unsorted array and swapped with
the leftmost element, and that element becomes a part
of the sorted array. This process continues moving
unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets as
its average and worst case complexities are of O(n2),
where n is the number of items.

How selection sort works:


Consider the following depicted array as an example.

14 33 27 10 35 19 42 44

For the first position in the sorted list, the whole list is scanned sequentially.
The first position where 14 is sorted presently, we search the whole list and
find that 10 is the lowest value.

14 33 27 10 35 19 42 44

So we replace 14 with 10. After one iteration 10, which happens to be the
minimum value in the list, appears in the first position of the sorted list.

14 33 27 10 35 19 42 44

For the second position, where 33 is residing, we start scanning the rest of the
list in a linear manner.

~ 32 ~
10 33 27 14 35 19 42 44

We find that 14 is the second lowest value in the list and it should appear at
the second place. We swap these values.

10 33 27 14 35 19 42 44

After two iterations, two least values are positioned at the beginning in a
sorted manner.

10 14 27 33 35 19 42 44

The same process is applied to the rest of the items in the array.

Following is a pictorial depiction of the entire sorting process.

10 14 27 33 35 19 42 44

10 14 27 33 35 19 42 44

10 14 19 33 35 27 42 44

10 14 19 33 35 27 42 44

10 14 19 27 35 33 42 44

10 14 19 27 35 33 42 44

~ 33 ~
10 14 19 27 35 33 42 44

10 14 19 27 33 35 42 44

10 14 19 27 33 35 42 44

Algorithm:
STEP-1 Set MIN to location 0

STEP-2 Search the minimum element in the list

STEP-3 Swap with value at location MIN

STEP-4 Increment MIN to point to next element

STEP-5 Repeat until list is sorted

Program for selection sort:


#include<stdio.h>

#include<conio.h>

void main()

int a[5],i,j,temp;

clrscr();

printf(“Enter the array elements:-\n”);

for(i=0;i<=5;i++)

scanf(“%d”,&a[i]);

~ 34 ~
}

printf(“Array elements before sorting:-\n”);

for(i=0;i<5;i++)

printf(“%d\n”,a[i]);

for(i=0;i<5;i++)

for(j=i+1;j<5;j++)

if(a[i]>a[j])

temp=a[i];

a[i]=a[j];

a[j]=temp;

printf(“Array elements after sorting:-\n”);

for(i=0;i<5;i++)

printf(“%d\t”,a[i]);

getch();

~ 35 ~
OUTPUT:
Enter the array elements:

55

45

Array elements before sorting:

55

45

Array elements after sorting:

45

55

~ 36 ~
Merge sort:
Merge sort is a sorting technique based on divide and
conquer technique. With worst-case time complexity
being O(n log n), it is one of the most respected
algorithms. Merge sort first divides the array into
equal halves and then combines them in a sorted
manner.

How merge sort works:

~ 37 ~
Algorithm:
STEP-1 If it is only one element in the list it is
already sorted, return.

STEP-2 Divide the list recursively into two halves


until it can no more be divided.

STEP-3 Merge the smaller lists into new list in


sorted order.

Program for merge sort:


#include<stdio.h>

#include<conio.h>

int a[10]={10,14,19,26,27,31,33,35,42,44};

int b[10];

void merging(int low,int mid,int high)

int l1,l2,i;

for(l1=low,l2=mid+1,i=low;l1<=mid&&l2<=high;i++)

if(a[l1]<=a[l2]);

b[i]=a[l1++];

else

b[i]=a[l2++];

while(l1<=mid)

b[i++]=a[l1++];

while(l2<=high)

b[i++]=a[l2++];

~ 38 ~
for(i=low;i<=high;i++)

a[i]=b[i];

void sort(int low,int high)

int mid;

if(low<high)

mid=(low+high)/2;

sort(low,mid);

sort(mid+1,high);

merging(low,mid,high);

else

return;

void main()

int i;

printf(“List before sorting:-\n”);

for(i=0;i<=max;i++)

printf(“%d”,a[i]);

sort(0,max);

~ 39 ~
printf(“\n List after sorting:-\n”);

for(i=0;i<=max;i++)

printf(“%d”,a[i]);

getch();

OUTPUT:
List before sorting:-

10 14 19 26 27 31 33 35 42 44 0

List after sorting:-

0 10 14 19 26 27 31 33 35 42 44

~ 40 ~
Insertion sort:
This is an in-place comparison based sorting
algorithm. Here, a sub-list is maintained which is
always sorted. For example, the lower part of an
array is maintained to be sorted. An element which is
to be inserted in this sorted sub-list, has to find
its appropriate place and then it has to be inserted
there. Hence, the name insertion sort.

The array is searched sequentially and unsorted items


are moved and inserted into the sorted sub-list(in
the same array). This algorithm is not suitable for
large data sets as its average and worst case
complexity are of O(n2), where n is the number of
items.

How insertion sort works:

~ 41 ~
Algorithm:
STEP-1 If it is the first element, it is already
sorted. Return 1

STEP-2 Pick next element.

STEP-3 Compare with all elements in the sorted sub-


list.

STEP-4 Shift all the elements in the sorted sub-list


that is greater than the value to be sorted.

STEP-5 Insert the value.

STEP-6 Repeat until list is sorted.

PROGRAM-

#include<stdio.h>

#include<conio.h>

void main()

int n, i, j, temp, a[1000];

clrscr();

printf(“Enter the number of elements:-“);

scanf(“%d”,&n);

printf(“Enter the array elements:-“);

for(i=0;i<n;i++)

scanf(“%d”,&a[i]);

for(i=0;i<=n;i++)

~ 42 ~
{

j=i;

while(j>0&&a[j-1]>a[j])

temp=a[j];

a[j]=a[j-1];

a[j-1]=temp;

j--;

printf(“\n Sorted array:-“);

for(i=0;i<=n-1;i++)

printf(“%d\t”,a[i]);

getch();

~ 43 ~
Quick sort:
Quick sort is a very popular sorting
method. The name comes from the fact that in general,
quick sort can sort a list of data elements
significantly faster than any of the common sorting
algorithms. This algorithm is based on the fact that
it is faster and easier to sort two smaller arrays
than one larger array. The basic strategy of quick
sort is to divide and conquer.

How quick sort works:

~ 44 ~
Algorithm:
Using pivot algorithm recursively, we end up
with smaller possible partitions. Each
partition is then processed for quick sort. We
define recursive algorithm for quicksort as
follows:

Step1- Make the right-most index value pivot.


Step2- Partition the array using pivot value.
step3- Quick sort left partition recursively.
step4- Quick sort right partition recursively.

~ 45 ~
Stack & Queue
Stack:
A stack is an Abstract Data Type(ADT), commonly used
in most programming languages. It is named stack as
it behaves like a real world stack, for example, a
deck of cards or a pile of plates, etc.

Stack ADT allows all data operations at one end only.


At any given time, we can only access the top element
of a stack. This feature makes it a LIFO data
structure. LIFO stands for Last-in-first-out. Here,
the element which is placed last, is accessed first.
In stack terminology, insertion operation is called
push operation and removal operation is called pop
operation.

Basic operations:
Stack operations may involve initializing the stack,
using it and then de-initializing it. Apart from
these basic stuffs, a stack is used for the two
primary operations-

1.push operation

2.pop operation

~ 46 ~
To use a stack efficiently, we need to check the
status of stack as well. For the same purpose, the
following functionality is added to stacks-

peek()- Get the top data element of the stack without


removing it.

isfull()- Checks if stack is full.

isempty()- Checks if stack is empty.

1.push operation: The process of putting a new data


element onto stack is known as a push operation. Push
operation involves a series of steps-

Step1: Checks if the stack is full.

Step2: If the stack is full, produces an error and


exit.

Step3: If the stack is not full, increments top to


point next empty space.

Step4: Adds data element to the stack location, where


top is pointing.

Step5: Returns success.

~ 47 ~
Algorithm for push operation:
begin procedure push: stack, data

if stack is full

return null

endif

top <- top+1

stack[top]<- data

end procedure

Implementation of algorithm in ‘C’:


void push(int data){

if(!isfull()){

top=top+1;

stack[top]=data;

}else{

printf(“Could not insert data, Stack is full.\n”);

~ 48 ~
2.pop operation: Accessing the content while removing
it from the stack, is known as a pop operation.

A pop operation may involve the following steps-

Step1: Checks if the stack is empty.

Step2: If the stack is empty, produces an error and


exit.

Step3: If the stack is not empty, accesses the data


element at which top is pointing.

Step4: Decreases the value of top by 1.

Step5: Returns success.

Algorithm for pop operation:


begin procedure pop: stack

if stack is empty

return null

endif

data<- stack[top]

top<- top-1

return data

end procedure

~ 49 ~
Implementation of algorithm in ‘C’:
int pop(int data){

if(!isempty()){

data=stack[top];

top=top-1;

return data;

}else{

printf(“Could not retrieve data, stack is empty.\n”);

~ 50 ~
Queue:
Queue is an abstract data structure, somewhat similar
to stacks. Unlike stacks, a queue is open at both its
ends. One end is always use to insert data and the
other is used to remove data. Queue follows First-in-
First-out methodology(FIFO), i.e., the data item
stored first will be accessed first.

A real-world example of queue can be a single-lane


one-way road, where the vehicle enters first, exits
first. More real-world examples can be seen as queues
at the ticket windows of bus-stops and others.

Basic Operations:
Queue operations may involve initializing or defining
the queue, utilizing it, and then completely erasing
it from the memory. Here we shall try to understand
the basic operations associated with queues −
enqueue() − add (store) an item to the queue.
dequeue() − remove (access) an item from the
queue.
Few more functions are required to make the above-
mentioned queue operation efficient. These are −
peek() − Gets the element at the front of the
queue without removing it.
isfull() − Checks if the queue is full.
isempty() − Checks if the queue is empty.

~ 51 ~
In queue, we always dequeue (or access) data, pointed
by front pointer and while enqueing (or storing) data
in the queue we take help of rear pointer.
Let's first learn about supportive functions of a
queue −

peek():

This function helps to see the data at the front of


the queue. The algorithm of peek() function is as
follows −
Algorithm
begin procedure peek
return queue[front]
end procedure

isfull():

As we are using single dimension array to implement


queue, we just check for the rear pointer to reach at
MAXSIZE to determine that the queue is full. In case
we maintain the queue in a circular linked-list, the
algorithm will differ. Algorithm of isfull()
function:
Algorithm:
begin procedure isfull

if rear equals to MAXSIZE


return true
else
return false
endif

end procedure

~ 52 ~
Implementation of isfull() function in C programming
language:
Example:
bool isfull() {
if(rear == MAXSIZE - 1)
return true;
else
return false;
}

isempty()

Algorithm of isempty() function −


Algorithm:
begin procedure isempty

if front is less than MIN OR front is greater


than rear
return true
else
return false
endif

end procedure
If the value of front is less than MIN or 0, it tells
that the queue is not yet initialized, hence empty.
Here's the C programming code −
Example:
bool isempty() {
if(front < 0 || front > rear)
return true;
else
return false;
}

Enqueue Operation:

~ 53 ~
Queues maintain two data pointers, front and rear.
Therefore, its operations are comparatively difficult
to implement than that of stacks.
The following steps should be taken to enqueue
(insert) data into a queue −
 Step 1 − Check if the queue is full.
 Step 2 − If the queue is full, produce overflow
error and exit.
 Step 3 − If the queue is not full,
increment rear pointer to point the next empty
space.
 Step 4 − Add data element to the queue location,
where the rear is pointing.
 Step 5 − return success.

Sometimes, we also check to see if a queue is


initialized or not, to handle any unforeseen
situations.

~ 54 ~
Algorithm for enqueue operation:

procedure enqueue(data)

if queue is full
return overflow
endif

rear ← rear + 1
queue[rear] ← data
return true

end procedure
Implementation of enqueue() in C programming
language:
Example:
int enqueue(int data)
if(isfull())
return 0;

rear = rear + 1;
queue[rear] = data;

return 1;
end procedure

Dequeue Operation:
Accessing data from the queue is a process of two
tasks − access the data where front is pointing and

~ 55 ~
remove the data after access. The following steps are
taken to perform dequeue operation −
 Step 1 − Check if the queue is empty.
 Step 2 − If the queue is empty, produce underflow
error and exit.
 Step 3 − If the queue is not empty, access the
data where front is pointing.
 Step 4 − Increment front pointer to point to the
next available data element.
 Step 5 − Return success.

Algorithm for dequeue operation:

procedure dequeue

~ 56 ~
if queue is empty
return underflow
end if

data = queue[front]
front ← front + 1
return true

end procedure

Implementation of dequeue() in C programming


language:
Example:
int dequeue() {
if(isempty())
return 0;

int data = queue[front];


front = front + 1;

return data;
}

Linked List
~ 57 ~
Linked list:
Linked list is a linear data structure
that contains sequence of elements such that each
element links to its next element in the sequence.
Each element in a linked list is called as “Node”.

Node- Each node contains data item and a pointer


which is address of next node in list.

Next- A pointer field which contains address of next


node in list.

Linked list presentation:

Types of linked list:


Following are the various types of
linked list-

1. Singly linked list-

~ 58 ~
Item navigation is forward only.

2. Doubly linked list-

Items can be navigated forward and


backward.

3. Circular linked list-

Last item contains link of the


first element as next and the first element has a
link to the last element as previous.

Advantages of linked list:


Following are the advantages of
linked list-

a. Linked list is a Dynamic data structure.

b. Linked list can grow and shrink during run time.

c. Insertion and deletion operations are easier.

d. Efficient memory utilization, i.e., no need to


pre-allocate memory.

e. Faster access time can be expanded in constant


time without memory overhead.

f. Linear data structures such as stack, queue can be


easily implemented using linked list.

Disadvantages of linked list:


a. Memory wastage if required space is known.

b. Searching operations is difficult.

~ 59 ~
Basic operations on linked list:
1. Insertion-

Adds an element at the beginning of


the list.

2. Deletion-

Deletes an element at the beginning


of the list.

3. Display-

Displays the complete list.

4. Search-

Searches an element using the given


key.

Program of linked list:


#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

~ 60 ~
struct node

int num;

struct node * next ptr;

}*stnode;

void create(int n);

void display();

void main()
{

int n;

clrscr();

printf(“Input the number of nodes:-“);

scanf(“%d”,&n);

create(n);

printf(“\n Data entered in the list:-\n”);

display();

void create(int n)

struct node*fnode,*tmp;

int num,i;

stnode=(struct node*)malloc(size of(struct node));

if(stnode==NULL)

printf(“Memory cannot be allocated”);

~ 61 ~
}

else

printf(“Input data for node 1:-“);

scanf(“%d”,&num);

stnode num=num;

stnode nextptr=NULL;

tmp=stnode;

for(i=2;i<n;i++)

fnode=(struct node*)malloc(size of(struct node));

if(fnode==NULL)

printf(“Memory cannot be allocated”);

break;

else

printf(“Input data for node %d:-“,i);

scanf(“%d”,&num);

fnode num=num;

fnode=nextptr=NULL;

tmp=nextptr=fnode;

tmp=tmp=nextptr;

~ 62 ~
}

void display()

struct node*tmp;

if(stnode==NULL)

printf(“List is empty”);

else

tmp=stnode;

while(tmp!=NULL)

printf(“Data=%d\n”,tmp=num);

tmp=tmp=nextptr;

}
}

Beginning with ‘C++’

~ 63 ~
A C++ program contains four sections – include files,
class declaration, member function definition, main
function. These sections may be placed in different
source files and then compiled independently or
jointly.

Characteristics:
1. Like C, the C++ program is a collection of
functions.

2.Every C++ program must have a main function.

3.Like C, the C++ statements terminate with


semicolon(;)

C++ program to find simple interest:


#include<iostream.h>

#include<conio.h>

void main()

~ 64 ~
{

clrscr();

int p,r,t,si=0;

cout<<”Enter principle:-“;

cin>>p;

cout<<”Enter rate:-“;

cin>>r;

cout<<”Enter time:-“;

cin>>t;

si=(p*r*t)/100;

cout<<”Simple interest is:-“<<si;

getch();

Structure:
A structure is a group of basic data types and
other data types.

SYNTAX-

~ 65 ~
struct name_of_structure

Data_type member1;

Data_type member2;

----------

----------

};

Union:
Union is similar to structure but the size of
union type is equal to the size of its largest
member’s type. In union, all the members have a same
memory space.

‘Union’ keyword is used to define a union.

SYNTAX-

union item

Int m;

Float x;

Char c;

}item 1;

Implicit type conversion:


This type of
conversion is performed by the compiler with
programmer intermission. An implicit conversion is

~ 66 ~
applied generally whenever different data types are
intermixed so as not to lose information.

Example:
If a=7(int) & b=9.5(floating point) then the
value of expression is-

2*a+b will be 23.5000

Program:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a=7,b=8;
float x, y=7.5;
x=a+y;
cout<<"x=%f"<<x;
x=(float)a/b;
cout<<"\nx=%f"<<x;
getch();
}

Explicit type conversion:


An explicit type of conversion is
user-defined that forces an expression to be
specified type.

Program:
#include<iostream.h>
#include<conio.h>
void main()
{

~ 67 ~
clrscr();
int i=5;
float f=30.57;
cout<<"i="<<i;
cout<<"\n f="<<f;
cout<<"\n float(i)="<<float(i);
cout<<"\n int(f)="<<int(f);
getch();
}

Operators, Expressions and


Control Structures
~ 68 ~
All operators in ‘C’ are also valid in ‘C++’. In
addition, ‘C++’ introduces some new operators. They
are as following:-

<< INSERTION OPERATOR:


It prints the contents of the variable on its right
to the output screen.

>> DELETION OPERATOR:


It takes the value from the keyboard and assign it to
the variable on its right.

:: SCOPE RESOLUTION OPERATOR:


‘C++’ is a block-structured language. Same variable
name can be used in different blocks. The scope
resolution operator is used to access global version
of a variable.

PROGRAM:

#include<iostream.h>

#include<conio.h>

int x=10;

~ 69 ~
void main()
{

int x=20;

cout<<”Inner block\n”;

int x=30;

cout<<”x=”<<x<<”\n”;

Cout<<”::x=”<<::x<<”\n”;

cout<<”Outer block\n”;

cout<<”x=”<<x<<”\n”;

cout<<”::x=”<<::x<<”\n”;

getch();

Control structures:
There are three types of control structures-

1. Sequence structure:
Statements are executed sequentially as they are
written in program.

~ 70 ~
EXAMPLE:
--------

Statement1;

Statement2;

Statement3;

--------

Program:
#include<iostream.h>

#include<conio.h>

void main()

clrscr();

int l, b, area=0;

cout<<”Enter length:-“;

cin>>l;

cout<<”Enter breadth:-“;

cin>>b;

area=l*b;

cout<<”Area of rectangle is:-“<<area;

getch();

2. Selection structure:
Two or more paths of execution
out of which one is selected based on a condition.

The following types of selection statements are:

1. Simple if statement

~ 71 ~
2. If-else statement
3. Nested if-else statement
4. Else-if stairs
5. Switch statement

1.Simple if statement:
In this statement, condition is checked first, if it
is true then it will executes statement group
otherwise not. Statements group can be one or more
than one statements.

SYNTAX:

if(condition)

Statement

Program:

/*Program to find whether the number is even or not*/


#include<stdio.h>
#include<conio.h>
void main()

~ 72 ~
{
int n;
clrscr();
printf("Enter number:");
scanf("%d",&n);
if(n%2==0)
printf("It is an even number.");
getch();
}

Output:
Enter number:16
It is an even number.

~ 73 ~
2. if-else statement:
This statement tests a condition, if the condition is
true, then first group of statement executes and if
false then second group executes.

SYNTAX:

if(condition)

Set of statement 1

else

Set of statement 2

~ 74 ~
Program:

/*Program to find greater between two numbers*/


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter first number:");
scanf("%d",&a);
printf("Enter second number:");
scanf("%d",&b);
if(a>b)
printf("First number is greater.");
else
printf("Second number is greater.");
getch();
}

Output:
Enter first number:45
Enter second number:55
Second number is greater

~ 75 ~
3.Nested if-else statement:
When a if-else statement is written in another if-
else, then it is called as nested if-else statement.

SYNTAX:

if(condition 1)

if(condition 2)

Statement 1

else

Statement 2

else

Statement 3

else

Statement 4

~ 76 ~
Program:

/*Program to compare two numbers*/


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter first number:");
scanf("%d",&a);
printf("Enter second number:");
scanf("%d",&b);
if(a>b)
printf("First number is greater");
if(a==b)
printf("First number is equal to the second");
else
printf(" second number is greater");
getch();
}

Output:
Enter first number:46
Enter second number:46
First number is equal to the second

~ 77 ~
4.Statement else-if stairs:
These if statement are used to multipurpose
statements. This statement is used when condition is
to be written result of one by one.

SYNTAX:

if(condition 1)

Statement 1

else if(condition 2)

Statement 2

else if(condition 3)

Statement 3

else

Statement 4

~ 78 ~
Program:
/*Program to print result of a student*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,sum=0;
float per;
clrscr();
printf("Marks in English:");
scanf("%d",&a);
printf("Marks in Maths:");
scanf("%d",&b);
printf("Marks in Science:");
scanf("%d",&c);
sum=a+b+c;
printf("Total:%d\n",sum);
per=(sum*100)/300;
printf("Percentage:%f\n",per);
if(per>=60)
printf("Result: First Division");
else if(per>=40)
printf("Result: Second Division");
else if(per>=36)
printf("Result: Third Division");
else
printf("Result: Fail");
getch();
}

Output:

Marks in English:89

Marks in Maths:91

Marks in Science:87

Total:267

Percentage:89.00

Result: First Division

~ 79 ~
5.Switch statement:
Switch case can be used to select one option among
multiple options. It also included a condition like
if-else. Switch statement executes various statements
according to the value of expression or variable. But
value of variable or expression should be an integer
or constant.

SYNTAX:

switch(variable o expression)

case value 1:no. of statements;

break;

case value 2:no. of statements;

break;

case value 3:no. of statements;

break;

case value n:no. of statements;

break;

default : no. of statements;

~ 80 ~
Program:
/*Program to print name of the day according to the
given number from 1to 7*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter any number from 1 to 7:-");
scanf("%d",&n);
switch (n)
{
case 1:printf("Monday");
break;
case 2:printf("Tuesday");
break;
case 3:printf("Wednesday");
break;
case 4:printf("Thursday");
break;
case 5:printf("Friday");
break;
case 6:printf("Saturday");
break;
case 7:printf("Sunday");
default:printf("ERROR");
}
getch();
}

Output:
Enter any number from 1 to 7:-3

Wednesday

~ 81 ~
3. Loop structure:
Looping statements checked the
condition and if it is true than loop will executed
otherwise control will come out from loop.

 for loop
 while loop
 do-while loop
 Nested loop

~ 82 ~
for loop:
In this loop, if the condition is true then loop will
execute else not.

SYNTAX:

for(exp 1;exp 2;exp 3)

Looping body

Where; exp 1:tells the initial value of counter


variable and it is executed only once.

exp 2: It is a condition expression, if it is true


then loop will execute.

Exp 3: It is used to increase or decrease the value


of counter variable.

~ 83 ~
Program:
/*Program to print your name 10 times*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=0;i<=9;i++)
printf("My name is Vidhi\n");
getch();
}

Output:
My name is Vidhi

My name is Vidhi

My name is Vidhi

My name is Vidhi

My name is Vidhi

My name is Vidhi

My name is Vidhi

My name is Vidhi

My name is Vidhi

My name is Vidhi

~ 84 ~
while loop:
While loop is entry controlled loop. It is used when
we don’t know how many times a loop is to be
executed. Until the condition is true it will execute
otherwise the loop execution will be stopped.

SYNTAX:

while (condition)

Looping body

~ 85 ~
Program:
/*Program to print numbers from 1 to 10*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
printf("%d\n",i);
i++;
}
getch();
}

Output:
1

10

~ 86 ~
do-while loop:
It is a exit controlled loop. In this loop, first the
loop body will be executed and then the condition
will be checked, it means this loop will execute at
least one time. This loop will be executed until the
condition is true otherwise it will be terminated.

SYNTAX:

do

Loop body

while (condition);

~ 87 ~
Program:

/*Program to print all even numbers between 50 to


60*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=50;
clrscr();
do
{
printf("%d\n",i);
i+=2;
}
while(i<=60);
getch();
}

OUTPUT:
50

52

54

56

58

60

~ 88 ~
Nested Loop:
A loop may contain another loop in its body. This
form of a loop is called nested loop. But in a nested
loop, the inner loop must terminate before the outer
loop.

SYNTAX:

for (condition)

for (condition)

~ 89 ~
Program:
/*Program to print tables of 1 to 10*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=10;i++)
{
j=1;
while(j<=10)
{
printf("%d\t",i*j);
j++;
}
printf("\n");
}
getch();
}

OUTPUT:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

~ 90 ~
Functions in ‘C++’
Function:
A function is a self-contained
program segment that is used for some specific well
defined task.

Call by reference:
#include<iostream.h>

#include<conio.h>

void main()

clrscr();

int count=0;

void update(int &);

cout<<”count=”<<count<<”\n”;

update(count);

cout<<”count=”<<count;

getch();

void update(int &x)

x=x+1;

~ 91 ~
Return by reference:
A function can also return a
reference.

Program:
#include<iostream.h>

#include<conio.h>

void main()

int x=6, y=9;

int & min(int &, int &);

min(x,y)=-1;

cout<<”x=”<<x<<”\n”;

cout<<”y=”<<y;

getch();

int & min(int &a, int &b)

if(a<b)

return a;

else

return b;

~ 92 ~
Function overloading:

#include<iostream.h>

#include<conio.h>

int sum(int,int);

int sum(int,int,int);

void main()

cout<<”Sum of two numbers is”<<sum(5,10);

cout<<”\n”;

cout<<”Sum of three numbers is”<<sum(10,20,30);

getch();

int sum(int x,int y)

return(x+y);

int sum(int a, int b, int c)

return(a+b+c);

~ 93 ~
Classes and Objects
Class:
A class is a user defined data type that
binds data and function together. The class
declaration includes the declaration of its data
members and member function.

SYNTAX-

class class_name

private:

variable function;

function declaration ;

public:

variable function;

function declaration;

};

EXAMPLE-

Inside the class:


#include<iostream.h>

#include<conio.h>

class point

int x,y;

~ 94 ~
public:

void input(int a, int b)

x=a;

y=b;

void output(void)

cout<<”x=”<<x<<”\n”;

cout<<”y=”<<y;

};

void main()

clrscr();

point p;

int a,b;

cout<<”enter first value:-“<<endl;

cin>>A;

cout<<”enter second value:-“<<endl;

cin>>b;

p.input(a,b);

p.output();

getch();

~ 95 ~
Inside the class:
The function declaration is replaced
by the actual definition of the member function
inside the class. The function defined inside the
class are treated as an inline function.

EXAMPLE-

#include<iostream.h>

#include<conio.h>

class point

int x,y;

public:

void input(int a, int b)

x=a;

y=b;

void output()

cout<<”x=”<<x<<”\n”;

cout<<”y=”<<y;

};

void main()

clrscr();

~ 96 ~
point p;

p.input(2,4);

p.output();

getch();

Outside the class:


#include<iostream.h>

#include<conio.h>

class point

int x,y;

public:

void input(inta, int b);

void output();

};

void point::input( int a, int b)

x=a;

y=b;

void point::output()

cout<<”x=”<<x<<”\n”;

~ 97 ~
cout<<”y=”<<y;

void main()

clrscr();

point p;

p.input(5,10);

p.output();

getch();

~ 98 ~
ARRAYS WITHIN CLASS:
Program:
#include<iostream.h>
#include<conio.h>
class data
{
int a[5];
public:
void getdata();
void showdata();
};
void data::getdata();
{
int i;
cout<<"Enter array elements:-\n";
for(i=0;i<5;i++)
{
cin<<a[i];
}
}
void data::showdata();
{
int i;
cout<<"Array elements are:-\n";
for(i=0;i<5;i++)
{
cin>>a[i]<<"\t";
}
}
void main()
{
clrscr();
data d;
d.getdata();
d.showdata();
getch();
}

~ 99 ~
STATIC DATA MEMBER:
The data members of a class
can be declared as a static. The characteristics of
static data members are:-

 Its initial value is set to zero, when first


object of its class is created.
 Only single copy of the data member is created
and it is shared by all the objects of the
class.
 Since it is associated with the entire class,
it is also called class variables.

~ 100 ~
Program:
#include<iostream.h>
#include<conio.h>
class test
{
static int x;
int y;
public:
void getdata(int a);
{
y=a;
x++;
}
void show_x();
{
cout<<"x="<<x<<endl;
}
};
int test::x;
void main()
{
clrscr();
test t;
t1.show_x();
t2.show_x();
t1.getdata(10);
t2.getdata(20);
cout<<"After reading data";
t1.show_x();
t2.show_x();
getch();
}

~ 101 ~
Static member function:
A member function declared
with static is called static member function. The
properties of static member functions are:-

 It can access only other static data members and


member functions in the same class.
 They are invoked using the class name.

Program:
#include<iostream.h>
#include<conio.h>
class test
{
static int x;
int y;
public:
void getdata(int a);
{
y=a;
x++;
}
void show_x();
{
cout<<"x="<<x<<endl;
}
};
int test::x;
void main()
{
clrscr();
test t;
t1.show_x();
t2.show_x();
t1.getdata(10);
t2.getdata(20);
cout<<"After reading data";
t1.show_x();
t2.show_x();
getch();
}

~ 102 ~
Friend function: Friend function can be a friend of
some another class. A friend function can access the
private data of a class through the object of that
class. The function is declared with keyword friend.
A friend function has following characteristics:

 It is invoked like a normal function, not with


the any object of the class.
 It can only access the members of the class by
using the object of that class.
 It can be declared anywhere in the class.
 Generally, it has objects as arguments.

Program:
#include<iostream.h>

#include<conio.h>
class new
{
int x,y;
public:
void getdata(int a, int b)
{
x=a;
y=b;
}
friend int sum(new n);
};
int sum(new n)
{
return(n.x+n.y);
}
void main()
{
clrscr():
new e;
e.getdata(5,5);
cout<<"sum="<<new(e);
getch();
}

~ 103 ~
Friend function:
A member function of a class can be
friend function of another class. If all the member
function of one class are declared as friend
functions in another class, then the class is called
friend class.

Program:
#include<iostream.h>

#include<conio.h>

class second;

class first

int x;

public:

void set_value(int a)

x=a;

friend void max(first,second);

};

class second

int y;

public:

void set_value(int b)

~ 104 ~
y=b;

friend void max(first,second);

};

void max(first f, second s)

if(f.x>s.y)

cout<<”Maximum is”<<f.x;

else

cout<<”Maximum is”<<s.y;

void main()

clrscr();

first a;

second b;

a.set_value(10);

b.set_value(20);

max(a,b);

getch();

~ 105 ~
Constructors and Destructors
Constructors:
A constructor is a special member
function of the class that is used to initialize the
objects of its class. It is called automatically when
the objects of its class are created.

Parameterized constructor:
The constructors that
receive arguments are called parameterized
constructors.

EXAMPLE-

#include<iostream.h>

#include<conio.h>

class point

int x,y;

public:

point(int a , int b);

};

point::point(int a, int b)

x=a;

y=b;

cout<<”value of x is:-“<<x<<endl;

~ 106 ~
cout<<”value of y is:-“<<y;

void main()

clrscr();

point p(10,20);

getch();

~ 107 ~
Multiple constructors:
A class can have more
than one constructors and it is called constructor
overloading.

PROGRAM-

#include<iostream.h>

#include<conio.h>

class point

int x,y;

public:

point()

x=0;

y=0;

point (int a)

x=y=a;

point(int m, int n)

x=m;

y=n;

~ 108 ~
void show()

cout<<”x=”<<x<<endl;

cout<<”y=”<<y;

};

void main()

clrscr();

point p1;

point P2(5);

point p3(7,11);

cout<<”coordinates of p1 are:-\n”);

p1.show();

cout<<”coordinates of p2 are:-\n”);

p2.show();

cout<<”coordinates of p3 are:-\n”);

p3.show();

getch();

~ 109 ~
Constructor with default arguments:
The constructor can take default arguments.

PROGRAM-

#include<iostream.h>

#include<conio.h>

class point

int x,y;

public:

point();

};

point::point()

x=0;

y=0;

cout<<”value of x is:-“<<x;

cout<<endl;

cout<<”value of y is:-“<<y;

void main()

clrscr();

point p;

getch();

~ 110 ~
Copy constructor:
A constructor that is used
to declare and initialize object from another object
of the same class is known as copy constructor.

EXAMPLE-

#include<iostream.h>

#include<conio.h>

class product

int code;

public:

product(){}

product(int x)

code=x;

product(product &y)

code=y.code;

void display()

cout<<code;

void main()

~ 111 ~
{

clrscr();

product p1(10);

product p2(P1);

product p3=p1;

cout<<”code of p1:-“;

p1.display();

cout<<”\n code of p2:-”);

p2.display();

cout<<”\n code of p3:-”);

p3.display();

getch();

~ 112 ~
Destructors:

A special member function of the class that is used


to destroy the objects that have been created by
constructor.

Special characteristics of destructors:

1. Its name is same as class name but preceeded by


tilde(~).

2. It never takes any argument and does not return


any value.

3. It is invoked implicitly by the compiler upon exit


from the program or block or function.

~ 113 ~
Operator Overloading

Operator overloading:
The mechanism of giving
special meanings to an operator for a data type is
known as operator overloading.

Overloading unary operators using member


function:
#include<iostream.h>

#include<conio.h>

class point

int x,y;

public:

void getdata( int a, int b)

x=a;

y=b;

void show()

cout<<”x=”<<x<<endl;

cout<<”y=”<<y;

~ 114 ~
void operator++(int)

x++;

y++;

};

void main()

clrscr();

point p;

p.getdata(5,8);

cout<<”p:-“;

p.show();

p++;

cout<<”p++:-“;

p.show();

getch();

~ 115 ~
Overloading unary operator using friend
function:
#include<iostream.h>

#include<conio.h>

class point

int x,y;

public:

void getdata(int a, int b)

x=a;

y=b;

void show()

cout<<”x=”<<x<<endl;

cout<<”y=”<<x;

friend void operator—(point &s)

s.x=s.x-1;

s.y=s.y-1;

};

void main()

~ 116 ~
{

clrscr();

point p;

p.getdata(7,10);

cout<<”p:-“;

p.show();

--p;

cout<<”--p:-“;

p.show();

getch();
}

Overloading binary operators using member


function:
#include<iostream.h>

#include<conio.h>

class matrix

int mat[2][2];

public:

void getmatrix();

matrix operator+(matrix);

void showmatrix():

};

void matrix::getmatrix()
{

~ 117 ~
for(i=0;i<2;i++)

for(j=0;j<2;j++)

cout<<”enter the number:-“;

cin>>mat[i][j];

matrix matrix::operator+(matrix m)

matrix temp;

for(i=0;i<2;i++)

for(j=0;j<2;j++)

temp.mat[i][j]=mat[i][j]+m.mat[i][j];

return temp;

void matrix::showmatrix()

for(i=0;i<2;i++)

for(j=0;j<2;j++)

cout<<mat[i][[j]<<”\t”;

cout<<”\n”;

void main()

~ 118 ~
{
matrix m1,m2,m3;

m1.getmatrix();

m2.getmatrix();

m3=m1+m2;

cout<<”matrix m1:-\n”);

m1.showmatrix();

cout<<”matrix m2:-\n”);

m2.showmatrix();

cout<<”resultant matrix:-\n”);

m3.showmatrix();

getch();

Overloading binary operators using friend


function:
#include<iostream.h>

#include<conio.h>

class complex

float real;

float imag;

public:

void input(float x, float y)

real=x;

imag=y;

~ 119 ~
}

friend complex operator+(complex a, complex b)

complex c;

c.real=a.real+b.real;

c.imag=a.imag+b.imag;

return c;

void show()

cout<<real<”+i<<imag<<”\n”;

};

void main()

complex c1,c2,c3;

c1.input(1.6,6.2);

c2.input(2.3,3.4);

c3=c1+c2;

cout<<”c1=”;

c1.show();

cout<<”c2=”;

c2.show();

cout<<”c3=”;

c3.show();

getch();

~ 120 ~
Inheritance
Introduction:
The existing classes are used to
create new classes, this mechanism is called
inheritance. The existing class is called base class
or parent class or super class and the new class is
called derived class or subclass.

Single inheritance:
#include<iostream.h>

#include<conio.h>

class data

protected:

int x,y;

public:

void getdata(int a, int b)

x=a;

y=b;

void showdata()

cout<<”x=”<<x<<”\n”;

~ 121 ~
cout<<”y=”<<y<<”\n”;

};

class maximum :public data

public:

void max()

{
if(x>y)
cout<<”maximum is:-“<<x;

else

cout<<”maximum is:-<<y;

};

void main()

clrscr();

maximum m;

m.getdata(4,9);

m.showdata();

m.max();

getch();

~ 122 ~
Multilevel inheritance:
#include<iostream.h>

#include<conio.h>

class data1

protected:

int x;

public:

void get_x(int a)

x=a;

void show_x()

cout<<”x=”<<x<<”\n”;

};

class data2:public data1

{
protected:

int y;

public:

void get_y(int b)

y=b;

~ 123 ~
}

void show_y()

cout<<”y=”<<y<<”\n”;

};

class addition: public data2

int z;

public:

void sum()

z=x+y;

void show_z()

cout<<”z=”<<z<<”\n”;

};

void main()
{

clrscr();

addition a;

a.get_x(4);

a.get_y(7);

~ 124 ~
a.sum();

a.show_x();

a.show_y();

a.show_z();

getch();

~ 125 ~
Multiple inheritance:
#include<iostream.h>

#include<conio.h>

class b1

protected:

int x;

public:

void get_x(int a)

x=a;

};

class b2

protected:

int y;

public:

void get_y(int b)

y=b;

};

class d: public b1,public b2

~ 126 ~
int z;

public:

void multiply()

z=x*y;

void display()

cout<<”x=”<<x<<”\n”;

cout<<”y=”<<y<<”\n”;

cout<<”z=”<<z<<”\n”;

};

void main()

clrscr();

d d;

d.get_x(5);

d.get_y(3);

d.multiply();

d.display();

getch();

~ 127 ~
DBMS Concepts
A database is an organized collection of data,
generally stored and accessed electronically from a
computer system. Where databases are more complex
they are often developed using formal design and
modeling techniques.
The database management system (DBMS) is
the software that interacts with end users,
applications, and the database itself to capture and
analyze the data. The DBMS software additionally
encompasses the core facilities provided to
administer the database. The sum total of the
database, the DBMS and the associated applications
can be referred to as a "database system". Often the
term "database" is also used to loosely refer to any
of the DBMS, the database system or an application
associated with the database.
Computer scientists may classify database-management
systems according to the database models that they
support. Relational databases became dominant in the
1980s. These model data as rows and columns in a
series of tables, and the vast majority use SQL for
writing and querying data. In the 2000s, non-
relational databases became popular, referred to
as NoSQL because they use different query languages.

~ 128 ~
Relational Database:
A relational database is a set of formally
described tables from which data can be accessed or
reassembled in many different ways without having to
reorganize the database tables. The standard user and
application programming interface (API) of a
relational database is the Structured Query
Language (SQL). SQL statements are used both for
interactive queries for information from a relational
database and for gathering data for reports.

SQL:
Structured Query Language or SQL is a standard
Database language which is used to create, maintain
and retrieve the data from relational databases like
MySQL, Oracle, SQL Server, PostGre, etc. The recent
ISO standard version of SQL is SQL:2019.
As the name suggests, it is used when we have
structured data (in the form of tables). All
databases that are not relational (or do not use
fixed structure tables to store data) and therefore
do not use SQL, are called NoSQL databases. Examples
of NoSQL are MongoDB, DynamoDB, Cassandra, etc

~ 129 ~
Creating Database:
mysql>create database 123;
query ok, 1 row affected(0,01 sec)

mysql>use 123;
database changed
mysql>create table student

 (sId int,
 sName varchar(20),
 sAddress varchar(20),
 sDOB date,
 sCity varchar(20));
query ok, 0 rows affected(0.12 sec)

mysql>describe student;
Field Type Null Key Default Extra
sId Int Yes Null
sName Varchar(20) Yes Null
sAddress Varchar(20) Yes Null
sDOB Date Yes Null
sCity Varchar(20) Yes Null
5 rows in set(0.10 sec)

mysql> insert into student

 values(12345,’pranav’,’ram vihar’,’1-1-
2001’,’jodhpur’);
query ok, 1 row affected(0.06 sec)

mysql>insert into student

 values(12346,’riya’,shanti nagar’,’2-2-
2002’,’jaipur’);

~ 130 ~
query ok, 1 row affected(0.06 sec)

mysql>insert into student

 values(12347,’raman’,’shastri nagar’,’3-3-
2003’,’udaipur’);
query ok, 1 row affected(0.06 sec)

mysql>insert into student

 values(12348,’seema’,’vidhya nagar’,’4-4-
2004’,’alwar’);
query ok, 1 row affected(0.06 sec)

mysql>insert into student

 values(12349,’shayam’,’chaura rasta’,’5-5-
2000’,’puna’);

mysql>select * from student;


sId sName sAddress sDOB sCity
12345 pranav Jhotwara 1-1-2001 Jodhpur
12346 Riya Chandpol 2-2-2002 Jaipur
12347 Raman Mansarover 3-3-2003 Udaipur
12348 Seema Eidgah 4-4-2004 Alwar
12349 Shayam Chaurarasta 5-5-2000 Puna

5 rows in set(0.10 sec)

 Query 4. Change the city name of the student whose


name is raman

~ 131 ~
mysql>update student
set sCity=madhopur
where sName like ‘raman’;

sId sName sAddress sDOB sCity

12347 Raman mansarover 3-3-2003 madhopur

 Query 5. Delete the record of the riya mysql>delete


from student
where sName like ‘riya’;
Query ok, 1 row affected (0.02 sec)
sId sName sAddress sDOB sCity
12345 Pranav Jhotwara 1-1-2001 Jodhpur
12347 Raman Mansarover 3-3-2003 Madhopur
12348 Seema Eidgha 4-4-2004 Alwar
12349 Shayam Chaura rasta 5-5-2000 Puna

 Query 6. Arrange all records in decending order


mysql>select * from student
 order by sName desc;
sId sName sAddress sDOB sCity
12349 Shayam Chaura rasta 5-5-2000 Puna

12348 Seema Eidgha 4-4-2004 Alwar

~ 132 ~
12347 Raman mansarover 3-3-2003 madhopur

12345 Paranav jhotwara 1-1-2001 jodhpur

 Query 7. Display name of student whose second


letter of name is A
mysql>select sName from student
where sName like ‘_r%’

sName

Pranav

 Query 8. Display name of student whose name ends


with an
mysql>select sName from student
where sName like ‘%an’

sName

Raman

 Query 9. Count number of record in the table


student
mysql>select count(*)from student

Count(*)

~ 133 ~
~ 134 ~

You might also like