Module - 4

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Introduction to C Programming (BESCK104E)

Module-4
TWO – DMENSIONAL ARRAYS
 Arrays which are specified with 2 subscripts (2 set of square brackets [ ] [ ]) are
called 2- dimensional arrays.
 Arrays with two or more dimensions are called Multi-dimensional arrays.
 In 2-Dimensional Array, the first index indicates the “row size”( the number of
rows) and second index indicates the “column size”( the number of columns).
Ex: inta[10][10]; //Two-dimensional array
Declaration of Two-dimensional arrays
As we declare the variables before they are used in a program, an array must also be declared
before it is used using the following syntax.

Syntax: data_typearray_name [row_size][col_size];


data_type: It can be int, float, char etc.
array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.
Semicolon is must at the end.
The size used during declaration of the array is useful to reserve the specified memory locations.

The array “a” is a 2-dimensional array with 2 rows and 4 columns. This declaration informs the
compiler to reserve 8 locations (2*4=8 locations, 2*8=16 bytes in total) continuously one after
the other.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 1


Introduction to C Programming (BESCK104E)

Initialization of 2-dimensional arrays


As we initialize a variable to the required value, we can initialize the individual elements of the
array during initialization.
Syntax
data_typearray_name[row_size][col_size]={
{a1,a2, ---- ,an},
{b1,b2, ---- ,bn},
..…………...,
{z1,z2, ---- ,zn}
};
data_type: It can be int, float, char etc.
array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.
a1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2nd row and so
on.
Ex: 1. int a[4][3]= {{11,22,33}, {44,55,66},{77,88,99},{10,20,30} };
The array has 4 rows and 3 columns.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 2


Introduction to C Programming (BESCK104E)

Reading/Writing Two dimensional arrays


 To read the 2-dimensional array, we have to use two for loops along with scanf(), where
the outer for loop indicates the number of rows to be read and the inner for loop indicates
the number of columns to be read.
 To read the “n” array elements of Two dimensional array:
for(i=0;i<m;i++)
{
for(j=0;j<n;i++)
{
scanf(“%d”,&a[i][j]);
}
}

 To write/print the 2-dimensional array elements, we have to use two for loops along with
printf(), where the outer for loop indicates the number of rows to be printed and the inner
for loop indicates the number of columns to be printed.
 To print the “n” array elements of Two dimensional array:
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 3


Introduction to C Programming (BESCK104E)

printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}
Example Programs:
1. Write a C Program to read and print 2-dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n;
printf(“Enter the number of Rows and Columns of the Array:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the Array elements:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Entered array elements are:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
}
printf(“\n”);
}
}

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 4


Introduction to C Programming (BESCK104E)

Output:
Enter the number of Rows and Columns of the Array:
22
Enter the Array elements:
1
2
3
4
Entered array elements are:
1 2
3 4

OPERATIONS ON TWO-DIMENSIONAL ARRAYS


We can perform the following operations on a two-dimensional array:
Transpose: Transpose of a m x n matrix A is given as an x m matrix B where, Bi,j= Aj,i

Sum Two matrices that are compatible with each other can be added together thereby storing the
result in the third matrix. Two matrices are said to be compatible when they have the same
number of rows and columns. Elements of the matrices can be added by writing: Ci,j= Ai,j + Bi,j

Difference Two matrices that are compatible with each other can be subtracted thereby storing
the result in the third matrix. Two matrices are said to be compatible when they have the same
number of rows and columns. Elements of the matrices can be subtracted by writing: Ci,j= Ai,j-Bi,j

Product Two matrices can be multiplied with each other if the number of columns in the first
matrix is equal to the number of rows in the second matrix. Therefore, m X n matrix A can be
multiplied with a p x q matrix if n = q.
Elements of the matrices can be multiplied by writing:
Ci,j= Σ Ai,kBj,k for k=1 to k<n.

Write a program to transpose a 3 x 3 matrix.


#include <stdio.h>

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 5


Introduction to C Programming (BESCK104E)

#include <conio . h>


int main ()
{
int i, j, mat [3] [3], transposed_mat [3] [3] ;
clrscr ();
printf ("\n Enter the elements of thematrix" );
printf ("\n **************************" );
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf ("\n mat [%d] [%d] = ",i, j);
scanf ("%d", &mat [i] [j] );
}
}
printf ("\n The elements of the matrix are ");
printf ("\n **************************" );
for (i=0; i<3; i++)
{
printf ("\n");
for (j=0 ; j<3; j++)
printf ("\t mat [%d] [%d] = %d", i, j,mat [i] [j] );
}
for (i=0 ; i<3; i++)
{
for (j =0; j<3; j++)
transposed_mat [i] [j] = mat [j] [i];
}
printf ("\n The elements of the transposedmatrix are ");
printf ("\n **************************" );
for (i=0 ; i<3; i++)

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 6


Introduction to C Programming (BESCK104E)

{
printf ("\n");
for (j=0; j<3; j++)
printf ("\t transposed_mat [%d] [%d]=%d", i, j, transposed_mat [i][j]);
}
return 0;
}
Output
Enter the elements of the matrix
**************************
123456789
The elements of the matrix are
**************************
123
456
789
The elements of the transposed matrix are
147
258
369

Write a C program to add 2 matrices A and B and store sum in C.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 7


Introduction to C Programming (BESCK104E)

#include<stdio.h>
void main( )
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the elements of Matrix B:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“The Resultant Matrix C is:\n”);
for(i=0;i<m;i++)

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 8


Introduction to C Programming (BESCK104E)

{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
Output
Enter the size of matrix: 2 2
Enter the elements of Matrix A:
1 2
3 4
Enter the elements of Matrix B:
5 6
7 8
The Resultant Matrix C is:
6 8
10 12

Implement Matrix multiplication and validate the rules of multiplication.


# include <stdio.h>
#include<conio.h>
int main()
{
int a[10][10], b[10][10], c[10][10];
int m , n , p , q , i ,j , k;
printf("\n Enter the order of the matrix A :");
scanf("%d %d", &m , &n);
printf("\n Enter the order of the matrix B :");
scanf("%d %d",&p,&q);

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 9


Introduction to C Programming (BESCK104E)

if(n == p)
{
printf("\n Enter the elements of Matrix A \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < n ; j++)
scanf("%d", &a[i][j]);
}
printf("\n Enter the elements of matrix B \n");
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];
}
}
}
printf("\n MATRIX A \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < n ; j++)
{
printf(" %d \t", a[i][j]);

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 10


Introduction to C Programming (BESCK104E)

}
printf("\n")
}
printf("\n MATRIX B \n");
for(i = 0 ; i< p ; i++)
{
for(j = 0 ; j < q ; j++)
{
printf(" %d \t", b[i][j]);
}
printf("\n");
}
printf("\n MATRIX C \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < q ; j++)
{
printf(" %d \t", c[i][j]);
}
printf("\n");
}
}
else
printf("Matrix multiplication is not possible");
getch();
return 0;
}

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 11


Introduction to C Programming (BESCK104E)

TWO-DIMENSIONAL ARRAYS FORINTER-FUNCTION COMMUNICATION


There are three ways of passing parts of the two-dimensional array to a function (process). First,
we can pass individual elements of the array. This is exactly same as passing the elements of a
lD array. Second, we can pass a single row of the 2D array. This is equivalent to passing the
entire ID array to a function. This has already been discussed in the previous section. Third, we
can pass the entire 2D array to the function. Refer Figure which shows the three ways of using
two-dimensional arrays for inter-function communication.

Passing a Row
A row of a 2D array can be passed by indexing the array name with the row number. When we
send a single row of a two-dimensional array, then the called function receives a one-
dimensional array. Figure illustrates how a single row of a 2D array is passed to the called
function

main ( ) // Calling Function


{
intarr [2] [3] = ( (1, 2, 3), (4, 5, 6));
func (arr [1] ) ;
}
void func (intarr []) // Called Function
{
int i;
Calling function

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 12


Introduction to C Programming (BESCK104E)

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


Figure 11.34
printf (" %d", arr [i] * 10) ;
}
Passing the Entire Array
To pass a 2D array to a function, we use the array name as the actual parameter. (The same we
did in case of a 1D array). However, the parameter in the called function must indicate that the
array has two dimensions.

MULTIDIMENSIONAL ARRAYS
A multidimensional array in simple terms is anarray of arrays. Like we have one index in a
1Darray, two indices in a 2D array, in the same way wehave n indices in an, n-dimensional array
or multidimensional array.Conversely, an n-dimensionalarray is specified using n indices. An n-
dimensionalm1 X m2 X m3 X ... mn, array is a collection m1 * m2 *m, * m3……mn elements. In a
multidimensional array, a particularelement is specified by using n subscripts as A [I 1] [I2]
[I3] . ..In], where,
I1<= M1, I2< = M2, I3<= M3, . In<= Mn
A multidimensional array can contain as many indicesas needed and the requirement of the
memory increaseswith the number of indices used. However, practicallySpeaking we will hardly
use more than three indices inany program. Figure shows a three-dimensional(3D) array. The
array has three pages, four rows, and twocolumns.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 13


Introduction to C Programming (BESCK104E)

STRINGS
“A string is a sequence of characters enclosed within double quotes”.
or
“String is an array of characters and terminated by NULL character which is denoted by
“\0”.
A string is stored as a sequence of characters in an array terminated by „\0‟ (NULL character).
Ex: Consider the String “DAVANGERE”.
This string is stored in the form of an array as shown below:

Declaring String variables


• A string is declared like an array of characters.
Syntax: char string_name[size/length];
Where,
• char: data type used to declare the strings or characters.
• string_name: It specifies the name of the given string.
• size: The size or maximum length (number of characters including “\0”) of the
string is specified in square brackets.

Length of the String: The „length‟ is the number of characters stored in the string up to but not
including the null character.
Example
1. char name[21];
Size of the string is 21, means that it can store up to 20 characters plus one null character.
2. charstr[10];
Size of the string is 10, means that it can store up to 10 characters plus one null character.

Initializing the Strings


• We can initialize an array of characters (Strings) in the declaration itself.
Examples:

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 14


Introduction to C Programming (BESCK104E)

1. char a[9]={„C‟, „O‟, „M‟, „P‟, „U‟, „T‟, „E‟, „R‟, „\0‟};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized
with the characters in the order specified.

2. char b[10]={„R‟, „A‟, „M‟, „A‟, „\0‟};


The compiler allocates 10 memory locations ranging from 0 to 9 and these locations are
initialized with the characters in the order specified. The remaining locations are automatically
initialized to null-characters as shown below:

3. char b[ ]={„C‟, „O‟, „M‟, „P‟, „U‟, „T‟, „E‟, „R‟, „\0‟};
• For this declaration, the compiler will set the array size to the total number of initial
values.
• i.e. 9. The characters will be stored in these memory locations in the order specified as
shown below:

4. char b[ ]= “COMPUTER”;
• Here, the string length is 8 bytes. But string size is 9 bytes. So, the compiler reserves 8+1
memory locations and these locations are initialized with the characters in the order
specified. The string is terminated by “\0” by the compiler.

String Input / Output Functions


Token-Oriented I/O functions
 The Input/Output operations performed by scanf() and printf() functions are called token-
oriented Input/Output.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 15


Introduction to C Programming (BESCK104E)

Reading a String using scanf( )


 It is possible to read a string using “scanf()”.
 The conversion specification for reading a string using scanf() is “%s”.
 The scanf() function stops reading characters when it finds the first white space character
( spaces, tabs and new line characters).
Example: char name[20];
printf(“Enter the name:”); scanf(“%s”, name);
Printing a String using printf( )
 The „printf()‟ function prints the given string (all the characters but not the null
character).
 The printf() conversion specification for a string variable is “%s”.

Example:
char name[20];
printf(“Enter the name:\n”); scanf(“%s”, name);
printf(“The entered name is:%s”, name);
Output: Enter the name: Rama
The entered name is: Rama

Write a C program to read and display a string using scanf() and printf().
#include<stdio.h>
void main()
{
charstr[20];
printf(“Enter your name:\n”);
scanf(“%s”,str);
printf(“Entered name is:%s\n”,str);
}
Output:
Enter your name: Rajashekhar
Entered name is: Rajashekhar

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 16


Introduction to C Programming (BESCK104E)

Write a program to display a string using printf ( ).


#include <stdio.h>
#include <conio.h>
main ( )
{
char str [ ] = “Introduction to C”;
clrscr ( );
printf (“\n |%s|", str);
printf (“\n |%20s|", str);
printf (“\n |%-20s|", str);
printf (“\n |%.4s|", str);
printf ("\n |%20.4s|", str);
printf (“\n |%-20.4s|", str);
getch ( );
return 0;
}
Output
|Introduction to C|
| Introduction to C|
|Introduction to C|
|Intr|
| Intr|
|Intr |

Write a program to read and display a string.


#include <stdio.h>
#include <conio.h>
main ( )
{
charstr [50] ;
printf ("\n Enter the string: ");

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 17


Introduction to C Programming (BESCK104E)

scanf ("%s", str) ;


clrscr ( );
printf ("\n |%s|", str);
printf ("\n |%20s|", str);
printf ("\n |%-20s|", str);
printf (“\n |%.4s|", str);
printf ("\n |%20.4s|", str);
printf ("\n |%-20.4s|", str);
getch( );
return 0;
}
Output
Enter the string:
|Introduction|
| Introduction|
|Introduction |
|Intr|
| Intr|
|Intr |

Line-Oriented I/O functions


 The Input/Output operation performed by gets() and puts() functions are called line-
oriented Input/Output.
 The prototypes for these functions are in “string.h”.
 This type of I/O functions processes entire line (string with white spaces). Hence these
are called line-oriented I/O.

Reading a String using gets( )


 gets() function is used to read a sequence of characters (string) with spaces in
between.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 18


Introduction to C Programming (BESCK104E)

 The “gets()” function allows us to read an “entire line” of input including whitespace
characters.
Syntax : gets(string);
Example:
char name[20];
printf(“Enter the name:”);
gets(name);
Printing a String using puts( )
 “puts()” function is used for printing the given strings.
 Whenever we want to display a sequence of characters stored in memory locations on the
screen, then puts() function can be used.
Syntax : puts(string);
Example:
char name[20];
printf(“Enter the name:\n”);
gets(name);
printf(“The entered name is:\n”);
puts(name);
Output:
Enter the name:
Abdul Kalam
Entered name is:
Abdul Kalam

The sprintf() Function


The library function sprintf ( ) is similar to printf ( ).The only difference is that the formatted
output is written to a memory area rather than directly to a standard output(screen). The sprintf ()
function is useful in situations when a formatted string in a memory has to be transmitted over a
communication channel or to a special device.
The syntax of sprintf () can be given as
intsprintf (char * buffer, const char *format [, argument ,...] );

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 19


Introduction to C Programming (BESCK104E)

Here, buffer is the place to store the resulting string from using the function. The argument
command is an ellipsis so you can put as many types of arguments as you want. Finally, the
format is the string that contains the text to be printed. The string may contain format tags.
#include <stdio.h>
main ( )
{
Charbuf [100];
intnum = 10;
sprintf(buf, “ num = %3d”, num);
}
substring is: there

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 20

You might also like