0% found this document useful (0 votes)
13 views67 pages

Arrays and Strings Basics in C

Uploaded by

BL Shruthi
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)
13 views67 pages

Arrays and Strings Basics in C

Uploaded by

BL Shruthi
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

Module-3: Arrays and Strings

Arrays and Strings: Introduction, Declaration and Initialization of One-dimensional and Two-
Dimensional. Arrays, Declaring and Initializing String Variables, Example programs using
arrays, Reading Strings from Terminal, Writing Strings to Screen, Arithmetic Operations on
Characters, Comparison of Two Strings, String-handling Functions.

What is an Array?
An array is a collection of variables of the same data type, stored at contiguous memory
locations, and accessed using a single name.

Instead of creating 5 separate integer variables like this:

int a1, a2, a3, a4, a5;

We can use an array:

int marks[5];

This means marks is a group of 5 integers stored in a sequence.

Why use arrays?


✅To store large amounts of data efficiently (e.g., marks of 100 students).
✅ Easy to access and process data using loops.
✅ Simplifies code readability and management.

Memory representation
If you create:

int marks[5] = {10, 20, 30, 40, 50};

Index marks[0] marks[1] marks[2] marks[3] marks[4]

Value 10 20 30 40 50

CSE|ACSCE Page 1
Module-3: Arrays and Strings

Each element is stored contiguously in memory.

• An array is a collection of items of same data type stored at contiguous memory locations.

• Array of character is a string.

• Each data item of an array is called an element.

• And each element is unique and located in separated memory location.

• Each of elements of an array share a variable but each element having different index no.
known as subscript.

Any element in an array can be accessed using

1. Name of the array

2. Position of the element in an array.

There are 2 types of array

1. Single dimensional array

2. Multi-dimensional array

Declaration of 1-Dimensional arrays

• Arrays are declared using following syntax:

Syntax: data_type array_name[size];

where, data_type can be int, float or char.

name is the name of the array.

size indicates number of elements in the array.

Example: int marks[10];

CSE|ACSCE Page 2
Module-3: Arrays and Strings

Storing values in an Array

Initialization can be done using the following syntax:

type array_name[size]={list of values};

1. Initializing all specified memory location: int a[5]={10,20,30,40,50}

2. Partial array initialization int a[5]={10,20}

3. Array initialization without size:

int a[ ]={10,20,30,40,50}

CSE|ACSCE Page 3
Module-3: Arrays and Strings

4. Array initialization without elements


int a[5]={0}

Inputting values from keyboard

int i, marks[10]; for(i=0;i<10;i++)

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

Assigning values to Individual Elements

int i, arr1[10], arr2[10];

arr1[i]={0,1,2,3,4,5,6,7,8,9};

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

arr2[i] = arr1[i];

[Link] to read and write one dimensional array.

#include<stdio.h>

void main()

{ int i,a[5];

printf("Enter the elements: ");

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

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

CSE|ACSCE Page 4
Module-3: Arrays and Strings

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

printf("Array a[%d]=%d\n",i,a[i]);

Output:

Enter the elements: 1 2 3 4 5

Array a[0]=1

Array a[1]=2

Array a[2]=3

Array a[3]=4

Array a[4]=5

[Link] to search an element in an array.

#include<stdio.h>

void main()

int i,a[20],n,key;

printf("Enter the number of elements: ");

scanf("%d",&n);

printf("Enter the elements: ");

CSE|ACSCE Page 5
Module-3: Arrays and Strings

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

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

printf("Enter the key element to be searched: ");

scanf("%d",&key);

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

if(key==a[i])

printf("Element found at position %d\n",i+1);

Output:

Enter the number of elements: 5

Enter the elements: 1 2 3 4 5

Enter the key element to be searched: 5

Element found at position 5

[Link] to print the position of smallest of numbers using array.

#include<stdio.h>

void main()

int i,a[20],n,small,pos;

CSE|ACSCE Page 6
Module-3: Arrays and Strings

printf("Enter the number of elements: ");

scanf("%d",&n);

printf("Enter the elements: ");

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

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

small=a[0];

pos=0;

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

if(a[i]<small)

small=a[i];

pos=i;

printf("The smallest element is %d and the position is %d",small,pos+1);

Output:

Enter the number of elements: 5

Enter the elements: 2 3 4 5 6

CSE|ACSCE Page 7
Module-3: Arrays and Strings

The smallest element is 2 and the position is 1

Operations on array

1. Traversing an array

2. Inserting an element in an array

3. Deleting an element from an array

4. Merging 2 arrays

5. Searching an element in an array

6. Sorting an array in ascending or descending order

1. Traversing an array

• Traversing an array means accessing each and every element of the array for a specific
purpose.

Algorithm for Array Traversal:

Step 1: [Initialization] SET I=lower_bound


Step 2: Repeat steps 3 and 4 while I<=upper_bound
Step 3: Apply process to A[I]
Step 4: Set I=I+1;
Step 5: Exit

2. Inserting an element in an array


• Inserting an element in an array means adding a new data element to an already existing
array.

Algorithm to insert a new element to the end of the array:

Step 1: Set upper_bound= upper_bound+1//Increment the value of Upper bound


Step 2: Set A[upper_bound]= VAL(Value that has to be inserted]//New value is stored

CSE|ACSCE Page 8
Module-3: Arrays and Strings

Step 3: EXIT

Algorithm to insert a new element in middle of the array:

Step 1: Set I=N//N=Number of elements


Step 2: Repeat 3 and 4 while I>=POS//POS=position at which element has to be inserted
Step 3: Set A[I+1]=A[I]
Set A[I+1]=A[I]
Step 4: Set N=N+1
Step 5: Set A[POS]=VAL
Step 6: EXIT

WAP to insert a number at a given location in an array.


#include<stdio.h>
void main()
{
int i,a[20],n,num,pos;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be inserted: ");

scanf("%d",&num);

printf("Enter the postion at which number has to be inserted: ");


scanf("%d",&pos);

for(i=n-1;i>=pos;i--)

a[i+1]=a[i];

a[pos]=num;

n++;

CSE|ACSCE Page 9
Module-3: Arrays and Strings

printf("The array after insertion of %d is :",num);

for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
Output:

Enter the number of elements: 5

Enter the elements: 1 2 4 5 6

Enter the number to be inserted: 3

Enter the postion at which number has to be inserted: 2

The array after insertion of 3 is : 1 2 3 4 5 6

CSE|ACSCE Page 10
Module-3: Arrays

WAP to insert a number in an array that is already sorted in ascending order.


#include<stdio.h>
void main()
{
int i,n,j,num,a[10];
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be inserted: ");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(a[i]>num)
{
for(j=n-1;j>=i;j--)
a[j+1]=a[j];
a[i]=num;
break;
}
} n++;
printf("The array after insertion of %d is: ",num);
for(i=0;i<n;i++)
printf("\t%d",a[i]);
}
Output:

Enter the number of elements: 5

Enter the elements: 1 2 3 4 5

Enter the number to be inserted: 0

The array after insertion of 0 is: 0 1 2 3 4 5

ACSCE, Page 11
Module-3: Arrays

Deleting an element in an array

• Deleting an element from an array means removing a data element from an already existing
array.

Algorithm to delete a new element to the end of the array:

Step 1: Set upper_bound= upper_bound-1

Step 2: EXIT

Algorithm to delete element from middle of the array:

Step 1: Set I=POS// POS=position at which element has to be deleted

Step 2: Repeat 3 and 4 while I<=N-1//N=Number of elements in the array

Step 3: Set A[I] = A[I+1]

Step 4: Set I=I+1

Step 5: Set N=N-1

Step 6: EXIT

WAP to delete a number from a given location in an array.

#include<stdio.h>

void main()

int i,a[20],n,pos;

printf("Enter the number of elements: ");

scanf("%d",&n);

printf("Enter the elements: ");

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

scanf("%d",&a[i]); }
ACSCE, Page 12
Module-3: Arrays

printf("Enter the postion from which number has to be deleted: ");

scanf("%d",&pos);

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

a[i]=a[i+1]; n--;

printf("The array after deletion is :");

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

printf("\nA[%d]=%d",i,a[i]);

Output:

Enter the number of elements: 5

Enter the elements: 1 2 3 4 5

Enter the postion from which number has to be deleted: 4

The array after deletion is :

A[0]=1

A[1]=2

A[2]=3

A[3]=4

ACSCE, Page 13
Module-3: Arrays

WAP to delete a number from an array that is already sorted in ascending order

#include<stdio.h> void

main()

int i,n,j,num,a[10];

printf("Enter the number of elements: ");

scanf("%d",&n);

printf("Enter the elements: ");

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

scanf("%d",&a[i]); }

printf("Enter the number to be deleted: ");

scanf("%d",&num);

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

if(a[i]==num)

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

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

ACSCE, Page 14
Module-3: Arrays

printf("The array after deletion is");

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

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

Output:

Enter the number of elements: 5

Enter the elements: 1 2 3 4 5

Enter the number to be deleted: 3

The array after deletion is 1 2 4 5

Merging 2 arrays

• Merging of 2 arrays in a third array means first copying the contents of the first array into
the third array and then copying the contents of second array into the third array.

• Hence, the merged array contains contents of the second array.

WAP to merge 2 unsorted arrays.

#include <stdio.h> void

main()

int a1[10],a2[10],a3[10],i,n1,n2,m,index=0;

printf("Enter the number of elements in array1:");

scanf("%d",&n1);

printf("Enter the elements in array1:");

ACSCE, Page 15
Module-3: Arrays

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

scanf("%d",&a1[i]);

printf("Enter the number of elements in array2:");

scanf("%d",&n2);

printf("Enter the elements in array2:");

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

scanf("%d",&a2[i]);

m=n1+n2;

for(i=0;i<n1;i++) {

a3[index]=a1[i];

index++;

for(i=0;i<n2;i++) {

a3[index]=a2[i];

index++;

printf("\n\nThe merged array is\n");

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

printf("\t Arr3[%d]=%d\n",i,a3[i]);

ACSCE, Page 16
Module-3: Arrays

Output:

Enter the number of elements in array1:3

Enter the elements in array1:1 2 3

Enter the number of elements in array2:3

Enter the elements in array2:4 5 6

The merged array is

Arr3[0]=1

Arr3[1]=2

Arr3[2]=3

Arr3[3]=4

Arr3[4]=5

Arr3[5]=6

WAP to merge 2 sorted arrays.

#include <stdio.h> void

main()

int a1[10],a2[10],a3[10],i,n1,n2,m,index=0,index_1=0,index_2=0;

printf("Enter the number of elements in array1:");

scanf("%d",&n1);

printf("Enter the elements in array1:");

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

ACSCE, Page 17
Module-3: Arrays

scanf("%d",&a1[i]);

printf("Enter the number of elements in array2:");

scanf("%d",&n2);

printf("Enter the elements in array2:");

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

scanf("%d",&a2[i]);

m=n1+n2;

while(index_1<n1&&index_2<n2)

if(a1[index_1]<a2[index_2])

a3[index]=a1[index_1];

index_1++;

} else

a3[index]=a2[index_2];

index_2++; }

index++;

if(index_1==n1)//if elements of the first array are over and the second array has some elements

while(index_2<n2)
ACSCE, Page 18
Module-3: Arrays

a3[index]=a2[index_2];

index_2++; index++;

else if(index_2==n2) //if elements of the second array are over and the first array has
some elements

while(index_1<n1)

a3[index]=a1[index_1];

index_1++;

index++;

printf("\n\nThe contenets of merged array are");

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

printf("\n Arr[%d] = %d",i,a3[i]);

Output:

Enter the number of elements in array1:3

Enter the elements in array1:4 5 6


ACSCE, Page 19
Module-3: Arrays

Enter the number of elements in array2:3

Enter the elements in array2:1 2 3

The contenets of merged array are

Arr[0] = 1

Arr[1] = 2

Arr[2] = 3

Arr[3] = 4

Arr[4] = 5

Arr[5] = 6

Searching for a value in an array

• Searching means to find whether a particular value is present in the array or not.

• If the value is present in the array then search is said to be successful and the search
process gives the location of that array.

• If the value is not present, the search process displays the appropriate message.

Linear search: ALGORITHM

Step1: [Initialization] Set pos=-1 Step2:

[Initialization] Set I=0

Step3: Repeat Step 4 while I<=N

Step4: IF A[I]= val

SET POS=I

PRINT POS

Go to Step 6

[END OF IF]
ACSCE, Page 20
Module-3: Arrays

SET I=I+1

[END OF LOOP]

Step5: IF POS= -1,

PRINT “VALUE IS NOT PRESENT IN THE ARRAY”

[END OF IF]

Step6: EXIT

Program:

#include<stdio.h> void

main()

int a[10],num,i,n,found=0,pos=-1;

printf("Enter the number of elements in an array: ");

scanf("%d",&n);

printf("Enter the elements: ");

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

scanf("%d",&a[i]); printf("Enter the number that has to be

searched: ");

scanf("%d",&num);

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

ACSCE, Page 21
Module-3: Arrays

if(a[i]==num)

found=1;

pos=i;

printf("\n%d is found in the array at position %d",num,i+1);

break;

if(found==0)

printf("Element not found in the array");

Output:

Enter the number of elements in an array: 5

Enter the elements: 50 9 6 7 1

Enter the number that has to be searched: 6

6 is found in the array at position 3

Binary Search:

#include<stdio.h>

void main()

int i,low,high,mid,n,key,a[20];

ACSCE, Page 22
Module-3: Arrays

printf("Enter the number of elements in an array: ");

scanf("%d",&n);

printf("Enter the elements: ");

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

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

printf("Enter the value to find: ");

scanf("%d",&key);

low=0;

high=n-1;

while(low<=high)

mid=(low+high)/2;

if(a[mid]==key)

printf("%d found at location %d",key,mid+1);

break;

else if(a[mid]<key)

low=mid+1;

else

high=mid-1;
ACSCE, Page 23
Module-3: Arrays

if(low>high)

printf("%d not found in the array",key);

Output:

Enter the number of elements in an array: 5

Enter the elements: 1 2 3 4 5

Enter the value to find: 3

3 found at location 3

WAP to sort n numbers in ascending order using bubble sort technique:

#include<stdio.h> void

main()

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

printf("Enter the number of elements in an array: ");

scanf("%d",&n);

printf("Enter the elements: ");

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

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

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

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

ACSCE, Page 24
Module-3: Arrays

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

temp=a[j];

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

a[j+1]=temp;

printf("Array after implementing bubble sort:");

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

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

Output:

Enter the number of elements in an array: 5

Enter the elements: 60 9 8 5 100

Array after implementing bubble sort: 5 8 9 60 100

ACSCE, Page 25
Module-3: Arrays

WAP to sort n numbers in decending order using bubble sort technique:

#include<stdio.h>

void main()

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

printf("Enter the number of elements in an array: ");

scanf("%d",&n);

printf("Enter the elements: ");

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

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

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

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

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

temp=a[j];

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

a[j+1]=temp;

ACSCE, Page 26
Module-3: Arrays

printf("Array after implememting bubble sort:");

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

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

Output:

Enter the number of elements in an array: 5

Enter the elements: 90 7 6 100 99

Array after implememting bubble sort: 100 99 90 7 6

2-Dimensional Array
Arrays with 2 dimensions are called 2 –Dimensional array or 2-D array.

Declaration of 2-D array:

data_type array_name[row_size][column_size]; data_type can be

any primitive data type.

array_name is a variable name row_size is the maximum number of rows

in the array. column_size is the maximum number of column in the array.

Example: int a[2][3];

This can be read as

ACSCE, Page 27
Module-3: Arrays

Initialization of 2-D array:

1. Initialize with total number of elements:

int a[2][3]={1,2,3,4,5,6}

2. Initialize with sets

int a[2][3]={{1,2,3},{4,5,6}}

3. Partial initialization

int a[2][3]={{1,1},{2}}

4. Initialize without size int a[ ][3]={{1,2,3},{4,5,6}}

Initialization of 2-D array:

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

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

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

WAP to read and display elements from 2-D array.

ACSCE, Page 28
Module-3: Arrays

#include<stdio.h> void

main()

int a[20][20],m,n,i,j;

printf("Enter the number of rows and columns: ");

scanf("%d,%d",&m,&n);

printf("Enter the elements of the array:");

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

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

scanf("%d",&a[i][j]);

printf("The array elements are:\n");

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

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

printf("%d\t",a[i][j]);

printf("\n");
ACSCE, Page 29
Module-3: Arrays

Output:

Enter the number of rows and columns: 3,3 Enter the

elements of the array:1 2 3 4 5 6 7 8 9

The array elements are:

1 2 3

4 5 6

7 8 9

WAP to generate Pascal’s triangle.

#include<stdio.h> void

main()

int a[5][5]={0},row=2,col,i,j;

a[0][0]=a[1][0]=a[1][1]=1;

while(row<5)

a[row][0]=1; for(col=1;col<=row;col++)

a[row][col]=a[row-1][col-1]+a[row-1][col];

row++;

ACSCE, Page 30
Module-3: Arrays

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

printf("\n");

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

printf("%d\t",a[i][j]);

Output:

1 1

1 2 1

1 3 3 1

1 4 6 4 1

Operations on 2-Dimensional Array

1. Transpose

2. Sum

3. Difference

4. Product

ACSCE, Page 31
Module-3: Arrays

WAP to transpose 3 X 3 matrix.

#include<stdio.h> void main()

int a[20][20],m,n,i,j,b[20][20];

printf("Enter the number of rows and columns: ");

scanf("%d,%d",&m,&n);

printf("Enter the elements of the array:");

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

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

scanf("%d",&a[i][j]);

printf("The array elements are:\n");

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

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

printf("%d\t",a[i][j]);

printf("\n");
ACSCE, Page 32
Module-3: Arrays

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

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

b[i][j]=a[j][i];

printf("The elemnts of transposed matrix are:\n");

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

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

printf("%d\t",b[i][j]);

printf("\n");

Output:

Enter the number of rows and columns: 3,3 Enter the

elements of the array:1 2 3 4 5 6 7 8 9

ACSCE, Page 33
Module-3: Arrays

The array elements are:

1 2 3

4 5 6

7 8 9

The elemnts of transposed matrix are:

1 4 7

2 5 8

3 6 9

WAP to input 2 m x n matrices and then calculate the sum of their corresponding elements
and store it in third m x n matrix.

#include<stdio.h> void

main()

int a[20][20],b[20][20],c[20][20],m,n,p,q,r,t,i,j;

printf("Enter the number of rows and columns in first matrix: ");

scanf("%d,%d",&m,&n);

printf("Enter the number of rows and columns in second matrix: ");

scanf("%d,%d",&p,&q);

if(m!=p||n!=q)

printf("Number of rows and columns of both the matrix should be equal");

ACSCE, Page 34
Module-3: Arrays

r=m;

t=n;

printf("Enter the elements of the array 1:");

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

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

scanf("%d",&a[i][j]);

printf("Enter the elements of the array 2:"); for(i=0;i<p;i++)

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

scanf("%d",&b[i][j]);

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

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

{
ACSCE, Page 35
Module-3: Arrays

c[i][j]=a[i][j]+b[i][j];

printf("The elements of the resultant matrix are:\n");

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

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

printf("%d\t",c[i][j]);

printf("\n");

Output:

Enter the number of rows and columns in first matrix: 2,2

Enter the number of rows and columns in second matrix: 2,2

Enter the elements of the array 1:2 2 2 2

Enter the elements of the array 2:2 2 2 2

The elements of the resultant matrix are:

4 4

4 4

ACSCE, Page 36
Module-3: Arrays

WAP to input 2 m x n matrices and then calculate the product of their corresponding
elements and store it in third m x n matrix.

#include<stdio.h> void

main()

int a[20][20],b[20][20],c[20][20],m,n,p,q,k,i,j;

printf("Enter the number of rows and columns in first matrix: ");

scanf("%d,%d",&m,&n);

printf("Enter the number of rows and columns in second matrix: ");

scanf("%d,%d",&p,&q); if(n!=p)

printf("Matrix multiplication is not possible");

printf("Enter the elements of the array 1:");

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

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

scanf("%d",&a[i][j]);

ACSCE, Page 37
Module-3: Arrays

printf("Enter the elements of the array 2:");

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

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

scanf("%d",&b[i][j]);

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

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

c[i][j]=0;

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

c[i][j]=a[i][k]*b[k][j]+c[i][j];

printf("The elements of the resultant matrix are:\n"); for(i=0;i<m;i++)

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

printf("%d\t",c[i][j]);
ACSCE, Page 38
Module-3: Arrays

printf("\n");

Output:

Enter the number of rows and columns in first matrix: 2,2

Enter the number of rows and columns in second matrix: 2,2

Enter the elements of the array 1:2 2 2 2

Enter the elements of the array 2:2 2 2 2

The elements of the resultant matrix are:

8 8

8 8

Multi-Dimensional array
• A Multi-Dimensional array is an array of arrays.

• Like we have 1 index in 1-D array, 2 index in 2-D array, we have n index in n-
dimensional array.

WAP to read and display 2 x 2 x 2 array.

#include<stdio.h> void

main()

int a[2][2][2],i,j,k;

ACSCE, Page 39
Module-3: Arrays

printf("Enter the elements of the matrix: ");

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

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

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

scanf("%d",&a[i][j][k]);

printf("The matrix is: \n");

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

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

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

printf("a[%d][%d][%d]=%d\t",i,j,k,a[i][j][k]);

printf("\n");

}
ACSCE, Page 40
Module-3: Arrays

Output:

Enter the elements of the matrix: 1 2 3 4 5 6 7 8 9 The matrix is:


a[0][0][0]=1 a[0][0][1]=2

a[0][1][0]=3 a[0][1][1]=4

a[1][0][0]=5 a[1][0][1]=6

a[1][1][0]=7 a[1][1][1]=8

Applications of array

• Storing and accessing data: Arrays are used to store and retrieve data in a specific
order. For example, an array can be used to store the scores of a group of students, or the
temperatures recorded by a weather station.

• Sorting: Arrays can be used to sort data in ascending or descending order. Sorting
algorithms such as bubble sort, merge sort, and quick sort rely heavily on arrays.

• Searching: Arrays can be searched for specific elements using algorithms such as linear
search and binary search.

• Matrices: Arrays are used to represent matrices in mathematical

computations such as matrix multiplication, linear algebra, and image processing.

• Stacks and queues: Arrays are used as the underlying data structure for implementing
stacks and queues, which are commonly used in algorithms and data structures.

• Graphs: Arrays can be used to represent graphs in computer science. Each element in
the array represents a node in the graph, and the relationships between the nodes are
represented by the values stored in the array.

*****End*****

ACSCE, Page 41
Module-3: Arrays

STRINGS
A string is a sequence of characters enclosed within quotation marks and used to represent
textual data in programming.
Or
A string is a finite sequence of characters (letters, numbers, or symbols) terminated by a special
character (such as the null character '\0' in C)
Example: char name[]=”Ram”;
here :
name: is the string variable name
“Ram”: is the string literal
Internally it is stored has as

Index 0 1 2 3

Value R a m \0

The null character ‘\0’ marks the end of the string.

Characteristics

1. Immutable (in most languages like Python, Java) – Once created, the string cannot be
changed.
2. Indexed – Each character in a string has a position (index), starting from 0.
Example:
"CAT"[0] → 'C'
3. Can include letters, digits, symbols, and spaces.
Example: "CS101 @ 2025"

String Variable
A string variable is a character array that can store a string. A named memory location that
is used to store a string value (a sequence of characters).

Syntax: char variable_name[size];

ACSCE, Page 42
Module-3: Arrays

char: data type for characters.


variable_name: name of the string.
Size: number of characters including null character.

Example: char city[10]=”Mysore”;

Mysore has 6 letters and one extra space is reserved for ‘\0’.

Program

#include <stdio.h>

int main() {

char name[20];

printf("Enter your name: ");

scanf(“%s”, name);

printf("Hello %s!", name);

return 0;

}
Output
Enter your name: Ram
Hello Ram!

String Declaration and Initialization In C


Declaration

You declare a string as a character array:

char name[20];

Initialization

You can initialize in three ways:


ACSCE, Page 43
Module-3: Arrays

Method 1: With double quotes

char name[20] = "Programming";

Method 2: Character-by-character

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

(Note '\0' → string termination character)

Method 3: Using pointers

Char *name= “Ram”;

Important points:

• "Ram" is stored in read-only memory.

• name points to the first character.

• You must NOT modify this string (undefined behavior).

Example Program:

#include<stdio.h>

int main() {

char city1[20]=”Bangalore”;

char city2[20]={‘M’, ’y’, ’s’, ’o’, ’r’, ’e’, ’\0’};

char *city3=”Chennai”;

char city4[20];

printf(“Enter the name of city 4 :\n”);

scanf(“%s”,city4);

printf(“City1 %s \n”, city1);

printf(“City2 %s \n”, city2);


ACSCE, Page 44
Module-3: Arrays

printf(“City3 %s \n”, city3);

printf(“City4 %s \n”, city4);

Reading Strings from the Terminal in C


In C programming, reading strings (words, sentences, names, etc.) from the user is very
important.

A string is basically a collection of characters ending with a null character (\0).

We can read strings from the user using different input functions:

1. Using scanf()

Syntax: scanf("%s", str);

Advantages

Easy to use

Good for single-word inputs

Limitation: Stops reading when a space is encountered(so "Ram N Bhatt" → only "Ram" is
read)

Example:

#include <stdio.h>

int main() {

char name[20];

char city[20];

printf("Enter your name: ");

scanf("%s", name);

ACSCE, Page 45
Module-3: Arrays

printf("Enter your City: ");

scanf("%s", city);

printf("You entered: %s", name);

printf("Your city is: %s", city);

return 0;

2. Using gets() (NOT RECOMMENDED)

gets(); reads an entire line including spaces.

BUT it is unsafe → may cause buffer overflow.

Hence, DO NOT USE IN MODERN C.

3. Using fgets() (BEST & SAFE)

Syntax:

fgets(str, size, stdin);

✔ Advantages

Reads spaces

Safe (prevents overflow)

Recommended for real programs

Example:

#include <stdio.h>

int main() {

char sentence[50];
ACSCE, Page 46
Module-3: Arrays

printf("Enter a sentence: ");

fgets(sentence, sizeof(sentence), stdin);

printf("You entered: %s", sentence);

return 0;

Note: fgets() also stores the newline (\n). You can remove it if needed.

Writing Strings to the Screen in C


After reading strings from the user, we often need to display (print) strings on the screen.
C provides multiple functions to do this.

1. Using printf()

The most common way to print strings.

Syntax: printf("%s", stringVariable);

Example:

#include <stdio.h>

int main() {

char name[] = "Shruthi";

printf("Name: %s", name);

return 0;

ACSCE, Page 47
Module-3: Arrays

Why it’s useful?

• Can print combined text and variables.

• Most frequently used output function.

2. Using puts()

puts(); prints a string and automatically adds a newline (\n).

Example:

#include <stdio.h>

int main() {

char message[] = "Welcome to C programming!";

puts(message); // Prints message and moves to next line

return 0;

Advantages

• Simple to use

• Always prints on a new line

3. Using fputs()

Used to print strings to a file or the screen.

To print on the screen, we use:

fputs(string, stdout);

Example:

#include <stdio.h>

int main() {

char text[] = "Hello Students!";


ACSCE, Page 48
Module-3: Arrays

fputs(text, stdout);

return 0;

Advantage

• Does not add a newline automatically

• Good for controlled output

Arithmetic Operations on Characters in C

In C, characters (char) are internally stored as integers using the ASCII code.
This means each character has a numeric value.

For example:

ASCII
Character Value

'A' 65

'B' 66

'a' 97

'0' 48

'1' 49

Because characters behave like integers, they can be used in arithmetic operations ( + , – , * ,
/ ).

ACSCE, Page 49
Module-3: Arrays

1. Characters Are Treated as Integers

When you perform arithmetic on characters:

• The character is converted to its ASCII value.

• Operation is performed on that number.

• The result can be converted back to a character if needed.

Example:

char c = 'A';

int x = c + 1; // c is 65, so x becomes 66

2. Addition with Characters

You can move forward in the character set.

Example:

char c = 'A';

char next = c + 1; // 'B'

Output:

Because:

• 'A' → 65

• 65 + 1 → 66 → 'B'

3. Subtraction with Characters

You can find the difference between characters.

Example:

char c1 = 'd';

char c2 = 'a';
ACSCE, Page 50
Module-3: Arrays

int diff = c1 - c2;

Output:

Because:

• 'd' → 100

• 'a' → 97

• 100 – 97 = 3
But characters are 0-indexed, so 'd' is 3 letters after 'a'.

4. Checking Distance Between Characters

Example: How many letters between 'A' and 'D'?

'A' = 65

'D' = 68

68 – 65 = 3

5. Converting Between Cases (Upper ↔ Lower)

Convert uppercase → lowercase:

Using ASCII logic:

lowercase = uppercase + 32

Example:

char upper = 'A';

char lower = upper + 32; // 'a'

Convert lowercase → uppercase:

uppercase = lowercase - 32

ACSCE, Page 51
Module-3: Arrays

Example:

char lower = 'z';

char upper = lower - 32; // 'Z'

6. Character to Integer and Integer to Character

Character → Integer

char c = '5';

int x = c - '0'; // Converts '5' to 5

Integer → Character

int n = 7;

char c = n + '0'; // Converts 7 to '7'

7. Arithmetic Expressions with Characters

You can even combine multiple characters in expressions.

Example:

char a = 'A';

char b = 'C';

int result = (b - a) + 5;

Explanation:

'C' = 67, 'A' = 65

67 – 65 = 2

2+5=7

ACSCE, Page 52
Module-3: Arrays

8. Using Characters in Loops

You can use character arithmetic to loop through alphabets.

Example:

for (char c = 'A'; c <= 'Z'; c++) {

printf("%c ", c);

Because 'A' increments as 65 → 66 → 67 ... → 90

Complete Program Example

#include <stdio.h>

int main() {

char c = 'A';

printf("Character: %c\n", c);

printf("ASCII value: %d\n", c);

printf("Next character: %c\n", c + 1);

printf("Previous character: %c\n", c - 1);

printf("Uppercase to lowercase: %c\n", c + 32);

char d = 'd';

printf("Lowercase to uppercase: %c\n", d - 32);

printf("Distance between 'd' and 'a': %d\n", 'd' - 'a');


ACSCE, Page 53
Module-3: Arrays

return 0;

}
Operation Meaning
'A' + 1 : Next alphabet
'A' - 1 : Previous alphabet
'a' - 'A' : Difference between characters
lowercase = uppercase + 32 Convert case
numeric_value = char - '0' Convert digit char → int
char = int + '0' Convert int → digit char

ASCII Values of All Alphabets (A–Z, a–z) and Numbers (0–9)


ASCII Values of Digits (0–9)

Character ASCII

'0' 48

'1' 49

'2' 50

'3' 51

'4' 52

'5' 53

'6' 54

'7' 55

'8' 56

ACSCE, Page 54
Module-3: Arrays

Character ASCII

'9' 57

ASCII Values of Uppercase Alphabets (A–Z)

Character ASCII Character ASCII

A 65 N 78

B 66 O 79

C 67 P 80

D 68 Q 81

E 69 R 82

F 70 S 83

G 71 T 84

H 72 U 85

I 73 V 86

J 74 W 87

K 75 X 88

L 76 Y 89

M 77 Z 90
ACSCE, Page 55
Module-3: Arrays

ASCII Values of Lowercase Alphabets (a–z)

Character ASCII Character ASCII

a 97 n 110

b 98 o 111

c 99 p 112

d 100 q 113

e 101 r 114

f 102 s 115

g 103 t 116

h 104 u 117

i 105 v 118

j 106 w 119

k 107 x 120

l 108 y 121

m 109 z 122

String-Handling Functions in C
String-handling functions are predefined functions in the string.h library used to perform
operations on strings such as copying, comparing, measuring length, joining, searching, and
modifying strings.

ACSCE, Page 56
Module-3: Arrays

To use these functions:

#include <string.h>

1. strlen() — Find Length of a String

Returns the number of characters in a string excluding the null character (\0).

Syntax :int strlen(const char *str);

Example

strlen("hello") → 5

Program

printf("Length = %d", strlen(str));

2. strcpy() — Copy One String to Another

Copies contents of source string into destination.

Syntax: strcpy(dest, src);

Program

strcpy(name2, name1);

Note: Destination must have enough space.

3. strncpy() — Copy First N Characters

Copies only first N characters.

Syntax: strncpy(dest, src, n);

Use Case

When you want partial copy.


ACSCE, Page 57
Module-3: Arrays

4. strcmp() — Compare Two Strings


Compare Only First N Characters
Syntax
strncmp(s1, s2, n);
Example
strncmp("computer", "compete", 4)
Result → 0 because first 4 letters comp match.
When to Use?
• Comparing prefixes
• Checking file extensions
• Comparing only part of strings

4. Case-Insensitive Comparison (Ignore Upper/Lower Case)

Some compilers provide:


strcasecmp(s1, s2);
stricmp(s1, s2);
Example
"Hello" vs "hello" → equal
Because case difference is ignored.

5. Manual String Comparison (Logic Behind strcmp)

int compare(char s1[], char s2[]) {


int i = 0;
while (s1[i] != '\0' && s2[i] != '\0') {
if (s1[i] != s2[i])
return s1[i] - s2[i];
i++;
}
return s1[i] - s2[i];
}
This shows exactly how strcmp() works.

ACSCE, Page 58
Module-3: Arrays

6. Understanding “Greater Than” and “Less Than”

Comparison uses ASCII values:


• 'a' (97) > 'A' (65)
• "bat" > "ball"
because at 4th position:
't' (116) > 'l' (108)

Example Program Using strcmp()

#include <stdio.h>
#include <string.h>

int main() {
char s1[20], s2[20];

printf("Enter first string: ");


scanf("%s", s1);

printf("Enter second string: ");


scanf("%s", s2);

int result = strcmp(s1, s2);

if (result == 0)
printf("Strings are equal");
else if (result > 0)
printf("First string is greater");
else
printf("Second string is greater");

return 0;
}

ACSCE, Page 59
Module-3: Arrays

5. strncmp() — Compare First N Characters

Compares only the first n characters.

Syntax: strncmp(s1, s2, n);

6. strcat() — Concatenate (Join) Strings

Adds src at the end of dest.

Syntax: strcat(dest, src);

Example

strcat(first, last); // joins strings

Note: Destination must have enough space.

7. strncat() — Join First N Characters

Appends only N characters of source.

Syntax: strncat(dest, src, n);

8. strchr() — Find First Occurrence of a Character

Searches for a character in a string.

Syntax:strchr(str, ch);

Returns

Pointer to first occurrence OR NULL.

Example

strchr("computer", 'm') → points to "mputer"

ACSCE, Page 60
Module-3: Arrays

9. strrchr() — Find Last Occurrence of a Character

Syntax: strrchr(str, ch);

Example

strrchr("banana", 'a') → last 'a'

10. strstr() — Find First Occurrence of a Substring

Searches for a substring inside a string.

Syntax:strstr(str, substr);

Example

strstr("information", "mat") → points to "mation"

11. strtok() — Tokenize (Split) a String

Breaks a string into tokens using a delimiter (space, comma, etc.)

Syntax:strtok(str, delimiter);

Example

strtok("C,Java,Python", ",");

Returns tokens:
C → Java → Python

12. strrev() (Compiler-Specific)

Reverses a string (available in some compilers like Turbo C).

Syntax

strrev(str);

ACSCE, Page 61
Module-3: Arrays

Simple Example Program Covering Key Functions

#include <stdio.h>

#include <string.h>

int main() {

char s1[50] = "Hello";

char s2[50] = "World";

printf("Length of s1 = %d\n", strlen(s1));

strcat(s1, s2);

printf("After concatenation: %s\n", s1);

strcpy(s2, "Hello");

if (strcmp(s1, s2) == 0)

printf("Strings are equal\n");

else

printf("Strings are different\n");

return 0;

ACSCE, Page 62
Module-3: Arrays

C Program Demonstrating All Major String-Handling Functions.

#include <stdio.h>

#include <string.h>

int main() {

char str1[50] = "Hello";

char str2[50] = "World";

char str3[50];

char str4[100] = "C programming is amazing!";

char *ptr;

// 1. strlen()

printf("1. Length of str1 (\"%s\") = %lu\n", str1, strlen(str1));

// 2. strcpy()

strcpy(str3, str1);

printf("2. After strcpy(str3, str1): str3 = %s\n", str3);

// 3. strncpy()

strncpy(str3, str2, 3);

str3[3] = '\0'; // ensure null termination

printf("3. After strncpy(str3, str2, 3): str3 = %s\n", str3);

ACSCE, Page 63
Module-3: Arrays

// 4. strcat()

strcat(str1, str2);

printf("4. After strcat(str1, str2): %s\n", str1);

// 5. strncat()

strncat(str1, "Programming", 5);

printf("5. After strncat(str1, \"Programming\", 5): %s\n", str1);

// 6. strcmp()

int res = strcmp("apple", "banana");

printf("6. strcmp(\"apple\", \"banana\") = %d\n", res);

// 7. strncmp()

res = strncmp("computer", "composition", 4);

printf("7. strncmp(\"computer\", \"composition\", 4) = %d\n", res);

// 8. strchr()

ptr = strchr(str4, 'a');

if (ptr)

printf("8. First occurrence of 'a' in \"%s\" = %s\n", str4, ptr);

// 9. strrchr()

ptr = strrchr(str4, 'a');


ACSCE, Page 64
Module-3: Arrays

if (ptr)

printf("9. Last occurrence of 'a' in \"%s\" = %s\n", str4, ptr);

// 10. strstr()

ptr = strstr(str4, "am");

if (ptr)

printf("10. Substring \"am\" found in str4 = %s\n", ptr);

// 11. strtok()

printf("11. Using strtok() to split \"C,Java,Python\":\n");

char str5[50] = "C,Java,Python";

char *token = strtok(str5, ",");

while (token != NULL) {

printf(" Token: %s\n", token);

token = strtok(NULL, ",");

ACSCE, Page 65
Module-3: Arrays

QUESTIONS
Q1 Explain the concept of one-dimensional and two-dimensional arrays in C. Write the
syntax for declaration and initialization.

Q2 Differentiate between static and dynamic initialization of arrays with suitable examples.

Q3 Write a C program to read marks of N students, store them in an array, and compute total,
average, highest, and lowest marks.

Q4 Write a program to read a 3×3 matrix and display its


(a) row-wise sum
(b) column-wise sum
(c) diagonal sum

Q5 Analyze how memory is allocated for 1D and 2D arrays in C. Explain row-major order
with a diagram.

Q6 Explain how strings are declared, initialized, and stored in memory in C. Mention the
importance of the null character (‘\0’).

Q7 Discuss the difference between declaring a string using

char str[20];

char *str;

Explain with diagrams.

Q8 Write a C program to perform linear search using arrays and display the position of the
element if found.

Q9 Write a C program to sort an array in ascending order using bubble sort.

Q10 Write a C program to read two matrices and perform matrix addition.

Q11 Explain different ways of reading and writing strings in C (scanf, gets, puts, fgets,
printf). State advantages and disadvantages.

Q12 Write a C program to read a sentence using fgets() and display it using puts().

Q13 Define ASCII. Write ASCII values for digits, uppercase, and lowercase letters.

Q14 Write a program to convert a lowercase string to uppercase using ASCII arithmetic.
ACSCE, Page 66
Module-3: Arrays

Q15 Explain how characters are internally represented in memory. Illustrate with ASCII-
based arithmetic examples.

Q16 Explain how two strings can be compared manually without using library functions.

Q17 Write a program to compare two strings using strcmp() and display appropriate
messages.

Q18 Differentiate between lexicographical comparison and length comparison. Provide


examples.

Q19 List all major string-handling functions in C and write their purpose.

Q20 Explain the working of the following functions with examples:


strlen(), strcpy(), strcat(), strcmp(), strstr().

Q21Write a C program demonstrating any five string-handling functions.

Q22 Analyse differences between strcpy() and strncpy(). Explain memory safety issues.

Q23 Design a menu-driven C program to perform multiple string operations like:

• Count characters

• Reverse the string

• Copy string

• Find substring

• Convert case

Q24 Explain how arrays and strings are similar and different in C. Include memory diagrams.

Q25 Develop a C program that reads n student names, sorts them alphabetically, and prints
them.

ACSCE, Page 67

Common questions

Powered by AI

The binary search algorithm differs from a linear search in that binary search is more efficient and requires that the array be sorted prior to search. Binary search works by repeatedly dividing the array in half and comparing the middle element to the target value. If the middle element matches the target, the search is complete. If the target is less than the middle element, the search continues in the left half, otherwise in the right half. This reduces the search space by half each iteration. Linear search, however, checks each element sequentially until it finds the target or reaches the end of the array, and does not benefit from the array being sorted .

The strcmp() function in C is used to compare two strings, returning 0 if they are equal, a negative number if the first string is less than the second, and a positive number if the first string is greater. The comparison is based on the ASCII values of characters. The function iterates through both strings, comparing characters one by one until a difference is found or the end of strings is reached. This comparison logic relies on the way strings are stored in memory as arrays of characters, allowing direct access and comparison using their ASCII values .

In C programming, characters are treated as integers because they are represented by their corresponding ASCII values. This allows for arithmetic operations on characters as if they were numbers. For example, adding 1 to the character 'A' results in 'B', since 'A' has an ASCII value of 65, and adding 1 results in 66, which corresponds to 'B'. Subtraction can also be used to determine the distance between characters in the ASCII table. This integer treatment of characters facilitates operations such as converting between uppercase and lowercase, or iterating through character sequences efficiently .

Merging two arrays into a third array involves iterating through each element of the two source arrays and sequentially copying them into the target array. This can be done by starting with the first array, copying all its elements into the third array, and then continuing with the second array. If the arrays' elements are expected to overlap or interleave according to some condition (like respecting an order), additional logic is implemented to intersperse elements appropriately based on this condition. The process ensures that all elements from both arrays are preserved in the new array without data duplication or omission .

The algorithm to delete an element from an array ensures coherence by shifting all elements to the right of the deleted element one position to the left. This fills the gap left by the removed element. The array size is then decremented by one to reflect the removal of an element. This operation maintains the order of remaining elements and the array's integrity, ensuring that there are no gaps or duplicate entries and that all elements are still accessible in their new positions .

The strcat() function in C is used to concatenate two strings. It appends the second string to the end of the first, modifying the first string in the process. This function assumes that the first string has enough space allocated to accommodate the new combined length. By using strcat(), programmers can easily join strings together, supporting operations like string construction and formatting. This function is crucial for string manipulation tasks such as creating dynamic messages or combining data in a readable format .

In C programming, ASCII values play a crucial role in converting and comparing characters. All characters are associated with ASCII values, which allows them to be treated like integers. This enables arithmetic operations for case conversion, sequence iteration, and difference calculation directly on characters. However, reliance on ASCII means that such operations assume the presence of an ASCII-compatible encoding system. This can affect portability because systems using different character encodings may not align with ASCII, causing these operations to produce incorrect results on such systems. To ensure consistency across different environments, it is crucial to consider the encoding standards of the deployment system .

The bubble sort algorithm involves multiple passes over the array. On each pass, adjacent elements are compared, and if they are in the wrong order (e.g., the first is greater than the second in an ascending sort), they are swapped. This process is repeated until the array is sorted, which can be determined when a complete pass produces no swaps. The primary inefficiency of the bubble sort is its O(n^2) time complexity for average and worst cases, making it inefficient on large datasets, as it repeatedly iterates over elements that are already sorted, performing unnecessary comparisons and swaps .

To insert an element into a specific position of an unsorted array, the elements from that position onwards need to be shifted one position to the right to create space for the new element. This is accomplished by iterating from the end of the array to the insertion position, copying each element to the next index. Once the space is created, the new element is placed at the specified position. This ensures that no data is lost and the array's integrity is maintained, as all original elements are preserved and the array size is incremented by one .

The process of inserting an element into an array that is already sorted in ascending order involves identifying the correct position where the new element should be inserted to maintain the order. This can be done by iterating over the elements of the array and comparing each one with the new element until a larger element is found. At this point, the elements from that position onwards are shifted one position to the right to make space for the new element, which is then inserted at the correct position. By doing this, the array remains sorted in ascending order .

You might also like