Unit 3
Unit 3
UNIT-III
Array:
An array is collection of homogeneous elements that are represented under a single
variable name.
(Or)
An array is collection of same data type elements in a single entity.
It allocates sequential memory locations.
Individual values are called as elements.
A value in an array is identified by index or subscript enclosed in square brackets with
array name.
The individual data items can be integers, floating point numbers, and characters and so
on, but they must be the same type and same storage class.
Arrays can be classified into
(i) One-Dimensional arrays
(ii) Two-Dimensional arrays
(iii) Multi-Dimensional arrays
Page 1
INTRADUCTION TO PROGRAMMING UNIT-III
Examples
float temp[24]; //floating-point array
Declare the group as an array to contain a maximum of 24 real constants.
char name[10]; //character array
Declare the name as a character array (string) variable that can hold a maximum of 10
characters.
C array indices start from 0. So for an array with N elements, the index that last element is N-1
Page 2
INTRADUCTION TO PROGRAMMING UNIT-III
While initializing the array at the time of declaration, the programmer may omit the size
of the array.
For example, int marks[]= {98, 97, 90};
If the number of values in initializer-is less than the size of an array, only those many first
locations of the are assigned the values. The remaining locations are assigned zero.
Example: int a[9]={1, 2, 3, 4};
1 2 3 4 0 0 0 0 0
If the number of values listed within initialize- list for an array is greater than the size of
the array, compiler raises error.
Example: int a[5]={1, 2, 3, 4, 5, 6, 7, 8, 9};
If the static array is declared without initialize- list then all locations are set to zero.
Example: static int a[9];
0 0 0 0 0 0 0 0 0
If the size is omitted in a 1-d array declaration, which is initialized, the compiler will
supply this value by examining the number of values in the initialize-list.
Example: int a[]={1, 2, 3, 4, 5, 6, 7, 8, 9};
1 2 3 4 5 6 7 8 9
Array elements cannot be initialized selectively. An attempt initialize only 2nd location is
illegal.
Example: int a[6]={, 6]; is illegal.
Page 3
INTRADUCTION TO PROGRAMMING UNIT-III
Page 4
INTRADUCTION TO PROGRAMMING UNIT-III
Write a C Program to print the maximum and minimum element in the array.
#include <stdio.h>
int main()
{
int i, n, a[20], max, min;
printf("Enter the number of elements in the array : ");
scanf("%d", &n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
printf("a[%d] = ",i);
scanf("%d",&a[i]);
}
max = min = a[0];
for(i=1;i<n;i++)
{
if(a[i]<min)
min = a[i];
if(a[i]>max)
max = a[i];
}
printf("\n The smallest element is : %d\n", min);
printf("\n The largest element is : %d\n", max);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The smallest element is : 1
The largest element is : 5
Page 5
INTRADUCTION TO PROGRAMMING UNIT-III
1. Linear search
2. Binary search.
Linear Search
Linear search, also called as sequential search, is a very simple method used for
searching an array for a particular value. It works by comparing the value to be searched with
every element of the array one by one in a sequence until a match is found. It is mostly used to
search an unordered list of elements. For example, if an array a[] is declared and initialized as,
int a[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is
present in the array or not. If yes, then it returns the position of its occurrence. Here, POS = 3
(index starting from 0).
Write a C Program to search an element in an array using the linear search technique.
#include <stdio.h>
int main()
{
int a[100],n,i,key,flag=0;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter elements\n");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
printf("Enter an element to be searched:");
scanf("%d", &key);
/* linear search starts here */
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf("%d is found at position %d\n", key, i);
flag=1;
break;
}
}
if(flag==0)
printf("%d is not found\n",key);
return 0;
}
Page 6
INTRADUCTION TO PROGRAMMING UNIT-III
Output
Enter number of elements: 5
Enter elements
Enter a[0] = 14
Enter a[1] = 5
Enter a[2] = 23
Enter a[3] = 9
Enter a[4] = 15
Enter an element to be searched: 9
9 is found at position 3
Sorting
Sorting means arranging the elements of an array in specific order may be either
ascending or descending. There are different types of sorting techniques are available:
1. Bubble sort
2. Selection sort
3. Insert sort
4. Merge sort
5. Quick sort etc.
Bubble sort:
sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps
through the list to be sorted, compares each pair of adjacent items and swaps them if they are
in the wrong order.
C Program to implement Bubble Sort Technique
#include <stdio.h>
int main()
{
int a[100],n,i,j,temp;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter elements\n");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
Page 7
INTRADUCTION TO PROGRAMMING UNIT-III
}
/* bubble sort logic starts from here */
for(i=0;i<n;i++)
{
for(j=0;j<n-i;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
printf("Sorted elements .... \n");
for(i=0;i<n;i++)
printf("%3d",a[i]);
printf("\n");
return 0;
}
Output
Enter number of elements: 5
Enter elements
Enter a[0] = 14
Enter a[1] = 5
Enter a[2] = 23
Enter a[3] = 9
Enter a[4] = 15
Sorted elements ....
5 9 14 15 23
Page 8
INTRADUCTION TO PROGRAMMING UNIT-III
- a[0][0] refers to data item in the first row and first column.
-a[0][2] refers to data item in the first row and third column.
-a[2][3] refers to data item in the second row and third column.
-a[3][3] refers to data item in the third row and third column.
This initialization can also be done row by row. The above statement can be equivalently
written as
int table[2][3] = { {0,0,0}, {1,1,1} };
Commas are required after each curly brace that closes of a row, except in case of last row.
If the values are missing in an initializer, they are automatically set to zero.
Ex: int table [2] [3] = {
{1,1}, \\ 1 1 0
{2} \\ 2 0 0
};
Page 9
INTRADUCTION TO PROGRAMMING UNIT-III
When all the elements are to be initialized to zero, the following short-cut method may be
used.
int m[3][5] = { {0}, {0}, {0}};
The first element of each row is explicitly initialized to zero while the other elements are
automatically initialized to zero.
int m[3][5] = { 0 };
Operations on 2d arrays:
Write a C program to perform addition or subtraction of two matrices
PROGRAM:
#include<stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
printf("enter the rows and columns for a & b matrices\n");
scanf("%d%d",&m,&n);
printf("Enter the First matrix->");
for(i=0;i<m;i++)
{
Page 10
INTRADUCTION TO PROGRAMMING UNIT-III
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix->");
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]; // for subtract, use minus (-) instead of plus (+) sign
}
}
printf("\nThe Addition of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",c[i][j]);
}
return 0;
}
OUTPUT:
enter the rows and columns for a & b matrices
2
2
Enter the first matrix->1
2
3
4
Enter the second matrix->1
2
3
4
The Addition of two matrix is
2 4
6 8
Page 11
INTRADUCTION TO PROGRAMMING UNIT-III
#include<stdio.h>
#include<conio.h>
int main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q,k;
printf("enter the rows and columns for matrix a\n");
scanf("%d%d",&m,&n);
printf("enter the rows and columns for matrix b\n");
scanf("%d%d",&p,&q);
if ( n != p )
{
printf("matrix multiplcation is not possible");
}
else
{
printf("Enter the First matrix->");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix->");
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]=c[i][j]+a[i][k]*b[k][j];
Page 12
INTRADUCTION TO PROGRAMMING UNIT-III
}
}
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
}
}
return 0;
}
OUTPUT:
Enter the rows and columns of matrix a
2
2
Enter the rows and columns of matrix b
3
2
Matrix multiplication is not possible
Page 13
INTRADUCTION TO PROGRAMMING UNIT-III
Page 14
INTRADUCTION TO PROGRAMMING UNIT-III
Output
Enter number of rows and columns: 3 3
Enter elements of matrix
Enter a[0][0]=4
Enter a[0][1]=7
Enter a[0][2]=3
Enter a[1][0]=9
Enter a[1][1]=5
Enter a[1][2]=2
Enter a[2][0]=6
Enter a[2][1]=1
Enter a[2][2]=8
The Matrix A
4 7 3
9 5 2
6 1 8
Transpose of a given matrix
4 9 6
7 5 1
3 2 8
Write a c program to find row average and column average of a table or matrix
#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10];
Page 15
INTRADUCTION TO PROGRAMMING UNIT-III
}
void AddColumns(int arr[10][10], int i, int j)
{
int rows, columns, Sum = 0;
float Avg;
printf("THE AVERAGE OF EACH COLUMN OF GIVEN MATRIX IS\n");
for(columns = 0; columns < j; columns++)
{
Avg=0;
for(rows = 0; rows < i; rows++)
{
Sum = Sum + arr[rows][columns];
}
Avg=Sum/i;
printf("The average of %d Column Elements in a Matrix = %f \n",columns, Avg );
}
}
void AddRows(int arr[10][10], int i, int j)
{
int rows, columns, Sum = 0;
float Avg;
printf("THE AVERAGE OF EACH ROW OF GIVEN MATRIX IS\n");
for(rows = 0; rows < i; rows++)
{
Avg=0;
for(columns = 0; columns < j; columns++)
{
Sum = Sum + arr[rows][columns];
}
Avg=Sum/i;
printf("The average of %d row Elements in a Matrix = %f \n",rows, Avg );
}
}
OUTPUT
Page 16
INTRADUCTION TO PROGRAMMING UNIT-III
Initializing 3D Array
Like the one-dimensional arrays, three-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
This initializes the elements of first two dimensional (matrix) first row to zero’s and the second row
to one’s and second matrix elements are first row to six’s and the second row to seven’s.
This initialization is done row by row.
The above statement can be equivalently written as
{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}
}
/* Program to accept the elements of a 3-d array and display them */
#include<stdio.h>
main()
{
int a[2][3][3], i, j k;
printf(“Enter the elements of matrix a of order 2*3*3(two tables of sizes 3*3) \n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
for(k=0;k<3;k++)
scanf(“%d”, &a[i][j][k]);
}
printf(“ The 3-d array a \n”);
for(i=0;i<2;i++)
{
printf(“a-table %d \n”, i+1);
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
printf(“%3d”, a[i][j][k]);
printf(“\n”);
}
printf(“\n”);
}
getch();
}
Page 18
INTRADUCTION TO PROGRAMMING UNIT-III
Strings In C
In ‘C’ language the group of characters, digits and symbols enclosed within
quotation marks are called as strings
otherwise strings are array of characters.
Null character (‘\0’) is used to mark the end of the string.
The terminating null (‘\0’) is important, because it is the only way the functions
that work with a string can know where the string ends.
V A H I N I \0
Initialization of Strings
char name[ ]="VAHINI";
char name[]= {’V’, ‘A’ ,’H’ ,’I’ ,’N’ ,’I’,’\0’};
The characters of the string are enclosed within a pair of double quotes.
The initialization of NULL character is not essential because the C compiler inserts the
NULL (\0) character automatically at the end of the string.
Reading And Writing String
The '%s' control string can be used in scanf() statement to read a string from the terminal
and the same may be used to write string to the terminal in printf() statement.
char s[10];
scanf(“%s”,s);
printf(“%s”,s);
scanf() function can only read a string upto a single space character .
To read the string including space charecters we use functions like getchar(), gets()
i.e to read a line of text we use getchar() or gets() functions
Page 19
INTRADUCTION TO PROGRAMMING UNIT-III
#include<stdio.h>
int main()
{
char s1[ 20], s2[20 ];
int i=0;
printf (“enter string 1”);
gets(s1);
printf (“enter string 2”);
gets(s2);
while((s1[i]==s2[i]) && s1[i]!=’\0’ && s2[i]!=’\0’)
{
i=i+1;
}
Page 20
INTRADUCTION TO PROGRAMMING UNIT-III
Output :
Enter string1 hello
Enter string2 hello
Two strings are equal.
Write A C Program To COPY content of one Strings to another string Without Using Library
Functions
#include<stdio.h>
int main()
{
char s1[ 20], s2[20 ];
int i=0;
printf (“enter string 1”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
s2[i]=s1[i];
}
s2[i]=’\0’;
printf(“copied string is %s”,s2);
return 0;
}
Output
Enter string 1 hello
Copied string is hello
Page 21
INTRADUCTION TO PROGRAMMING UNIT-III
#include<stdio.h>
int main()
{
char s1[ 20];
int i=0,length=0;
printf (“enter string 1”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
length=length+1;
}
printf(“length of string is %d”,length);
return 0;
}
Output
Enter string 1 hello
Length of string is 5
#include<stdio.h>
int main()
{
char s1[ 20];
int i=0,j,length=0;
printf (“enter string 1”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
length=length+1;
}
i=0
j=length;
while(i<j)
{
temp=s1[i];
s1[i]=s1[j-1];
s1[j-1]=temp;
Page 22
INTRADUCTION TO PROGRAMMING UNIT-III
i++;
j--;
}
printf(“reverse of string is %s”,s1);
return 0;
}
Output
Enter string 1 hello
reverse of string is olleh
With every C compiler a large set of useful string handling library functions are provided. For
using these functions, we need to include the header file string.h
strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if string1>string2
strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2
strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by ignoring case (upper
or lower)
Page 23
INTRADUCTION TO PROGRAMMING UNIT-III
stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case (similar
to strcmpi())
strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of character 'b' in string1
strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of character 'b' in string1
strstr() strstr(string1, string2) Returns a pointer to the first occurrence of string2 in string1
strset() strset(string1, 'B') Sets all the characters of string1 to given character 'B'.
strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given character 'B'.
Strlen() Function
This function counts the number of characters present in a string. Syntax for strlen() function is
given below:
int strlen(string);
The function takes a single argument, i.e, the string variable whose length is to be found, and
returns the length of the string passed.
Page 24
INTRADUCTION TO PROGRAMMING UNIT-III
#include<stdio.h>
#include<string.h>
int main( )
{
char str[ ] = "Henry" ;
int len1, len2 ;
len1 = strlen ( str ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nThe string %s length is %d", str, len1 ) ;
printf ( "\nThe string %s length is %d\n", "Humpty Dumpty", len2 ) ;
return 0;
}
Output
The string Henry length is 5
The string Humpty Dumpty length is 13
Strcpy( ) Function
This function copies the contents of one string into another. Syntax for strcpy() function is given
below.
strcpy ( destination, source );
Example
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2
If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30.
Then, only 20 characters from source string will be copied into destination string and
remaining 10 characters won’t be copied and will be truncated.
strcat( ) function
It combines two strings. It concatenates the source string at the end of the destination string.
Syntax for strcat( ) function is given below.
strcat ( destination, source );
For example, “Bombay” and “Nagpur” on concatenation would result a new string
“BombayNagpur”.
Example : C program that illustrates the usage of strcat() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char source[ ] ="Students!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", target ) ;
return 0;
}
Output
Source string = Students!
Destination string = HelloStudents!
strcmp( ) function
It compares two strings to find out whether they are same or different. The two strings are
compared character by character until there is a mismatch or end of one of the strings is
reached, whichever occurs first.
If the two strings are identical, strcmp( ) returns a value zero. If they’re not identical, it returns
the numeric difference between the ASCII values of the first non-matching pairs of characters.
Syntax for strcmp( ) function is given below.
int strcmp ( str1, str2)
Page 26
INTRADUCTION TO PROGRAMMING UNIT-III
Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example : C program that illustrates the usage of strcmp() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
Example : Program for checking string’s palindrome property.
#include<stdio.h>
#include<string.h>
int main()
{
char str1[25],str2[25];
int d=0;
printf("\nEnter a string:");
gets(str1);
strcpy(str2,str1);
strrev(str1);
d= strcmp(str1,str2);
if(d==0)
printf("\n%s is pallindrome",str2);
else
printf("\n%s is not a pallindrome",str2);
return 0;
}
strstr() Function
The strstr() function searches the given string in the specified main string and returns the
pointer to the first occurrence of the given string.
Syntax:
strstr(str, searchString)
str – The string to be searched.
searchString – The string that we need to search in string str
Page 27
INTRADUCTION TO PROGRAMMING UNIT-III
Page 28
INTRADUCTION TO PROGRAMMING UNIT-III
Input/Output
These statements are used to Input/Output a single/group of characters from/to the
input/output devices. Here the user cannot specify the type of data that is going to be
input/output.
Input and Output Functions
(1) Unformatted Input/Output Statements:
Input Output
getc( ); putc( );
getchar( ); putchar( );
gets( ); puts( );
(2) Formatted Input/Output Statements:
Input Output
scanf( ); printf( );
fscanf( ); fprintf( );
getc() Function
This is used to accept a single character from the standard input to a character variable.
Syntax character variable=getc();
Description Character variable is the valid 'c' variable of the type of char data type
Example char c;
c=getc();
putc() Fucntion
This is used to display a single character in a character variable to standard output device.
Syntax putc (character variable);
Description Character variable is the valid 'c' variable of the type of char data type
Example char c;
putc(c);
gets & puts Function
The gets () function is used to read the string (string is a group of characters) from the
standard input device (keyboard).
The puts () function is used to display/write the string to the standard output device
(Monitor).
/* Program using gets() and puts() function */
#include<stdio.h>
main()
{
char stu_name[40];
puts("Enter Name:");
Page 29
INTRADUCTION TO PROGRAMMING UNIT-III
Page 30