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

Chapter 6 Array and Pointer

Chapter 6 covers arrays and pointers in C programming, detailing the types and properties of arrays, including one-dimensional and multi-dimensional arrays, as well as string handling functions. It explains the concept of contiguous memory allocation and provides examples of array declaration, initialization, and accessing elements. Additionally, the chapter discusses the advantages and disadvantages of arrays, along with various programming exercises to reinforce the concepts.

Uploaded by

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

Chapter 6 Array and Pointer

Chapter 6 covers arrays and pointers in C programming, detailing the types and properties of arrays, including one-dimensional and multi-dimensional arrays, as well as string handling functions. It explains the concept of contiguous memory allocation and provides examples of array declaration, initialization, and accessing elements. Additionally, the chapter discusses the advantages and disadvantages of arrays, along with various programming exercises to reinforce the concepts.

Uploaded by

karunbth14
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 6

Array and Pointer

1
Contents
• Array
• One dimensional array, Two dimensional array, multi dimensional array, string
and string handling functions (strlen(), strcpy(), strcat(), strrev(), strcmp(),
strlwr(), strupr()), Array of string.
• Passing array and string to function
• Pointer
• Definition, declaration and types [null, void etc]
• Pointer arithmetic
• Relationship between pointer and array

2
Background
• So far we have used only single variable name for storing one data
item.
• If we need to store multiple copies of the same data then it is very
difficult for the user. To overcome the difficulty a new data structure is
used called arrays.

3
Contd…
• An array is a linear and homogeneous data structure.
• Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc.
It also has the capability to store the collection of derived data types,
such as pointers, structure, etc.
• An array permits homogeneous data. It means that similar types of
elements are stored contiguously in the memory under one variable
name.
• An array can be declared of any standard or custom data type.

4
Example of array
• Suppose we have to store the roll numbers of the 100 students the we
have to declare 100 variables named as roll1, roll2, roll3, …….
roll100 which is very difficult job.
• Concept of C programming arrays is introduced in C which gives the
capability to store the 100 roll numbers in the contiguous memory
which has 100 blocks and which can be accessed by single variable
name.
int roll[100];

5
Properties of Array
• Each element of an array is of same data type and carries the
same size, i.e., int = 2 bytes, char = 1 byte, float = 4 bytes etc.
• Elements of the array are stored at contiguous memory locations
where the first element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can
calculate the address of each element of the array with the given base
address and the size of the data element

6
Pictorial representation of C Arrays

The above array is declared as int a [5];


a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index
variables.

7
Index or Subscript Variable:
1. Individual data items can be accessed by the name of the array and
an integer enclosed in square bracket called subscript variable /
index .
2. Subscript Variables helps us to identify the item number to be
accessed in the contiguous memory.

8
What is Contiguous Memory?
1. When Big Block of memory is reserved or allocated then that
memory block is called as Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory
addresses for special purposes then we can say that these 200 blocks are
going to reserve contiguous memory.

9
Contiguous Memory allocation
1. Two registers are used while implementing the contiguous memory
scheme. These registers are base register and limit register.
2. When OS is executing a process inside the main memory then
content of each register are as:

10
Contd…

Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents
noncontiguous allocation of memory.

3. When process try to refer a part of the memory then it will firstly refer the base address
from base register and then it will refer relative address of memory location with respect to
base address.
11
Advantages
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the
elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few
lines of code only.
4) Random Access: We can access any element randomly using the
array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the
array, we can't exceed the limit.

12
Array Terminologies
Size: Number of elements or capacity to store elements in an array. It is
always mentioned in square brackets [ ].
Type: Refers to data type. It decides which type of element is stored in
the array. It is also instructing the compiler to reserve memory
according to the data type.
Base: The address of the first element is a base address. The array name
itself stores address of the first element.
Index: The array name is used to refer to the array element. For example
num[x], num is array and x is index. The value of x begins from [Link]
index value is always an integer value.

13
Contd…
Range: Value of index of an array varies from lower bound to
upper bound. For example in num[100] the range of index is 0
to 99.
Word: It indicates the space required for an element. In each
memory location, computer can store a data piece. The space
occupation varies from machine to machine. If the size of
element is more than word (one byte) then it occupies two
successive memory locations. The variables of data type int,
float, long need more than one byte in memory.
14
Characteristics of Array
1. The declaration int a [5] is nothing but creation of five variables of integer types in

memory instead of declaring five variables for five values.

2. All the elements of an array share the same name and they are distinguished from one

another with the help of the element number.

3. The element number in an array plays a major role for calling each element.

15
Contd…
4. Any particular element of an array can be modified separately without disturbing the

other elements.

5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or

array variable of its type.

6. Array elements are stored in contiguous memory locations.

16
Array Declaration:

• Array has to be declared before using it in C Program. Array is


nothing but the collection of elements of similar data types.

• Syntax: <data type> array name [size1][size2].....[sizen];

17
Array Declaration Requirements

18
Declaration of C Array
Syntax
data_type array_name[array_size];
Example :
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index.
Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
19
Input data into the array
All the input values are stored in the corresponding array
elements using scanf () function.
Eg: int marks[6];
int i;
// Suppose we are intended to get marks of 5 subjects from
keyboard
for(i=0;i<5;i++)
Reading out data from an array
{
Suppose, if we want to display the
printf("Enter marks: \n");
scanf("%d”,&marks[i]);
elements of the array then we can use the
} for loop in C like this.
for (i=0; i<5;i++)
{
printf(“marks\n", marks[i]);
} 20
What does Array Declaration tell to
Compiler?
1. Type of the Array
2. Name of the Array
3. Number of Dimension
4. Number of Elements in Each Dimension

21
Type of array
1) One dimensional array: having only one index ; eg: marks[5]
2) Two dimensional array: having two indices;eg: marks[5][5]
3) Multi dimensional array: having more than 2 indices; eg:
marks[5][5]…[5]

22
Single/ One dimensional Array
• Single or One Dimensional array is used to represent and
store data in a linear form.
• Array having only one subscript variable is called One-
Dimensional array.
• It is also called as Single Dimensional Array or Linear
Array.

23
Single Dimensional Array Declaration and
initialization:
• Syntax for declaration: <data type> <array name> [size];
• Examples for declaration: int iarr[3]; char carr[20]; float farr[3];
• Syntax for initialization:
<data type> <array name> [size] = {val1, val2, …, valn};

Examples for initialization:


int iarr[3] = {2, 3, 4};
char carr[20] = “program”; float farr[3] = {12.5, 13.5, 14.5};

24
Different Methods of Initializing 1-D
Array
Method 1: Array Size Specified Directly
In this method, we try to specify the Array Size directly.

int num [5] = {2,8,7,6,0};


In the above example we have specified the size of array as 5 directly in the initialization statement.
Compiler will assign the set of values to particular element of the array.

num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;

25
• Method 2: Size Specified Indirectly
In this scheme of compile time Initialization, we do not provide size to an
array but instead we provide set of values to the array.
int num[ ] = {2,8,7,6,0};
Explanation:
1. Compiler Counts the Number Of Elements Written Inside Pair of Braces
and Determines
the Size of An Array.
2. After counting the number of elements inside the braces, The size of array
is considered
as 5 during complete execution.
3. This type of Initialization Scheme is also Called as “Compile Time
Initialization“

26
Example Program
#include <stdio.h>
int main()
{
int num[] = {2,8,7,6,0};
int i;
for (i=0;i<5;i++)
{
printf(“\n Array Element num [%d] = %d”,i, num[i]);
}
return 0;
}

27
WAP to find the average of array elements

#include<stdio.h> scanf("%f",&marks[i]);
#include<conio.h> sum=sum+marks[i];
void main( ) }
{ avg=sum/i; // because latest value of
float marks[5],sum=0,avg; int i; i is 5
for(i=0;i<5;i++) printf("Average=%f",avg);
{ getch( );
printf("Enter element %d:",i); }

28
WAP to calculate total marks of 7 subjects, calculate their sum and
average.
#include <stdio.h>
int main()
{
int marks[10],i, sum=0;
float avg;
printf("Enter marks of seven subjects\n");
for(i=0;i<7;i++)// reading marks from user
{
printf("Subject [%d]: ",i+1);
scanf("%d",&marks[i]);
}
for(i=0;i<7;i++)
{
sum=sum+marks[i];
}
avg=(float)sum/i;
printf("Total=%d\n Average=%f",sum,avg);
return 0; 29
WAP to read ‘n’ numbers from user and find the largest
#include <stdio.h>
one
#include <stdlib.h>
int MAX=100;
int main()
{ n=4
int num[MAX],i,n,large;
num 10 20 40 30
printf("Enter value of n:\n");
scanf("%d",&n); Num[0] Num[1] Num[2] Num[3
printf("Enter the numbers\n"); ]
Large=num[2]=40
for(i=0;i<n;i++)// reading marks from user
{
printf("number[%d]: ",i+1);
scanf("%d",&num[i]);
}
large=num[0];// initializing large= first number of
array
for(i=1;i<n;i++)
{
if(num[i]>=large)
large=num[i];
}
printf("largest number: %d",large);
return 0; 30
}
Accessing Array
• Array can be accessed using array-name and subscript variable written
inside pair of square brackets [ ].
• Consider the below example of an array

arr[0] = 51; arr[1] = 32; arr[2] = 43; arr[3] = 24; arr[4] = 5; arr[5] =26

31
WAP to find the largest element of the
array
#include<stdio.h> for(i=1;i<5;i++)
#include<conio.h> {
void main( ) if(num[i]>max)
{ {
float num[5], max; int i; max=num[i];
for(i=0;i<5;i++) }
{ }
printf(“Enter element %d: ”,i); printf(“\n The highest element is
scanf(“%f”,&num[i]); %f”,max);
} }
max=num[0];

32
Try
• WAP to find smallest elements of array

33
WAP to calculate sum and product of
elements in array
#include <stdio.h> /*calculate sum and product*/
int main() sum=0;
{ product=1;
int arr[10]; for(i=0; i<10; i++)
int sum,product,i; {
/*Read array elements*/ sum=sum+arr[i];
printf("\nEnter elements : \n"); product=product*arr[i];
for(i=0; i<10; i++) }
{ printf("\nSum of array is : %d" ,sum);
printf("Enter arr[%d] : ",i); printf("\nProduct of array is : %d\n",product);
scanf("%d",&arr[i]); return 0;
} }

34
WAP to sort the elements of array in
ascending order
Logic
• Declare array with maximum possible value.
• Input no of elements of array that user wishes
to input.(say n)
• Input n-elements from user.
• Now starting from 0 index array, compare two
consecutive numbers with each other, if lower
order number is greater than higher order, swap
the elements in array else do not change.
• Finally print the sorted array elements.

35
Code
#include <stdio.h> if (num[i] > num[j]){
int MAX=100; a = num[i];
void main () num[i] = num[j];
{ num[j] = a;
int num[MAX]; }
int i, j, a, n; }
printf("Enter number of elements in an array"); }
scanf("%d", &n); printf("The numbers in ascending order is:");
printf("Enter the elements"); for (i = 0; i < n; ++i)
for (i = 0; i < n; ++i) {
scanf("%d", &num[i]); printf("%d\n", num[i]);
for (i = 0; i < n; ++i){ }
for (j = i + 1; j < n; ++j) }
{
36
WAP to read ‘n’ numbers from user and sort in ascending order. display the largest and
second largest number
for(i=0;i<n;i++)
{
#include <stdio.h> for(j=i+1;j<n;j++)
#include <stdlib.h> {
int MAX=100;
int main() if(num[i]>num[j])
{ {
int num[MAX],i,j,n,temp; temp=num[i];
printf("Enter value of n:\n"); num[i]=num[j];
scanf("%d",&n); num[j]=temp;
printf("Enter the numbers\n"); }
for(i=0;i<n;i++)// reading marks from }
user
{ }
printf("number[%d]: ",i+1); printf("Sorted number in ascending
scanf("%d",&num[i]); order\n");
} for(i=0;i<n;i++)// Sorted number
{
// sorting in ascending order printf("%d\t",num[i]);
}
printf(“largest no=%d\n second largest
no=%d”, num[n-1], num[n-2]);
return 0;
37
}
WAP to reverse the order of elements of
arrays
• Hint: The first element is placed at last, second is placed at second last,
and so on.

38
Algorithm

39
Code
#include<stdio.h> scanf("%d", &arr[i]);
#include<conio.h> }
int N=10; printf("\nThe array elements in reverse
int main() order:\n");
{ for(i=n-1; i>=0; i--)
int arr[N], i,n; {
printf("How many element do you wish to printf("%d \t", arr[i]);
input?"); }
scanf("%d",&n); getch();
for(i=0; i<n; i++) return 0;
{ }

40
Two dimensional array
• The two-dimensional array can be defined as an array of arrays.
• The 2D array is organized as matrices which can be represented as the collection
of rows and columns. However, 2D arrays are created to implement a relational
database lookalike data structure.
• It provides ease of holding the bulk of data at once which can be passed to any
number of functions wherever required.
• The syntax to declare the 2D array:
data_type array_name[rows][columns];
• Consider the following example.
int matrix[4][3]; // declares 2D array with 4 rows and 3 columns.
float num[3][3];
char name[5][20];// declares array of strings

41
Declaration and Initialization of 2D array:
datatype var_name[row][column]= { list of values separated by
comma}
Example:
int table[2][3]= {1,2,3,0,5,4}
int table[2][3]={{1,2,3},{0,5,4}} i/j J=0 J=1 J=2
int table[ ][3]= { {1,2,3},{0,5,4}} i=0 1 2 3
i=1 0 5 4
Errors while initialization:
int marks[3][ ]= {1,2,3,0,5,4}
int marks [][]= {1,2,3,0,5,4}

42
WAP to read a matrix of size 2x3 from the
user and display it to screen
#include <stdio.h> {
void main () for (j = 0; j < 3; j++)
{ {
int matrix[2][3],i,j; printf("%d\t", matrix[i][j]);
for (i = 0; i < 2; i++) }
{ printf("\n");
for (j = 0; j < 3; j++) }
{ } Enter value for matrix[0][0]: 5
printf("Enter value for matrix[%d][%d]: ", i, Enter value for matrix[0][1]: 10
j); Enter value for matrix[0][2]: 15
scanf("%d", &matrix[i][j]); Enter value for matrix[1][0]: 25
} Enter value for matrix[1][1]: 30
} Enter value for matrix[1][2]: 35
printf("\nDisplaying the matrix:\n"); Displaying the matrix:
for(i = 0; i < 2; i++) 5 10 15
25 30 35 43
WAP to read two matrices of size 3x3 from the user and
display it to screen. Also display the sum of two matrices
#include <stdio.h>
//calculation
int main() for(i=0;i<3;i++)
{
{
int [100][100],B[100][100],C[100][100],i,j;
for(j=0;j<3;j++)
printf("Enter the elements of matrix A"); {
for(i=0;i<3;i++) C[i][j]=A[i][j]+B[i][j];
{ }
for(j=0;j<3;j++)
{
}
scanf("%d",&A[i][j]); printf("\nelements of matrix C:\n");
} for(i=0;i<3;i++)
} {
printf("Enter the elements of matrix B");
for(j=0;j<3;j++)
for(i=0;i<3;i++)
{ {
for(j=0;j<3;j++) printf("%d\t",C[i][j]);
{ }
scanf("%d",&B[i][j]); printf("\n");
}
} }
return 0; 44
}
C Program to Find Sum of Diagonal
Elements of a Matrix
#include <stdio.h>
void main ()
Problem Solution {
1. Create a matrix and define its elements.
2. Declare two variables which will store sum of main and static int array[10][10];
int i, j, m, n, a = 0, sum = 0;
opposite diagonal.
3. Now run a single for loop and extract main diagonals printf("Enetr the order of the matix \n");
elements adding to the first variable and opposite diagonal scanf("%d %d", &m, &n);
elements to the second variable. if (m == n )
{

printf("Enter the co-efficients of the


matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}

45
Contd
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}

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


{
sum = sum + array[i][i];
a = a + array[i][m - i - 1];
}

printf("\nThe sum of the main diagonal elements is = %d\n", sum);


printf("The sum of the off diagonal elements is = %d\n", a);

else
printf("The given order is not square matrix\n");

}
46
WAP to read a matrix of size mxn from the user and display
it’s transpose.

47
#include <stdio.h> printf("\n");
}
int max=50; // Transpose of a matrix
int main() for(i=0;i<n;i++)
{ {
int A[max][max],AT[max][max],m,n,i,j; for(j=0;j<m;j++)
printf("Enter the size of matrix"); {
scanf("%d%d",&m,&n); AT[i][j]=A[j][i];
printf("Enter the matrix elements"); }
for(i=0;i<m;i++) }
{ printf("Transpose of matrix:\n");
for(j=0;j<n;j++) for(i=0;i<n;i++)
{ {
scanf("%d",&A[i][j]); for(j=0;j<m;j++)
} {
} printf("%d\t",AT[i][j]);
printf("Original Matrix:\n"); }
for(i=0;i<m;i++) printf("\n");
{ }
for(j=0;j<n;j++)
{ return 0;
printf("%d\t",A[i][j]); }
}
48
WAP to read two matrices of size mxn and nxp from the user .Display the product of two
matrices.
 Hint:
If A=[aij] is an m×n matrix and B=[bij] is an n×p matrix, the product C= AB is an
m×p matrix.
AB=C=[cij] , where cij=ai1b1j+ai2b2j+...+ainbnj
To obtain this element, you:
first multiply all elements of the ith row of the matrix A pairwise with all the
elements of the jth column of the matrix B;
and then you add these n products.

To multiply two
matrices, the number
of columns of the first
matrix should be
equal to the number
of rows of the second
matrix.
49
We first assume the following:

50
51
So it requires 3 loops

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


{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
C[i][j] += A[i][k] * B[k][j];
}
}
}

52
#include <stdio.h> for(j=0;j<n;j++)
#include <stdlib.h> {
int max=50; scanf("%d",&A[i][j]);
int main() }
{ }
int A[max][max],B[max][max],C[max][max], printf("Read second matrix\n");
m,n,p,q,i,j,k; for(i=0;i<p;i++)
printf("Read size of first matrix\n");
{
scanf("%d%d",&m,&n);
for(j=0;j<q;j++)
printf("Read size of second matrix"); {
scanf("%d%d",&p,&q);
scanf("%d",&B[i][j]);
if(n==p)
}
{ }
printf("Read first matrix\n");
for(i=0;i<m;i++)
contd…
{
53
for(i=0;i<m;i++) } printf("%d\t",C[i][j]);
{ printf("\n"); }
for(j=0;j<q;j++) } printf("\n");
{ printf("Matrix B\n"); }
C[i][j]=0; for(i=0;i<p;i++) }
for(k=0;k<n;k++) { else
{ for(j=0;j<q;j++) {
{ printf("Product cannot be calculated!!
C[i][j]=C[i][j]+A[i][k]*B[k][j]; ");
printf("%d\t",B[i][j]);
} }
}
} return 0;
printf("\n");
} }
}
printf("Matrix A\n");
printf("Matrix C\n");
for(i=0;i<m;i++)
for(i=0;i<m;i++)
{
{
for(j=0;j<n;j++)
for(j=0;j<q;j++)
{
{ 54
printf("%d\t",A[i][j]);
String and string manipulation
• Strings:
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 you follow the rule of array initialization then you can write the above
statement as follows −
char greeting[] = "Hello";
55
Contd…
 Following is the memory presentation of the above defined
string in C:

56
Sample Code
#include <stdio.h>

int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
/*char greeting[]=“Hello”;
char greeting[6];
gets(greeting);
scanf(“%s”,greeting);*/
printf ("Greeting message: %s\n", greeting );
return 0;
}
57
Traversing String
• Traversing the string is one of the most important aspects in any of the
programming languages. We may need to manipulate a very large text which
can be done by traversing the text. Traversing string is somewhat different
from the traversing an integer array. We need to know the length of the array
to traverse an integer array, whereas we may use the null character in the
case of string to identify the end the string and terminate the loop.
• Hence, there are two ways to traverse a string.
By using the length of string
By using the null character.

58
Using the length of string
• Let's see an example of counting the number of vowels in a string.
#include<stdio.h>
int main ()
{
char s[ ] = “world is beautiful";
int i = 0, count = 0;
while(i<18)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels= %d", count);
return 0;
} 59
Using the null character
• Let's see the same example of counting the number of vowels by using the null character.
#include<stdio.h>
int main ()
{
char s[ ] = “world is beautiful";
int i = 0, count = 0;
while(s[i]!=‘\0’) // we can use NULL keyword replacing ‘\0’
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels= %d", count);
return 0;
}

60
WAP to enter a line of strings and count the total number of words
present in it.

for (i = 0;s[i] != '\0';i++)


#include <stdio.h> {
#include <string.h> if (s[i] == ' ' && s[i+1] != ' ')
count++;
void main() }
{ printf("Number of words in given
char s[200]; string are: %d\n", count + 1);
}
int count = 0, i;

printf("Enter the string:\n");


scanf("%[^\n]s", s);
61
Arrays of String
 String is an array of characters. Thus, an array of string is two dimensional
array of characters.
Eg: name[5][10];
it signifies the we have declared an array of string variable name which is
capable of storing 5 different strings each capable of storing 10 characters.

Index i,j Columns j


i/j 0 1 2 3 4 5 6 7 8 9
Rows i 0 R A M ‘\0’
1 H A R I ‘\0’
2 S I T A ‘\0’
3 G E E T A ‘\0’
4 R I T A ‘\0’ 62
WAP to read 5 different person name using array of string and display them

#include <stdio.h> {
#include <stdlib.h> printf("%s\n",name[i]);
}
int main()
{ return 0;
int i; }
char name[5][10];
printf("\n enter 5 names\n");
for(i=0;i<5;i++)
{
scanf("%s",name[i]);
}
printf("\n Here are the names: \n");
for(i=0;i<5;i++)

63
String Handling Functions (<string.h>)
Function Syntax (or) Example Description
strcpy() strcpy(string1, string2) Copies string2 value into string1
strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1

strlen() strlen(string1) returns total number of characters in string1

strcat() strcat(string1,string2) Appends string2 to string1


strncat() strncpy(string1, string2, 4) Appends first 4 characters of string2 to string1

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if string1>string2

strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by ignoring case (upper or
lower)
stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case (similar
to strcmpi())
strlwr() strlwr(string1) Converts all the characters of string1 to lower case.

strupr() strupr(string1) Converts all the characters of string1 to upper case. 64


Function Syntax (or) Example Description
strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to string1
strset() strset(string1, 'B') Sets all the characters of string1 to given character 'B'.
strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given character 'B'.
strrev() strrev(string1) It reverses the value of string1

65
Limitation of scanf
Stops at Whitespace: Cannot read strings with spaces (e.g., "John Doe").
Buffer Overflow: Exceeds buffer size if input is too long, causing undefined
behavior.
Does Not Handle Line Endings Properly: Leaves \n in the input buffer,
causing issues for subsequent input.
Input Format Dependency: Fails if input does not match the expected
format.
Difficulty Handling Mixed Input: Issues when alternating between reading
different data types.

66
strlen()
#include<stdio.h>
#include <string.h>
int main()
{
char ch[20]=“Nepal”;
int len;
len=strlen(ch);
printf("Length of string is: %d",len);
return 0;
}
67
Strcpy()
#include<stdio.h>
#include <string.h>
int main()
{
char str[ ]=“Nepal”;
char str2[20];
strcpy(str2,str);
printf("Value of second string is: %s",str2);
return 0;
}
68
Strcat()
#include<stdio.h>
#include <string.h>
int main()
{
char ch[10]=“Ram”;
char ch2[10]={‘t’, ‘h’, ‘a’, ‘p’, ‘a’, ‘\0’};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}

OUTPUT: Ramthapa
69
strcmp()
#include <stdio.h> printf("Same string");
#include <stdlib.h> else
int main() printf("Different strings");
{ return 0;
char str1[50],str2[50]; }
printf("Enter first string");
gets(str1);
printf("Enter second string");
gets(str2);
if(strcmp(str1,str2)==0)
70
Strrev()
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
71
WAP to delete an element at desired position from an array

72
WAP to delete an element at desired position from an array
#include <stdio.h> printf("Enter the position to delete");
#include <stdlib.h> scanf("%d",&pos);
int main() for(i=0;i<n-1;i++)
{ {
int A[50],i,pos,n; if(i>pos-2)
printf("Enter the size of array"); {
scanf("%d",&n); A[i]=A[i+1];
printf("Enter the array }
element"); }
for(i=0;i<n;i++) for(i=0;i<n-1;i++)
{ {
scanf("%d",&A[i]); printf("%d\t",A[i]);
} }
printf("array element are:\n"); return 0;
for(i=0;i<n;i++)
{ }
printf("%d\t",A[i]);
}

73
WAP to insert an element at desired position to an array

74
WAP to insert an element at desired position to an array
#include <stdio.h> for(i=0,j=0;i<n;i++,j++)
#include <stdlib.h> {
int main() if(i==pos-1)
{ {
temp[j]=num;
int A[50],temp[50],i,j,num,pos,n; temp[j+1]=A[i];
printf("Enter the size of array"); j++;
scanf("%d",&n); continue;
printf("Enter the array element"); }
for(i=0;i<n;i++) temp[j]=A[i];
{ }
scanf("%d",&A[i]); for(i=0;i<n+1;i++)//assigning temp array to A[i]
} {
printf("array element are:\n"); A[i]=temp[i];
}
for(i=0;i<n;i++) printf("Elements of A are:\n");
{ for(i=0;i<n+1;i++)
printf("%d\t",A[i]); {
} printf("%d\t",A[i]);
printf("\nEnter the position to }
insert"); return 0;
scanf("%d",&pos); }
printf("Enter a number to insert");
scanf("%d",&num);
75
WAP to read 5 different names of student.
Sort and display them in ascending order.
#include <stdio.h> printf("Enter %d names (one per line):\n",
MAX);
#include <string.h>
for (i = 0; i < MAX; i++)
#define MAX 5
#define NAME_LENGTH 50 {
printf("Name %d: ", i + 1);
int main()
gets(names[i]);
{
char names[MAX][NAME_LENGTH]; }
// Sorting names in ascending order
char temp[NAME_LENGTH];
int i, j;
// Input names

76
for (i = 0; i < MAX - 1; i++) printf("\nNames in ascending order:\n");
{ for (i = 0; i < MAX; i++) {
for (j = i + 1; j < MAX; j++) printf("%s\n", names[i]);
{ }
if (stricmp(names[i], names[j]) > 0)
{ return 0;
// Swap names[i] and names[j] }
strcpy(temp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp);
}
}
} 77
Alternatively, following approach can also be used for swapping

for (i = 1; i < n; i++) { printf("%s\n", names[i]);


for (j = 0; j < n - i; j++) { }
if (str[j] > str[j + 1]) { return 0;
ch = str[j]; str[j] = str[j + 1]; }
str[j + 1] = ch;
}
}
}
printf("\nNames in ascending order:\n");
for (i = 0; i < MAX; i++) {

78
Passing array as an argument to the function
• Passing array elements to a function is similar to passing variables to a
function.
• Arrays in C are always passed to the function as pointers pointing to the
first element of the array.
• There are 3 ways to declare the function which is intended to receive an
array as an argument:
First way:
return_type function(type arrayname[])

Second Way:
return_type function(type arrayname[SIZE])

Third way:
return_type function(type *arrayname)
79
Example 1: Pass Individual Array
Elements
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}

int main() {
int ageArray[] = {2, 8, 4, 12};

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}

80
Passing Multidimensional Array
#include <stdio.h> return 0;
void displayNumbers(int num[2][2]); }
int main() void displayNumbers(int num[2][2])
{ {
int num[2][2]; printf("Displaying:\n");
printf("Enter 4 numbers:\n"); for (int i = 0; i < 2; ++i) {
for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) {
for (int j = 0; j < 2; ++j) { printf("%d\n", num[i][j]);
scanf("%d", &num[i][j]); }
} }
} }
displayNumbers(num);
81
WAP to enter a line of strings and count the total number of words
present in it using user defined function.
#include <stdio.h> int wordcount(char str[])
#include <stdlib.h> { int i=0,count=0;
int wordcount(char []);
while(str[i]!='\0')
int main()
{ {
char str[100]; if(str[i]==‘ ‘&& str[i+1]!=‘ ‘)
int i=0,count; count++;
printf("Enter a line of string"); i++;
gets(str); }
count= wordcount(str); return count;
printf("no of words=%d",count+1);
}
return 0;
}

82
Sorting array in ascending order
#include<stdio.h> }
void asc_sort(int a[100], int n); /* Function definition for asc_sort */
void main() void asc_sort(int a[10], int n)
{ {
int a[100], i, n; int i, j, temp;
printf("Enter n:\n"); for(i=0;i< n-1;i++)
scanf("%d", &n); {
/* Reading array */ for(j=i+1;j< n;j++)
for(i=0;i< n;i++) {
{ if(a[i]>a[j])
printf("a[%d]=",i); {
scanf("%d", &a[i]); temp = a[i];
} a[i] = a[j];
/* Function Call */ a[j] = temp;
asc_sort(a,n); }
/* Displaying sorted array */ }
printf("Array in ascending order is:\n"); }
for(i=0;i< n;i++) }
{
printf("%d\t", a[i]);
83
}
WAP to count the length of string using user defined functions
#include <stdlib.h>
#include <string.h>
int xstrlen(char []);
int main()
{
char str[]="kathmandu";
int len;
len=xstrlen(str);
printf("length of the string is : %d",len);
return 0;
}
int xstrlen(char str[100])
{
int i=0;
while(str[i]!='\0')
{
i++;
}
return i;
}
84
String concatenation using user
defined function
#include <stdio.h> void xstrcat(char str1[],char str2[])
{
#include <stdlib.h>
int i=0,j=0;
void xstrcat(char [], char []); while(str1[i]!=NULL)
int main() {
i++;
{
}
char str1[]="Hello"; while(str2[j]!=NULL)
char str2[]="Nepal"; {

printf("string1=%s\nstring2=%s",str1,str2); str1[i]=str2[j];
i++;
xstrcat(str1,str2);
j++;
printf("\n afterfunction:\ns tring1=%s\n string2=%s",str1,str2); }
return 0; str1[i]='\0';
}
}
85
String compare using user defined
#include <stdio.h>
function
int xstrcmp(char str1[], char str2[])
#include <stdlib.h> {
int xstrcmp(char [],char []);
int main() int i=0;
{ while(str1[i]!='\0' && str2[i]!='\0')
char str1[50],str2[50]; {
int diff; if(str1[i]==str2[i])
printf("Enter first string"); i++;
gets(str1);
printf("Enter second string"); else
gets(str2); return (str1[i]-str2[i]);
diff=xstrcmp(str1,str2); }
if(diff==0) return (str1[i]-str2[i]);
printf("Same string"); }
else
printf("Different strings");
return 0;
}
86
Reversing a string using user defined
function
#include <stdio.h> void xstrrev(char str[])
#include <stdlib.h> {
void xstrrev(char []); int i=0,j=0;
int main() char temp[50];
{ while(str[i]!='\0')
char str[50]; {
printf("Enter a string"); temp[i]=str[i];
i++;
gets(str); }
printf("Before reverse=%s",str); i--;
xstrrev(str);// function call while(i>=0)
printf("After reverse=%s",str); {
return 0; str[j]=temp[i];
} j++;
i--;
}
87
}
• WAP to insert 5 different names of student. Sort and display them
in ascending order using user defined function.

88
POINTERS

89
OVERVIEW
• Introduction
• Pointer declaration
• Pointer arithmetic
• Pointer and array

90
Pointers
• A pointer is a special variable in C programming language which stores the memory address of other
variables of the same data type. As a pointer is variable, it is also created in some memory location.
Declaration of Pointer Variable
data_type * pointer_name;
Here, data_type can be any valid C data types and pointer_name can be any valid C identifier.
Examples of Declaration of Pointer:
int *ptr;
Here ptr is a pointer variable and it is read as a pointer to integer since it can point to integer variables.
float *fptr;
Here fptr is a pointer variable and it is read as a pointer to float since it can point to float variables.
char *cp;
Here cp is a pointer variable and it is read as a pointer to character since it can point to character variables.
91
Referencing of Pointer (Initialization of Pointer):
• Making a pointer variable to point other variables by providing address of that variable to the pointer is known as
referencing of pointer.
• It is also known as initialization of pointers. For proper use of pointer, pointer variables must point to some valid
address and it is important to note that without referencing, pointer variables are meaningless.
General syntax for referencing of pointer is:
pointer_variable = &normal_variable;
Here pointer_variable and normal_variable must be of the same data types.
Examples of Referencing of Pointer:
int a=10;
int *ptr; a variable
ptr = &a; 10 value
Here pointer ptr got address of variable a 0x2000 address
so, pointer ptr is now pointing to variable a. ptr Pointer variable
0x2000 value
ox3000 address

92
Contd…
int *ptr = &num;

93
float val=5.5;
float *p;
p = &val;
Here pointer p got address of variable val so, pointer p is now pointing to
variable val.
But!!!
float x=30.4;
int *iptr;
iptr = &x;
is invalid!!! Because pointer iptr cannot store address of float variable.

Initialization of pointer variable at the time of declaration:


int x, *y=&x; Valid!!
int *y=&x, x; Invalid!!

94
Dereferencing of Pointer (*)
• The operator * (asterisk) used in front of the name of the pointer variable is known as pointer or
dereferencing or indirection operator.
• After valid referencing of pointer variable, * pointer_variable gives the value of the variable pointed by
pointer variable and this is known as dereferencing of pointer.
• Simply, *pointer_variable after referencing instructs compilers that go to the memory address stored by
pointer_variable and get value from that memory address.
Operators:
& address of
* Value at address

95
Example
#include <stdio.h>
int main(void);
int main(void)
{
int num = 10;
int *ptr = &num;
printf("Value of num = %d", num);
printf("\n\rAddress = %p", &num);
printf("\n\rPointer ptr = %p", ptr);
printf("\n\rValue pointer is pointing at = %d", *ptr);

return 0;
}

96
Uses of Pointer
• Pointer enables us to access a variable that is defined outside the function.
• Pointers reduce length and complexity of program and increase execution speed.
• Pointers are more efficient in handling data tables.
• Use of pointer array to character string results in saving data storage in memory.
• Without pointers, dynamic memory allocations are impossible.
• When data type of particular data is unknown, then pointer can be used to access the data
regardless of data types as pointers holds only address which is of integer data type.
Disadvantages of Pointer:
• Pointers are unsafe because its easy for a pointer to get you wrong.
• Uninitialized pointers will cause segmentation fault.
• Improper handling of pointers in dynamic memory allocation will leads to memory leaks.
• Its very hard to debug pointer issues.

97
#include <stdio.h>
#include <stdlib.h>

int main()
{
int x=10,y;
int *p;
p=&x;
y=*p;
printf("value of x:%d\n",x);
printf("%d is stored at %d\n",x,&x);
printf("%d is stored at %d\n",*&x,&x);
printf("%d is stored at %d\n",*p,p);
printf("%d is stored at %d\n",p,&p);
printf("%d is stored at %d\n",y,&y);
*p=50;
printf("\nNow value at x:%d",x);
return 0;
}
98
Reference(&) and deference(*) operator
Reference operators:
• Address of operator (“&”) is known as referencing operator.
• This operator returns the address of the variable associated with the operator.
• For e.g., if we write “&x”, it will return the address of the variable “x’.
• Hence, if we have a pointer “p”, which we want to point to a variable x, then we need to copy the
address of the variable “x” in the pointer variable “p”.
• This is implemented by the statement: p = &x;

Dereference operators:
• Value of operator (“*”) is known as dereference operator.
• This operator returns the value stored in the variable pointed by the specified pointer.
• For e.g., if we write “*p”, it will return the value of the variable pointed by the pointer “p”.
• Hence, if we want the value of the variable pointed by the pointer “p” to be stored in a variable “y”, then
the expression can be written as: y = *p;

99
Bad Pointer
• When a pointer is first allocated, it does not have a pointee. The pointer is "uninitialized" or simply
"bad". A dereference operation on a bad pointer is a serious runtime error.
• Each pointer must be assigned a pointee before it can support dereference operations. Before that, the
pointer is bad and must not be used.
• In fact, every pointer starts out with a bad value. Correct code overwrites the bad value with a correct
reference to a pointee, and thereafter the pointer works fine.
Example:
int* p; // allocate the pointer, but not the pointee
*p = 42; // this dereference is a serious runtime error
Correct code:
int x=42,*p;
p=&x;

100
void pointer
• A void pointer is a special type of pointer . It can point to any data type, from an
integer value to a float and a string of characters.
• Using void pointer, the pointed data can not be referenced directly( i.e,
*(asterisk) operator cannot be used on them.)
• Type casting or assignment must be used to change the void pointer to a
concrete data type to which we can refer.
• Void pointer is highly preferred in dynamic memory allocation using malloc() and
calloc().
• A void pointer is a most convention way in c for storing a raw address.

101
Sample code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=10;
float b=4.56;
char *ch="NEPAL";
void *vptr;
vptr=&a;
printf("value=%d\n",*(int *)vptr);
vptr=&b;
printf("value=%f\n",*(float *)vptr);
vptr=&ch;
printf("value=%s\n",*(char **)vptr);
return 0;
}
102
NULL pointer
• C program defines the states that for each pointer type, when a pointer variable is
declared and initialized either by a Null value or by 0 explicitly then the pointer
variable is said to be null pointer.
• Conceptually a null pointer is a pointer that points nowhere, it doesn't have an
address of any function or a variable , instead pointer is initialized
with zero or null to indicate that this pointer variable is still unused.

Syntax - Null Pointer

data type *pointer_variable = NULL;

103
What will be the output of following?
#include<stdio.h>
int main() {
if(! NULL)
printf("C programming is easy");
else
printf("C programming is not easy");
return 0;
}

104
Pointer to Pointer(Double Pointer)
• A pointer variable
containing the address of Example: A=5
another pointer variable is B=10
known as pointer to pointer ptr= &A
or a chain of pointers. The
pointer variable that holds dptr= &ptr
the address of another
variable should be declared A 5 223344
with additional asterisk (*).
B 10 443322
ptr 223344 556688
dptr 556688 112234

105
#include <stdio.h>
int main()
{
int i = 5;
int *ptr1, **ptr2;
ptr1 = &i;
ptr2 = &ptr1;
printf("The value of i = %d ", i);
printf("\nThe value of ptr1 = %d ", *ptr1);
printf("\nThe value of ptr2 = %d ", **ptr2);
printf(“\n The address of i=%d”,&i);
printf(“\n The value assigned to ptr1=%d and value at address=%d”,ptr1,*ptr1);
printf(“\n The value assigned to ptr2=%d and single indirection value=%d and double indirection
value=%d”,ptr2,*ptr2,**ptr2);
return 0;
}

106
Pointer Arithmetic( Pointer Operations)
• Performing arithmetic operations on pointers is different from performing them on
regular integer data types.
• To illustrate the pointer, let us consider following declaration of ordinary variables
and pointer variables.
int a,b;
Float c;
int *p1,*p2;
float *f;
1) A pointer variable can be assigned the address of an ordinary variable.
i.e, p1=&a; p2=&b; f=&c;
2) Content of one pointer can be assigned to other pointer provided they point to
same data type.
p1=p2; // valid!!
f=p1; //invalid!! 107
3) Integer data can be added to or subtracted from pointer variables.
Eg: p1+2; // specifies an address which is two memory blocks for integer data
beyond the address pointed by p1;

Pointer variable
p1 p1+1 p1+2

Address 65516 65518 65520

Similiarly, f+1;// specifies an address which is one memory block for folat data
beyond the address pointed by f.
Pointer variable
f f+1 f+2

Address 655200 655204 655208

108
4) One pointer can be subtracted from other pointer provided they point to the
elements of same array. For example:
int main()
{
int a[]={45,89,90,20}, *pf,*pl;
pf=a;
pl=a+2;
printf(“%d\n”,pl-pf);
printf(“%d”,*pf-*pl);
OUTPUT: 2
-45
5) Two pointer variables can be compared provided both pointers point to objects of
same data type.
if(p1<p2)
{
……..
………
} // is a valid comparision
109
6) There is no meaning in assigning an integer to a pointer variable.
p1=100; //It has no meaning.
p2=65560;
7) Two pointer variables can not be multiplied and added together.
p1+p2; // invalid!!
p1*p2; // invalid!!
8) A pointer variable cannot be multiplied by a constant.
p1*2; //invalid!!
9) NULL value can be assigned to a pointer variable.
p1=NULL; // Valid!!

110
What will be the output of following
problem?
#include<stdio.h>

void main()
10 65510 65550
{
int a=10, *b, **c;
a b
b=&a; 65550 c
65510
c=&b; 65580
printf("%d\t%d\t%d\n", &a,&b,&c);
printf("%d\t%d\n", b,*c);
printf("%d\t%d\n", c,**c);
printf("%d\t%d",*b+5, &c+2); Output
65510 65550 65580
} 65510 65510
65550 10
15 65588
111
Array of Pointers
• Since a pointer variable always contains an address, an array of pointer would be nothing
but a collection of address.
• The address present in the array of pointers can be address of isolated variables or address
of array elements. Example:
int main()
{
int *arr[3];
int i=30,j=20,k=40,m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
for(m=0;m<3;m++)
{
printf(“%d\t”,*arr[m]);
}
return 0;
}
112
Array and Pointers
• An array is a block of sequential data. Array name by itself is an address.
• It points to the address of the first element( 0th element of array).
For one dimensional array:
let us consider pointer representation of
let us consider an array:
array:
int x[5];
int *x;
Address Value Address Value
Representation Representation Representation Representation
&x[0] x[0] x OR (x+0) *(x+0)
&x[1] x[1] x+1 *(x+1)
&x[4] x[4] x+4 *(x+4)

113
Alternative Representation: Example
#include <stdio.h>
int main() {
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
// ptr is assigned the address of the third element
Output:
ptr = &x[2]; *ptr = 3
printf("*ptr = %d \n", *ptr); *(ptr+1) = 4
*(ptr-1) = 2
printf("*(ptr+1) = %d \n", *(ptr+1));
printf("*(ptr-1) = %d", *(ptr-1));
return 0;
}

114
WAP input 5 numbers and display their sum.
// Pointer representation of One dimensional Array
// One dimensional Array #include <stdio.h>
#include <stdio.h> #include <stdlib.h>
#include <stdlib.h> int main()
int main() {
{ int *num,i,sum=0;
int num[5],i,sum=0; printf("Enter 5 numbers");
printf("Enter 5 numbers"); for(i=0;i<5;i++)
for(i=0;i<5;i++) {
{ scanf("%d",(num+i));
scanf("%d",&num[i]); }
} // calculation
// calculation for(i=0;i<5;i++)
for(i=0;i<5;i++) {
{ sum=sum+ *(num+i);
sum=sum+num[i]; }
} printf("\nSummation=%d",sum);
printf("\nSummation=%d",sum); return 0;
return 0; }
}
115
WAP to sort ‘n’ numbers and sort them in ascending order using pointer
#include <stdio.h> // sorting
#include <stdlib.h> for(i=0;i<n;i++)
int main() {
{ for(j=i+1;j<n;j++)
int *num,n,i,j,temp; {
printf("Enter the value of n:"); if(*(num+i)>*(num+j))
scanf("%d",&n); {
printf("Enter the numbers"); temp=*(num+i);
for(i=0;i<n;i++) *(num+i)=*(num+j);
{ *(num+j)=temp;
printf("\n num-%d:",i+1); }
scanf("%d",num+i); }
} }
printf("Numbers in ascending order\n");
for(i=0;i<n;i++)
{
printf("%d\t",*(num+i));
}
return 0;
}

116
WAP to count the number of words present in a line of paragraph using
pointer
#include <stdio.h>// without using pointer #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main() int main()
{ {
char *ch; char ch[100];
int count=0,i=0; int count=0,i=0;
printf("Enter a line of paragraph:\n"); printf("Enter a line of paragraph:\n");
scanf("%[^\n]",ch); scanf("%[^\n]",ch);
//gets(ch); //gets(ch);
while(ch[i]!='\0') while(*(ch+i)!='\0')
{ {
if(ch[i]==32) if(*(ch+i)==32)
{ {
count++; count++;
} }
i++; i++;
} }
printf("\nTotal no of words=%d",count+1); printf("\nTotal no of words=%d",count+1);
return 0; return 0;
} }
117
Two dimensional Array
Syntax for 2-D array representation:
datatype (* pointer_variable)[size];
let us consider pointer representation of
let us consider an 2-D array:
2-D array:
int x[5][5];
int (*x)[5];

Address Value Address Value


Representation Representation Representation Representation
&x[0][0] x[0][0] *(x+0)+0 *(*(x+0)+0)
&x[1][1] x[1][1] *(x+1)+1 *(*(x+1)+1)
&x[2][3] x[2][3] *(x+2)+3 *(*(x+2)+3)

118
Program to sort 10 numbers using user defined
numbers
#include <stdlib.h> void sort(int *arr) // defination
#include<stdio.h> {
void sort(int *); int i, j,temp;
for(i = 0; i<10; i++)
void main ()
{
{
for(j = i+1; j<10; j++)
int num[10] = {5,10,20,6,9,11,15,30,25,1}; {
int i; if(*(arr+i)>*(arr+j))
sort(&num); // function call {
printf("Printing Sorted Element List ...\n"); temp = *(arr+i);
for(i = 0; i<10; i++) *(arr+i) =
*(arr+j);
{ *(arr+j) =
printf("%d\n",num[i]); temp;
} } } } }
119
}
WAP to input elements of 3X2 matrix and display the elements in matrix order
#include <stdio.h>
#include <stdlib.h>
int main()
{
int (*A)[5],i,j;
printf("Enter elements of 3X2 array:\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",*(A+i)+j);
}
}
//Display the elements
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("%d",*(*(A+i)+j));
}
printf("\n");
}
return 0;
} 120
WAP to multiply two mXn and pXq matrix and display the result using
pointer
// Calculate the product
#include <stdio.h>
for(i=0;i<m;i++)
#include <stdlib.h>
{
int main()
for(j=0;j<q;j++)
{
{
int (*A)[10],(*B)[10],(*C)[10],m,n,p,q,i,j,k;
*(*(C+i)+j)=0;
printf("Read size of first matrix\n");
for(k=0;k<n;k++)
scanf("%d%d",&m,&n);
{
printf("Read size of second matrix");
*(*(C+i)+j)=*(*(C+i)+j)+*(*(A+i)+k)*
scanf("%d%d",&p,&q); *(*(B+k)+j);
if(n==p) }
{ }
printf("Read first matrix\n"); }
for(i=0;i<m;i++) printf("Matrix C\n");
{ for(i=0;i<m;i++)
for(j=0;j<n;j++) {
{ for(j=0;j<q;j++)
scanf("%d",*(A+i)+j); {
} printf("%d\t",*(*(C+i)+j));
} }
printf("Read second matrix\n"); printf("\n");
for(i=0;i<p;i++) }
{ }
for(j=0;j<q;j++) else
{ {
scanf("%d",*(B+i)+j); printf("Product cannot be calculated!! ");
} }
} return 0; 121
}
#include <stdio.h> int i;
#include <string.h>
#define MAX_STUDENTS 5 // Initialize pointers to the rows of the 2D array
#define MAX_NAME_LENGTH 100 for (i = 0; i < MAX_STUDENTS; i++) {
// User-defined function to sort an array of strings in ascending namePointers[i] = studentNames[i];
order }
void sortNames(char *names[], int n)
{ // Input 5 different student names
char *temp; printf("Enter %d different student names:\n",
for (int i = 0; i < n - 1; i++) { MAX_STUDENTS);
for (int j = i + 1; j < n; j++) { for (i = 0; i < MAX_STUDENTS; i++) {
if (strcmp(names[i], names[j]) > 0) { printf("Name %d: ", i + 1);
// Swap the pointers scanf("%s", studentNames[i]);
temp = names[i]; }
names[i] = names[j];
names[j] = temp; // Sort the names using the user-defined function
} sortNames(namePointers, MAX_STUDENTS);
}
} // Display the sorted names
} printf("\nSorted names in ascending order:\n");
for (i = 0; i < MAX_STUDENTS; i++) {
int main() printf("%s\n", namePointers[i]);
{ }
char
studentNames[MAX_STUDENTS][MAX_NAME_LENGTH]; return 0;
char *namePointers[MAX_STUDENTS]; } 122
Practice Question
• Write a C program to input a string containing alphabets, numbers, and
special characters from the user. Using pointers, create a new string
that contains only the alphabets from the input string. The program
should not use any library functions like isalpha. Use manual checks to
determine whether a character is an alphabet.

123
#include <stdio.h> }
void transferAlphabets(const char *input, char *output) {
while (*input != '\0') int main() {
{ // Traverse the input string until null terminator char input[100], output[100];
// Check if the character is an alphabet (A-Z or a-z) // Input a string from the user
if ((*input >= 'A' && *input <= 'Z') || (*input >= 'a' && *input printf("Enter a string: ");
<= 'z')) gets(input)
{ // Call the function to transfer alphabets
*output = *input; // Transfer the character to the output string transferAlphabets(input, output);
output++; // Move the output pointer forward // Display the resulting string with alphabets
} printf("String with alphabets only: %s\n", output);
input++; // Move to the next character in the input string return 0;
} }
*output = '\0'; // Null-terminate the output string
124
Questions:
Write a progmm to read a 3*3 square matrix, find minimum integer
value of a matrix, replace the diagonal elements by the minimum
element and display it using point

125
#include <stdio.h> }
}
int main() { }
int matrix[3][3];
int min, i, j; // Replacing diagonal elements with the minimum value
for (i = 0; i < 3; i++) {
// Pointer to the 2D matrix ptr[i][i] = min;
int (*ptr)[3] = matrix; }

// Reading the 3x3 matrix // Displaying the modified matrix


printf("Enter the elements of a 3x3 matrix:\n"); printf("\nModified matrix with diagonal elements replaced
for (i = 0; i < 3; i++) { by minimum value:\n");
for (j = 0; j < 3; j++) { for (i = 0; i < 3; i++) {
printf("Enter element [%d][%d]: ", i + 1, j + 1); for (j = 0; j < 3; j++) {
scanf("%d", &ptr[i][j]); printf("%d ", ptr[i][j]);
} }
} printf("\n");
}
// Finding the minimum element in the matrix
min = ptr[0][0]; // Initialize with the first element return 0;
for (i = 0; i < 3; i++) { }
for (j = 0; j < 3; j++) {
if (ptr[i][j] < min) {
126
min = ptr[i][j];
Dynamic Memory Allocation
• Since C is a structured language, it has some fixed rules for
programming. One of them includes changing the size of an array. An
array is a collection of items stored at contiguous memory locations.
As can be seen, the length (size) of the array above is 9.
But what if there is a requirement to change this length
(size)? For example,
•If there is a situation where only 5 elements are needed
to be entered in this array. In this case, the remaining 4
indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9
to 5.
•Take another situation. In this, there is an array of 9
elements with all 9 indices filled. But there is a need to
enter 3 more elements in this array. In this case, 3 indices
more are required. So the length (size) of the array needs
to be changed from 9 to 12.
127
Contd…
• Therefore, C Dynamic Memory Allocation can be defined as a
procedure in which the size of a data structure (like Array) is changed
during the runtime.
C provides some functions to achieve these tasks. There are 4 library
functions provided by C defined under <stdlib.h> header file to
facilitate dynamic memory allocation in C programming. They are:
• malloc()
• calloc()
• free()

128
malloc() Method
• The “malloc” or “memory allocation” method in C is used to dynamically
allocate a single large block of memory with the specified size. It returns a
pointer of type void which can be cast into a pointer of any form. It doesn’t
Initialize memory at execution time so that it has initialized each block with
the default garbage value initially.
• Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
Example
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the
allocated memory.

129
Contd…

130
calloc()

131
free()

132
Example
// Program to calculate the sum of n numbers entered by if(ptr == NULL) {
the user
printf("Error! memory not allocated.");
return 1;// terminates the program.
#include <stdio.h>
}
#include <stdlib.h>
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
int main() {
scanf("%d", ptr + i);
int n, i, *ptr, sum = 0;
sum += *(ptr + i);
}
printf("Enter number of elements: ");
printf("Sum = %d", sum);
scanf("%d", &n);
// deallocating the memory
free(ptr);
ptr = (int*) malloc(n * sizeof(int));
return 0;
}
// if memory cannot be allocated
133
End of Chapter 6

134

You might also like