0% found this document useful (0 votes)
84 views31 pages

Unit 2

The document discusses arrays and strings in C programming. It covers one-dimensional and two-dimensional arrays, string operations like length, compare, concatenate and copy. It also discusses array sorting techniques like selection sort and searching algorithms like linear and binary search. Several example programs are provided to demonstrate array and string operations like computing mean, median, mode of arrays and matrix addition among others.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views31 pages

Unit 2

The document discusses arrays and strings in C programming. It covers one-dimensional and two-dimensional arrays, string operations like length, compare, concatenate and copy. It also discusses array sorting techniques like selection sort and searching algorithms like linear and binary search. Several example programs are provided to demonstrate array and string operations like computing mean, median, mode of arrays and matrix addition among others.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT II

ARRAYS AND STRINGS

Introduction to Arrays: Declaration, Initialization - One dimensional array - Example


Program: Computing Mean, Median and Mode - Two dimensional arrays -
Example Program: Matrix Operations (Addition, Scaling, Determinant and
Transpose) - String operations: length, compare, concatenate, copy - Selection
sort, linear and binary search

PART A
1. What is an array? Write the syntax for multi-dimensional array. [APR/MAY
2018](OR) What is an array? Give the general form of array declaration.
An array is a collection of variables of the same data type that are referenced by
a common name.
Syntax: <datatype><variable_name>[index];
Syntax for multi-dimensional array:

<datatype>array_name[a][b]…..[k];

Arrays of three or more dimensions may be used, depending upon the situations and
also these array occupy more amount of memory space

For example int mark[2][4][3];

2. Design a C program for compare any two string. [APR/MAY 2018]


#include <stdio.h>
#include <string.h>
void main()
{
char s1[20], s2[20];
int result;
printf("\nEnter first string: ");
gets(s1);
printf("\nEnter second string: ");
gets(s2);
result = strcmp(s1, s2);
if (result == 0)
printf("\nBoth strings are equal");
else
printf("\nBoth strings are not equal");
getch();
}
3. State the rules for using subscript variable?
 They must be an integer.
 The subscript laws cannot be negative.
 The subscript must be within square braces after the array name.
Example: int a[5];
 If there are more than one script each should be given in separate braces
continuously without any commas.
Example: int a[5][5][5];
4. Give the declaration for the string “welcome” in c.
Syntax:
char array_name[size]= “string”;
char mess[]= {‘w’,’e’,’l’,’c’,’o’,’m’,’e’};
(or)
char mess[]=”welcome”;
5. What is mean?
Mean is same as average. The mean is found by adding up all of the given data
and dividing by the number of elements.
Example: mean of 1,2,3,4,5 is 3
6. What is median?
The median is the middle number in an ordered list (ascending or descending).
First you arrange the numbers in orders in ascending order, then you find the
middle number and that number is a median.
Example: 1,2,3,4,5
Median is 3
7. What is mode?
Mode is the element which happen most number of times in the list. If no element
happens more than once, all the elements are considered as mode.
8. What is the difference between a “C” character and a “C” string?
A character is delimited by single quotes. For example ‘S’.
A string is delimited by double quotes and the string is always terminated by the
null character ‘\0’. For example “Chennai”.
9. Declaration of string variables?
A string variable is any ‘C’ variable name and is always declared as an array. The
general form of the declaration of the string is
Char stringname[size];
The size determines the number of characters in the string name.
10. What is reading strings?
The input function scanf can be used with %s to read in a string of characters.
Example: char a[10];
Scanf(“%s”,a);
11. What is writing strings?
The output function printf can be used with %s format to print strings to the
screen. The format % can be used to display an array of characters that is
terminated by the null character.
Example: printf”%s”,name);
12. What is string array?
The two dimensional array is used to create an array of strings.
char name[20][10];
13. List the various string operations.
 strcat() concatenates two strings
 strcmp() compares two string
 strcpy() copies one string to another
 strlen() returns the length of the given string
14. What is null character? What is its use in a string?
A null character is specified as ‘0’. It is used as a terminator in the string.
PART B
1. Write the C program to multiply two matrices (two dimensional array )
which will be entered by a user. The user will enter the order of a matrix and
then its elements and similarly input the second matrix. If the entered
orders of two matrices are such that they can’t be multiplied by each other,
then an error message is displayed on the screen. [APR/MAY 2018]

#include <stdio.h>

int main()

int m, n, p, q, i, j, k, sum = 0;

int a[10][10], b[10][10], c[10][10];

printf("Enter number of rows and columns of first matrix\n");

scanf("%d%d", &n, &m);

printf("Enter number of rows and columns of second matrix\n");

scanf("%d%d", &p, &q);

printf("Enter elements of first matrix\n");

for (i = 0; i < n; i++)

for (j = 0; j < m; j++)

scanf("%d", &a[i][j]);

printf("Enter elements of second matrix\n");

for (i = 0; i < p; i++)

for (j = 0; j < q; j++)

scanf("%d", &b[i][j]);

if (m != p)

printf("The matrices can't be multiplied with each


other.\n");

else

{
for (i = 0; i < n; i++)

for (j = 0; j < q; j++)

for (k = 0; k < p; k++)

C[i][j]=c[i][j]+a[i][k]*[k][j];

printf("Product of the matrices:\n");

for (i = 0; i < m; i++)

for (k = 0; k < q; k++)

printf("%d\t", c[i][j]);

printf("\n");

return 0;

2. What are the different types of string function? Describe with their purpose.
[APR/MAY 2018] (OR) Describe about the string operation?
There are four important string handling function in the C language
I. strlen() function
II. strcpy() function
III. strcat() function
IV. strcmp() function

the header filr #include<string.h> is used when these functions are called in C
program.
I. strlen() function:
strlen() function is used to find the length of the character string.
Example:
int n;
char ss[10]=”Chennai;’
n=strlen(ss);
this will return a length of the string 7 which is assigned to an integer
variable n.
The null character ‘\0’ available at the end of a string is not counted.
II. strcpy() function:
strcpy() function is used to copy a character string to a character variable.
Example:
char city[20];
strcpy(city,”chennal”);
this will assign the string “Chennai” to the character variable city.
A character value like city=”Chennai” cannot be assigned in the C
language.
III. strcat() function:
strcat() function is used to join character strings. When two strings are
joined it is referred as concatenation of strings.
Example:
char city[20]=”Chennai”;
char pin[8]=”650 006”;
strcpy(city,pin);
this will join the two strings and store the result in city as
“Chennai 650 006”.
The resultant string is always stored in the left side string variable.
IV. strcmp() function:
strcpy() function is used to compare two character strings. It returns a 0
when the two strings are identical. Otherwise it returns a numerical value
which is the difference ASCII values of the first mismatching characters of
the strings being compared.
Example:
char city[20]=”one”;
char town[20]=”two”;
strcmp(city,town);

this will return an integer value -5 which is the difference in the ANCII
value of the first mismatching letters ‘c’ and ‘t’.
The integer value obtained as the difference may be assigned to an
integer variables as follows,
int n;
n=strcmp(city,town)

Program:
#include<stdio.h>

#include<conio.h>
void main()
{

char str1[20],str2[20],str3[40];

int res,len;

clrscr();

printf(“\n enter the string 1”);


scanf(“%s”,&str1);
printf(“\n enter the string 2”);
scanf(“%s”,&str2);
len=strlen(str1);
printf(“\n strlen(str1) :%d”,len);
if (strcmp(str1,str2)==0)
printf(“both str1 and str2 are equal”);
else if(strcmp(str1,str2)>0)
printf(“str1>str2”);
else
printf(“str1<str2”);
strcpy(str3,str1);
printf(“\t strcpy (str3,str1):%s”,str3);
strcat(str1,str2);
printf(“\n strcat(str1,str2):%s “,str1);
getch();
}

Output:
Enter the string 1 babu
Enter the string 2 rubin
Strlen(str1):4
Str1<str2
Strcpy (str3,str1):babu
Strcat(str1,str2):baburubin

3. Write the C program to find the number of vowels, consonants, Digits and
white space in a string. [APR/MAY 2018]

#include <stdio.h>

int main()

char line[150];

int i, vowels, consonants, digits, spaces;

vowels = consonants = digits = spaces = 0;

printf("Enter a line of string: ");

scanf("%s \n", line);

for(i=0; line[i]!='\0'; ++i)

if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' ||


line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U')

++vowels;

else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))

++consonants;

else if(line[i]>='0' && line[i]<='9')

++digits;

else if (line[i]==' ')

++spaces;

printf("Vowels: %d",vowels);

printf("\nConsonants: %d",consonants);

printf("\nDigits: %d",digits);

printf("\nWhite spaces: %d", spaces);

return 0;

Output

Enter a line of string: adfslkj34 34lkj343 34lk


Vowels: 1

Consonants: 11

Digits: 9

White spaces: 2

4. Define array. Explain about the types of array with examples?


An array is an collection of variables of the same data type that are referenced by
a common name.
Types:
 One dimensional array
 Two dimensional array
 Multi dimensional array

One dimensional array:

One dimensional array is like a list and the item in an array can be accessed
by just giving one subscript.

Syntax:

<datatype> identifier_name[size];

Example:

int a[5];

Array initialisation:

The initialisation of global arrays and static local arrays at the time of
declaration.

Syntax:

<datatype>array_name[size]={value list};

The value list is a common separated list of constants whose type is


compatible with the type specified.

Example: int i[5]={1,2,3,4,5};


Character array that hold strings allow a shortcut initialization of the form:

char array_name[size]=”string”;

Example:

Charn mess[]={‘w’,’e’,’l’,’c’,’o’,’m’,’e’};

Program:

#include <stdio.h>

int main()

int marks[10], i, n, sum = 0, average;

printf("Enter n: ");

scanf("%d", &n);

for(i=0; i<n; ++i)

printf("Enter number%d: ",i+1);

scanf("%d", &marks[i]);

sum += marks[i];

average = sum/n;

printf("Average = %d", average);

return 0;

Output:

Enter n: 5

Enter number1: 45

Enter number2: 35
Enter number3: 38

Enter number4: 31

Enter number5: 49

Average = 39

Two dimensional array:

Two dimensional array can store a table of values.

Syntax:

<datatype> array_name[row_size][column_size];

In two dimensional array also element declaration(both in 5row and in column)


is done with “zero origin subscripting”.

int a[3][3];

col 0 col1 col2

row 0 a[0][0] a[0][1] a[0][2]

row 1 a[1][0] a[1][1] a[1][2]

row 2 a[2][0] a[2][1] a[2][2]

Initialization Of Two Dimensional Arrays:

Two dimensional array can also be initialized by following their declaration


with a list of initial values enclosed in braces.

Example:

int a[2][3]={1,1,1,2,2}

Program:

#include<stdio.h>

int main()
{
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
}
}
}

Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

Multidimensional array:

C allows more than two dimensions. The exact limit, if any is determined by
the compiler under use,

Syntax:

<datatype>array_name[a][b]…..[k];

Arrays of three or more dimensions may be used, depending upon the situations and
also these array occupy more amount of memory space

For example int mark[2][4][3];

5. Computing Mean, Median, and Mode for the one dimensional array?
Computing Mean:
#include<stdio.h>
void main()
{
int i,n,a[20],sum=0;
float mean;
printf(“Enter N:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\nEnter %d number:”,i+1);
scanf(“%d,&a[i];
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
mean=(float)sum/n;
printf(“\nThe mean value is %f”,mean);
}
OUTPUT:
Enter N: 5
Enter 1 number: 12
Enter 2 number: 134
Enter 3 number: 14
Enter 4 number: 5
Enter 5 number: -8
The mean value is 31.400000

Computing Median:
#include<stdio.h>
void main()
{
int i,,j,temp,n,a[20],sum=0;
float median;
printf(“Enter N:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\nEnter %d number:”,i+1);
scanf(“%d,&a[i];
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
{
median=((a(n/2)+a(n/2-1))/2.0);
}
else
{
median= a(n/2);
}
printf(“\n The median value is %f”,median);
getch();
}
OUTPUT:
Enter N: 4
Enter 1 number: 14
Enter 2 number: 12
Enter 3 number: 11
Enter 4 number: 13
The median value is 12.50000

Computing Mode:
#include<stdio.h>
void main()
{
int maxvalue=0, maxcount=0,i,j,a[20],n,count=0;
printf(“Enter N:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\nEnter %d number:”,i+1);
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++)
{
//int count=0;
for(j=0;j<n;j++)
{
if(a[j]==a[i])
++count;
}
if(count>maxcount)
{
maxcount=count;;
maxvalue=a[i];
}
}
printf(“The mode value is %d”,maxvalue);
getch();
}
OUTPUT:
Enter N: 4
Enter 1 number: 0
Enter 2 number: 6
Enter 3 number: 7
Enter 4 number: 2
Enter 5 number: 7
The mode value is 7
6. Matrix operation for addition, multiplication, scaling, determinant and
transpose in two dimensional array?
Matrix addition:
#include<stdio.h>
void main()
{
int i,j,p,q,n,m,a[3][3],b[3][3],c[3][3];
printf(“Enter the size of the matrix A”);
scanf(“%d%d”,&n,&m);
printf(“Enter the size of the matrix B”);
scanf(“%d%d”,&p,&q);
if((n==p) && (m==q))
printf(“Enter the first matrix”);
for(i=1;i<=n,i++)
{
for(j=1;j<=m;j++)
{
scanf(“%d”,&a[i][j];
}
}
printf(“Enter the second matrix”);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
C[i][j]=a[i][j]+b[i][j];
}
}
printf(“ Display addition matrix”);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
printf(“%d \t”,c[i][j]);
}
printf(“\n”);
}
getch();
}
OUTPUT:
Enter the size of matrix: 3
Enter the first matrix
1 2 3
2 1 2
3 1 1
Enter the second matrix
1 2 3
2 1 2
3 1 1
Display addition matrix
2 4 6
4 2 4
6 2 2
Matrix scaling:
#include<stdio.h>
void main()
{
int i,j,a[3][3];
int n,num;
printf(“Enter the size of the matrix”);
scanf(“%d”,&n);
printf(“Enter the first matrix”);
for(i=1;i<=n,i++)
{
for(j=1;j<=n;j++)
{
scanf(“%d”,&a[i][j];
}
}

/* Input multiplier from user */

printf("Enter any number to multiply with matrix A: ");

scanf("%d", &num);

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
a[i][j]=num * a[i][j];
}
}
printf(“ Display addition matrix”);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(“%d \t”,a[i][j]);
}
printf(“\n”);
}
getch();
}

Matrix determinant:
Matrix determinant of 2x2:

a b
A=
c d |A|= ad-bc

#include<stdio.h>
void main()
{
int a[2][2],i,j;
long determinant;
printf(“Enter the 4 elements of matrix:”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&a[i][j];
}
}
determinant=a[0][0]*a[1][1]-a[1][0]*a[0][1];
printf(“\n Determinant of 2x2 matrix:%ld”, determinant);
getch();
}
OUTPUT:
Enter the 4 elements of matrix:
4 8
3 9 Determinant of 2x2 matrix: 12
Matrix transpose:
#include<stdio.h>
void main()
{
int i,j,a[3][3];
printf(“Enter the matrix”);
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Transpose matrix”);
for(j=1;j<=3;j++)
{
for(i=1;i<=3;i++)
{
printf(“%d\t”,a[i][j]);
}
Print(“\n”);
}
getch();
}
OUTPUT:
Enter the matrix
1 2 3
2 3 4
5 8 7
Transpose matrix
1 2 5
2 3 8
3 4 7
7. Write the program to sort the element using Selection sort?

 Selection sort is one of the simplest sorting algorithm


 We take the smallest element and put in the first position and the second
smallest at the second position and so on.
 We first check for smallest element in the array and swap it with the first
element of the array . again we check the smallest number in a subarray
excluding the first element of the array as it is where it should be (at the first
position) and put it in the second position of the array.
 The time complexity of selection sort is (O(n2)).

Steps:

 Start from the first element in the array and search for the smallest
element in the array.
 Swap the first element with the smallest element of the array.
 Take a subarray and search for the smallest number in the subarray
and swap it with the first element of the array.
 Repeat the step 2 and 3 with new subarrays until the array gats sorted.

Working of selection sort:

Initial array

16 19 11 15 10 12 14

First iteration

16 19 11 15 10 12 14
10 19 11 15 16 12 14

Second iteration

10 19 11 15 16 12 14
10 11 19 15 16 12 14
Third iteration

10 11 19 15 16 12 14
10 11 12 15 16 19 14

Fourth iteration

10 11 12 15 16 19 14
10 11 12 14 16 19 15

Fifth iteration

10 11 12 14 16 19 15
10 11 12 14 15 19 16

Sixth iteration

10 11 12 14 15 19 16
10 11 12 14 15 16 19

Final iteration

10 11 12 14 15 16 19

Program:

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

int a[10];
int i,j,k,n,temp,index_of_smallest;

clrscr();

printf(“Enter the value for n:\n”);

scanf(“%d”,&n);

printf(“Enter %d values in the array:\n”,n);

for(k=0;k<n;k++)

scanf(“%d”,&a[k]);

i=0;

while(i<n)

//finding the smallest number in the subarray

index_of_smallest=i;

for(j=i;j<n;j++)

if(a[j]<a[index_of_smallest])

index_of_smallest=j;

//swapping

temp=a[i];

a[i]=a[index_of_smallest];
a[index_of_smallest]=temp;

i++;

printf(“\n The sorted element in the array are:\n”);

for(i=0;i<n;i++)

printf(“%d\t”,a[i];

getch();

Output:

Enter the value for n:

Enter 7 values in the array:

16 19 11 15 19 12 14

The sorted elements in the array are:

10 11 12 14 15 16 19
8. Write a program to search for an element using (a) linear search (b) binary
search
(a) Linear search:
Linear search is also called as sequential search. Linear search is a method
for finding a particular value in a list. That consists of checking every one of its
elements, one at a time and in sequence, until the desired one is found.
Program:
#include<stdio.h>
void main()
{
int a[100],n,i,s,flag;
clrscr;
printf(“\n Enter the limit:”);
scanf(“%d”,&n);
printf(“\n Enter the element:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n Enter the elements to be searched:”);
scanf(“%d”,&s);
for(i=0;i<n;i++)
{
if(s==a[i])
{
flag=1;
break;
}
else
{
flag=0;
}
}
if(flag=1)
printf(“\n The element is %d in the position %d”,s,i+1);
else
printf(“\n %d is not found in the list”,s);
getch();
}
Output:
Enter the limit: 4
Enter the elements: 25 85 95 13
Enter the element to be searched: 87
87 is not found in the list

(b) Binary search:


 The binary search algorithm is one of the most efficient searching
techniques, which requires the list to be sorted in ascending order.
 To search for an element in the list, the binary search algorithm splits the
list and locates the middle element of the list.
 It is then compared with the search element. If the search element is less
than the middle element, if the first part of the list is searched else second
part of the list is searched

Steps:

The array consists of 7 elements

1 2 3 4 5 9 8

0 1 2 3 4 5 6

Suppose that we have to search the element 9 from the list.

Step1:

The given array is in osorted ascending order. Item to be searched is 9.

Step 2:

beg=0, end=n-1=7-1=6 so end=6, n number of element in the list.

Mid=(beg+end)/2 =(0+6)/2= 3.

The center of the element i.e middle of the element is array[3]. The
element in array[3] is 4. So the middle of the element is 4.

Step 3:

Check whether the middle of the element is as same as the item to be


searched. Here both are not same. i.e 4!=9.

Then check whether the element to be searched is less than the middle
of the element. If it is so then search the element from the half of the
array, this condition is not satisfied here.
Check whether the element to be searched is greater than the middle
of the element. If it is so then search the element from the second half
of the array. This condition is satisfied here i.e 9>4

Beg end

5 9 8

4 5 6

Mid= (beg+end)/2 =(4+6)/2 =5

Now the center of the element is array [5]=9

Step 4:

Check whether the middle of the element is same as the item to be


searched.

The condition is satisfied here, a[5]=9

Search is successful.

Advantage of binary search:

 It is more efficient for large set of data.

Drawback :

 It can be performed only for ordered list.

Program:

1. #include <stdio.h>
2.
3. void main()
4. {
5. int array[10];
6. int i, j, num, temp, keynum;
7. int low, mid, high;
8.
9. printf("Enter the value of num \n");
10. scanf("%d", &num);
11. printf("Enter the elements one by one \n");
12. for (i = 0; i < num; i++)
13. {
14. scanf("%d", &array[i]);
15. }
16. printf("Enter the element to be searched \n");
17. scanf("%d", &keynum);
18. /* Binary searching begins */
19. low = 1;
20. high = num;
21. do
22. {
23. mid = (low + high) / 2;
24. if (keynum < array[mid])
25. high = mid - 1;
26. else if (keynum > array[mid])
27. low = mid + 1;
28. } while (keynum != array[mid] && low <= high);
29. if (keynum == array[mid])
30. {
31. printf("SEARCH SUCCESSFUL \n");
32. }
33. else
34. {
35. printf("SEARCH FAILED \n");
36. }
37. }

Output:

Enter the value of num


5
Enter the elements one by one
23
90
56
15
58
Enter the element to be searched
58
SEARCH SUCCESSFUL
9. Write the program for bubble sort?

#include<stdio.h>

void main()

int a[20], n, temp, i, j;

printf(“Enter the number of term:”);

scanf(“%d”,&n);

printf(“Enter the elements of the array”);

for(i=0;i<n;i++)

scanf(“%d”,&a[i]);

for(i=0;i<n;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(“After sorting:\n”);
for(i=0;i<n;i++)

printf(“%d\t”,a[i]);

Output:

Enter the number of terms: 5

Enter the elements of the array:

12 0 -14 5 16

After sorting:

-14 0 5 12 16

You might also like