Unit - 3
Unit - 3
UNIT-3
ARRAYS
Using Arrays in C
C supports a derived data type known as array that can be used to handle large amounts of data (Multiple
values) at a time.
Definition:
Or
An array is a collection of data that holds fixed number of values of same type.
Or
Array is a collection or group of elements (data). All the elements of array are homogeneous (similar). It
has contiguous memory location.
Or
An array is a data structured that can store a fixed size sequential collection of elements of same data type.
Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be
typical and hard to manage. For example we cannot access the value of these variables with only 1 or 2
lines of code.
Another way to do this is array. By using array, we can access the elements easily. Only few lines of code
is required to access the elements of array.
1
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of Array
Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it
doesn't grow the size dynamically like Linked List
Declaration of an Array
For example:
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 last element will occupy arr[9].
Initialization of an Array
2
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value).
An array can be initialized at either compile time or at runtime.
Example
int age[5]={22,25,30,32,35};
1 : Initializing all specified memory locations : If the number of values to be initialized is equal to size of
array. Arrays can be initialized at the time of declaration. Array elements can be initialized with data items
of type int, float, char, etc.
int a[5]={10,20,30,40,50};
During compilation, 5 contiguous memory locations are reserved by the compiler for the variable a and all
these locations are initialized.
3
If the size of integer is 2 bytes, 10 bytes will be allocated for the variable a.
2: Partial Array Initialization: partial array initialization is possible in C language. If the number of values
to be initialized is less than the size of the array, then the elements are initialized in the order from 0th
location. The remaining locations will be initialized to zero automatically.
int a[5]={10,15};
Even though compiler allocates 5 memory locations, using this declaration statement, the compiler
initializes first two locations with 10 and 15, the next set of memory locations are automatically initialized
to zero.
You can access elements of an array by indices/index. You can use array subscript (or index) to access any
element stored in array. Subscript starts with 0, which means array name [0] would be used to access first
element in an array.
In general array name [n-1] can be used to access nth element of an array. Where n is any integer number.
Example
float mark[5];
Suppose you declared an array mark as above. The first element is mark [0], second element is mark[1] and
so on.
4
Few key notes:
If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4]
Suppose the starting address of mark [0] is 2120d. Then, the next address, a[1], will be 2124d,
address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.
Input data into array
As you can see, in above example that I have used „for loop‟ and „scanf statement‟ to enter data into array.
You can use any loop for data input.
Code:
scanf("%d", &num[x]);
For example you want to read and display array elements, you can do it just by using any loop. Suppose
array is mydata [20].
Exmaple
#include<stdio.h>
#include<conio.h>
void main()
5
int i;
printf("%d\t",arr[i]);
getch();
Output
234
Exmaple
1. include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=0;
6. clrscr();
7.
8. //traversal of array
9. for(i=0;i<5;i++){
11. }
12.
13. getch();
14. }
Output
6
20
30
40
50
60
An array can also be initialized at runtime using scanf() function. This approach is usually used for
initializing large array, or to initialize array with user specified values.
Example
#include<stdio.h>
#include<conio.h>
void main()
int arr[4];
int i, j;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
printf("%d\n",arr[j]);
getch();
7
Two‐Dimensional Arrays
The two dimensional array in C language is represented in the form of rows and columns, also known as
matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional
arrays.
data_type array_name[size1][size2];
Example
int twodimen[4][3];
Example :
int a[3][4];
Initialization of 2D Array
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index
of the array.
Example
1. #include <stdio.h>
8
2. #include <conio.h>
3. void main(){
4. int i=0,j=0;
5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
6. clrscr();
7. //traversing 2D array
8. for(i=0;i<4;i++){
9. for(j=0;j<3;j++){
11. }//end of j
12. }//end of i
13. getch();
14. }
Output:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
9
arr[3][2] = 6
#include<stdio.h>
#include<conio.h>
void main()
int a[25][25],b[25][25],c[25][25],i,j,m,n;
clrscr();
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("\t%d",&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("\t%d",&b[i][j]);
for(i=0;i<m;i++)
10
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",a[i][j]);
for(i=0;i<m;i++)
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",a[i][j]);
for(i=0;i<m;i++)
printf("\n");
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\t%d",c[i][j]);
getch();
11
Write a C program Multiplication of Two Matrices.
#include<stdio.h>
#include<conio.h>
void main()
int a[25][25],b[25][25],c[25][25],i,j,m,n,k,r,s;
clrscr();
scanf("%d%d",&m,&n);
scanf("%d%d",&r,&s);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("\t%d",&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("\t%d",&b[i][j]);
for(i=0;i<m;i++)
12
{
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",a[i][j]);
for(i=0;i<m;i++)
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",b[i][j]);
for(i=0;i<m;i++)
printf("\n");
for(j=0;j<n;j++)
c[i][j]=0;
for(k=0;k<m;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
for(i=0;i<m;i++)
13
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",c[i][j]);
getch();
Multidimensional Arrays
You can initialize a three dimensional array in a similar way like a two dimensional array. Here's an example
int test[2][3][4] = {
};
Example
#include <stdio.h>
int main()
int i, j, k, test[2][3][2];
scanf("%d", &test[i][j][k]);
14
}
printf("\nDisplaying values:\n");
return 0;
Output
Enter 12 values:
123456789101112
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
15
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
STRINGS:
String Concepts
String is an array of characters that is terminated by \0 (null character). This null character indicates the end
of the string. Strings are always enclosed by double quotes ( " " ). Whereas, character is enclosed by single
quotes.
Or
In „C‟ language the group of characters, digits, and symbols enclosed within double quotation ( " " ) marks
are called as string otherwise a string is an array of characters and terminated by NULL character which is
denoted by the escape sequence „\0‟.
C Strings
Declaration of String: C does not support string as a data type. However, it allows us to represent strings
as character arrays. In C, a string variable is any valid C variable name and it is always declared as an array
of characters.
Note: In declaration of string size must be required to mention otherwise it gives an error.
16
Using this declaration the compiler allocates 9 memory locations for the variable a ranging from 0 to 8.
Here, the string variable a can hold maximum of 9 characters including NULL(\0) character.
Note: In Initialization of the string if the specific number of character is not initialized it then rest of all
character will be initialized with NULL.
char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
Note: In initialization of the string we can not initialized more than size of string elements.
Ex:
17
Char b[9]={„C‟,‟O‟,‟M‟,‟P‟,‟U‟,‟T‟,‟E‟,‟R‟};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized with the
characters in the order specified. The remaining locations are automatically initialized to null characters.
2 : Partial Array Initialization : If the characters to be initialized is less than the size of the array, then
the characters are stored sequentially from left to right. The remaining locations will be initialized to NULL
characters automatically.
int a[10]={„R‟,‟A‟,‟M‟,‟A‟ };
The compiler allocates 10 bytes for the variable a ranging from 0 to 9 and
initializes first four locations with the ASCII characters of „R‟, „A‟, „M‟, „A‟.The remaining locations are
automatically filled with NULL characters (i.e,\0).
3 : Initialization without size : consider the declaration along with the initialization
char b[]={„C‟,‟O‟,‟M‟,‟P‟,‟U‟,‟T‟,‟E‟,‟R‟};
In this declaration, The compiler will set the array size to the total number of initial values i.e 8. The
character will be stored in these memory locations in the order specified.
4) Array Initialization with a String : consider the declaration with string initialization.
char b[ ] = “COMPUTER”;
18
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.
The string “COMPUTER” contin 8 charactes, because it is a string. It always ends with null character. So,
the array is 9 bytes (i.e string length+1 byte for null character).
Reading and Writing Strings : 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.
Example :
char name[10];
scanf(“%s”,name);
printf(“%s”,name);
Example:
1. #include <stdio.h>
2. void main ()
3. {
4. char ch[13]={'c', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', i', „n‟, „g‟, „\0‟};
5. char ch2[13]="cprogramming";
6.
9. }
Output
19
Example:
#include <stdio.h>
int main()
char name[20];
scanf("%s", name);
return 0;
Output
It is clear from the output that, the above code will not work for space separated strings. To make this code
working for the space separated strings, the minor changed required in the scanf function, i.e., instead of
writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which instructs the compiler to store the string s
while the new line (\n) is encountered. Let's consider the following example to store the space-separated
strings.
Example:
#include<stdio.h>
void main ()
char s[20];
scanf("%[^\n]s",s);
20
}
Output
The strings can be read from the keyboard and can be displayed onto the monitor using various functions.
The various input and output functions that are associated with can be classified as
1 : getchar() function : A single character can be given to the computer using „C‟ input library function
getchar().
The getchar() function is written in standared I/O library. It reads a single character from a standared input
device. This function do not require any arguments, through a pair of parantheses, must follow the
statements getchar().
#include<stdio.h>
21
#include<conio.h>
#include<ctype.h>
void main()
char ch;
clrscr();
ch=getchar();
if(isalpha(ch)>0)
printf("it is a alphabet:%c\n",ch);
else if(isdigit(ch)>0)
printf("it is a digit:%c\n",ch);
else
printf("it is a alphanumeric:%c\n",ch);
getch();
}.
it is a alphabet:a
2 : putchar() function :The putchar() function is used to display one character at a time on the standared
output device. This function does the reverse operation of the single character input function.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
22
char ch;
ch=getchar();
if(islower(ch))
putchar(toupper(ch));
else
putchar(tolower(ch));
getch();
3 : gets() : The gets() function is used to read the string (String is a group of characters) from the standard
input device (keyboard).
Ex :#include<stdio.h>
#include<conio.h>
void main()
char str[40];
clrscr();
gets(str);
getch();
23
Print the string :reddy
4 : puts() :The puts() function is used to display the string to the standared output device (Monitor).
#include<stdio.h>
#include<conio.h>
void main()
char str[40];
gets(str);
puts(str);
getch();
subbareddy
Subbareddy
24
String Manipulation Functions/ String Handling Functions
The various string handling functions that are supported in C language are as shown
1 : strlen(string) – String Length : This function is used to count and return the number of characters
present in a string.
Syntax : var=strlen(string);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
char name[]="JBREC";
int len1,len2;
clrscr();
25
len1=strlen(name);
len2=strlen("JBRECECE");
getch();
OUTPUT :
#include <stdio.h>
int main()
char str[100];
int i,length=0;
scanf("%s",str);
return 0;
26
Output:
Enter a string:
PREPINSTA
2 : strcpy(string1,string2) – String Copy : This function is used to copy the contents of one string to
another string.
Syntax : strcpy(string1,string2);
Where
#include <stdio.h>
#include <string.h>
int main() {
char str2[20];
strcpy(str2, str1);
puts(str2); // C programming
return 0;
#include <stdio.h>
int main()
27
// s1 is the source( input) string and
s2[i] = s1[i];
s2[i] = '\0';
return 0;
3 : strlwr(string) – String LowerCase : This function is used to converts upper case letters of the string in
to lower case letters.
Syntax : strlwr(string);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
char str[]="JBREC";
clrscr();
strlwr(str);
getch();
28
}
#include<stdio.h>
#include<conio.h>
void main()
char str[10];
int index;
scanf("%s",str);
for(index=0;str[index]!='\0';index++)
str[index]=str[index]+32;
getch();
4 : strupr(string) – String UpperCase : This function is used to converts lower case letters of the string in
to upper case letters.
Syntax : strupr(string);
#include<stdio.h>
29
#include<conio.h>
#include<string.h>
void main()
char str[]="jbrec";
strupr(str);
printf("UpperCase is :%s\n",str);
getch();
#include<stdio.h>
#include<conio.h>
void main()
char str[10];
int index;
scanf("%s",str);
for(index=0;str[index]!='\0';index++)
str[index]=str[index]-32;
30
getch();
5. strcmp(string1,string2) – String Comparison : This function is used to compares two strings to find out
whether they are same or different. If two strings are compared character by character until the end of one
of the string is reached.
Case 2: when the strings are unequal, it returns the difference between ASCII values of the characters that
differ.
#include <stdio.h>
#include <string.h>
int main()
int result;
return 0;
31
}
Output
strcmp(str1, str2) = 1
strcmp(str1, str3) = 0
#include <stdio.h>
#include <string.h>
int main()
int result, i;
gets(Str1);
gets(Str2);
32
}
else
return 0;
OUTPUT:
Syntax : strcat(sting1,string2);
Where
when the above function is executed, string2 is combined with string1 and it removes the null character
(\0) of string1 and places string2 from there.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
33
char str1[10]="jbrec";
char str2[]="ece";
strcat(str1,str2);
printf("%s\n",str1);
printf("%s\n",str2);
getch();
OUTPUT : jbrecece
Ece
#include<stdio.h>
void main(void)
char str1[25],str2[25];
int i=0,j=0;
gets(str1);
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
str1[i]=str2[j];
j++;
34
i++;
str1[i]='\0';
7. strrev(string) - String Reverse :This function is used to reverse a string. This function takes only one
argument and return one argument.
Syntax : strrev(string);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
char str[20];
scanf("%s",str);
getch();
int main()
35
int begin, end, count = 0;
printf("Input a string\n");
gets(s)
count++;
end = count - 1;
r[begin] = s[end];
end--;
r[begin] = '\0';
printf("%s\n", r);
return 0;
36
37