UNIT-III Arrays and Strings
Introduction
Array is defined as collection of elements of the same type
of data stored at continuous memory locations.
Arrays are derived data types in 'C' which can store the
primitive types of data such as int, char, float etc.
Array start at index '0' and ends at the index (size - 1).
Advantages of Array:
I. Code Optimization: Less code to access the data.
II. Easy to traverse data: By using for loop, we can retrieve
the elements of an array easily.
III. Easy to sort data: To sort the elements of array, we need a
few lines of code only.
IV. Random Access: We can access any element randomly using the
array.
Disadvantages of Array:
I. Fixed Size:The size of the array is declared at the time of
declaration. Size cannot be altered dynamically at run
time.
II. Only Same Data Type:Arrays can only store elements of the
same data type.
Declaration of an Array:
Array is declared as follows
Datatype variable_name[size/length of array];
Data type denotes the type of elements in the array.
Array name denotes name of the array.
Size denotes number of elements an array can store.
Note: Array size must be a positive value.
For example:
int arr[10];
Initialization of an Array:
Initialization means to assign or store a value into any
variable.
An array can be initialized at either compile time or at
runtime.
Compile time initialization of array elements is same as
ordinary variable initialization.
Syntax :
Datatype array_name[size]={v1,v2,v3, …vn};
Example:
int age[5]={25,20,15,30,40};
int marks[4]={17, 37, 26, 47}; //integer array initialization
float area[5]={33.4, 16.8, 25.5}; //float array initialization
int marks[4]={17, 37, 26, 47, 50}//Compile time error
Accessing elements of an array
To access the elements of an array, we use the array name
followed by the index value enclosed in square brackets [ ]
of the element.
The index value of an array starts with 0 for the
1stelement, is incremented by 1 for each element, and ends
with [size - 1].
Example :Write a C program to print array elements
#include <stdio.h>
void main()
{
int a[4] = {41, 23, 38, 45};
for (i=0;i<=3;i++)
printf("%d", a[i]);
getch();
}
Output:
41 23 38 45
Example: Program to print array elements and also find its sum.
#include <stdio.h>
void main()
{
int a[4] = {21, 26, 13, 34};
int i, sum = 0;
for (i = 0; i <= 3; i++)
{
sum = sum + a[i];
}
printf("sum = %d", sum);
}
Output:
Sum = 94
Program: To find maximum and minimum value in an array.
#include <stdio.h>
int main() {
int i;
int a[5], max, min;
for(i = 0; i < 5; i++) {
printf("Enter array element %d: ", i + 1);
scanf("%d", &a[i]);
}
max = min = a[0];
for (i = 0; i< 5; i++)
{
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
printf("Max = %d, Min = %d\n", max, min);
return 0;
}
Output:
Enter array element 1: 30
Enter array element 2: 20
Enter array element 3: 50
Enter array element 4: 61
Enter array element 5: 80
Max = 80, Min = 20
Program to search an element using Linear Search
#include <stdio.h>
void main()
{
int array[100], search, c, number;
printf("Enter the number of elements in array\n");
scanf("%d",&number);
printf("Enter %d numbers\n", number);
for ( c = 0 ; c < number ; c++ )
scanf("%d",&array[c]);
printf("Enter the number to search\n");
scanf("%d",&search);
for ( c = 0 ; c < number ; c++ )
{
if ( array[c] == search )
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if ( c == number )
printf("%d is not present in array.\n", search);
}
Output :
Enter the number of elements in array
5
Enter 5 numbers
34
7
234
65
9
Enter the number to search
234
234 is present at location 3.
Example :Program to print the array elements in reverse order
#include <stdio.h>
void main()
int a[10], i, n;
printf("Array size is ");
scanf("%d", &n);
printf("Enter elements ");
for (i = 0; i< n; i++)
scanf("%d", &a[i]);
printf("Reversed no is ");
for (i = n - 1; i>= 0; i--)
printf("%d", a[i]);
Output:
Array size is 5
Enter elements 20 40 60 80 100
Reversed no is 100 80 60 40 20
Two‐Dimensional Arrays or Multi-Dimensional Arrays
Multi Dimensional Array:
1. Array having more than one subscript variable is called
Multi-Dimensional array.
2. The two dimensional, three dimensional or other dimensional
arrays are also known as multidimensional arrays.
Two‐Dimensional Arrays :
Two dimensional arrays are used to represent data in the form
of rows and columns also known as Matrix.
It is a combination of rows and columns of homogeneous
elements.
Syntax: data_type array_name[row_size][column_size];
Declaration:
int array1[2][3];
Here,int is a data type, array1 is array name, ‘2’ represents
the number of rows and ‘3’ represents the number of columns.
Initialization of 2D Array
int arr[2][4]={{31,24,13,94},{82,23,15,49}};
Example: write a ‘c’ program to print array elements in the two
dimensional array with row size2 and column size3
#include <stdio.h>
int main()
{
int a[2][3] = {50, 20, 10, 40, 90, 60};
printf("a[0][0] = %d\n", a[0][0]);
printf("a[0][1] = %d\n", a[0][1]);
printf("a[0][2] = %d\n", a[0][2]);
printf("a[1][0] = %d\n", a[1][0]);
printf("a[1][1] = %d\n", a[1][1]);
printf("a[1][2] = %d\n", a[1][2]);
return 0;
}
Output:
a[0][0] = 50
a[0][1] = 20
a[0][2] = 10
a[1][0] = 40
a[1][1] = 90
a[1][2] = 60
Example: write a C program for addition of two Matrices
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, m, n;
clrscr();
printf("Enter the rows and columns of two matrices:\n");
scanf("%d %d", &m, &n);
printf("\nEnter the elements of A matrix:");
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &a[i][j]);
printf("\nEnter the elements of B matrix:");
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &b[i][j]);
printf("\nThe addition of two matrices is:\n");
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
c[i][j] = a[i][j] + b[i][j];
printf("\t%d", c[i][j]);
}
printf("\n");
}
}
Output:
Enter the rows and columns of two matrices:
3 2
Enter the elements of A matrix:
90 30
50 10
80 60
Enter the elements of B matrix:
20 50
40 10
70 60
The addition of two matrices is:
110 80
90 20
150 120
Algorithm: The algorithm for the matrix addition:
Step 1: Start
Step 2: Declare three 2D arrays `a[10][10]`, `b[10][10]`, and
`c[10][10]` to store the matrices.
Step 3: Declare variables `m`, `n` for rows and columns, and
loop counters `i`, `j`.
Step 4: Prompt the user to enter the number of rows (`m`) and
columns (`n`) of the matrices.
Step 5: Read values of `m` and `n`.
Step 6: Prompt the user to enter elements of Matrix A.
Step 7: Repeat for `i = 0` to `m - 1`
Repeat for `j = 0` to `n - 1`
Read `a[i][j]`
Step 8: Prompt the user to enter elements of Matrix B.
Step 9:Repeat for `i = 0` to `m - 1`
Repeat for `j = 0` to ‘n – 1’
Read `b[i][j]`
Step 10: Perform matrix addition and store result in Matrix C
Step 11:Repeat for `i = 0` to `m - 1`
Repeat for `j = 0` to `n - 1`
Set `c[i][j] = a[i][j] + b[i][j]`
Step 12: Display Matrix C (the result)
Step 13: End
Program: Write a C program for matrix multiplication
#include <stdio.h>
int main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, k;
int rowsA, colsA, rowsB, colsB;
// Input dimensions of Matrix A
printf("Enter rows and columns of Matrix A: ");
scanf("%d%d", &rowsA, &colsA);
// Input dimensions of Matrix B
printf("Enter rows and columns of Matrix B: ");
scanf("%d%d", &rowsB, &colsB);
// Check if multiplication is possible
if (colsA != rowsB) {
printf("Matrix multiplication not possible\n");
}
else{
// Input elements of Matrix A
printf("\nEnter elements of Matrix A:\n");
for (i = 0; i<rowsA; i++) {
for (j = 0; j <colsA; j++) {
printf("A[%d][%d]: ", i, j);
scanf("%d", &a[i][j]);
}
}
// Input elements of Matrix B
printf("\nEnter elements of Matrix B:\n");
for (i = 0; i<rowsB; i++) {
for (j = 0; j <colsB; j++) {
printf("B[%d][%d]: ", i, j);
scanf("%d", &b[i][j]);
}
}
// Initialize result matrix C to 0
for (i = 0; i<rowsA; i++) {
for (j = 0; j <colsB; j++) {
c[i][j] = 0;
}
}
// Perform matrix multiplication
for (i = 0; i<rowsA; i++) {
for (j = 0; j <colsB; j++) {
for (k = 0; k <colsA; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
// Print the resulting matrix
printf("\nResult Matrix (A x B):\n");
for (i = 0; i<rowsA; i++) {
for (j = 0; j <colsB; j++) {
printf("%d\t", c[i][j]);
}
printf("\n");
}
}
}
Output:
Enter rows and columns of Matrix A: 2 3
Enter rows and columns of Matrix B: 3 2
Enter elements of Matrix A:
A[0][0]: 2
A[0][1]: 4
A[0][2]: 6
A[1][0]: 1
A[1][1]: 3
A[1][2]: 5
Enter elements of Matrix B:
B[0][0]: 1
B[0][1]: 0
B[1][0]: 2
B[1][1]: 1
B[2][0]: 3
B[2][1]: 2
Result Matrix (A x B):
28 16
22 13
Introduction to Strings
String is a sequence of characters enclosed in double quotes.
The string can be defined as the one dimension array of
characters terminated by '\0' (or) null.
There are 2 ways to declare a string
i) char array
ii) string literal
i) Char array:
Char array is an array used to store a sequence of
characters
Each letter is represented in single quotes and enclosed
with curly braces { }
‘char’ is the data type and ‘ch[10]’ is an array of
characters with maximum size 10.
Example: char ch[10] = {‘c’,’o’,’l’,’l’,’e’,’g’,’e’}
ii) String literal:
String literal is a sequence of characters enclosed in
double quotes (" ").
String ends with a special character \0 to indicate the end
of the string.
Example: char s[] = “c programming”
String functions (or) string handling functions (or) string
built in functions:
I. Header file for string function is
a. #include<stdio.h>
b. #include<string.h>
II. String functions are :
a. strlen()
b. strlwr()
c. strupr()
d. strrev()
e. strcpy()
f. strcmp()
g. strcat()
a) strlen(): This function is used to find the length of a
given string. Counts white spaces and null char is not
counted.
It returns non-negative integer value as a result.
Syntax: variable=strlen(string);
b) strlwr(): This function is used to convert the letters into
lowercase letters.
Syntax: variable=strlwr(string);
c) strupr(): It converts the letters into uppercase letters.
Syntax: variable= strupr(string);
d) strrev(): This function is used to reverse the given string.
Syntax: variable=strrev(string);
e) strcpy(): This function is used to copy the source string
into destination string.
Syntax: variable = strcpy(destination, source);
f) strcmp(): This function is used to compare two strings
character by character.
Syntax: variable = strcmp(string1, string2);
g) strcat(): This function is used to concatenate one string
at the end of the another string.
Syntax: variable = strcat(string1, string2);
Write a c program using string functions
#include <stdio.h>
#include <string.h> // for string functions
int main() {
char str1[20] = "programming";
char str2[20] = "language";
char str3[20];
char str4[20] = "COLLEGE";
printf("Length of str1 = %d\n", strlen(str1));
strcpy(str3, str1);
printf("After strcpy, str3 = %s\n", str3);
strcat(str1, str2);
printf("After strcat, str1 = %s\n", str1);
printf("Lowercase of str4 = %s\n", strlwr(str4));
printf("Uppercase of str3 = %s\n", strupr(str3));
printf("Reverse of str3 = %s\n", strrev(str3));
if (strcmp(str1, str3) == 0)
printf("str1 and str3 are equal\n");
else
printf("str1 and str3 are not equal\n");
return 0;
}
Output:
Length of str1 = 11
After strcpy, str3 = programming
After strcat, str1 = programminglanguage
Lowercase of str4 = college
Uppercase of str3 = PROGRAMMING
Reverse of str3 = GNIMMARGORP
str1 and str3 are not equal
Array of Strings
String is a one-dimensional array.
Array of strings is a two-dimensional array.
It contains both rows and columns.
Each row is terminated with '\0' (or) null character.
Strings and array of strings are represented with double
quotations " ".
Syntax: char variable-name[size1][size2];
Here, size 1 represents the number of rows in a string
array, size2 represents the number of characters in each
row
Example Program
#include <stdio.h>
#include <string.h>
int main()
char set[2][10] = { "IT", "Workshop" };
inti;
printf("Array of strings is:");
for (i = 0; i < 2; i++)
printf("\t%s", set[i]);
return 0;
Output:
Array of strings is: IT workshop