C Programming
C Programming
TWO-DIMENSIONAL ARRAYS
A two-dimensional array is specified using two subscripts where one subscript denotes
row and the other denotes column. Two dimensional array can be viewed as an array of arrays
as shown below.
If some values are missing during initialization, then it is automatically set to zero.
For example, the below statement will initialize the first row and the remaining
elements will be initialized to zero.
int marks[3][4]= {{1,2,3,4}};
Individual elements can also be initialized using assignment operator as shown below:
marks[1][2]=10;
marks[2][1]=marks[1][1] + 10;
In order to input the values from the keyboard, we must use the following code:
for(i=0; i<3; i++)
for(j=0;j<4;j++)
{
scanf(“ %d”, &marks[i][j]);
}
ACCESSING THE ELEMENTS OF TWO-DIMENSIONAL ARRAYS
The elements of a 2D array are stored in contiguous memory locations. Two for loops
are used to scan the elements. The first for loop will scan each row in the 2D array and the
second for loop will scan individual columns for every row in the array.
Write a program to print the elements of a 2D array
#include<stdio.h>
int main(){
int rows, columns;
int a[2][2] = {{10, 20}, {30, 70}};
printf("\nPrinting the 2D Array\n");
C i, j = A i, j + B i, j
Difference: Two matrices that are compatible can be subtracted storing the result in the
third matrix. Two matrices are said to be compatible when they have the same number of
rows and columns.
C i, j = A i, j - B i, 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. A matrix of order m X n can
be multiplied with the matrix of order p X q if n is equal to p.
int main() {
int a[10][10], transpose[10][10], r, c,i,j;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
printf("\nEnter matrix elements:\n");
for ( i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
scanf("%d", &a[i][j]);
}
Output:
Enter rows and columns:
2
3
Enter matrix elements:
1 4 0 -5 2 7
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 2D array, then the called function receives a one-
dimensional array.
main()
{
int arr[2][3] = {{1,2,3},{4,5,6}};
func(arr[1]);
}
void func(int arr[])
{
Prof. Praneetha G N, Dept of ISE, SCE 7
MODULE 4 – ARRAYS AND STRINGS
int i;
for(i=0;i<3;i++)
printf(“%d”,arr[i]);
}
Passing an Entire 2D array: To pass a 2D array to a function, array name can be used as the
actual parameter.
main()
{
int arr[2][3] = {{1,2,3},{4,5,6}};
func(arr);
}
void func(int arr[])
{
int i,j;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
printf(“%d”,arr[i][j]);
}
MULTIDIMENSIONAL ARRAY
A multidimensional array is an array of arrays.
contain as many indices as needed and the requirement of the memory increases with number
of indices.
Write a program to read and display a 2 X 2X 2 array.
include <stdio.h>
int main()
{
int a[2][2][2],i,j,k;
printf("Enter elements of the matrix: \n");
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("\nDisplaying values:\n");
for (i = 0; i < 2;i ++)
{ printf(“\n\n”);
for (j = 0; j < 2; j++)
{ printf(“\n”);
for ( k = 0; k < 2;k ++)
{
printf("\t arr[%d] [%d] [%d]",i,j,k,a[i][j][k]);
}
}
}
return 0;
}
Output:
Enter the elements of the matrix
1 2 3 4 5 6 7 8
Displaying Values:
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
Prof. Praneetha G N, Dept of ISE, SCE 9
MODULE 4 – ARRAYS AND STRINGS
SPARSE MATRICES
Sparse matrix is a matrix that has large number of elements with a zero value. There
are two types of sparse matrices.
Lower triangular matrix: Here, all the elements above the main diagonal have zero
value
Upper triangular matrix: In this matrix, all the elements below the main diagonal have
zero value.
0 2 0
0 0 4
0 0 0
The first row give the number of rows(3) , number of columns (3) and number of non-
zero elements(2) in the sparse matrix
The second row specifies the location and value of first non-zero element. The first
non-zero value is 2 is at (0,1) location.
Similarly, third row specifies the location and value of the next non-zero i.e, value 4
at (1,2) location.
Write a program that shows the array representation of a sparse matrix
#include<stdio.h>
void sparse_matrix(int mat[3][3],int, int, int);
void main()
{
int i, j, rows, cols, num_values=0,mat[30][30];
printf(“enter number of rows and columns \n”);
scanf(“%d %d”,&rows,&cols);
printf(“enter the elements of the array \n”);
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf(“%d”, &mat[i][j]);
}
}
printf(“the sparse matrix is :\n”);
for(i=0;i<rows;i++)
{ printf(“\n”);
for(j=0;j<cols;j++)
{
Prof. Praneetha G N, Dept of ISE, SCE 11
MODULE 4 – ARRAYS AND STRINGS
Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter the elements of array: 1 0 0 0
The sparse matrix is:
1 0
0 0
The new matrix is:
2 2 1
0 0 1
APPLICATIONS OF ARRAYS
Arrays are widely used to implement mathematical vectors, matrices and other
kinds of rectangular tables.
Many databases include one-dimensional arrays where elements are recorded.
Arrays are also used to implement other data structures such as strings, stacks,
queues, heaps and hash tables.
Arrays can be used for sorting elements in ascending or descending order.
#include<stdio.h>
void main( )
{
Prof. Praneetha G N, Dept of ISE, SCE 13
MODULE 4 – ARRAYS AND STRINGS
int i,j,n,temp,a[100];
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-i)-1;j++)
{
if( a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
}
Selection Sort
Selection sort will start by comparing the first element with other elements and finds
minimum element and swaps, then it starts comparing by taking second element with other
elements and so on.
#include<stdio.h>
int smallest(int arr[], int k, int n);
void selection_sort(int arr[] , int n);
void main( )
{
int arr[100],i,n;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
selection_sort(arr,n);
printf(“ sorted array is :\n”);
Prof. Praneetha G N, Dept of ISE, SCE 14
MODULE 4 – ARRAYS AND STRINGS
for(i=0;i<n;i++)
printf("%d", a[i]);
getch();
}
int smallest(int arr[], int k, int n)
{
int pos=k, small=arr[k] , i;
for(i=k+1; i<n; i++)
{
if(arr[i]<small)
{
small=arr[i];
pos=i;
}
}
return pos;
}
INSERTION SORT
It is a very simple sorting algorithm in which the sorted array is built one element at a
time. It inserts each item into its proper place in the final list. It works by moving the current
data element past the already sorted values and repeatedly interchanging it with the preceding
value until it is in its correct place.
#include<stdio.h>
void insertion_sort(int arr[], int n);
void main( )
{
int arr[100],I,n;
printf("Enter the value of n\n");
scanf("%d",&n);
printf("Enter the numbers in unsorted order:\n");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
insertion_sort(arr,n);
printf("The sorted array is\n");
for(i=0;i<n;i++)
{
printf("%d\n",arr[i]);
}
getch();
}
void insertion_sort(int arr[], int n)
{ int i, j, temp
for(i=1;i<n;i++)
{
temp=arr[i];
j=i-1;
while((temp<arr[j]) && (j>=0))
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}
Prof. Praneetha G N, Dept of ISE, SCE 16
MODULE 4 – ARRAYS AND STRINGS
STRINGS
A String is a null-terminated character array. Last character is array in ‘\0’ null
character.
Example: char str[]=”PROGRAM”;
In the above example, str is a string storing the sequence of characters “PROGRAM”.
To store a string of length 7, we need 7+1 location ( 1 extra for the null character). The name
of the character array is a pointer to the beginning of the string. The subscript starts with a
zero. All the characters of a string array are stored in successive memory locations. In figure,
we can see the address is 1000, 1001 and so on.
Declaring string variables: A string is declared like an array of characters.
Syntax: char string_name[size];
Ex: char name[21];
Size 21 means it can store up to 20 characters plus the null character. Entire storage location
name is divided in to 21 boxes called bytes, each of which holds one character. Each character
is element of data type char.
Initializing the string in the declaration:
The following code shows to initialize a string as an array of characters. We need to explicitly
add the null character.
char str[]={‘H’,’E’,’L’,’L’,’O’,’\0’};
We can also declare a string with size much larger than the number of elements that are
initialized.
char str[10]=”HELLO”;
Reading Strings
Strings can be read using 3 ways
Using scanf() function
Using gets() function
Using getchar(), getch() or getche() function
The disadvantage of scanf() is that the function terminates as soon as it finds a blank space.
For example, if the user enters Hello World, then name will contain only Hello.
WRITING STRINGS
Strings can be displayed on screen using 3 ways
Using printf() function
Using puts() function
Using putchar() repeatedly
printf(“%5.3s”,str);
The above statement would print only the first three characters in a total field of five
characters. Here, the strings are right justified. To make the string left justified, we must use a
minus sign
printf(“%-5.3s”,str);
Using putchar()
Strings can also be written by calling the putchar() function repeatedly to print a
sequence of single characters.
i=0;
while(str[i]!=’\0’)
{
putchar(str[i]);
i++;
}
H E L L O
H E L L
H E L
H E
H
#include<stdio.h>
void main()
{
int i,w,p;
char str[]=”HELLO”;
printf(“\n”);
for(i=0;i<5;i++)
{
p=i+1;
printf(“\n % -5.*s”,p,str);
}
printf(“\n”);
for(i=4;i>=0;i--)
{
p=i+1;
printf(“\n % -5.*s”,p,str);
}
getch();
}
sprintf() Function
It is similar to printf() function. The only difference is that the formatted output is
written to a memory area rather than directly to standard output(screen). It is useful in situations
when formatted strings in memory have to be transmitted over a communication channel or to
a special device. Syntax is as follows:
int sprintf( char * buffer, const char * format [ , argument , . . . ]);
Where
Buffer is the place where string needs to be stored.
arguments command is an ellipsis so you can put as many types of arguments as you want
format is the string that contains the text to be printed
#include<stdio.h>
void main()
{
char buf[100];
int num=10;
Prof. Praneetha G N, Dept of ISE, SCE 20
MODULE 4 – ARRAYS AND STRINGS
SUPPRESSING INPUT
The scanf() function can be used to read a field without assigning it to any variable.
This is done by preceeding that field’s format code with a *. For example,
scanf(“%d *c %d”, &hr, &min);
The time is read as 9:05. Here colon would be read but not assigned to anything.
Using a scanset
Scanset is used to define a set of characters which may be read and assigned to the
corresponding string. It is defined by placing the characters inside square brackets prefixed
with a % as shown in the example.
%[“aeiou”]
When we use the above scanset, scanf() will continue to read characters and put them into the
string until it encounters a character that is not specie in the scanset.
#include<stdio.h>
void main()
{
char str[10];
scanf(“%[aeiou]”, str);
printf(“ string is : %s”, str);
}
The following code will accept characters other than those specified in the scanset.
scanf(“%[^aeiou]”, str);
The following code will accept any character enclosed in opening and closing square brackets.
scanf(“%[0123456789. ^ [] () _ + -$%&*]”, str);
The following code will accept any character from small a to z. Range is specified using a
hyphen.
scanf(“%[a-z]”,str);
sscanf() Function
It accepts a string from which to read input. It is similar to scanf() function except that
the first argument of sscanf specifies a string from which to read, whereas scanf can only read
from standard input. Syntax is as follows:
int sscanf(const char * str, const char * format, [p1,p2 , . . . ]);
Here, sscanf() reads data from str and stores then according to the parameters format into the
locations given by additional arguments.