Unit-2 Notes - PS
Unit-2 Notes - PS
MODULE-2
Arrays and Strings
Introduction to Arrays: Declaration, Initialization One dimensional array Two dimensional arrays -
String operations: length, compare, concatenate, copy Selection sort, linear and binary search.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements requiredby an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a 10-element
array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write –
The above statement assigns the 5th element in the array with a value of 50.0. All arrays have
0 as the index of their first element which is also called the base index and the last index of an
array will be total size of the array minus 1. Shown below is the pictorial representation of the
array we discussed above −
An element is accessed by indexing the array name. This is done by placing the index of the
2 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary
variable.
datatype arrayname[size];
datatype: kind of values it can store Example int, float, char, double.
arrayname:To identify the an Array
Size:maximum number of values that an array
can hold. Ex: int a[4];
Sample
program1:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
printf(“%d \t%d\t%d\t%d”,a[0],a[1],a[2],a[3]);
getch();
}
Output:
20 45 67 89
Sample program2: The efficient way of accessing array elements is using loop
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4]={20,45,67,89};
int i;
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
20 45 67 89
Note:
By default the elements of an array are not initialized. They may contain some garbage
value, so before using array we must initialize the array or read some meaningful data into it.
Sample program 3
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a[4],i;
printf(“Enter the elements\n”);
for(i=0;i<4;i++)
{
scanf(“%d\t”,&a[i]);
}
for(i=0;i<4;i++)
{
printf(“%d\t”,a[i]);
}
getch();
}
Output:
20 45 67 89
ARRAY PROGRAMS
1. Program to read the numbers and print the given numbers in reverse order
#includ
e<stdio.
h>
#includ
e<conio
.h> void
main()
{
int a[10],i;
clrscr();
printf("Enter the
elements");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("The elements
are"); for(i=4;i>=0;i-
-)
{
printf("%d\t",a[i]);
}
getch();
}
Output:
printf("Enter Elements");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<5;i++)
{
sum=sum+a[i];
}
}
}
Output:
Enter
Elements 2
3
4
5
6
The Sum of elements in an
array is 20 The Avg of
elements in an array is 4
1. // largest in an array
#include <stdio.h>
int main() {
int a[10],i, max,n;
printf("enter the count of numbers");
scanf("%d", &n);
printf("enter list of numbers");
for (i=0;i<5;i++)
scanf("%d",&a[i]);
max=a[0];
for(i=1;i<5;i++)
if (max<a[i])
max=a[i];
printf("Largest = %d",max);
return 0;
7
Programming In C Module 2
2. //Second Largest
#include <stdio.h>
int main() {
int array[10] = {101, 11, 3, 4, 50, 69, 7, 8, 9, 0};
int loop, largest, second;
return 0;
}
3. Linear Search
#include <stdio.h>
int main() {
int a[10],i, key, flag=0;
printf("enter list of numbers");
for (i=0;i<5;i++)
scanf("%d",&a[i]);
printf("enter search element");
scanf("%d",&key);
for(i=0;i<5;i++)
{if (key==a[i])
{printf("%d found at %d", key,i+1);
flag=1;
}
8
Programming In C Module 2
}
if (flag==0)
printf("Not found");
return 0;
}
a. Divide the search space into two halves by finding the middle index “mid”.
b. Compare the middle element of the search space with the key.
c. If the key is found at middle element, the process is terminated.
d. If the key is not found at middle element, choose which half will be used as the
next search space.
e. If the key is smaller than the middle element, then the left side is used for next
search.
f. If the key is larger than the middle element, then the right side is used for next search.
g. This process is continued until the key is found or the total search space is exhausted.
Program:
#include <stdio.h>
int main() {
int n, key, low, high, mid, arr[20];
scanf("%d", &arr[i]);
}
// Binary Search
low = 0;
high = n - 1;
int found = 0; // Flag to indicate if key is found
if (arr[mid] == key) {
printf("Element %d found at index %d.\n", key, mid);
found = 1;
break;
} else if (arr[mid] < key) {
low = mid + 1; // Search in the right half
} else {
high = mid - 1; // Search in the left half
}
}
if (!found) {
printf("Element %d not found in the array.\n", key);
}
return 0;
}
Sample Output 1
Enter the number of elements in the array: 5 Enter 5
integers:
10 3 5 7 1
Enter an integer to search: 5
Sample Output 2
10
Programming In C Module 2
Iteration 1:
Iteration 2:
Iteration 3:
11
Programming In C Module 2
Iteration 4:
Iteration 5:
Program
#include <stdio.h>
int main() {
int n, i,arr[20],j,temp;
return 0;
}
Sample Output:
Before Using Bubble Sort:
13 46 24 52 20 9
After Using bubble
12
Programming In C Module 2
sort: 9 13 20 24 46 52
6. Selection Sort
int main()
{
int n,i, temp, min;
int arr[20];
printf("Enter number of elements you want to sort: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d Element: ",i+1); scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(arr[min]>arr[j])
min = j;
}
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
printf("After Selection sort elements are: ");
for (i=0; i<n;i++)
printf(“%d ”, arr[i]);
13
Programming In C Module 2
Syntax:
Datatype arrayname [size of row] [size of column];
elements of each row are enclosed within curly braces and separated by commas. All
rows are enclosed within curly braces.
Syntax:
datatype arrayname[size of row][size of column]={values separated by
comma};Example: int a[3][2]={{10,20},{30,40},{50,60}};
14
Programming In C Module 2
Col 0 Col 1
Row 0 10 20
Row 1 30 40
Row 2 50 60
Sample
program 4:
#include<stdio.h
>
#include<conio.h
> void main()
{
clrscr();
int a[3][2]={{10,20},{30,40},{50,60}};
printf(“%d\t”,a[0][0]);
printf(“%d\n”,a[0][1]);
printf(“%d\t”,a[1][0]);
printf(“%d\n”,a[1][1]);
printf(“%d\t”,a[2][0]);
printf(“%d\n”,a[2][1]);
}
Output:10 20
30 40
50 60
Sample program
#include<stdio.h>
#include<conio.h>voi
d main()
{
int a[3][2]={{10,20},{30,40},{50,60}};
int i,j;
printf("\nThe
Matrix");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
{
15
Programming In C Module 2
printf("\t%d",a[i][j]);
}
getch();
}
Output:
10 20
30 40
50 60
16
Programming In C Module 2
ii) Run time initialization: : Two-dimensional array can be initialization at run timeusing
loop.
int a[2][3];
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
Sample program :
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3];int i,j;
printf(“Enter the elements\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, &a[i][j]);
}
}
printf(“\nThe elements
are”); for(i=0;i<2;i++)
{
printf(“\n”);
for(j=0;j<3;j++)
{
printf(“%d\t”, a[i][j]);
}
}
}
17
Programming In C Module 2
1
2
3
4
The elements are
1 2
3 4
2. MATRIX ADDITION
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2];
int i,j,k;
clrscr();
printf("Enter Matrix A");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter matrix
B");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nThe result");
for(i=0;i<2;i++)
18
Programming In C Module 2
{
printf("\n");
for(j=0;j<2;j++)
{
printf("\t%d",c[i][j]);
}
}
getch();
}
Output:
Enter Matrix
A1 2 3 4
Enter Matrix
B1 2 3 4
The result2
4
6 8
3. MATRIX SUBTRACTION
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2];
int i,j,k;
clrscr();
printf("Enter Matrix
A"); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter matrix
B");
for(i=0;i<2;i++)
{
19
Programming In C Module 2
for(j=0;j<2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]-b[i][j];
}
}
printf("\nThe
result");
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
{
printf("\t%d",c[i][j]);
}
}
getch();
}
Output:
Enter Matrix
A1 2 3 4
Enter Matrix B
1
1
1
1
Output:
01
2 3
20
Programming In C Module 2
4. MATRIX MULTIPLICATION
Input:
mat1[][] = {{1, 2},
{3, 4}}
mat2[][] = {{5, 6},
{7, 8}}
Multiplication of two matrices:
{{1*5 + 2*7 1*6 + 2*8},
{3*5 + 4*7 3*6 + 4*8}}
Output:
{{19, 22},
{43, 50}}
5.
Multiplication of two matrices is done by multiplying corresponding elements from the rows of the
first matrix with the corresponding elements from the columns of the second matrix and then adding
these products.
Note: The number of columns in the first matrix must be equal to the number of rows in the second
matrix.
Lab Prog. 4
4. Implement Matrix multiplication and validate the rules of multiplication
Input:
first[][] = {{1, 2}, {3, 4}}
second[][] = {{5, 6}, {7, 8}}
Multiplication of two matrices:
{{1*5 + 2*7 1*6 + 2*8},
{3*5 + 4*7 3*6 + 4*8}}
Output:
{{19, 22},
{43, 50}}
Multiplication of two matrices is done by multiplying corresponding elements from the rows of the
first matrix with the corresponding elements from the columns of the second matrix and then
adding these products.
Note: The number of columns in the first matrix must be equal to the number of rows in the second
matrix.
#include <stdio.h>
21
Programming In C Module 2
int main()
{
int m, n, p, q, i, j, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("\nEnter the number of rows and columns of first matrix:\n");
scanf("%d%d", &m, &n);
printf("\nEnter the number of rows and columns of second matrix:\n");
scanf("%d%d", &p, &q);
//Checking if Matrix Multiplication is possible
if ( n != p )
{
printf("\nMatrices with entered orders can't be multiplied with each other.\n");
printf("\nThe column of first matrix should be equal to row of second.\n");
}
else
{
//Entering elements of first matrix
printf("\nEnter the elements of first matrix:\n");
for ( i = 0 ; i< m ; i++ )
for ( j = 0 ; j < n ; j++ )
scanf("%d", &first[i][j]);
//Entering elements of second matrix
printf("\nEnter the elements of second matrix:\n");
for ( i = 0 ; i < p ; i++ )
for ( j= 0 ; j< q ; j++ )
scanf("%d", &second[i][j]);
22
Programming In C Module 2
#include<stdio.h>
#include<conio.h>void main()
{
int a[2][2] , i, j;
clrscr(); printf("Enter matrix A");
for(i=0;i<2;i++)
{
printf("\n"); for(j=0;j<2;j++)
{
printf("\t%d",a[i][j]);
}
}
printf("\nTranspose");
23
Programming In C Module 2
for(i=0;i<2;i++)
{
printf("\n"); for(j=0;j<2;j++)
{
printf("\t%d",a[j][i]);
}
}
getch();
}
Output:
Enter matrix A1 2
3 4
Transpose
1 3
2 4
24
Programming In C Module 2
Strings
The group of characters, digits, & symbols enclosed within double quotes is called as Strings.
Strings are actually one-dimensional array of characters terminated by a null character '\0'.
E.g. “INDIA” is a string. Each character of string occupies 1 byte of memory. The last
character isalways ‘\0’.
Declaration:
Syntax
char stringname[size];
Initialization:
We can use 2 ways for initializing.
1. By using string constant
E.g. char test[20]= “Hello”;
2. By using initialisation list
E.g. char test[20]={‘H’, ‘e’, ‘l’, ‘l’, ;o’, ‘\0’};
int main()
{
char nickname[20];
printf("Enter your Nick
name:");scanf("%s",
nickname);
printf("Your Nick
name:%s",nickname); return 0;
25 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
Output:
Enter your Nick
name:Negan Your Nick
name:Negan
strcpy() Copies a string from the source to the destination. strcpy(dest, src);
strlen() function
It is used to find the length of a string. The terminating character (‘\0’) is not
counted.Syntax:
temp_variable = strlen (string_name);
#include
<stdio.h>
#include
<string.h> int
main()
{
char str1[20] = "Hello";
printf("Length of string str1: %d",
strlen(str1)); return 0;
}
Output:
Length of string str1: 5
Strlen() vs sizeof()
Strlen() returns you the length of the string stored in
array. sizeof() returns the total allocated size assigned
to the array.
1. strnlen(str,n)
It returns length of the string if it is less than the value specified for maxlen (maximum
length)otherwise it returns maxlen value.
Example:
#include
<stdio.h>
#include
<string.h> int
main()
{
2. strcmp() function
It is used to compare 2
strings temp_varaible=strcmp(string1,string2)
If the first string is greater than the second string a positive number is returned.
If the first string is less than the second string a negative number is returned.
If the first and the second string are equal 0 is returned.
Example:
#include
<stdio.h>
#include
<string.h> int
main()
{
char s1[20] = "Hello";
char s2[20] = "Hello";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
28 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}
int main() {
char str1[100], str2[100];
int i, flag = 0;
return 0;
}
3. Strncmp(str1,str2)
It compares both the string till n characters or in other words it compares first n characters of
boththe strings. #include <stdio.h>
29 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
#include
<string.h> int
main()
{
char s1[20] =
"Hello"; char s2[20]
= "Hello";
if (strncmp(s1, s2,4) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
4. strcpy() function
It copies the source string to the destination
string Syntax
strcpy(destination,source);
#include
<stdio.h>
#include
<string.h> int
main()
{
char s1[30] = "string
1"; char s2[30] = " New
String"; strcpy(s1,s2);
printf("String s1 is: %s",
s1); return 0;
}
//String Copy without Built in function
#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
5. strncpy(s1,s2)
Case1: If length of str2 > n then it just copies first n characters of str2 into
str1. Case2: If length of str2 < n then it copies all the characters of str2 into str1 and
appends several terminator chars(‘\0’) to accumulate the length of str1 to make it n.
#include
<stdio.h>
#include
<string.h> int
main()
{
char s1[10] = "Hello";
char s2[10] =
"welcome";
strncpy(s1,s2,5);
printf("String s1 is: %s",
s1); return 0;
6. strchr(str) / strrchr(str)
It searches string str for character ch.
#include
<stdio.h>
#include
<string.h> int
main()
{
char mystr[30] = "Hai! Hello!
Welcome! ";
printf ("%s", strchr(mystr, 'W'));
return 0;
}
7. strstr(str,search)
It is similar to strchr, except that it searches for string srch_term instead of a single char.
#include<stdio.h>
#include <string.h>
int main()
8. strcat() function
It concatenates a second string to the end of the first
string. #include <stdio.h>
#include strcat(firststring, secondstring);
<string.h> int
main()
{
char s1[10] = "Hello";
char s2[10] = "World";
32 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
#include<stdio.h>
#include<string.h>
void main()
{
9. strlwr() function
It converts all the uppercase characters in that string to lowercase characters.
#include
<stdio.h>
#include
<string.h> int
main()
{
33 by Pooja Shrivastav, Department of MCA
Programming In C Module 2
char mystr[30] = "HAI HELLO WELCOME! ";
printf("%s",
strlwr(mystr)); return 0;
}
10. strupr() function
It converts all the lowercase characters in that string to uppercase characters.
#include
<stdio.h>
strupr(string_name);
#include
<string.h> int
main()
{
char mystr[30] = "Hai Hello
Welcome! "; printf("%s",
strupr(mystr));
return 0;
}
11. strrev() function
It is used to reverse the string.
Syntax strrev(string_name);
#include <stdio.h>
#include <string.h>
int main()
{
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str[100];
int length, i;
printf("Enter a string: ");
scanf("%s", str);
length = strlen(str);
printf("Reversed string: ");
for ( i = length - 1; i >= 0; i--)
{
printf("%c", str[i]);
}
printf("\n");
return 0;
}
}
output
String Arrays
They are used to store multiple strings. 2-D char array is used for string arrays.
Declaration
char arrayname[rowsize][colsize];
E.g.
char s[2][30];
Here, s can store 2 strings of maximum 30 characters each.
Initialization
2 ways
1. Using string constants
char s[2][20]={“Ram”, “Sam”};
Array of Strings
Syntax:
The list of strings are stored by using two dimensional character array is termed as string of arrays.
datatype arrayname[row-size][column-size];
Example:
char a[4][7];
//it can store 4 strings and each string stores maximum 7
charactersInitialization of String of Array:
char A[4][5]={“Ram”,”Raj”,”Ravi”,”Jai”};
A[0] R a m \0
A[1] R a j \0
A[2] R a v i \0
A[3] J a i \0
int main() {
char name[25][50], temp[25];
int n, i, j;
return 0;
}
}
Output:
i) Program to convert upper case string to lower case string without using string
function
#includ
e<stdio.
h>
#includ
e<conio
.h> void
main()
{
char
s1[20],lower[20];
int i=0;
clrscr();
printf("\nEnter the string in upper case:");
gets(s1);
while(s1[i])
{
if(s1[i]>='A' &&
s1[i]<='Z')
lower[i]=s1[i]+32;
else
lower[i]=s1[i];
i++;
Output:
Enter the string in upper case: C PROGRAM
Lower String c program
ii) Converting lower case string to upper case string without using string function
#includ
e<stdio.
h>
#includ
e<conio
.h> void
main()
38
Programming In C Module 2
{
char s1[20],upper[20];
int i=0;
clrscr();
printf("\nEnter the string:");
gets(s1);
while(s1[i])
{
if(s1[i]>='a'
&&
s1[i]<='z')
upper[i]=s
1[i]-32;
else
uppe
r[i]
=s1[
i];
i++;
}
upper[i]='\0'; printf("\nUpper String");
puts(upper);
getch();
}
output:
String C PROGRAM
39
Programming In C Module 2
}
printf("The number of words is %d",count+1);
getch();
}
Output:
40