Problem Solving & Programming Notes - Unit - IV
Problem Solving & Programming Notes - Unit - IV
Problem Solving & Programming Notes - Unit - IV
ON
COMPUTER PROGRAMMING
I B.TECH I SEMESTER
Regulation: R20
(2020 – 2021)
Problem Solving & Programming
UNIT – IV
Learning Outcomes:
At the end of unit, students will be able to
1. Apply String manipulation functions.
2. Structure the individual date elements to simplify the solutions.
3. Organize homogenous data.
4. Facilitate efficient memory utilization.
ARRAYS
Introduction:
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type, hence an array is also
defined as homogeneous collection of elements.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers. A specific element in an array is
accessed by an index or subscript. An array index starts from 0(zero) by default.
All array elements consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
Types of Arrays:
Arrays are classified into two types based on their subscripts.
1. One-Dimensional Arrays
2. Multi-Dimensional Arrays
Ex:
25
32
45 25 32 45 56 87 95 67
56
Horizantal List of 7 elements
87
95
67
Since the elements of an array are arranged in only one dimension i.e; towards either x-
dimension or y-dimension, hence they are called as one-dimensional arrays.
The fundamental data types like int, float and char have a fact that a variable of these types
can store or hold only one value at any given time. Hence to use another value we need to
declare another new variable. It means for n values we need to declare ‘n’ different variables.
For example, to store marks of 6 subjects, it is required to declare 6 different variables as
follows:
int t, h, e, m, sc, so;
So, if we need to store a large volume of data in terms of reading, processing and printing, it is
not possible with an ordinary variable. Hence C supports a powerful data type called Array. It
is used to store more than one data value under a single name.
For example, to store marks of 6 subjects, declare an integer array called marks of size 6 as
follows:
int marks[6];
Declaration of an Array:
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows –
Syntax:
This is called a single-dimensional array. The array_size must be an integer constant greater
than zero and type can be any valid C data type.
Example:
To declare a 10-element array called price of type float, use this statement
float price[10];
To declare a 6-element array called marks of type int, use this statement
int marks[6];
Example:
Assume an array that stores marks of 6 subjects.
We can initialize an array in C either one by one or using a single statement.
Ex:
marks[0] = 75;
marks[1] = 95;
marks[2] = 85;
OR marks[6] = {75, 95, 85, 68, 74, 46};
marks[3] = 68;
marks[4] = 74;
marks[5] = 46;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 4
Problem Solving & Programming
The number of values between braces { } cannot be larger than the size of an array.
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
will creates exactly the same array as you did in the previous example.
int ages[10];
OR
OR
To read elements to an array, looping statement is used to change the index of the element,
since all the elements will differ by its index only.
Ex:
int ages[10], in;
for(in=0; in<10; in++)
{
scanf(“%d”, &ages[in]);
}
To print or display elements of an array, looping statement is used to change the index of the
element, since all the elements will differ by its index only.
The way we use to read the elements to an array is similar to that of printing an array.
Ex:
int ages[10], in;
for(in=0; in<10; in++)
{
printf(“%d \t”, ages[in]);
}
Element 25 37 48 85 56 98
Program:
Write a C program to illustrate the declaration and initialization of an array.
Source Code:
#include<stdio.h>
void main( )
{
int arr[6], i;
printf(“Enter array elements one by one:”);
for(i=0; i<6; i++)
{
scanf(“%d”, &arr[i]);
}
printf(“\n The array elements are:\n”);
for(i=0;i<6;i++)
{
printf(“arr[%d] = %d \n”, i, arr[i]);
}
Output:
Enter array elements one by one: 26
38
49
87
96
256
The array elements are:
arr[0] = 26
arr[1] = 38
arr[2] = 49
arr[3] = 87
arr[4] = 96
arr[5] = 256
Program:
Write a C program to find the sum of all array elements.
Source Code:
/* C Program to find sum of all array elements */
#include <stdio.h>
#define MAX 100
void main( )
{
int arr[MAX], N, i, sum = 0;
printf("Enter Number of Elements in Array:");
scanf("%d", &N);
printf("Enter %d numbers one by one:", N);
for(i = 0; i < N; i++) /* Read array elements */
{
scanf("%d", &arr[i]);
}
for(i = 0; i < N; i++) /* Add array elements */
{
sum = sum + arr[i];
}
printf("Sum of all Array Elements : %d", sum);
}
Output:
Enter Number of Elements in Array: 5
Enter 5 numbers one by one: 25
15
10
98
64
Sum of all Array Elements: 212
Program:
Write a C program to find the maximum and minimum element of an array.
Source Code:
#include <stdio.h>
#define SIZE 100
void main( )
{
int arr[SIZE], N, max, min, i;
printf("Enter Number of Elements in Array:");
scanf("%d", &N);
printf("Enter %d numbers one by one:", N);
for(i = 0; i < N; i++) /* Read array elements */
{
scanf("%d", &arr[i]);
}
max = min = arr[0];
for(i = 1; i < N; i++) /* find max and min of an array */
{
if(arr[i] > max)
max = arr[i];
if(arr[i] < max)
min = arr[i];
}
printf("Maximum element of an array : %d", max);
printf("Minimum element of an array : %d", min);
}
Output:
Enter Number of Elements in Array: 5
Enter 5 numbers one by one: 156
24
31
12
10
Maximum element of an array: 156
Minimum element of an array: 10
Program:
Write a C program to reverse an array.
Source Code:
#include <stdio.h>
#define SIZE 100
void main( )
{
int arr[SIZE], N, i;
printf("Enter Number of Elements in Array:");
scanf("%d", &N);
printf("Enter %d numbers one by one:", N);
for(i = 0; i < N; i++) /* Read array elements */
{
scanf("%d", &arr[i]);
}
printf("\n Array Elements are: \n");
for(i = 0; i < N; i++)
{
printf("%d \t", arr[i]);
}
printf("\n Reverse of an array: \n");
for(i=N-1; i>=0; i--)
{
printf("%d \t", arr[i]);
}
}
Output:
Enter Number of Elements in Array: 5
Enter 5 numbers one by one: 36
92
45
67
89
Array Elements are:
36 92 45 67 89
Reverse of an array:
89 67 45 92 36
Program:
Write a C program to sort an array in ascending order (increasing order).
Source Code:
#include<stdio.h>
#define MAX 100
void main()
{
int arr[MAX],i,j,n,temp;
printf("\n Enter no.of elements in array:");
scanf("%d",&n);
Output:
Multi-dimensional arrays:
An array with more than one-dimension is called a multi-dimensional array. Hence the
two dimensional, three dimensional or other dimensional arrays are also known as multi-
dimensional arrays.
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is defined as an array of one-dimensional arrays. A 2D-array is used to
organize the elements in a tabular form or matrix form. A 2D-array is best suitable for
manipulating matrices, since a matrix is defined as a collection of numbers arranged into a
fixed number of rows and columns.
General Form
Declaration of Two-dimensional arrays:
Syntax:
data type array_name [row_size ][col_size];
This is called a two-dimensional array. The row_size, col_size must be an integer constant
greater than zero and data type can be any valid C data type.
Example:
int a[3][4];
It is a two-dimensional integer array having maximum 3 rows and 4 columns.
For example:
The array int a[10][20] can store (10*20) = 200 elements.
Similarly array int a[5][10][20] can store (5*10*20) = 1000 elements.
a[0][0]
a[0][1]
a[0][2]
a[0][3]
a[1][0]
a[1][1]
a[1][2]
a[1][3]
a[2][0]
a[2][1]
a[2][2]
a[2][3]
To print or display elements of a 2D-array, nested looping statement is used to change the
row_index and column_index of the element, since all the elements will differ by its row and
column index only.
The way we use to read the elements to an array is similar to that of printing an array.
Ex:
int matA[5][5], ri, ci;
for(ri=0; ri<5; ri++)
{
for(ci=0;ci<5;ci++)
{
printf(“%d\t”, matA[ri][ci]);
}
printf(“\n”);
}
Address of an element of any array say “A[I][J]” is calculated in two forms as given:
(1) Row Major System (2) Column Major System
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [( I – Lr ) + M * ( J – Lc )]
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 16
Problem Solving & Programming
Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
Example:
Consider a two-dimensional array: int a[3][4];
Address Element Reference
25001 25 a[0][0]
25003 36 a[0][1]
25005 84 a[0][2]
25007 56 a[0][3]
25009 15 a[1][0]
25011 12 a[1][1]
25013 14 a[1][2]
25015 17 a[1][3]
25017 83 a[2][0]
25019 62 a[2][1]
25021 97 a[2][2]
25023 95 a[2][3]
Program:
Write a C program to read and display a matrix of any order.
Source Code:
#include<stdio.h>
#define ROWS 10
#define COLS 10
void main( )
{
int mat[ROWS][COLS];
int i,j,r1,c1;
printf("Enter no. of rows and columns in a matrix:");
scanf("%d%d",&r1,&c1);
printf("\n Enter %d elements one by one:",r1*c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d", &mat[i][j]);
}
}
printf("\n Matrix is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t", mat[i][j]);
}
printf("\n\n");
}
}
Output:
Enter no. of rows and columns in a matrix: 3 3
Enter 9 elements one by one: 16
25
34
85
97
54
62
13
15
Matrix is:
16 25 34
85 97 54
62 13 15
Program:
Write a C program to read two matrices and then find the sum of two matrices.
Source Code:
#include<stdio.h>
#define ROWS 10
#define COLS 10
void main()
{
int a[ROWS][COLS], b[ROWS][COLS], c[ROWS][COLS];
int i,j,r1,c1,r2, c2;
printf("Enter no. of rows and columns in matrix A:");
scanf("%d%d",&r1,&c1);
printf("Enter no. of rows and columns in matrix B:");
scanf("%d%d",&r2,&c2);
if((r1==r2)&&(c1==c2))
{
printf("Enter elements of matrix A:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter elements of matrix B:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("Matrix A is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t", a[i][j]);
}
printf("\n\n");
}
printf("\n Matrix B is:\n\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t", b[i][j]);
}
printf("\n\n");
}
Output-1:
Matrix A is:
12 15 13
10 11 16
Matrix B is:
10 4 5
16 17 14
22 19 18
26 28 30
Output-2:
Write a C program to read two matrices and then find the product of two matrices.
Source Code:
#include<stdio.h>
#define ROWS 10
#define COLS 10
void main()
{
int a[ROWS][COLS],b[ROWS][COLS],c[ROWS][COLS];
int i,j,k,r1,c1,r2,c2;
printf("Enter no.of rows and columns in matrix A:");
scanf("%d%d",&r1,&c1);
printf("Enter no.of rows and columns in matrix B:");
scanf("%d%d",&r2,&c2);
if(c1==r2) /* no. of columns in matrix A and no. of rows in matrix B must be equal */
{
printf("Enter elements of matrix A:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of matrix B:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Matrix A is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n\n");
}
printf("\n Matrix B is:\n\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n\n");
}
printf("\n Product Matrix C is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n\n");
}
}
else
{
printf("\n Oops! Matrix Multiplication is not possible.\n");
}
}
Output-1:
Matrix A is:
1 1 1
1 1 1
Matrix B is:
1 1
1 1
1 1
3 3
3 3
Output-2:
Program-1:
Program to illustrate how array elements passed as an argument to a function
Source Code:
#include <stdio.h>
void disp( char );
int main( )
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
disp (arr[x]); // passing array elements one by one
}
return 0;
}
void disp( char ch)
{
printf("%c ", ch);
}
Output:
a b c d e f g h i j
Program-2:
Program to update elements of an array using functions such that each element of an array
should be multiplied by 5.
Source Code:
Output:
Enter no. of elements: 5
Enter 5 elements: 10 20 30 40 50
Before update:
10 20 30 40 50
After update:
50 100 150 200 250
There are 3 ways to declare the function which is intended to receive an array as an argument.
Syntax-1:
return_type function(type arrayname[]);
Declaring blank subscript notation [] is the widely used technique.
Syntax-2:
return_type function(type arrayname[SIZE]);
Optionally, we can define size in subscript notation [].
Syntax-3:
return_type function(type *arrayname);
You can also use the concept of a pointer.
To call any function by passing an entire array as an argument, we need to pass array_name as
argument, since array name itself acts as a pointer, this method of passing mechanism is
called call-by-reference.
Syntax:
function_name(array_name);
Example:
read_array(arr);
Program:
Program to find square of each element of an array using functions.
Source Code:
/* Program to pass an entire array as argument to a function */
#include<stdio.h>
#define MAX 50
int main()
{
int arr[MAX],n;
void read_array(int[ ], int);//function declaration
void display_array(int[ ], int);
void squaring(int[ ], int);
printf("Enter no. of elements:");
scanf("%d", &n);
printf("Enter %d elements:",n);
read_array(arr, n);//function call
printf("\n Before squaring:\n");
display_array(arr, n);
squaring(arr, n);//calling squaring function
printf("\n After squaring:\n");
display_array(arr, n);
}
void read_array(int a[ ],int n)
{
int idx;
for(idx=0;idx<n; idx++)
scanf("%d", &a[idx]);
}
Output:
Enter no. of elements: 6
Enter 6 elements: 2 4 6 8 10 12
Before squaring:
2 4 6 8 10 12
After squaring:
4 16 36 64 100 144
Program:
Program to find the transpose of a given matrix using functions
Source Code:
/* Program to find transpose of a matrix */
#include<stdio.h>
#define ROW 15
#define COL 15
int main( )
{
void read_matrix(int[ ][COL], int, int); // function declaration
void display_matrix(int[ ][COL], int, int);
void transpose(int[ ][COL], int, int);
int mat[ROW][COL], m, n;
printf("Enter the size of a matrix:");
scanf("%d %d", &m, &n);
printf("Enter %d elements of a matrix:",m*n);
read_matrix(mat, m, n);//function call for reading the elements
printf("Before Transposing:\n");
display_matrix(mat, m, n); // calling display_matrix function
printf("\n After Transposing:\n");
transpose(mat, m, n);//calling transpose function
}
void read_matrix(int a[ ][COL], int m, int n)
{
int i, j;
for(i=0;i<m; i++)
for(j=0;j<n; j++)
scanf("%d", &a[i][j]);
}
void display_matrix(int a[ ][COL], int m, int n)
{
int i, j;
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
void transpose(int a[ ][COL], int m, int n)
{
int i, j;
for(i=0;i<n; i++)
{
for(j=0;j<m; j++)
printf("%d ",a[j][i]);
printf("\n");
}
}
Output:
Enter the size of a matrix: 2 3
Enter 6 elements of a matrix: 12 14 15 21 22 23
Before Transposing:
12 14 15
21 22 23
After Transposing:
12 21
14 22
15 23
Program Assignment:
STRINGS
Introduction:
C does not support strings as a data type, hence strings are always should be declared as
character arrays.
Syntax-1:
char string_name[size] = “string”;
Example:
char college_name = “SRIT”;
char student_name = “Gautham”;
Syntax-2:
char string_name[size] = {‘ch1’,’ch2’,’ch3’, . . . . . . . . . ,’\0’};
Example:
char student_name = {‘G’,’A’,’U’,’T’,’H’,’A’,’M’,’\0’};
Note: When we initialize a character array as character by character, we must supply the null
character explicitly.
Here,
Example:
char student_name[25];
scanf(“%[^\n]s”, student_name);
This is another method called unformatted input function to read a string of text.
Syntax:
gets(string_name);
Example:
gets(student_name);
Displaying strings on the screen:
int main()
char student_name[25],branch[5],city[15];
scanf("%[^\n]s", student_name);
gets(branch);
gets(city);
Output:
Every C compiler supports a large no. of string handling library standard functions,
defined in <string.h> header file. Hence to perform any manipulation on strings, programmer
can use these standard library functions.
1. strlen( ) function
The strlen( ) function calculates the length of a given string. The strlen( ) function takes
a string as an argument and returns its length. The returned value is of type size_t (the
unsigned integer type).
Syntax:
strlen(string);
Example:
char fruit[20] = “Mango”;
strlen(fruit);
strlen(“Mango”);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 36
Problem Solving & Programming
#include<stdio.h>
#include<string.h>
int main()
{
char str1[] = "This is strings program";
printf("Length of str1 = %d ", strlen(str1));
return 0;
}
Output:
Length of str1 = 23
2. strcpy( ) function
The strcpy( ) function copies the source string (including the null character) to the
destination string. The strcpy( ) function also returns the copied string.
Syntax:
strcpy(destination_string, source _string);
Example:
char name1[15] = “Machine Learning”;
char name2[15];
strcpy(name2, name1); // name1 is copied to name2
#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "This is copy function", str2[30];
strcpy(str2, str1);
printf("Original String : %s ", str1);
printf("\nCopied String : %s ", str2);
return 0;
}
Output:
3. strncpy( ) function
The strncpy( ) function copies the specified length of source string to the destination string.
The strncpy( ) function also returns the copied string.
Syntax:
strncpy(destination_string, source _string, n);
here, n denotes no. of characters to be copied.
Example:
char name1[15] = “Machine Learning”;
char name2[15];
strncpy(name2, name1, 5); // first 5 characters of name1 is copied to name2
Program:
To copy required no. of characters of a string to another string
Source Code:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "awesome strncpy", str2[10] = "This is ";
strncpy(str1, str2, 8);
printf("Str1 : %s ", str1);
return 0;
}
Output:
4. strcmp( ) function
It compares the two strings and returns an integer value. It is a case-sensitive function.
If both the strings are same (equal) then this function would return 0 otherwise it may
return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative
value.
If string1 > string2 then it would return positive value.
Syntax:
int strcmp(string1, string2);
Example:
result = strcmp(“Good”, “good”);
Note: stricmp( ) function is also similar to strcmp( ) function but this is case-insensitive
function.
Program:
To compare two strings
Source Code:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
printf("Enter any two strings:");
gets(str1);
gets(str2);
if(strcmp(str1, str2) == 0)
printf("The strings %s and %s are same ",str1,str2);
if(strcmp(str1, str2) > 0)
printf("The string %s is greater than %s",str1,str2);
if(strcmp(str1, str2) < 0)
printf("The string %s is less than %s ",str1,str2);
return 0;
}
Output:
Apple
Ball
5. strncmp( ) function
It compares the two strings upto the specified length (no. of characters) and returns an
integer value. It is a case-sensitive function.
If both the strings are same (equal) then this function would return 0 otherwise it may
return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative
value.
If string1 > string2 then it would return positive value.
Syntax:
int strncmp(string1, string2, length);
Example:
result = strncmp(“Good”, “good”,3);
Note: strnicmp( ) function is also similar to strncmp( ) function but this is case-insensitive
function.
6. strlwr( ) function
The strlwr( ) function returns string of characters in lowercase. It is used to convert
uppercase string into lowercase string.
Syntax:
strlwr(uppercase_string);
Example:
strlwr(“COUNTRY”); // returns country
Program:
To convert a string into lowercase string
Source Code:
#include<stdio.h>
#include<string.h>
int main()
{
char str[30] = "THIS IS STRLWR";
printf(" %s ", strlwr(str));
return 0;
}
Output:
this is strlwr
6. strupr( ) function
The strupr( ) function returns string of characters in uppercase. It is used to convert
lowercase string into uppercase string.
Syntax:
strupr(lowercase_string);
Example:
strupr(“country”); // returns COUNTRY
Program:
To convert a given string into uppercase
Source Code:
#include <stdio.h>
#include<string.h>
int main()
{
char str[30] = "this is strupr";
printf("The string in uppercase : %s ", strupr(str));
return 0;
}
Output:
7. strcat( ) function
The strcat( ) function appends the target string at the end of source string.
Concatenation of two strings can be done by this function. This function returns the
concatenated string.
Syntax:
strcat(string1, string2);
Here, string2 will be joined at the end of string1.
Example:
strcat(“Hello”, “world”);
Note: The strncat( ) function is also similar to strcat( ) function but it concatenates the
string2 to string1 up to the specified length.
Syntax: strncat(string1, string2, length); // length denotes no. of characters to append.
Program:
Program to concatenate two strings.
Source Code:
#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "How are ", str2[30] = "you";
strcat (str1, str2);
printf("Str1 : %s ", str1);
return 0;
}
Output:
Str1 : How are you
8. strchr( ) function
The strchr() function finds the first occurrence of a character in a string. The
character c can be the null character (\0); the ending null character of string is included in the
search. The strchr() function returns a pointer to the first occurrence of c that is converted to
a character in string.
Syntax:
char* strchr(char *string, char ch);
Here, *string -> character pointer to the string
ch -> character to be searched
Example:
char *chp = strchr(“Engineering”,’e’);
It returns the address of first occurrence of ‘e’ in “Engineering”.
Note: The function returns NULL if the specified character is not found.
Program: To check whether the given character is present in the string or not
Source Code:
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main( )
{
char buffer1[SIZE] = "computer program";
char *ptr;
char ch = 'p';
ptr = strchr( buffer1, ch );
if(ptr)
printf(“%c is present in %s”, ch, buffer1);
else
printf(“%c is not present in %s”, ch, buffer1);
}
Output:
p is present in computer program
Note: strchr( ) searches the first occurrence of character whereas strrchr( ) searches the last
occurrence of character in the given string.
9. strstr( ) function
The strstr( ) function finds the first occurrence of string2 in string1. The function
ignores the null character (\0) that ends string2 in the matching process.
The strstr( ) function returns a pointer to the beginning of the first occurrence
of string2 in string1. If string2 does not appear in string1, the strstr( ) function returns NULL.
If string2 points to a string with zero length, the strstr( ) function returns string1.
Syntax:
char *strstr(char *string1, char *string2);
Example:
char *stp = strstr(“Choclate”, ”ate”);
Program:
To check whether the given string is substring or not.
Source Code:
#include <string.h>
#include <stdio.h>
int main( )
{
char *string1 = "Eating chocolate makes you relaxed";
char *string2 = "ate";
char *result;
result = strstr(string1,string2);
if(result)
printf(“%s is present in %s”, string2, string1);
else
printf(“%s is not present in %s”, string2, string1);
}
Program:
To print the reverse of a given string
Source Code:
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s", str);
printf("\nReverse String is: %s", strrev(str));
return 0;
}
Output:
Enter string: Example
String is: Example
Reverse String is: elpmaxE
Syntax:
char *strset(char *string, int ch);
Example:
strset(“Password”,’*’); // every character in Password will be replaced by ‘*’
Program:
To illustrate strset( ) function
Source Code:
#include <stdio.h>
#include<string.h>
int main( )
{
char str[20] = "password";
char chr = '*' ;
strset(str, chr);
printf("str: %s ", str);
return 0;
}
Output:
str: ********
Note: strnset( ) function is also similar to strset( ) function but it replaces required no. of
characters. It means if you want to set only n no. of characters by a character, you can do.
Array of Strings
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters.
Just like we can create a 2-D array of int, float etc; we can also create a 2-D array of
character or array of strings. Here is how we can declare a 2-D array of characters.
Array of strings is used to handle and manipulate multiple strings of different sizes.
Syntax:
char str_name[size][max_size];
Here, size -> No. of strings
max_size -> maximum string size
From the given syntax there are two subscripts first one is for how many strings to
declare and the second is to define the maximum length of characters that each string can
store including the null character.
Example:
char str_arr[3][10] = { {‘k’,’i’,’r’,’a’,’n’,’\0’}, {‘v’,’i’,’k’,’a’,’s’,’h’,’\0’},{‘r’,’a’,’v’,’i’,’\0’}};
(or)
char str_arr[3][10] = { “kiran”, ”vikash”, “ravi”};
We already know that the name of an array is a pointer to the 0th element of the array.
The str_arr is a pointer to an array of 10 characters or char(*)[10].
From this, we can conclude that:
(str_arr + 0) points to the 0th string or 0th 1-D array.
else
printf("Sorry..! %s You are not allowed to run this program.", name);
}
int factorial(int n)
{
int i, fact=1;
for(i=1;i<=n;i++)
fact = fact*i;
return fact;
}
Output:
Enter username: ravi
Welcome ravi !
Enter a number to calculate the factorial: 8
Factorial of 8 is 40320
POINTERS
Introduction:
Variables are used to hold the data values during the execution of a program
Every variable when declared occupies certain memory locations
The & operator is used to access and display the address of a variable
Inorder to store the address of a variable, there is a need of using another variable
which is called Pointer
A pointer is a derived datatype in C
Pointers contain memory addresses as their values, hence it is called a memory
variable
Definition:
A pointer is a special variable that stores the address of another variable. Unlike other
variables that hold values of a certain type, pointer holds the address of a variable. For
example, an integer variable holds (or you can say stores) an integer value, however an
integer pointer holds the address of an integer variable. This variable can be of type int, char,
array, function, or any other pointer. The size of the pointer depends on the architecture.
Features of Pointers:
1. Pointers save memory space.
2. Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.
3. Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well. Hence it can be said the Memory of pointers is dynamically allocated.
4. Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional arrays.
5. An array, of any type can be accessed with the help of pointers, without considering its
subscript range.
6. Pointers are used for file handling.
7. Pointers provide an efficient tool for manipulating data structures such as structures,
linked lists, stacks, queues and trees.
8. Pointers reduce length and complexity of programs.
9. Pointers are used to allocate memory dynamically.
Uses of pointers:
1. To pass arguments by reference
2. For accessing array elements
3. To return multiple values
4. Dynamic memory allocation
5. To implement data structures
6. To do system level programming where memory addresses are useful
Disadvantages of Pointers:
Representation of a variable
num 50 687654
num 50 687654
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
A pointer variable must be declared to the type of the value pointed by it.
Syntax:
datatype *pointer_name;
Here,
datatype any datatype in C
* dereference operator (asterisk)
pointer_name any valid identifier in C
Example:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The data type of pointer and the variable must match, an int pointer can hold the
address of int variable, and similarly a pointer declared with float data type can hold
the address of a float variable and so on.
Pointer of any datatype occupies same memory space (in bytes) to the address of a
variable of any datatype.
Initialization of a pointer:
A pointer must be initialized properly to the address of another variable. The
default initial value of a pointer is NULL if it is not initialized.
Syntax:
pointer_name = &variable_name;
Ex:
pnum = # /* The pointer pnum is assigned to the address of num. */
Note:
If a pointer in C is assigned to NULL, it means that it is pointing to nothing.
The content of the C pointer always be a whole number. i.e; address.
The operator & is called reference operator. It gives the address of a variable.
Likewise, there is another operator that gets the value from the address, it is called a
dereference operator (*). When a pointer is dereferenced, the value at the address stored by
the pointer is retrieved. Normal variables provides the direct access to their values where as
pointer provides indirect access to the values of the variable.
Note: The * sign when declaring a pointer is not a dereference operator. It is just a notation
that it represents a pointer.
Program:
Program to illustrate the concept of Pointers
Source Code:
#include<stdio.h>
int main()
{
int a,*pa;
float b,*pb;
printf("Enter an integer and floating-point number:");
scanf("%d %f",&a,&b);
pa = &a;
pb = &b;
printf("Address of a = %u",&a);
printf("\nAddress of b = %u",pa);
printf("\nValue of a = %d",a);
printf("\nValue of a = %d",*pa);
printf("\n");
printf("\nAddress of b = %u",&b);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 52
Problem Solving & Programming
printf("\nAddress of b = %u",pb);
printf("\nValue of b = %f",b);
printf("\nValue of b = %f",*pb);
}
Output:
Enter an integer and floating-point number:64
23.25
Address of a = 6356724
Address of b = 6356724
Value of a = 64
Value of a = 64
Address of b = 6356720
Address of b = 6356720
Value of b = 23.250000
Value of b = 23.250000
Program:
Source Code:
#include<stdio.h>
int main()
int a,b,*pa,*pb;
pa = &a;
pb = &b;
Output:
Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc.
However, as we know that pointer contains the address, the result of an arithmetic operation
performed on the pointer will also be a pointer if the other operand is of type integer. In
pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic
operations are possible on the pointer in C language:
Increment
Decrement
Addition
Subtraction
Comparison
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next
location. This is somewhat different from the general arithmetic since the value of the pointer
will get increased by the size of the data type to which the pointer is pointing.
We can traverse an array by using the increment operation on a pointer which will keep
pointing to every element of the array, perform some operation on that, and update itself in a
loop.
Note:
For 32-bit int variable, it will be incremented by 2 bytes.
For 64-bit int variable, it will be incremented by 4 bytes.
C Pointer Addition/Subtraction
We can add/subtract a value to the pointer. The formula of adding/subtracting value to
pointer is given below:
Note:
For 32-bit int variable, it will add/subtract 2 * number.
For 64-bit int variable, it will add/subtract 4 * number.
Program:
Program to illustrate pointer addition or subtraction
Source Code:
#include<stdio.h>
int main()
{
int a, b,*pa,*pb;
pa = &a;
pb = &b;
printf("Address in pa: %u", pa);
pa = pa + 3; //Adding 3 to the existing address
printf("\nAddress in pa: %u", pa);
printf("\nAddress in pb: %u", pb);
pb = pb - 3; //Subtracting 3 from the existing address
printf("\nAddress in pb: %u", pb);
}
Output:
Address in pa: 6356724
Address in pa: 6356736
Address in pb: 6356720
Address in pb: 6356708
There are various operations which cannot be performed on pointers. Since, pointer
stores address hence we must ignore the operations which may lead to an illegal address, for
example, addition, and multiplication.
When an array is declared, the compiler allocates a base address and sufficient amount
of storage to contain all elements of the array in continuous memory locations.
It is very important to note that, an array name by itself is an address or pointer, since when
we access the address of an array, the address of first element (0th) element is retrieved.
Hence the elements of the array together with their addresses can be displayed by using array
name itself.
Assume the base address of x is 2000. The five elements will be stored as follows:
Value 10 20 30 40 50
Base Address
We can use array name itself as a pointer, therefore the value of x is 2000. It is the address of
an array.
x = &x[0] = 2000
We can also declare an integer pointer ptr, we can make the pointer ptr that points to an array
x by the following statements.
ptr = x;
(or) ptr = &x[0];
The following table shows the relation between pointers and arrays
Address of each element of an array can be represented by any of the following expressions
Array Pointer
Expression Expression
&x[0] (x+0)
&x[1] (x+1)
&x[2] (x+2)
&x[3] (x+3)
&x[4] (x+4)
Value of each element of an array can be represented by any of the following expressions
Array Pointer
Expression Expression
x[0] *(x+0)
x[1] *(x+1)
x[2] *(x+2)
x[3] *(x+3)
x[4] *(x+4)
Note: The pointer accessing method is much faster than array indexing.
Program:
Write a C program to display array elements with their address using array name as pointer.
Source Code:
#include<stdio.h>
int main( )
{
int arr[5] = {10,20,30,40,50};
int idx = 0;
printf("ElementIndex \t Address\t Element");
for(idx=0; idx<5; idx++)
printf("\n arr[%d]\t\t %u\t %d", idx, (arr+idx),*(arr+idx));
}
Output:
ElementIndex Address Element
arr[0] 6356712 10
arr[1] 6356716 20
arr[2] 6356720 30
arr[3] 6356724 40
arr[4] 6356728 50
Program Assignment:
1. Write a C program to find the sum of all elements of an array. Use array name as pointer.
2. Write a C program to display sum of squares and cubes of array elements using pointer.
3. Write a C program to copy elements of one array to another array using pointers.
4. Write a C program to copy elements of one array into another array, order of elements of
Program:
Program to access a two dimensional array using pointer.
Source Code:
}
void printMatrix(int (*matrix)[COLS], int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
// *(*(matrix + i) + j) is equivalent to matrix[i][j]
printf("%d ", *(*(matrix + i) + j));
}
printf("\n");
}
}
Output:
Enter elements in 3x3 matrix.
123456789
Elements of 3x3 matrix.
1 2 3
4 5 6
7 8 9
Note:
You can use any of the two notations int matrix[][COLS] or int (*matrix)[COLS], to
access two dimensional array using pointers. The first int matrix[][COLS] is general array
notation. Whereas int (*matrix)[COLS] is a pointer to array.
Creating a string
In the following example we are creating a string str using char character array of size 6.
The variable name of the string str holds the address of the first element of the array i.e., it
points at the starting memory address.
So, we can create a character pointer ptr and store the address of the string str variable in it.
This way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.
The pointer variable ptr is allocated memory address 8000 and it holds the address of the
string variable str i.e., 1000.
Array of Pointers
We can create a two dimensional array and save multiple strings in it.
For example, in the given code we are storing 4 cities name in a string array city.
The problem with this approach is that we are allocating 4x12 = 48 bytes memory to the city
array and we are only using 33 bytes. We can save those unused memory spaces by using
pointers
Instead of making each row a fixed no.of characters we can make it as a array of pointers to
strings of varying length as shown below.
In the above code we are creating an array of character pointer cityPtr of size 4 to store the
name of the four cities.
The cityPtr pointer variable is allocated the memory address 8000 to 8007. Assuming integer
address value takes 2 bytes space. So, each pointer gets 2 bytes.
Name of the cities are saved in locations 1000, 2000, 3000 and 4000.
To access and print the values pointed by the array of pointers we take help of loop as shown
in the following example.
Program:
Program to access multiple strings of an array using array of pointers
Source Code:
#include <stdio.h>
int main(void)
{
// array of pointers
char *cityPtr[4] = {"Chennai", "Kolkata", "Mumbai", "New Delhi"};
int r;
for (r = 0; r < 4; r++) {
printf("%s\n", cityPtr[r]);
}
}
Output:
Chennai
Kolkata
Mumbai
New Delhi
Note:
Ragged Arrays: The character arrays with the rows of varying length are called “Ragged
Arrays”.
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example −
Program:
Program to illustrate double pointers.
Source Code:
#include<stdio.h>
int main( )
{
int num;
int *pnum = #
int **dpnum = &pnum;
printf("Enter a number:");
scanf("%d", &num);
printf("Value of num is:%d", num); // using variable name
printf("\nValue of num is:%d", *pnum); //using it’s pointer
printf("\nValue of num is:%d", **dpnum); // using it’s double pointer
}
Output:
Enter a number: 956
Types of Pointers
There are different types of pointers which are as follows −
Null pointer
Void pointer
Wild pointer
Dangling pointer
Null Pointer
You create a null pointer by assigning the null value at the time of pointer declaration. A null
pointer is a pointer whose initial value is assigned as NULL. This method is useful when you
do not assign any address to the pointer. A null pointer always contains value 0.
Example
Following is the C program for the null pointer −
#include <stdio.h>
int main(){
return 0;
Output
When the above program is executed, it produces the following result −
Void Pointer
It is a pointer that has no associated data type with it. A void pointer can hold
addresses of any type and can be typecast to any type. It is also called a generic pointer and
does not have any standard data type. It is created by using the keyword void. The limitation
of void pointers is that the pointed data cannot be referenced directly. Therefore type casting
or assignment must be used to turn the void pointer to a pointer of concrete data type.
Syntax:
void *pointer_name;
Example:
void *vptr;
Program:
Program to illustrate void pointers
Source Code:
#include<stdio.h>
int main( )
{
int p;
float d;
char ch;
void *pt; // Declaration of void pointer
pt = &p;
*(int*)pt = 12;
printf("Value of p = %d", p);
pt = &d;
*(float*)pt = 12.23;
printf("\nValue of d = %f", d);
pt = &ch;
*(char*)pt = 'm';
printf("\nValue of ch = %c", ch);
}
Output:
Value of p = 12
Value of d = 12.230000
Value of ch = m
Wild Pointer
Wild pointers are also called uninitialized pointers, because they point to some
arbitrary memory location and may cause a program to crash or behave badly.
This type of C pointer is not efficient, because they may point to some unknown memory
location which may cause problems in the program. This may lead to the crashing of the
program. It is advised to be cautious while working with wild pointers.
Example
Following is the C program for the wild pointer −
#include <stdio.h>
int main(){
printf("\n%d",*p);
return 0;
i.e. you won’t get output, some compilers show error message at
output
Dangling Pointer
Dangling pointer occurs at the time of the object destruction when the object is deleted
or de-allocated from memory without modifying the value of the pointer. It means It is a
pointer which is pointing to the memory, which is de-allocated. In such cases, the program
will show the undesirable result or may even crash. If the memory is re-allocated to some
other process, then we dereference the dangling pointer will cause the segmentation faults.
In the above figure, we can observe that the Pointer 3 is a dangling pointer. Pointer
1 and Pointer 2 are the pointers that point to the allocated objects, i.e., Object 1 and Object 2,
respectively. Pointer 3 is a dangling pointer as it points to the de-allocated object.
There are three different ways where Pointer becomes a dangling pointer.
1. Deallocation of Memory
Using free( ) function to de-allocate the memory.
In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a'
is a integer variable. The *ptr is a pointer variable which is created with the help
of malloc() function. As we know that malloc() function returns void, so we use int * to
convert void pointer into int pointer.
The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes
shown in the below image:
The statement free(ptr) de-allocates the memory as shown in the below image with a cross
sign, and 'ptr' pointer becomes dangling as it is pointing to the de-allocated memory.
If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory.
Therefore, we can say that ptr is not a dangling pointer, as shown in the below image:
#include<stdio.h>
int main()
{
char *str;
{
char a = ?A?;
str = &a;
}
// a falls out of scope
// str is now a dangling pointer
printf("%s", *str);
}
3. Function call
We will see how the pointer becomes dangling when we call the function.
#include <stdio.h>
int * fun()
{
int y=10;
return &y;
}
int main()
{
int *p=fun();
printf("%d", *p);
return 0;
}
First, we create the main() function in which we have declared 'p' pointer that contains
the return value of the fun().
When the fun() is called, then the control moves to the context of the int *
fun(), the fun() returns the address of the 'y' variable.
When control comes back to the context of the main() function, it means the variable 'y' is
no longer available. Therefore, we can say that the 'p' pointer is a dangling pointer as it
points to the de-allocated memory.
When an array is passed to a function as an argument, only the address of the first
element (base address) of the array is passed, but not the actual elements of array.
Ex:
Source Code:
#include<stdio.h>
int* larger(int*, int*); // larger( ) function returns an integer pointer
int main( )
{
int a,b;
int *p;
printf("Enter any two numbers:");
scanf("%d %d", &a, &b);
p = larger(&a, &b); //larger function returns either address of a or b
printf("%d is largest number",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x; // address of a will be returned
else
return y; // address of b will be returned
}
Output:
Enter any two numbers: 235 487
487 is largest number
3. Pointer to a Function
A function like a variable, has a type and an address location in the memory. Hence it is also
possible to declare a pointer to a function.
A pointer to a function is declared as follows:
Syntax:
data_type (*function_pointer_name)( );
The above declaration tells the compiler that function_pointer_name is a pointer to a function,
which return same data_type value.
Example:
int (*add_ptr)(int, int);
The paranthesis around *function_pointer_name are necessary, because the declaration like
data_type *function_pointer_name( );
would declare function_pointer_ name as a function returning a pointer of some data_type.
We can make a function pointer to point to a specific function by simply assigning the name of
the function to the pointer.
Ex:
double multiply(int, int);
double (*p1)( );
p1 = multiply; // assigning the name of the function to the pointer p1
To call the function multiply( ), we may now use the pointer p1 with the list of parameters.
Ex:
(*p1)(x, y); // Function Call
which is equivalent to multiply(x, y)
memory spaces then the remaining 10 memory spaces would be wasted and this
wasted memory cannot even be utilized by other program variables.
4. Dynamically created lists insertions and deletions can be done very easily just by the
manipulation of addresses whereas in case of statically allocated memory insertions
and deletions lead to more movements and wastage of memory.
5. When you want you to use the concept of structures and linked list in programming,
dynamic memory allocation is a must.
These functions are also called as Memory Management Functions, C provides the
following Dynamic Memory Allocation functions:
1. malloc( )
2. calloc( )
3. realloc( )
4. free( )
Note: To use the above library functions, it is required to include the header file <stdlib.h>
1. malloc( )
Syntax:
void* malloc(size_t size);
where, size_t represents the size of the data type, defined by using sizeof( )
operator
Example:
int *ptr;
ptr = (int*) malloc(sizeof(int));
Program:
Program to illustrate malloc( ) function
Source Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;
ptr = (int*) malloc(sizeof(int)); //allocates memory for one integer
if(ptr != NULL)
{
*ptr = 46;
printf("Value entered is:%d",*ptr);
}
else
printf("Memory allocation is unsuccessfull\n");
free(ptr); //deallocates the allocated memory
ptr=NULL; //making pointer as a non-dangling pointer
}
Output:
Value entered is: 46
2. calloc( )
The name "calloc" stands for contiguous allocation.
calloc( ) will create the dynamic memory with given size usually used for allocating
memory for arrays.
It will return the base address of an allocated memory to the pointer variable, on
success. If calloc( ) unable to create the dynamic memory, it will return NULL. So, it is
mandatory to check the pointer before using it.
The malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero.
calloc( ) returns a void pointer, which can be casted into pointers of any form.
Syntax:
void* calloc(size_t element_count, size_t element_size);
Here,
size_t represents the size of the datatype, defined using sizeof( ) operator
element_count represents no. of elements need to store in an array.
Example:
int *array_ptr;-
array_ptr = (int*)calloc(50, sizeof(int)); // allocates memory for 50 elements and
returns the address of first element.
Program:
Program to illustrate calloc( ) function
Source Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,n,i;
printf("Enter no. of elements:");
scanf("%d", &n);
ptr = (int*)calloc(n, sizeof(int));//allocates memory for n integer array
if(ptr != NULL)
{
printf("Enter %d elements one by one:",n);
for(i=0;i<n; i++)
scanf("%d",(ptr+i));
printf("Array Elements are:\n");
for(i=0;i<n; i++)
printf("%d ",*(ptr+i));
}
else
printf("Memory allocation is unsuccessfull\n");
free(ptr);//deallocates the allocated memory
ptr=NULL;//making pointer as a non-dangling pointer
}
Output:
Enter no. of elements: 6
Enter 6 elements one by one: 10 20 30 40 50 60
Array Elements are:
10 20 30 40 50 60
Note: we can also use malloc( ) to allocate memory for arrays but the parameter must be a
single one, hence we can multiply number of elements and size of each element as follows:
int *ptr = (int*)malloc(sizeof(int)*n);
3. realloc( )
The name "realloc" stands for re-allocation.
If the dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using the realloc( ) function. It means
we can resize the memory area which is already created by malloc( ) or calloc( ).
If realloc( ) request is success, it will return a pointer to the newly allocated memory.
Otherwise, it will return NULL.
How realloc works?
realloc( ) will act as malloc( ) if the pointer variable is NULL.
If the given size is smaller than the actual, it will simply reduce the memory size.
If the given size is bigger than the actual, it will check whether it can expand the
already available memory. If it is possible it will simply resize the memory.
Otherwise, it will create the new block of memory with the larger size and copy the
old data to that newly allocated memory and then it will deallocate the old memory
area.
Syntax:
void* realloc(void *ptr, size_t new_size);
Here, ptr is a pointer to the previously allocated memory
new_size is size to reallocate
Example:
ptr = (int*) realloc(ptr, 100*sizeof(int));
4. free( )
Dynamically allocated memory created with either calloc( ) or malloc( ) doesn't get
freed on their own. You must explicitly use free( ) to release the space.
It's mandatory to deallocate the memory area which has created dynamically when
the memory is no longer needed.
If we don't deallocate the dynamic memory, it will reside in the heap section. It is also
called memory leak.
It will reduce the system performance by reducing the amount of available memory.
So, it is programmer’s responsibility to deallocate the dynamic memory which is no
longer needed.
Syntax:
void free(void* ptr);
Example:
free(ptr);
************