STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
UNIT-III
Arrays in C
In C language, arrays are referred to as structured data types. An array is defined as finite ordered
collection of homogenous data, stored in contiguous memory locations. (collection of elements of
same data type)
Here the words,
• finite means data range must be defined.
• ordered means data must be stored in continuous memory addresses.
• homogenous means data must be of similar data type.
Example where arrays are used,
• to store list of Employee or Student names,
• to store marks of students,
• or to store list of numbers or characters etc.
•
Since arrays provide an easy way to represent data, it is classified amongst the data structures in C.
Other data structures in c are structure, lists, queues, trees etc. Array can be used to represent not
only simple list of data but also table of data in two or three dimensions.
Declaring an Array
Like any other variable, arrays must be declared before they are used. General form of array
declaration is,
data-type variable-name[size];
/* Example of array declaration */
int arr[10];
Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can
only contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e. first element of arr array will be stored at arr[0] address
and the last element will occupy arr[9].
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain garbagevalue(any random
value). An array can be initialized at either compile time or at runtime.
27
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Compile time Array initialization
Compile time initialization of array elements is same as ordinary variable initialization. The general
form of initialization of array is,
data-type array-name[size] = { list of values };
/* Here are a few examples */
int marks[4]={ 67, 87, 56, 77 }; // integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error
One important thing to remember is that when you will give more initializer(array elements) than the
declared array size than the compiler will give an error.
#include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}
234
Runtime Array initialization
An array can also be initialized at runtime using scanf() function. This approach is usually used for
initializing large arrays, or to initialize arrays with user specified values. Example,
#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
{
28
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
printf("%d\n", arr[j]);
}
}
Two dimensional Arrays
C language supports multidimensional arrays also. The simplest form of a multidimensional array is
the two-dimensional array. Both the row's and column's index begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
/* Example */
int a[3][4];
An array can also be declared and initialized together. For example,
int arr[][3] = {
{0,0,0},
{1,1,1}
};
Note: We have not assigned any row value to our array in the above example. It means we can
initialize any number of rows. But we must always specify number of columns, else it will give a
compile time error. Here, a 2*3 multi-dimensional matrix is created.
Runtime initialization of a two-dimensional Array
#include<stdio.h>
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
29
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}
Multi-dimensional Array
In C, we can define multidimensional arrays in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order).
General form of declaring N-dimensional arrays:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
Examples:
Two-dimensional array:
int two_d[10][20];
Three-dimensional array:
int three_d[10][20][30];
Size of multidimensional arrays
Total number of elements that can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
String and Character Array
String is a sequence of characters that is treated as a single data item and terminated by null
character '\0'. Remember that C language does not support strings as a data type. A string is actually
30
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
one-dimensional array of characters in C language. These are often used to create meaningful and
readable programs.
For example: The string "hello world" contains 12 characters including '\0' character which is
automatically added by the compiler at the end of the string.
Declaring and Initializing a string variables
There are different ways to initialize a character array variable.
char name[13] = "Study Tonight"; // valid character array initialization
char name[10] = {'L','e','s','s','o','n','s','\0'}; // valid initialization
Remember that when you initialize a character array by listing all of its characters separately then
you must supply the '\0' character explicitly.
Some examples of illegal initialization of character array are,
char ch[3] = "hell"; // Illegal
char str[4];
str = "hell"; // Illegal
String Input and Output
Input function scanf() can be used with %s format specifier to read a string input from the
terminal. But there is one problem with scanf() function, it terminates its input on the first white space
it encounters. Therefore, if you try to read an input string "Hello World" using scanf() function, it
will only read Hello and terminate after encountering white spaces.
However, C supports a format specification known as the edit set conversion code %[..] that can be
used to read a line containing a variety of characters, including white spaces.
#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}
Another method to read character string with white spaces from terminal is by using
the gets() function.
char text[20];
gets(text);
printf("%s", text);
31
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
String Handling Functions
C language supports a large number of string handling functions that can be used to carry out many
of the string manipulations. These functions are packaged in string.h library. Hence, you must
include string.h header file in your programs to use these functions.
The following are the most commonly used string handling functions.
Method Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show length of a string
strrev() It is used to show reverse of a string
strcpy() Copies one string into another
strcmp() It is used to compare two string
1) strcat() function
strcat("hello", "world");
strcat() function will add the string "world" to "hello" i.e., it will ouput helloworld.
2)strlen() function
strlen() function will return the length of the string passed to it.
int j;
j = strlen("studytonight");
printf("%d",j);
12
3) strcmp() function
strcmp() function will return the ASCII difference between first unmatching character of two strings.
32
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
int j;
j = strcmp("study", "tonight");
printf("%d",j);
-1
4) strcpy() function
It copies the second-string argument to the first-string argument.
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50];
char s2[50];
strcpy(s1, "StudyTonight"); //copies "studytonight" to string s1
strcpy(s2, s1); //copies string s1 to string s2
printf("%s\n", s2);
return(0);
}
StudyTonight
5) strrev() function
It is used to reverse the given string expression.
#include<stdio.h>
int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}
Enter your string: studytonight
Your reverse string is: thginotyduts
33
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
Other String Functions
1) strncpy
• strncpy( ) function copies portion of contents of one string into another string.
• Example:
strncpy ( str1, str2, n) – It copies first n characters of str2 into str1.
If destination string length is less than source string, entire source string value won’t be copied
into destination string.
EXAMPLE PROGRAM FOR strncpy( ) FUNCTION IN C:
In this program, only 5 characters from source string “fresh2refresh” is copied into target string using
strncpy( ) function.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strncpy ( target, source, 5 ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
COMPILE & RUN
OUTPUT:
source string = fresh2refresh
target string =
target string after strncpy( ) = fresh
2) strncat() function
• strncat( ) function concatenates (appends) portion of one string at the end of another string.
Example:
strncat ( str1, str2, n ); – First n characters of str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character (‘\0’).
In strncat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created after
strncat( ) operation.
34
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
EXAMPLE PROGRAM FOR strncat( ) FUNCTION IN C:
In this program, first 5 characters of the string “fresh2refresh” is concatenated at the end of the
string “C tutorial” using strncat( ) function and result is displayed as “C tutorial fresh”.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[ ]= "C tutorial" ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strncat ( target, source, 5 ) ;
printf ( "\nTarget string after strncat( ) = %s", target ) ;
}
OUTPUT:
Source string = fresh2refresh
Target string = C tutorial
Target string after strcat( ) = C tutorialfresh
3)strncmp() function
This function compares only the first n (specified number of) characters of strings and returns
following value based on the comparison.
Example:
strncmp ( str1, str2, n );
• 0, if both the strings str1 and str2 are equal
• negative number , if str1 is less than str2
• positive number, if str1 is greater than str2
EXAMPLE PROGRAM FOR strncmp( ) FUNCTION IN C:
/* C strncmp Function example */
#include <stdio.h>
#include<string.h>
int main()
{
char str1[50] = "abcdef";
char str2[50] = "abcd";
35
STUDY MATERIAL FOR BCA
PROGRAMMING IN C
SEMESTER - I, ACADEMIC YEAR 2022-23
char str3[] = "ghi";
int i, j, k;
i = strncmp(str1, str2, 4);
printf("\n The Comparison of str1 and str2 Strings = %d", i);
j = strncmp(str1, str2, 6);
printf("\n The Comparison of str1 and str2 Strings = %d", j);
k = strncmp(str1, str3, 3);
printf("\n The Comparison of str1 and str3 = %d", k);
}
OUTPUT:
The Comparison of str1 and str2 Strings = 0
The Comparison of str1 and str2 Strings = 1
The Comparison of str1 and str3 = -1
3)strstr() function
It can be used to locate a substring in a string.
Example:
strstr ( str1, str2);
searches str2 is contained in str1.
• if yes, returns the position of the first occurrence of str2.
• if no, returns null pointer.
EXAMPLE PROGRAM FOR strstr( ) FUNCTION IN C:
#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "Learning C is awesome";
char str2 [15] = "C";
char *st;
st = strstr(str1, str2);
printf("%s", st);
return 0;
}
OUTPUT:
C is awesome
36