Cps Module 3
Cps Module 3
MODULE-3
ARRAYS, STRINGS,
STRINGS, SEARCHING AND SORTING
Normally, the programmer makes the use of scalar variable to store and process
single value. However, it is necessary for the programmer to store and process
large volume of data in computer’s memory while developing the solve complex
problems and is possible by making the use of data structure or derived data type
named ARRAY.
“An array can define as a collection of similar type of data stored sequentially one
after the other in memory.”
example: salary[7]
0 1 2 3 4 5 6
salary 20000 10000 12000 10000 9000 8000 60000
A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscript variable or a one dimensional array
Analogy example:
∑ni=0 xi
x[0],x[1],x[3],………..x[n]
Syntax:
type variable-name[size];
example:
• int salary[10];
• float height[10];
• char name[20];
3.4.2 Initialization
Initialization of one-
one-dimensional Arrays
1. At compile time
2. At run time
example:
0 1 2
marks
28 30 26
#include<stdio.h>
void main()
{
output:
Salary=20000 Salary=10000 Salary=40000 Salary=50000
4. Compile time
time initialization may be partial:
#include<stdio.h>
void main()
{
output:
Salary=20000 Salary=10000 Salary=0 Salary=0
that is, the number of initializers may be less than the declare the size.
In such case, the remaining elements are initialized to zero, it the
array type is numeric and NULL if the type is char
example:
char city[9]=”margo”;
0 1 2 3 4 5 6 7 8
city
m a r g a o \0 \0 \0
5. If we have more initializers than the declared size, the compiler will
Produce an error.
error
int sum[100] , i;
output:
Example 2:
Write a program without using
using array structure to store marks of five
students.
#include<stdio.h>
void main()
{
int m1,m2,m3,m4,m5;
printf("Enter the student marks details\n");
scanf("%d%d%d%d%d",&m1.&m2.&m3,&m4,&m5);
printf{"The entered marks are\n");
prinft("m1=%d\t",m1);
prinft("m2=%d\t",m2);
prinft("m3=%d\t",m3);
prinft("m4=%d\t",m4);
prinft("m5=%d\t",m5);
}
output:
Example 3:
Write a program to find largest number and smallest number on n
number using array structure.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,n,max,min;
clrscr();
printf("Enter the value of n \n");
scanf("%d",&n);
printf("Enter the element of an array\n");
for(i=1; i<=n; i++)
scanf("%d",&a[i]);
max=min=a[1];
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\nLargest number is %d:",max);
prinft("\nSmallest number is %d:",min);
getch();
}
Example 4:
Write a program using a single-
single-subscripted variable to evaluate the
following expressions:
expressions:
10
total = ∑i=1 xi 2
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
float x[10],total=0.0;
clrscr();
printf("enter n real number\n");
scanf("%d",&n);
printf("entered the element\n");
for(i=1; i<=n; i++)
{
scanf("%f",&x[i]);
}
for(i=1; i<=n; i++)
{
total = total+x[i]*x[i];
}
printf("...........................\n");
for(i=1; i<=n; i++)
printf("x[%2d] = %5.2f\n",i,x[i]);
printf("...........................\n");
printf("\n total=%.2f\n",total);
printf("...........................\n");
getch();
}
OUTPOT
There could be situations where a table of values will have to be stored. Consider
the following data table, which shows the values of sales of three items by four
sales girls.
Name Item1 Item2 Item3
Salesgirls 1 310 275 365
Salesgirls 2 210 190 325
Salesgirls 3 405 235 240
Salesgirls 4 260 300 380
we can think of this table as a matrix consisting of four rows and four columns.
Each row represents the values of sales by a particular salesgirl and each column
represents the values of sales of a particular item.
type array_name[row_size][column_size];
Memory Layout:
Column
0 1 2 3
0 100 120 200 340
row
1 230 123 230 400
2 333 234 345 200
Two dimensional arrays may be initialized by specifying bracketed values for each
row. following is an array with 3 rows and each row has 4 columns.
int a[3][4]={
{0,1,2,3},
{4,5,6,7},
{8,9,10,11}
};
or
or
or
int a[ ][4]={
{0,1,2,3},
{4,5,6,7},
{8,9,10,11}
};
Note:
if the values are missing in an initializer, they are automatically set to zero.
int table[2][3] = {
{1,1},
{2}
}
Memory storage:
1 1 0
2 0 0
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3] = { {0,1,2},
{3,4,5},
{6,7,8}
};
output:
example:
Write a c program to add two x two matrix elements
2 2 2 2 4 4
a= b= c=
2 2 2 2 4 4
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],b[2][2],c[2][2];
int row,col;
clrscr();
printf("Enter the array element of A matrix \n");
for(row=0; row<2; row++)
{
for(col=0; col<2; col++)
{
scanf("%d",&a[row][col]);
}
}
printf("Enter the array element of B matrix \n");
for(row=0; row<2; row++)
{
for(col=0; col<2; col++)
{
scanf("%d",&b[row][col]);
}
}
for(row=0; row<2; row++)
{
for(col=0; col<2; col++)
{
c[row][col]=a[row][col]+b[row][col];
}
}
printf("THE ADDITION OF TWO MATRIX ARE \n");
for(row=0; row<2; row++)
{
for(col=0; col<2; col++)
{
printf("%d\t",c[row][col]);
}
printf("\n");
}
getch();
}
output:
e f axe+bxg axf+bxh
A= a b B= C= cxe+dxg cxf+dxh
c d g h
#include <stdio.h>
int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
#include<stdio.h>
#include<conio.h>
void main()
{
int value[4][3],girl_total[4],item_total[3];
int i,j,grand_total;
clrscr();
printf("enter value, one at a time, row-wise\n\n");
for(i=0; i<4; i++)
{
girl_total[i]=0;
for(j=0; j<3; j++)
{
scanf("%d",&value[i][j]);
girl_total[i]=girl_total[i]+value[i][j];
}
}
for(j=0; j<3; j++)
{
item_total[j]=0;
for(i=0; i<4; i++)
{
item_total[j]=item_total[j]+value[i][j];
}
}
grand_total=0;
for(i=0; i<4; i++)
grand_total=grand_total + girl_total[i];
3.6 MULTI-
MULTI-DIMENSIONAL ARRAY
is known as multi-dimensional array.
Multi Dimensional arrays are also known as arrays of arrays or matrix.
data_type array_name[SIZE_1][SIZE_2][SIZE_3]……[SIZE_N]
EXAMPLE;
int x[2][3][4] =
{
{ {0,1,2,3},
{4,5,6,7},
{8,9,10,11} },
{ {12,13,14,15},
{16,17,18,19},
{20,21,22,23} }
};
example:
int survey[3][5][12];
Month 1 2 12
………..
city
1 …………
Year1 2 …………
3 …………
4 ………….
5 ………..
Month 1 2 12
………..
city
1 …………
Year2 2 …………
3 …………
4 ………….
5 ………..
The array survey may represent a survey data of rainfall during the last three years
from January to December in five cities.
If the first index denotes year, the second city and the third month, then the
element survey[2][3][10] denotes the rainfall in the month of October during the
second year in city-3.
NOTE: ANSI C does not specify any limit for array dimension. However, most
compilers permit seven to ten dimensions. Some allow even more.
#include<stdio.h>
#include<conio.h>
void main()
{
// initializing the 3-dimensional array
int x[2][3][2] =
{
{ {0,1}, {2,3}, {4,5} },
{ {6,7}, {8,9}, {10,11} }
};
int i,j,k;
clrscr();
// output each element's value
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 3; ++j)
{
for (k = 0; k < 2; ++k)
{
printf( "Element at x[%d][%d][%d]=%d\n",i,j,k,x[i][j][k]);
}
}
getch();
}
Output:
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11
An array created at compile time by specifying size in the source code has a fixed
size and cannot be modified at run time. The process of allocating memory at
compile time is known as static memory allocation.
allocation
example:
printf(“ Sapthagiri College of Engineering”);
COMMON OPERATIONS
OPERATIONS PERFORMED ON CHARACTER STRINGS:
STRINGS
Example:
char city[20];
char name[30];
char city[5]=”INDIA”;
char city[5]={‘I’,’N’,’D’,’I’,’A’,’\0’};
• C permits to declare the size much larger than the string size in the
initializer.
char str[10] = “good”
g o o d \0 \0 \0 \0 \0 \0
int main () {
output:
Greeting message: Hello
Using scanf Function: The familiar input function scanf can be used with %s
format specification to read in a string of characters.
example:
char address[30];
scanf(“%s”,address);
Note 1:
1 Problem with the scanf function is that it terminates its input on the first
white space it finds. A white space includes blanks, tabs, carriage returns, form
feeds, and new lines. Therefore, if the following line of text is typed in at the
terminal,
Bangalore Karnataka
then only the string “Bangalore” will be read into the array address, since the
blank space after the word Bangalore will terminate the reading of string.
The scanf function automatically terminates the string that is read with a null
character and therefore the character array should be large enough to hold the
input string plus the null character.
Note 2: that unlike previous scanf calls, in the case of character arrays, the
ampersand (&) is not required before the variable name.
Note 3: we can also specify the field width using the form %ws in the scanf
function
Example:
char name[10];
scanf(“%5s”,name);
Program Example:
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
output:
Enter name: Dennis Ritchie
Your name is Dennis.
Even though Dennis Ritchie was entered in the above program, only "Ritchie"
was stored in the name string. It's because there was a space after Ritche.
READING A LINE OF
OF TEXT
C support to read a line of input from the keyboard and display the same on the
screen.
example:
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%[^\n]", name);
printf("Your name is %s.", name);
return 0;
}
output:
Enter name: Dennis Ritchie
Your name is Dennis Ritchie.
GETCHAR( )
To read a single character from the terminal, using the function getchar. We can
use this function repeatedly to read successive single characters form the input
and place them into a character array.
syntax :
char ch;
ch = getchar();
Write a program to read a line of text containing a series of words from the
terminal.
#include<stdio.h>
#include<conio.h>
void main()
{
char line[81], ch;
int i=0;
clrscr();
printf("Enter text, press <return> at end \n");
do
{
ch = getchar();
line[i]=ch;
i++;
}
while(ch!='\n');
i=i-1;
line[i]='\0';
printf("\n%s\n",line);
getch();
}
USING PUTCHAR:
PUTCHAR:
example:
char ch=’A’;
putchar(ch);
(or)
alternate way to print
printf(“%c”,ch);
example 2:
#include<stdio.h>
void main()
{
char name[6]=”INDIA”;
int i;
for(i=0; i<5; i++)
putchar(name[i]);
purchar(‘\n’);
}
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
OUTPUT:
Write a program to copy one string into another and count the number of
characters copied.
copied.
#include<stdio.h>
void main()
{
char string1[80],string2[80];
int i;
printf("Enter the string\n");
scanf("%s",string2);
for(i=0; string2[i]!='\0'; i++)
string1[i]=string2[i];
string1[i]='\0';
printf("\n");
printf("copied string is:");
printf("%s\n",string1);
printf("Number of characters = %d\n",i);
}
output:
We have used extensively the printf function with %s format to print strings to
the screen. The format %s can be used to display an array of characters that is
terminated by the null.
for example:
char name[10];
printf(“Enter the string\n”);
scanf(“%s”,name);
printf(“%s”,name);
S U D A R S A N \0 \0
printf(“%10.3s”,name);
S U D
example:
#include <stdio.h>
int main()
{
char s = 'm';
char t = 'z' - 'y';
printf("%d\n", s);
printf("%c\n", s);
printf("%d\n", (s+1));
printf("%c\n", (s+1));
printf("%d\n", (s-1));
printf("%c\n", (s-1));
printf("%d\n", t);
return 0;
}
output:
109
m
110
n
108
l
1
Write a program which would print the alphabet set a to z and A to Z in decimal
and character form.
form.
#include<stdio.h>
#include<conio.h>
void main()
{
char c;
clrscr();
printf("--------------------------\n\n");
for(c=65; c<=122; c=c+1)
{
if(c>90 && c<97)
{
continue;
}
printf("|%4d-->%c ",c,c);
}
printf("|\n");
printf("----------------------------\n\n");
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
char string1[5],string2[6];
int i;
clrscr();
printf("\nEnter the string1 value: ");
gets(string1);
i=0;
while(string1[i]==string2[i] && string1[i]!='\0' && string2[i]!='\0')
{
i=i+1;
}
if(string1[i] =='\0' && string2[i]=='\0')
printf("strings are equal\n");
else
printf("string are not equal");
getch();
The C library supports a large number of string handling functions that can be
used to carry out many of the string manipulations . Following are the moost
commonly used sting handling functions.
Function Action
strcat() Concatenates two strings
strcmp() Compares two strings
strcpy() Copies one string over another
strlen() Finds th length of a string
strcat() Function:
The strcat function joins two strings together.
syntax:
strcat(string1, string2);
where string1 and string2 are character arrays. When the functions strcat is
executed, string2 is appended to string1. it does so by removing the null character
at the end of string1 and placing string2 from there. The string at string2 remains
unchanged.
example:
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
strcat(a,b);
return 0;
strcmp() Function:
Function:
syntax:
strcmp(s1,s2)
output
nter 1st string: sudha
Enter 2nd string:sudha
Strings are equal
strcpy() Function:
syntax:
strcpy(s1,s2);
example:
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
output:
Value of second string is: javatpoint
strlen() Function:
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]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
output:
Length of string is: 10
strncpy() function:
The strncpy() function is similar to strcpy() function, except that at most n bytes
of src are copied. If there is no NULL character among the first n character of src,
the string placed in dest will not be NULL-terminated. If the length of src is less
than n, strncpy() writes additional NULL character to dest to ensure that a total of
n character are written.
Syntax:
return 0;
}
output:
Copied string: geeksforgeeks
strncat() Function:
this is another concatenation function that takes three parameters as shown
below:
strcncat(s1,s2,n);
#include <stdio.h>
#include <string.h>
int main () {
char src[50], dest[50];
return(0);
}
output:
Final destination string : |This is destinationThis|
strstr( ) Function:
strstr(s1,s2);
The function strstr searches the string s1 to see whether the string s2 is contained
in s1. If yes, the function returns the position of the first occurrence of the sub-
string. otherwise, it return a NULL POINTER.
#include <string.h>
#include <stdio.h>
int main()
{
// Take any two strings
char s1[] = "GeeksforGeeks";
char s2[] = "for";
char * p;
return 0;
}
output:
String found
First occurrence of string 'for' in 'GeeksforGeeks' is 'forGeeks'
1. Linear Search
2. Binary Search
Linear Search:
/*
* C program to input N numbers and store them in an array.
* Do a linear search for a given key and report success
* or failure.
*/
#include <stdio.h>
void main()
{ int num;
output:
Enter the number of elements 6
Enter the elements one by one
4
6
1
2
5
3
Binary search is a fast search algorithm with run-time complexity of O(log n).
This search algorithm works on the principle of divide and conquer. For this
algorithm to work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of
the collection. If a match occurs, then the index of item is returned. If the middle
item is greater than the item, then the item is searched in the sub-array to the left
of the middle item.
Otherwise, the item is searched for in the sub-array to the right of the middle
item. this process continues on the sub-array as well until the size of the subarray
reduces to zero.
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, arr[100],flag=0;
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter integer numbers in ascending order\n");
low = 0;
high = n - 1;
if (key == arr[mid])
{
flag=1;
break;
}
A 50 40 30 20 10
example:
#include<stdio.h>
int main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the array elements: ");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
return 0;
}
Output
SELECTION SORT:
A Selection Sort is a Sorting algorithm which finds the smallest element in the
array and swaps with the first element then with the second element and
continues until the entire array is sorted..
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,temp,a[20];
clrscr();
printf("Enter number of element in an array\n");
scanf("%d",&n);
printf("Enter the element in an array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);