UNIT II Arrays and Strings
UNIT II Arrays and Strings
(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
DATA SCIENCE
191GES204T – PROGRAMMING IN C
Unit II –Notes
PREPARED BY APPROVED BY
ARRAYS: INTRODUCTION
It also has the capability to store the collection of derived data types, such as
pointers, structure, etc. The array is the simplest data structure where each data element
can be randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different variables
for the marks in the different subject. Instead of that, we can define an array which can
store the marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
Properties of Array
Each element of an array is of same data type and carries the same size
i.e., int = 4 bytes.
Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.
Advantage of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will
learn later.
INITIALIZATION OF C ARRAY
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
DECLARATION OF C ARRAY
data_type array_name[array_size];
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
C array example
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Output
80
60
70
85
75
We can access any array element using array name and subscript/index written
inside pair of square brackets [ ].
Example:
Now we can access elements of array marks using subscript followed by array name.
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.
Output
20
30
40
50
60
In the following program, we are using bubble sort method to sort the array in ascending
order.
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
Output
Program to print the largest and second largest element of the array.
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
largest = arr[0];
sec_largest = arr[1];
for(i=0;i<n;i++)
{
if(arr[i]>largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i]>sec_largest && arr[i]!=largest)
{
sec_largest=arr[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);
Output
It provides ease of holding the bulk of data at once which can be passed to any
number of functions wherever required.
data_type array_name[rows][columns];
int twodimen[4][3];
initialization are being done simultaneously. However, this will not work with 2D
arrays. We will have to define at least the second dimension of the array. The two-
dimensional array can be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
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
arr[3][2] = 6
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
Matrix multiplication in C
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
STRINGS:
Each character in the array occupies one byte of memory, and the last character
must always be 0. The termination character ('\0') is important in a string since it is
the only way to identify where the string ends.
When we define a string as char s[10], the character s[10] is implicitly initialized
with the null in the memory.
By char array
By string literal
char ch[ ]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given
below.
0 1 2 3 4 5 6
w e l c o m e
While declaring string, size is not mandatory. So we can write the above code as given
below:
char ch[ ]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
We can also define the string by the string literal in C language. For example:
In such case, '\0' will be appended at the end of the string by the compiler.
There are two main differences between char array and literal.
We need to add the null character '\0' at the end of the array by ourself whereas, it
is appended internally by the compiler in the case of the character array.
The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as
a format specifier for the string in c language.
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
char ch2[11]="welcome";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Output
Traversing String
Traversing the string is one of the most important aspects in any of the
programming languages. We may need to manipulate a very large text which can be done
by traversing the text.
#include<stdio.h>
void main ()
{
char s[11] = "welcome";
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{
count ++;
}
i++;
}
printf("The number of vowels %d",count);
}
Output
C String Functions
3) strcat(first_string, concats or joins first string with second string. The result of
second_string) the string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.
The strlen() function returns the length of the given string. It doesn't count null character
'\0'.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'h', 'e', 'l', 'l', 'o', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output:
#include<stdio.h>
#include <string.h>
int main( ){
char ch[20]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}
Output:
The strcmp(first_string, second_string) function compares two string and returns 0 if both
strings are equal.
Here, we are using gets() function which reads string from the console.
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
The strrev(string) function returns reverse of the given string. Let's see a simple example of
strrev() function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output:
The strupr(string) function returns string characters in uppercase. Let's see a simple
example of strupr() function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}
Output:
C String strstr()
The strstr() function returns pointer to the first occurrence of the matched string in the
given string. It is used to return substring from first match till the last character.
Syntax:
string: It represents the full string from where substring will be searched.
Output:
is a c program
STRING ARRAYS
Here,
var_name is the name of the variable in C.
r is the maximum number of string values that can be stored in a string array.
c is a maximum number of character values that can be stored in each string array.
Example – 1
#include <stdio.h>
// Driver code
int main()
{
char arr[3][10] = {"Hel", "Hello", "Hellostudents"};
printf("String array Elements are:\n");
Output:
In C, a Character and a String are separate data types, unlike other programming
languages like Python. A String is a collection of Characters. Hence, to define a String, we
use a Character Array:
#include<stdio.h>
int main()
{
char str[8];
printf("Enter a String: ");
scanf("%s", &str);
printf("%s", str);
}
Output:
Example – 2
#include<stdio.h>
int main()
{
int i;
char Array[3][6] = {"Black", "Blame", "Block"};
printf("String Array: \n");
for(i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
return 0;
}
Output:
String Array:
Black
Blame
Block
Example – 3
#include<stdio.h>
int main()
{
int i;
char Array[3][6] = {"Black", "Blame", "Block"};
strcpy(Array[0], "Hello");
for(i = 0; i < 3; i++)
{
printf("%s\n", Array[i]);
}
Output:
String Array:
Hello
Blame
Block
#include <stdio.h>
void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
Output:
#include <stdio.h>
int main(){
int arr[50], num, x, y, temp;
printf("Please Enter the Number of Elements you want in the array: ");
scanf("%d", &num);
printf("Please Enter the Value of Elements: ");
for(x = 0; x < num; x++)
scanf("%d", &arr[x]);
for(x = 0; x < num - 1; x++){
for(y = 0; y < num - x - 1; y++){
if(arr[y] > arr[y + 1]){
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
printf("Array after implementing bubble sort: ");
for(x = 0; x < num; x++)
{
printf("%d ", arr[x]);
}
return 0; }
Output:
#include <stdio.h>
void main()
{
int num;
int i, key, element_found = 0;
printf("Enter number of elements you would like to take as input: ");
scanf("%d", &num);
int arr[num];
printf("\nEnter all the elements of your choice:");
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter the key element that you would like to be searched: ");
scanf("%d", &key);
/* Linear search starts */
for (i = 0; i < num ; i++)
{
if (key == arr[i] )
{
element_found = 1;
break;
}
}
if (element_found == 1)
printf("we got the element at index %d",i+1);
else
printf("we haven’t got element at any index in the array\n");
}
Output:
Implementing Binary Search in C
To find the Transpose of a Matrix
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
Output
Entered matrix:
1 4 0
-5 2 7
include<stdio.h>
int main()
{
int a[2500], n, i, t, j, max=0, c=0, mode=0;
float s=0, mean, median;
printf(“Enter how many data you want to input: “);
scanf(“%d”,&n);
printf(“Enter %d Data:\n”, n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
s+=a[i];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
// to find mean
mean = s/(float)n;
printf(“mean or average is: %.1f\n”,mean);
//to find median
if(n%2==0)
median=( (a[(n-1)/2] + a[(n-1)/2+1] ) / 2.0);
else
median=( (a[(n-1)/2]) / 2.0);
printf(“median is: %.1f\n”, median);
//to find mode
for(i=0; i<n; i++)
{
t=a[i];
c=0;
for(j=0; j<n; j++) { if(t==a[j]) c++; if(c>max)
{
max=c;
mode=t;
}
}
}
printf(“mode is %d”,mode);
return 0;
}
Output