Professional Documents
Culture Documents
Subject
Programming for Problem Solving (3110003)
Chapter – 4
Array & String
CONTENTS
1. CONCEPTS OF ARRAY
2. ONE-DIMENSIONAL ARRAYS
2.1. Declaration of One-dimensional Arrays
2.2. Initialization of One-dimensional Arrays
2.3. Solved Programs (One-dimensional Arrays)
3. TWO-DIMENSIONAL ARRAYS
3.1. Declaration of Two-dimensional Arrays
3.2. Initialization of Two-dimensional Arrays
3.3. Solved Programs (Two-dimensional Arrays)
4. MULTIDIMENSIONAL ARRAYS
5. STRINGS
5.1. Reading Strings
5.2. Printing Strings
6. BUILT-IN STRING FUNCTIONS (STRING-HANDLING FUNCTIONS)
6.1. strcat() Function
6.2. strcmp() Function
6.3. strcpy() Function
6.4. strlen() Function
6.5. strrev() Function
6.6. Other String Functions
7. SOLVED PROGRAMS (STRINGS)
1. CONCEPTS OF ARRAY
• An array is a collection of elements of similar data types referred by the same
variable name.
• An array is a linear and homogeneous data structure. Linear data structure stores
its individual data elements in a sequential order in the memory. Homogeneous
means all individual data elements are of the same data type.
• The individual elements of an array are referred by their index or sub-script
value. In C the index begins at zero and is always written inside square brackets.
• For example, if marks of 10 students are stored in an array named mark, then
mark[0] refers to the marks of the first student, mark[1] refers to the marks of the
second student and mark[9] refers to the marks of the tenth student, that is,
mark[n-1] refers to the marks of nth student.
Advantages of Array:
o Unlike variable an array can store number of values under single name.
o The array elements are stored contiguously.
o Array index helps to access any random values from the array and perform
operations on it.
o An array is a flexible data structure, means we can perform addition or
removal of elements at any position.
Disadvantages of Array:
o Only elements of same data types can be stored in an array. We cannot
store elements of multiple data types in a single array.
o If array size is big, that much amount of memory gets reserved.
o Big size of arrays and multi-dimensional arrays are complicated to access
and manipulate.
o If there is need to store more elements than array size, then it is not possible
and shortage of memory occurs.
o If less elements are stored than array size then it leads to memory wastage.
Types of Arrays:
o Arrays are categorized according to the dimensions used to define it. Here
the dimension indicates the number of rows and columns used to set size of an
array.
o There are following types of arrays:
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multidimensional arrays
2. ONE-DIMENSIONAL ARRAYS
• An array with single subscript is called as one-dimensional array.
where,
data_type = the type of data stored in the array
array_name = name of the array
size = maximum number of elements that an array can hold
• For example,
float height[20];
int marks[10];
char name[10];
declares the name as a character array (string) variable that can hold a
maximum number of 10 characters.
• Suppose we read the following string constant into the string variable name.
“WELL DONE”
• Each character of the string is treated as an element of an array name and is
stored in the memory as follows:
‘W’ ‘E’ ‘L’ ‘L’ ‘’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’
• When the compiler sees a character string, it terminates it with an additional null
character. Thus, the element name[10] holds the null character ‘\0’.
• When declaring character arrays, we must allow an extra element space for the
null terminator.
For example,
marks[0] = 35;
marks[1] = 70;
.
.
.
marks[9] = 86;
• You can also initialize the complete array directly.
Syntax:
data_type array_name[size] = {list of values};
For example,
int marks[10] = {35,70,40,55,26,43,56,82,78,86};
35 70 40 55 26 43 56 82 78 86
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]
is equivalent to
int marks[3] = {45,66,84};
In such cases, the subscript is assumed to equal to the number of elements in the
array (3 in this case).
• The elements which are not explicitly initialized are automatically set to zero.
Example:
int x[5] = {2,5};
implies
x[0] = 2;
x[1] = 5;
x[2] = 0;
x[3] = 0;
x[4] = 0;
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n;
float avg,sum=0;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
sum=sum+a[i];
}
avg=sum/n;
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nSum = %0.2f \nAverage = %0.2f",sum,avg);
getch();
}
Output:
Enter value of n (not more than 10): 5
Enter number 1: 12
Enter number 2: 23
Enter number 3: 8
Enter number 4: 56
Enter number 5: 9
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,max,min;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
max=a[0];
min=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nLargest = %d \nSmallest = %d",max,min);
getch();
}
Output:
Enter value of n (not more than 10): 5
Enter number 1: 7
Enter number 2: 2
Enter number 3: 9
Enter number 4: 5
Enter number 5: 6
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,odd=0,even=0;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
if(a[i]%2==0)
even++;
else
odd++;
}
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nNumber of Odd = %d \nNumber of Even =
%d",odd,even);
getch();
}
Output:
Enter value of n (not more than 10): 7
Enter number 1: 4
Enter number 2: 3
Enter number 3: 1
Enter number 4: 7
Enter number 5: 6
Enter number 6: 8
Enter number 7: 9
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,max,count;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
max=a[0];
}
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
count=0;
for(i=0;i<n;i++)
{
if(max==a[i])
count++;
}
printf("\nArray elements are: ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nMaximum number = %d and is repeated %d
times",max,count);
getch();
}
Output:
Enter value of n (not more than 10): 8
Enter number 1: 12
Enter number 2: 34
Enter number 3: 23
Enter number 4: 34
Enter number 5: 32
Enter number 6: 4
Enter number 7: 34
Enter number 8: 24
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,temp;
clrscr();
printf("Enter value of n (not more than 10): ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\nNumbers in ascending order:\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nNumbers in descending order:\n");
for(i=n-1;i>=0;i--)
printf("%4d",a[i]);
getch();
}
Output:
Enter value of n (not more than 10): 7
Enter number 1: 8
Enter number 2: -2
Enter number 3: 12
Enter number 4: 23
Enter number 5: -6
Enter number 6: 45
Enter number 7: 9
3. TWO-DIMENSIONAL ARRAYS
• An array with two subscripts is called as two-dimensional array.
• 2D arrays are mostly used to perform matrix operations.
• A matrix has two subscripts – the first subscript denotes the number of rows and
the second subscript denotes the number of columns.
where,
data_type = the type of data stored in the array
array_name = name of the array
row_size = maximum number of rows in the array
column_size = maximum number of columns in the array
• For example,
int table[2][3]; //implies 2 rows and 3 columns
declares the table to be an array containing 2 rows and 3 columns, i.e., total 6
real elements.
• A user can view this array as below.
Column 0 Column 1 Column 2
Row 0 [0][0] [0][1] [0][2]
Row 1 [1][0] [1][1] [1][2]
table[0][0] 4000
table[0][1] 4002
table[0][2] 4004 Memory
table[1][0] 4006 Address
table[1][1] 4008
table[1][2] 4010
initialize first row data as {0,0,0} and second row data as {1,1,1}.
• The above initialization is same as
• If the values are missing in an initializer, they are automatically set to 0. For
example, the statement
int table[2][3] = {{1,1},{2}};
will initialize the first two elements of the first row to 1, the first element of the
second row to 2, and all other elements to 0.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j,max;
clrscr();
printf("Enter the elements of matrix A:\n");
for(i=0;i<3;i++) //Get matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
max=a[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(a[i][j]>max)
max=a[i][j];
}
}
printf("\nThe Largest number in the matrix A is: %d",max);
getch();
}
Output:
Enter the elements of matrix A:
a[0][0] = 5
a[0][1] = 23
a[0][2] = 7
a[1][0] = 85
a[1][1] = 61
a[1][2] = 3
a[2][0] = 67
a[2][1] = 99
a[2][2] = 2
Matrix A:
5 23 7
85 61 3
67 99 2
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Enter the elements of first matrix:\n");
for(i=0;i<3;i++) //Get first matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("Enter the elements of second matrix:\n");
for(i=0;i<3;i++) //Get second matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display first matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for(i=0;i<3;i++) //Display second matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",b[i][j]);
}
printf("\n");
}
printf("\nAddition of matrix A and B:\n");
for(i=0;i<3;i++) //calculate sum and display result matrix
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%4d",c[i][j]);
}
printf("\n");
}
getch();
}
Output:
Enter the elements of first matrix:
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3
a[1][0] = 4
a[1][1] = 5
a[1][2] = 6
a[2][0] = 7
a[2][1] = 8
a[2][2] = 9
a[1][0] = 6
a[1][1] = 5
a[1][2] = 4
a[2][0] = 3
a[2][1] = 2
a[2][2] = 1
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf("Enter the elements of matrix:\n");
for(i=0;i<3;i++) //Get matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nTranspose of A:\n");
for(j=0;j<3;j++) //Display transpose of matrix
{
for(i=0;i<3;i++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
getch();
}
Output:
Enter the elements of matrix:
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3
a[1][0] = 4
a[1][1] = 5
a[1][2] = 6
a[2][0] = 7
a[2][1] = 8
a[2][2] = 9
Matrix A:
1 2 3
4 5 6
7 8 9
Transpose of A:
1 4 7
2 5 8
3 6 9
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,k,sum;
clrscr();
printf("Enter the elements of first matrix:\n");
for(i=0;i<3;i++) //Get first matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("Enter the elements of second matrix:\n");
for(i=0;i<3;i++) //Get second matrix data
{
for(j=0;j<3;j++)
{
printf("a[%d][%d] = ",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0;i<3;i++) //Display first matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for(i=0;i<3;i++) //Display second matrix row row-wise
{
for(j=0;j<3;j++)
{
printf("%4d",b[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++) //Finding multiplication of two matrices
{
for(j=0;j<3;j++)
{
sum=0;
for(k=0;k<3;k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
printf("\nMultiplication of matrix A and B:\n");
for(i=0;i<3;i++) //display result matrix
{
for(j=0;j<3;j++)
{
printf("%4d",c[i][j]);
}
printf("\n");
}
getch();
}
Output:
Enter the elements of first matrix:
a[0][0] = 1
a[0][1] = 2
a[0][2] = 3
a[1][0] = 4
a[1][1] = 5
a[1][2] = 6
a[2][0] = 7
a[2][1] = 8
a[2][2] = 9
a[1][0] = 2
a[1][1] = 2
a[1][2] = 2
a[2][0] = 3
a[2][1] = 3
a[2][2] = 3
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
1 1 1
2 2 2
3 3 3
4. MULTIDIMENSIONAL ARRAYS
• An array with more than two subscripts is called as multidimensional array.
• For example, suppose we want to store 5 students marks information for 2
different exams carried out in the term for 4 different subjects, this data can be
stored by using 3-dimensional array like,
int marks[5][2][4];
where, 5 students, 2 exams, and 4 subjects. So, total entries in the array will be
5*2*4 = 40.
• The array will span from marks[0][0][0] to marks[4][1][3].
5. STRINGS
• A string is a sequence of characters enclosed in double quotes.
• In C, each string is terminated by a special character called null character and it
is represented as ‘\0’ or NULL.
• Because of this reason, the character array must be declared one size larger
than the string required to be stored.
C O M P U T E R \0
• Here, the string stored is “COMPUTER”, which is having only 8 characters, but
actually 9 characters are stored because of NULL character at the end.
char name[20];
• This line declares an array name of characters of size 20. We can store any
string up to maximum length 19.
• String is basically an array of characters, so we can initialize the string by using
the method of initializing the single dimensional array as shown below.
char name[] = {‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’,’\0’};
OR
char name[] = “COMPUTER”;
• When the string is written is double quotes, the NULL character is not required, it
is automatically taken.
char name[20];
...
...
scanf(“%s”,name);
char name[20];
...
...
gets(name);
• The advantage of gets() is that we can read strings involving blanks and tabs.
While the scanf() reads only up to blank or tab character.
• So, scanf() is used to read word while gets() can be used to read sentence
involving many words.
• puts() can print only one string at a time, while one printf() can print multiple
strings by using %s many times in the printf().
• For example,
strcat(string1,string2);
• Here, string1 and string2 are character arrays (string2 can be string constant
also).
• The NULL character is removed from the end of string1 and string2 is stored from
this position.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50],string2[50];
clrscr();
printf("\nEnter the first string:\n");
gets(string1);
printf("\nEnter the second string:\n");
gets(string2);
strcat(string1,string2);
Output:
Enter the first string:
Programming in C
strcmp(string1,string2);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50],string2[50];
int diff;
clrscr();
printf("\nEnter the first string:\n");
gets(string1);
printf("\nEnter the second string:\n");
gets(string2);
diff=strcmp(string1,string2);
if(diff==0)
Output 1:
Enter the first string:
Programming
Output 2:
Enter the first string:
Programming
• Here, string1 is the target string which stores the contents of the source string
string2.
• The string2 may be a character array variable or a string constant.
• The string1 must have a size greater than or equal to that of string2.
• The string2 is copied into the string1 character by character and the process
terminates on getting NULL character (‘\0’). in the source string.
• Note that the contents of the target string will be lost and source string remains
unchanged.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50],string2[50];
clrscr();
printf("\nEnter a string:\n");
gets(string1);
strcpy(string2,string1);
printf("\nCopied string is:\n%s",string2);
getch();
}
Output:
Enter a string:
Viral Panchal
n=strlen(string);
• Here, n is an integer variable which stores the values of the length of the string.
• The string can be both a string variable or a string constant.
• The process of counting is terminated on first occurrence of NULL character (‘\0’).
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50];
int n;
clrscr();
printf("\nEnter a string:\n");
gets(string1);
n=strlen(string1);
printf("\nThe length of string is %d",n);
getch();
}
Output:
Enter a string:
Viral Panchal
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string1[50];
clrscr();
printf("\nEnter a string:\n");
gets(string1);
strrev(string1);
printf("\nReversed string is:\n%s",string1);
getch();
}
Output:
Enter a string:
Viral
strncpy()
• In addition to the function strcpy() that copies one string to another, we have
another function strncpy() that copies only the left-most n characters of the source
string to the target string variable.
• This is a three-parameter function and is invoked as follows:
strncpy(s1,s2,n);
• This statement copies the first 5 characters of the source string s2 into the target
string s1.
strncmp()
• A variation of the function strcmp() is the function strncmp(). This function has three
parameters as illustrated in the function call below:
strncmp(s1,s2,n);
strncat()
• This call will concatenate the left-most n characters of s2 to the end of s1.
Prepared by – Prof. Viral H. Panchal 30
Programming for Problem Solving (3110003) Chapter – 4: Array & String
strstr()
• The function strstr() searches the string s1 to see whether the string s2 is contained
in s1. If yes, the function returns the position of the first occurrence of the sub-
string. Otherwise, it returns a NULL pointer.
will locate the first occurrence of the character ‘m’ and the call
strrchr(s1,’m’);
will locate the last occurrence of the character ‘m’ in the string s1.
strupr()
strlwr()
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[50];
char ch='o';
clrscr();
printf("\nEnter a string:\n");
gets(string);
if(strchr(string,ch))
printf("The character %c is at position: %d\n",
ch,strchr(string,ch)-string+1);
else
printf("\nThe character is not found");
getch();
}
Output 1:
Enter a string:
program
Output 2:
Enter a string:
viral
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[50],chr,repl_chr;
int i=0;
clrscr();
printf("\nEnter a string: ");
gets(string);
printf("\nEnter a character to be replaced: ");
scanf("%s",&chr);
printf("\nEnter replacement character: ");
scanf("%s",&repl_chr);
while(string[i]!='\0')
{
if(string[i]==chr)
{
string[i]=repl_chr;
}
i++;
}
printf("\nModified string after replacement is: %s",
string);
getch();
}
Output:
Enter a string: abcadefa
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50],ch;
int i,j;
clrscr();
printf("\nEnter a string: ");
gets(str);
printf("\nEnter a character to delete from string: ");
scanf("%c",&ch);
//Accessing each element of string to perform delete
operation
for(i=0;i<strlen(str);i++)
{
if(ch==str[i])
{
//After deleting user provided element moving each
element one step forward to fill it's place
for(j=i;j<strlen(str);j++)
str[j]=str[j+1];
}
}
printf("\nString after deleting character: %s",str);
getch();
}
Output:
Enter a string: Viral Panchal
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50];
clrscr();
printf("\nEnter a string: ");
gets(str);
printf("\nThe string in upper case: %s",strupr(str));
getch();
}
Output:
Enter a string: viral panchal
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[50],str2[50];
int diff;
clrscr();
printf("\nEnter a string: ");
gets(str1);
strcpy(str2,str1);
strrev(str2);
diff=strcmp(str1,str2);
if(diff==0)
printf("\nString is a palindrome");
else
printf("\nString is not a palindrome");
getch();
}
Output 1:
Enter a string: malayalam
String is a palindrome
Output 2:
Enter a string: viral