0% found this document useful (0 votes)
8 views21 pages

C Arrays and Strings Basics

This document covers the fundamentals of arrays and strings in C programming, including one-dimensional and two-dimensional arrays, initialization, and string handling. It provides examples of array declarations, memory representation, and various functions for manipulating strings and arrays. Additionally, it discusses library functions available in string.h for common string operations.

Uploaded by

caludio olivera
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)
8 views21 pages

C Arrays and Strings Basics

This document covers the fundamentals of arrays and strings in C programming, including one-dimensional and two-dimensional arrays, initialization, and string handling. It provides examples of array declarations, memory representation, and various functions for manipulating strings and arrays. Additionally, it discusses library functions available in string.h for common string operations.

Uploaded by

caludio olivera
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

ARRAYS & STRINGS


5
One dimensional & Two dimensional arrays, initialization, string variables-declaration, reading, writing,
Basics of functions, Parameter passing, String handling function, user-defined functions, recursive
functions, variables and storage classes, scope rules, block structure, header files, C preprocessor, example
C programs.

In day to day life there are several occasions, where in we have to store, data of same type in contiguous
locations, like marks obtained by a student in six different subjects are shown in an array named marks
in Fig. 5.1. Elements of the array are referenced by array name followed by subscript. we have
shown an array named marks 3, six subject marks, scored by the student can be represented by
marks[0]=80.0 and marks[5]=70.0 etc.

M N O P Q R
ã ~êâë

U MKM V MKM N MM KM R MKM S RKM T MKM

ã ~êâë=xMz ã ~êâë=xNz ã ~êâë=xOz ã ~êâë=xRz


Fig. 5.1 Representation of an array

General syntax of array is : storage class data type array [expression]

Note that storage class is optional. Data type is data type of the array. Array is name and expression is a
positive integer. Example of valid declarations of array are:

float marks[6] = { 60.0, 66.0, 70.0, 80.0, 90.0, 100};


float marks[] = { 60.0, 66.0, 70.0, 80.0, 90.0, 100.0};// no need to declare dimension
char stg[]={ ‘g’,’o’,’o’,’d’};
104 C & Data Structures by Practice

5.1 HOW ARRAYS ARE STORED IN THE MEMORY


Consider an array named x, declared as int x[]= {80,90,100,50,65,70};

UM VM N MM RM SR TM

ñxMz ñxNz ñxOz ñxPz ñxQz ñxRz

memory 2000 2002 2004 2006 2008 2010 = 12 bytes


Fig. 5.2 Representation arrays with memory locations shown

The addresses shown above are dummy addresses. Using of sizeof operator would tell us the memory
requirement of data type int on your hardware. Assuming that it is 2 bytes, the memory of the array
element are shown in Fig. 5.2.

Example 5.1 array.c write a program to display the array elements along with their address.
Sizeof operator provide size of data type in bytes.
#include<stdio.h>
//#include<conio.h>
void main()
{ int i,n; //number of ements of array x
int x[]={80,90,100,50,65,70};
n= sizeof(x)/sizeof(int);
printf(“\n size of data type <int>%d “, sizeof(int));
printf(“\n Memory space allocated to x[6] : %d “, sizeof(x));
printf(“\n no of elements in array x = %d”,n);
// %u displays the address in unsigned decimal integer
// %x displays the address in hexa with 0x omitted.
printf(“\n array elements\t:\taddress “);
printf(“\naddress in unsigned decimal integer”);
for (i=0;i<n; i++)
printf(“\n%d\t:\t%u”, x[i],&x[i]);
printf(“\naddress in hexa with 0x omitted.\n”);
for (i=0;i<n; i++)
printf(“\n%d\t:\t%x”, x[i],&x[i]);
printf(“\n”);
}
output
size of data type <int>4
Arrays & Strings 105
Memory space allocated to x[6] : 24
no of elements in array x = 6
array elements : address
address in unsigned decimal integer
80 : 1245024
90 : 1245028
100 : 1245032
50 : 1245036
65 : 1245040
70 : 1245044
address in hexa with 0x omitted.
80 : 12ff60
90 : 12ff64
100 : 12ff68
50 : 12ff6c
65 : 12ff70
70 : 12ff74
Press any key to continue

5.2 ARRAY INITIALIZATION


You have already seen declaration and initialization of the type:
float marks[6] = { 60.0, 66.0, 70.0, 80.0, 90.0, 100};
char stg[]={ ‘g’,’o’,’o’,’d’};

We can use scanf to read into an array. In the following example, we will show use of scanf when we
reverse the string.

Example 5.2 revstg.c a program to read the input string character by character from keyboard
and reverse the string
#include<stdio.h>
#include<conio.h>
// function prototype declarations
int length(char a[20]);
void main()
{ int count=0,i;
int len; // length of the string
char c;
char x[20]; // array of characters. string
// get a character
printf(“\n Enter a word and press <enter>\n”);
106 C & Data Structures by Practice

c=getchar();
while ( c!=’\n’) // ‘\n’ is end of line character i.e. pressing enter key
{
x[count]=c;
count++;
c=getchar();
}
// we have reached end of line. Append ‘\0’ to the string
x[count]= ‘\0’;
len = count;
// Now display the string you have just read
printf(“\n String inputted : %s “, x);
printf(“\n space allocated to single char : %d byte”, sizeof(char));
printf(“\n Memory space allocated to string x[] : %d “, sizeof(x));
printf(“\n No of characters in the string x [] : %d “, length (x));
// now reverse the string
printf(“\n string X reversed.\n”);
for ( i=len-1;i>=0;i—)
printf(“%c”,x[i]);

}
int length(char a[]) /*function definition*/
{ int i=0;
while(a[i]!=’\0') /*when the character is not null*/
i++;
return i;

}/*end of function length*/


/*
Enter a word and press <enter>
HELLO

String inputted : HELLO


space allocated to single char : 1 byte
Memory space allocated to string x[] : 20
No of characters in the string x [] : 5
string X reversed.
OLLEH */
Arrays & Strings 107
5.3 MULTI DIMENSIONAL ARRAYS
Arrays can have more than one dimension. For example a matrix is two dimensional array, with
number of rows and number of columns.

` ç äì ã å ë
M N O P This is matrix A with dimensions 4 X 4.
^= written as A[4][4]. First dimension is row and
êç ï ë
M second dimension is columns.
NM
N As per C convention elements in row major
representation is
O A[0][0] A[0][1] A[0][2] A[0][3]
OM A[1][0] A[1[1] A[1][2] A[1][3]
A[2][0] A[2][1] A[2][2] A[2][3]
P A[3][0] A[3][1] A[3][2] A[3][3]
NT
Note A[0][0] = 10
Fig. 5.3 Two dimensional array matrix A[4][4] A[2][2] = 20
A[3][2] = 17

Example 5.3 transpose.c. A program to find the transpose of a matrix


//transpose.c
#include<stdio.h>

// functional prototype declarations


void Transpose( int A[10][10], int n );// n is the order of square matrix
void ReadMatrix( int A[10][10], int n );
void PrintMatrix( int A[10][10], int n );
void main()
{
int n,A[10][10];

printf(“Enter the order of square matrix <n>”);


scanf(“%d”,&n);
ReadMatrix(A,n);
printf(“The elements of the Matrix are:\n”);
PrintMatrix(A,n);
printf(“The elements of the Transpose Matrix are:\n”);
Transpose(A,n); /*function call. A is name of matrix. Name is address is */

} /*end of main*/

void Transpose(int A[10][10],int n) /*function definition*/


{
int i,j,t;
108 C & Data Structures by Practice

for(i=0;i<n;i++) /*loop1. i=1 because you don’t have to touch x[0][0]*/


{
for(j=0;j<i;j++) /*loop2*/
{
t=A[i][j];
A[i][j]=A[j][i]; /*swapping*/
A[j][i]=t;
} /*end of loop2*/
}

// output the matrix


PrintMatrix(A,n);
} /*end of function transpose*/

void ReadMatrix( int A[10][10], int n)


{
int i,j;
printf(“Enter the elements\n”);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
scanf(“%d”,&A[i][j]); /*input elements*/
}
}//end of ReadMatrix
void PrintMatrix( int A[10][10], int n)
{ int i,j;
for(i=0;i<n;i++)
{ for(j=0;j<n;j++)
{ printf(“ %d “,A[i][j]);
}
printf(“\n”);
}
}//end of ReadMatrix
/*output
Enter the order of square matrix <n>2
Enter the elements
1234
The elements of the Matrix are:
1 2
3 4
The elements of the Transpose Matrix are:
1 3
2 4 */
Example 5.4 matmul.c. A program to find the product of two matrices
//matmult.c
Arrays & Strings 109
#include<stdio.h>
// functional prototype declarations
void MatrixMul( int A[10][10],int B[10][10],int C[10][10],int m,int n,int p );// m and n are the order of
square matrix
void ReadMatrix( int A[10][10],int m,int n );
void PrintMatrix( int A[10][10],int m,int n );
void main()
{
int m,n,o,p,A[10][10],B[10][10],C[10][10];

printf(“Enter the order of 1st matrix\n”);


scanf(“%d %d”,&m,&n);
printf(“Enter the order of 2nd matrix\n”);
scanf(“%d %d”,&o,&p);
if(n == o)
{
ReadMatrix(A,m,n);
ReadMatrix(B,o,p);
printf(“\nThe elements of 1st Matrix are:\n”);
PrintMatrix(A,m,n);
printf(“\nThe elements of 2nd Matrix are:\n”);
PrintMatrix(B,o,p);
MatrixMul(A,B,C,m,n,p);
printf(“\nThe elements of Resultant multiplication matrix are:\n”);
PrintMatrix(C,m,p);
}

} /*end of main*/

void MatrixMul(int A[10][10],int B[10][10],int C[10][10],int m,int n,int p) /*function definition*/


{
int i,j,k;
for(i=0;i<m;i++)
for(j=0;j<p;j++)
C[i][j]=0; //initializing the resultant matrix as 0

for(i=0;i<m;i++)
for(k=0;k<p;k++)
for(j=0;j<n;j++)
C[i][k] += A[i][j] * B[j][k]; //matrix multiplication
}//end of function MatrixMul

void ReadMatrix( int A[10][10],int m,int n )


{
110 C & Data Structures by Practice

int i,j;
printf(“Enter the elements\n”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&A[i][j]); /*input elements*/
}//end of ReadMatrix

void PrintMatrix( int A[10][10],int m,int n )


{
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“ %d “,A[i][j]);
printf(“\n”);
}
}//end of PrintMatrix
/* output
Enter the order of 1st matrix
22
Enter the order of 2nd matrix
22
Enter the elements
1234
Enter the elements
1234
The elements of 1st Matrix are:
1 2
3 4
The elements of 2nd Matrix are:
1 2
3 4
The elements of Resultant multiplication matrix are:
7 10
15 22 */

5.4 CHARACTER ARRAY – STRING HANDLING IN C LANGUAGE


An array of characters is called string variable. A string variable will always be automatically terminated
with ‘\0’ (NULL) character. C compiler treats occurrence of NULL character to mean the end of string.
In the following program, we would check for occurrence of ‘\0’ to indicate the end of strings. Consider
string declaration shown below and which type of declaration is best.
char city[6] =”Mumbai”; //incorrect as no space for adding ‘\0’ (NULL) character.
char city[6] =”Mumbai”; // correct. ‘\0’ (NULL) character is added automatically.
Arrays & Strings 111
char city[] =”Mumbai”; // correct. ‘\0’ (NULL) character is added automatically.
// This is preferred mode and we will be using this mode
// through out the textt
Example 5.7 concat.c A program to concatenate two strings

#include<stdio.h>
#include<conio.h>
void concat ( char x[],char y[]);
void main()
{
char x[20],y[20]; // x 7 y are two strings
clrscr();
printf(“enter any 2 strings\n”);
scanf(“%s%s”,x,y); /*input 2 strings from the user*/
concat(x,y); /*function call*/
getch();
}/*end of main*/
void concat(char a[],char b[]) /*function definition*/
{ int i;
for(i=0;a[i]!=’\0';i++) // check for ‘\0’ occurence
printf(“%c”,a[i]);
for(i=0;b[i]!=’\0';i++)
printf(“%c”,b[i]);
} /*end of function concat*/

5.5 STRING.H – LIBRARY FUNCTION


C compiler provides a library function called string.h. The functions supported by the header file
string.h are:
strlen() : length of the char array
strcpy() : copies a string to another
strcat() : concatenates two strings
strcmp() : compares two strings .
strlwr() : converts from upper case to lower case
struper() : converts from upper case to lower case
strrev() : reverses a string

To be able to use above library function we have to include <string.h> or <stdlib.h>. The best ways to
learn programming is to write programs. Let us write our own code for achieving above. For all this
function, you can write main program and forward the character array through a function call. For
example ans=stglen(stg);, where char stg[20] ; is the character array declared. We provide a main
program which you can use to test the functions.
Example 5.8. stg.c
//stg.c. main program to test the string handling functions
112 C & Data Structures by Practice

#include<stdio.h>
#include<conio.h>
#include<stdio.h> // string functions line strlrn() etc
// Function prototype declarations
int stglen( char stg[20]);
int stgcopy( char stg2[20],char stg1[20]);

void main()
{ int len, flag ; // flag = 0 to false, flag =1 means true

char stg1[20],stg2[20], char stg3[20];

printf(“\n Enter<stg1>”);
gets(stg1);
printf(“\n Enter<stg2>”);
gets(stg2);
len=stglen(stg1);
printf(„\n length of the string thru our program : %d “,len);
printf(„\n length of the string thru string.h : %d “, strlen(stg1));
flag=stgcmp(stg1,stg2);
if ( flag) // i.e. if flag is true i.e. flag == 1
printf(“\n Both string stg1 and stg2 are identical);
else
printf(“\n Both string stg1 and stg2 are not equal);
getch();
} // end of main

5.8.1 String Length

int stglen( char stg[20])


{ int count=1;
while ( stg[count] !=’\0’) // ’\0’ is NULL character. Denotes end of string
count ++;
return count;
}
We can also use the function provided by string.h : len=strlen(stg);

5.8.2 String Copy

stg1 is a source string and stg2 is a destination string. strcpy(stg2,stg1) of string.h


would achieve the same result
void stgcopy( char stg2[20],char stg1[20])
{ int count = 0;
Arrays & Strings 113
while( stg1[count] !=’\0’)
{ stg2[count]=stg1[count];
count++;
}
stg2[count]= ’\0’; // we have to insert NULL at the end
}
5.8.3 String Compare

int stgcmp(char stg2[20],char stg1[20])


{ int count =0;
while ( ( stg1[count] == stg2[count] ) && stg1[count]!=’\0’
&& stg1[count]!=’\0’)
count ++
/* when you come out of loop, if both stg1 & stg2 are equal to ’\0’
then it can be said that both strings are [Link] such a case we will
return 1. Else, we will return a 0. */

if ( (stg1[count] ==’\0’) && (stg2[count] ==’\0’) )


return 1;
else
return 0;
}

5.8.4 Sub String Extraction from A String

In the main program, we need to pass as arguments the stg1 containing the string, stg2 to hold extracted
string, substring start position, and length of sub string. For example consider the string:
I LOVE INDIA. We would like to extract INDIA. The
extractstg(stg1,stg2,8,5); INDIA at position 8 and 5 characters

void extractstg(char stg1[20], char stg2[20],int pos,int len)


{ int count =1;
while( count <= pos )
count ++;
count=1;
while (count <= len )
stg2[count]=stg1[count];
stg2[count]=’\0’; // insert NULL character

Example 5.8.5 chararraysort.c A program to sort strings.


#include<stdio.h>
114 C & Data Structures by Practice

#include<string.h>
#define gappu
//fn prototype declarations
void charraysort(char x[10][10],int n);
void main()
{ int count = 0,n=0;
int i;
char stg[10][10];
// read in the string
printf(“\n Enter string<END to stop>: “);
scanf(“%s”,stg[count]);
while((strcmp(stg[count],”END”)!=0))
{ count++;
printf(“\n Enter string<END to stop>: “);
scanf(“%s”,stg[count]);
}
charraysort(stg,count);
printf(“\n Sorted strings……”);
for( i=0;i<count;i++)
puts(stg[i]);
} // end of main
// fun definition
void charraysort( char x[10][10],int n)
{ char temp[10];
int i,j;
for (i=0;i<n-1;i++)
{
for (j=i+1;j<n;j++)
{
if(strcmp(x[i],x[j])>0)
{ // swap
strcpy(temp,x[j]);
strcpy(x[j],x[i]);
strcpy(x[i],temp);
}
}
}
}// end of charraysort()
output:
Enter string<END to stop>: ramesh
Enter string<END to stop>: usha
Enter string<END to stop>: thunder
Enter string<END to stop>: anand
Enter string<END to stop>: gautam
Arrays & Strings 115
Enter string<END to stop>: END
Sorted strings…….
anand
gautam
ramesh
thunder
usha

OBJECTIVE QUESTIONS
1. __________ method copies the value of an argument into the formal parameters of the subroutine.
2. __________ method copies the address of the actual parameters into the formal parameters.
3. Character array must be terminated with
a) \0 b) \n c) \a d) \t
4. An array with out initial values contains
a) all zeros b) all 1s c) garbage value d) none of the above
5. Array can be initialized at the time of declaration it self using
a) square bracket b) braces c) ( and ) d) single quotes
6. The number in a square brackets of an array is called
a) super script b) subscript d) dimension d) range
7. Subscript of an array A with m elements can be dimensioned as
a) A[m] b) A[m-1] c) A[m+1] d) none
8. Array declared as array A[7] the elements are subscripted between
a) 0….m b) 0….m+1 c) 1……m d) 0…..m-1
9. An array is always passed using pass by value to a function TRUE/FALSE
10. In a row major representation, the first subscript refers to row TRUE/FALSE
11. In an array, array elements are stored in contiguous locations TRUE/FALSE
12. An array is a collection of different data types TRUE/FALSE
13. If int A[6] is a one dimensional array of integers, which of the following refers to the value of
fourth element in the array:
a) A[4] b) A[2] c) A[3] d) none
14. Consider the following declaration of a two-dimensional array in C:
char a[100][100];
Assuming that the main memory is byte-addressable and that the array is stored starting from
memory address 0,” the address of a[40][50] is
a) 4040 b) 4050 c) 5040 d) 5050
116 C & Data Structures by Practice

15. Suppose an array x contains the integer values [10,20,-10,25,0,-1]. The output of the following
program segment is:
for(i=1;i<6;i++)
{
if(x[i]<0)
continue;
if(x[i]==0)
break;
printf((“%d”,x[i]);
}
a) 10,20,-10,25,0,-1 b),-10,25,0,-1
c) 20,-10,25 d) 10,20,25

16) Spot the invalid array declarations


1) float c(20) 2) int x[]={1,5,8}; 3) int n(0..50) 4 char city[5]
a) 1,2 b) 1,3,4 c) 1,3 d) 1,2,4

REVIEW QUESTIONS

1 Write in detail about one dimensional and multidimensional arrays. Also write about how
initial values can be specified for each type of array?
(a) In what way array is different from ordinary variable?
(b) what conditions must be satisfied by the entire elements of any given array?
(c) What are subscripts? How are they written? What restrictions apply to the values that can
be assigned to subscripts?
(d) What advantage is there in defining an array size in terms of a symbolic constant rather
than a fixed integer quantity?
2 How are multidimensional arrays defined? Compare with the manner in which one- dimensional
arrays are defined.

SOLVED PROBLEMS

1 [Link] a C program to find the sum of elements of an array with recursion

//sum.c
#include<stdio.h>
// function prototype declarations
int sumofelements(int a[] , int n);
void main()
{
Arrays & Strings 117
int a[10],n,i,ans;

printf(“enter the number of elements\n”);


scanf(“%d”,&n); /*how many elements*/
printf(“enter the elements”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]); /*input elements from the user*/
// forward array a to function by call by ref method
ans=sumofelements(a,n); /*function call*/
printf(“sum of all elements=%d”,ans);

} /*end of main*/
sumofelements(int x[],int m) /*function definition*/
{ if(m==1) /*checking for value of m*/
return(x[0]);
else
return(x[m-1]+sumofelements(x,m-1)); /*calling function recursively*/
}/*end of function sumofelements*/
/*
OUTPUT:
enter the number of elements
3
enter the elements 1 2 3
sum of all elements=6*/

2 [Link] a C program that extracts a portion of the string starting from nth position
upto mth position/

//extract.c
#include<stdio.h>
#include<conio.h>
#include<string.h> // allows use of library contained in string header
//function prototype declarations
void Extract( char x[],int m, int n ); // m=start position, n= ending position
void main()
{
char x[40]; // x is a string of length 40
int i,m,n;
clrscr();
printf(“enter a string\n”);
scanf(“%[^\n]”,x); /*input from the user.”%[^\n]” allows white spaces also*/
printf(“enter values of starting (n),and ending (m) positions,n>m\n”);
scanf(“%d%d”,&m,&n); /*input from the user*/
118 C & Data Structures by Practice

Extract(x,m,n);
getch();
} /*end of main*/
void Extract(char a[], int m, int n)
{ int i;
for(i=m;i<=n;i++)
{
printf(“%c”,a[i]);
}
} /*end of function extract*/
/*
OUTPUT:
enter a string
education
enter values of starting (n),and ending (m) positions m,n> 2 4
uca
*/
3 stglen.c Write a program to find the length of a string/

//stglen.c
#include<stdio.h>
//function prototype declarations
int length(char x[]);
void main()
{ int ans;
char x[20]; // dimension of string array x
printf(“enter a string:”);
scanf(“%s”,x); /*input string from the user*/
ans =length(x); /*function call*/
printf(“length=%d\n”,ans);
getch();
}/*end of main*/
int length(char a[]) /*function definition*/
{ int i=0;
while(a[i]!=’\0') /*when the character is not null*/
i++;
return i;
}/*end of function length*/
/*
enter a string:hello
length=5 */
Arrays & Strings 119
4. matdet.c. Write a C program to find the determinant of a matrix

//Example 5.4 mat.c. A program to find the Det of a matrix


#include<stdio.h>
#include<conio.h>
#include<math.h>
// functional prototype declarations
int Det( int A[10][10],int n );// n is the order of square matrix
void ReadMatrix( int A[10][10],int n );
void PrintMatrix( int A[10][10],int n );
int det=0;
void main()
{
int n,A[10][10];
clrscr();
printf(“Enter the order of the matrix\n”);
scanf(“%d”,&n);
ReadMatrix(A,n);
printf(“\nThe elements of the given Matrix are:\n”);
PrintMatrix(A,n);
printf(“The Det of the given matrix is : %d “,Det(A,n));
getch();
} /*end of main*/

int Det(int A[10][10],int n ) /*function definition*/


{
int k,l,p,q,i=0,j,temp[10][10],sign;
if(n==2)
return (A[0][0] * A[1][1] - A[0][1] * A[1][0]);
else
{
for( j=0;j<n;j++)
{
for(k=0,p=0;k<n && p<n-1;k++,p++)
for(l=0,q=0;l<n && q<n-1;l++,q++)
{
if(k==i) k++;
if(l==j) l++;
temp[p][q]=A[k][l];
}
printf(“the sub matrix is:\n”);
PrintMatrix(temp,n-1);
sign=pow(-1,i+j);
det += A[i][j] * sign * Det(temp,n-1);
}
return det;
120 C & Data Structures by Practice

}
}//end of function Det
void ReadMatrix( int A[10][10],int n )
{
int i,j;
printf(“Enter the elements\n”);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf(“%d”,&A[i][j]); /*input elements*/
}//end of ReadMatrix

void PrintMatrix( int A[10][10],int n )


{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf(“ %d “,A[i][j]);
printf(“\n”);
}
}//end of PrintMatrix
/*
OUTPUT:
Enter the order of the matrix
3
The elements of the given Matrix are:
123456789
The elements of the given matrix are:
123
456
789
the sub matrix is:
56
89
the sub matrix is:
46
79
the sub matrix is:
45
78
The Det of the given matrix is : 0
*/
5 singular.c. Write a program to find the singular of a matrix. A matrix is called singular
matrix if its determinant is zero

//Example 5.4 mat.c. A program to find the Det of a matrix


Arrays & Strings 121
#include<stdio.h>
#include<math.h>
// functional prototype declarations
int Det( int A[10][10],int n );// n is the order of square matrix
void Determinent( int A[10][10], int B[10][10],int n);
void ReadMatrix( int A[10][10],int n );
void PrintMatrix( int A[10][10],int n );
int det=0;
void main()
{ int n,A[10][10],B[10][10];
printf(“Enter the order of the matrix\n”);
scanf(“%d”,&n);
ReadMatrix(A,n);
printf(“\nThe elements of the given Matrix are:\n”);
PrintMatrix(A,n);
Determinent(A,B,n);
printf(“\nThe Determinenet matrix is: \n”);
PrintMatrix(B,n);
if(Det(B,n)==0)
printf(“The given matrix is Singular”);
else
printf(“The given matrix is not Singular”);
getch();
} /*end of main*/

void Determinent( int A[10][10], int B[10][10],int n)


{
int k,l,p,q,i,j,temp[10][10],sign;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
for(k=0,p=0;k<n && p<n-1;k++,p++)
for(l=0,q=0;l<n && q<n-1;l++,q++)
{
if(k==i) k++;
if(l==j) l++;
temp[p][q]=A[k][l];
}
sign=pow(-1,i+j);
B[i][j] = A[i][j] * sign * Det(temp,n-1);
}
}
int Det(int A[10][10],int n ) /*function definition*/
{
122 C & Data Structures by Practice

int k,l,p,q,i=0,j,temp[10][10],sign;
if(n==2)
return (A[0][0] * A[1][1] - A[0][1] * A[1][0]);
else
{
for( j=0;j<n;j++)
{
for(k=0,p=0;k<n && p<n-1;k++,p++)
for(l=0,q=0;l<n && q<n-1;l++,q++)
{
if(k==i) k++;
if(l==j) l++;
temp[p][q]=A[k][l];
}

sign=pow(-1,i+j);
det += A[i][j] * sign * Det(temp,n-1);
}
return det;
}
}//end of function Det

void ReadMatrix( int A[10][10],int n )


{
int i,j;
printf(“Enter the elements\n”);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf(“%d”,&A[i][j]); /*input elements*/
}//end of ReadMatrix

void PrintMatrix( int A[10][10],int n )


{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf(“ %d “,A[i][j]);
printf(“\n”);
}
}//end of PrintMatrix
/*
OUTPUT:
Arrays & Strings 123
Enter the order of the matrix
3
enter the elements
123456789
The elements of the given Matrix are:
123
456
789
The Determinenet matrix is:
-3 12 -9
24 -60 36
-21 48 -27
The given matrix is Singular
*/
ASSIGNMENT PROBLEMS

1. Write a program to count number of vowels in a given line of text.


2. write a complete C program to convert a lower case string to upper case. accept the input using
scanf statement.
3. Write a program to print the given string in an alphabetical order.
4. Write function modules for finding
a) string length
b) string equality
c) concatenation of two strings.
d) Appending a string at the end of another string.
5 Write a file named mystring.h, comprising all above function modules. Include the header file in
your driver program and test all the modules.
6. The annual examination is conducted for 50 students for three subjects.
Write a program to the data and determine the following.
(a) Total marks obtained by each student.
(b) The highest marks in subject and the roll no of the student who Secured it.
(c) the student who obtained the highest total marks.
7 Write a program to find the largest element in an array?

Solutions to Objective Questions


1) call by value 2) call by ref 3) a 4) c
5) b 6) b 7) a 8) d 9) False
10) True 11) True 12) False 13) c 14) b
15) d 16) c

You might also like