0% found this document useful (0 votes)
61 views

Cps Module 3

The document discusses arrays, strings, searching, and sorting in C programming. It begins by defining an array as a collection of similar data stored sequentially in memory. One-dimensional arrays can be declared with syntax like type variable_name[size]; and initialized at compile-time with values like type array_name[size] = {list of values}. Two-dimensional arrays allow storing tables of data and are declared as type array_name[row_size][column_size]. Examples are provided to demonstrate initializing, accessing, and calculating with one-dimensional arrays.

Uploaded by

Ashray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Cps Module 3

The document discusses arrays, strings, searching, and sorting in C programming. It begins by defining an array as a collection of similar data stored sequentially in memory. One-dimensional arrays can be declared with syntax like type variable_name[size]; and initialized at compile-time with values like type array_name[size] = {list of values}. Two-dimensional arrays allow storing tables of data and are declared as type array_name[row_size][column_size]. Examples are provided to demonstrate initializing, accessing, and calculating with one-dimensional arrays.

Uploaded by

Ashray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

MODULE-3

ARRAYS, STRINGS,
STRINGS, SEARCHING AND SORTING

3.1 INTRODUCTION TO ARRAYS

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.

3.2 DEFINITION OF AN ARRAY

“An array can define as a collection of similar type of data stored sequentially one
after the other in memory.”

some example where the concept of an array can be used:


• List of temperature recorded every hours in a day, or a month, or a year.
• List of employees in an organization.
• List of products and their cost sold by a store.
• Test marks
• Telephone numbers etc.

An array is a sequenced collection of related data items that share a common


name. For instance, we can use an array name salary to represent a set of salaries
of a group of employees in an organization.

example: salary[7]
0 1 2 3 4 5 6
salary 20000 10000 12000 10000 9000 8000 60000

3.3 TYPES OF ARRAYS

The arrays can be classified according to the volume of data to be stored in


computer’s memory.

1. One dimensional Array


2. Two dimensional Array
3. Mult-dimensional Array

Dept. of ISE, Sapthagiri College of Engg. 1


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

3.4 ONE DIMENSIONAL ARRAY

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

in C single –subscripted variable xi can be expressed as

x[0],x[1],x[3],………..x[n]

3.4.1 Declaration of one-


one-dimensional arrays in C

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

After an array is declared, its elements must be initialized. otherwise,


they will contain “garbage”. An array can be initialized at either of the
following stages:

1. At compile time
2. At run time

Compile Time Initialization


Initialization

1. the general form of initialization of array is:

type array-name[size] = { list of values };

Dept. of ISE, Sapthagiri College of Engg. 2


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

example:

int marks[3]= {28 , 30,26};

0 1 2
marks
28 30 26

Write a program to initialize the one dimensional


dimensional array by using
Compile time Initialization.

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

long int salary[4]={20000,10000,40000,50000};


int i ;
for(i=0; i<4; i++)
{
printf(“Salary=%ld\t”,salary[i]);
}
}

output:
Salary=20000 Salary=10000 Salary=40000 Salary=50000

2. The size may be omitted

int counter[ ] = {1,2,3,4,5};

now compiler will take size of array is five.


five
0 1 2 3 4
counter
1 2 3 4 5

Dept. of ISE, Sapthagiri College of Engg. 3


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

3. Character arrays may be initialized in a similar manner

char name[ ]={ ‘J’,’O’,’H’,’N’,’\0’};


declares the name to be an array of five characters, initialized with the
string ‘JHON’ ending with the null character.

Alternatively, we can assign the string literal directly as under:

char name[] = “JHON”;

4. Compile time
time initialization may be partial:
#include<stdio.h>
void main()
{

long int salary[4]={20000,10000};


int i ;
for(i=0; i<4; i++)
{
printf(“Salary=%ld\t”,salary[i]);
}
}

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

Dept. of ISE, Sapthagiri College of Engg. 4


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

5. If we have more initializers than the declared size, the compiler will
Produce an error.
error

int number[1] = {23,22}

Run Time Initialization

An array can be explicitly initialized at run time. This approach is


usually applied for initializing large arrays.

for example. Consider the following segment of a C program


write a program to store
#include<stdio.h>
void main()
{

int sum[100] , i;

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


{
if ( i < 50 )
{
sum[i]=0;
}
else
{
sum[i]=1;
}
}

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


{
printf(“sum[%d] =%d\t”,i,sum[i]);
}
}

Dept. of ISE, Sapthagiri College of Engg. 5


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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:

Dept. of ISE, Sapthagiri College of Engg. 6


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

Above program using Array Structure


#include<stdio.h>
void main()
{
int m[5],i;
printf("Enter the student marks details\n");
for(i=1; i<=5; i++)
scanf("%d",&m[i]);
printf("The entered marks are\n");
for(i=1; i<=5; i++)
printf("MARKS[%d]=%d\t",i,m[i]);

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];

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


{

Dept. of ISE, Sapthagiri College of Engg. 7


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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;

Dept. of ISE, Sapthagiri College of Engg. 8


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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

Dept. of ISE, Sapthagiri College of Engg. 9


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

3.5 TWO DIMENSIONAL ARRARYS

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.

C allows us to define such tables of items by using two-dimensional arrays.


two-dimensional arrays are declared as follows:

type array_name[row_size][column_size];

example: int item[4][4];

Memory Layout:
Column
0 1 2 3
0 100 120 200 340
row
1 230 123 230 400
2 333 234 345 200

Compile Time Initialization

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

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Dept. of ISE, Sapthagiri College of Engg. 10


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

or

int a[3][4] = { {0,1,2,3},{4,5,6,7},{8,9,10,11}};

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

example: Write a C program to store 0 to 9 using two dimensional array


structure like a[3][3] .

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3] = { {0,1,2},
{3,4,5},
{6,7,8}
};

Dept. of ISE, Sapthagiri College of Engg. 11


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

printf("Array elements are \n");


for(row=0; row<3; row++)
{
for(col=0; col<3; col++)
{
printf("%d\t",a[row][col]);
}
printf("\n");
}
}

output:

Run Time Initialization


An array can be explicitly initialized at run time. This approach is usually applied
for initializing large arrays.

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++)

Dept. of ISE, Sapthagiri College of Engg. 12


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

{
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:

Dept. of ISE, Sapthagiri College of Engg. 13


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

Program to Multiply Two Matrices


To multiply two matrices, the number of columns of first matrix should be equal
to the number of rows to second matrix. This program displays the error until the
number of columns of first matrix is equal to the number of rows of second
matrix.

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;

printf("Enter rows and column for first matrix: ");


scanf("%d %d", &r1, &c1);

printf("Enter rows and column for second matrix: ");


scanf("%d %d",&r2, &c2);

// Column of first matrix should be equal to column of second matrix and


while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}

// Storing elements of first matrix.


printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}

Dept. of ISE, Sapthagiri College of Engg. 14


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

// Storing elements of second matrix.


printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}

// Initializing all elements of result matrix to 0


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}

// Multiplying matrices a and b and


// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}

// Displaying the result


printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return 0;
}
ooutput:

Enter rows and column for first matrix: 3


2
Enter rows and column for second matrix: 3
2

Dept. of ISE, Sapthagiri College of Engg. 15


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

Error! column of first matrix not equal to row of second.

EXAMPLE 3: Write a program using a two dimensional array to compute and


print the following information from the table of data discussed above table.
1. Total value of sales by each girl
2. Total value of each item sold
3. Grand total of sales of all items by all girls.

Dept. of ISE, Sapthagiri College of Engg. 16


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

#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];

printf("\n GIRL TOTAL\n\n");


for(i=0; i<4; i++)
printf("Salesgirl[%d] = %d\n",i+1,girl_total[i]);
printf("\n ITEM TOTAL\n\n");
for(j=0; j<3; j++)
printf("Item[%d] = %d\n",j+1,item_total[j]);

printf("\nGrand Total = %d\n", grand_total);


getch();
}

Dept. of ISE, Sapthagiri College of Engg. 17


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

An array having three or more subscript or dimensions

3.6 MULTI-
MULTI-DIMENSIONAL ARRAY
is known as multi-dimensional array.
Multi Dimensional arrays are also known as arrays of arrays or matrix.

The general form of multi-dimensional array is:

data_type array_name[SIZE_1][SIZE_2][SIZE_3]……[SIZE_N]

Dept. of ISE, Sapthagiri College of Engg. 18


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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];

survey is a three –dimensional array declared to contain 180 integers type


elements.

Month 1 2 12
………..
city
1 …………
Year1 2 …………
3 …………
4 ………….
5 ………..

Dept. of ISE, Sapthagiri College of Engg. 19


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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]);

Dept. of ISE, Sapthagiri College of Engg. 20


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

}
}
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

3.7 DYNAMIC ARRAYS

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

In C it is possible to allocate memory to arrays at run time. This feature is known


as dynamic memory allocation
allocation and the arrays created at run time are called
dynamic arrays.
Dynamic arrays are created using what are known as pointer variable and
memory management functions malloc, calloc and realloc. realloc these functions are
included in the header file <stdlib.h>.
<stdlib.h>. the concept of dynamic arrays is used in
creating and manipulating data structures such as linked lists, stacks and queues.

3.8 CHARACTER ARRAYS AND STRINGS

A string is a sequence of characters that is treated as a single data item.


Any group of characters defines between double quotation marks is a string
constant.

“Sapthagiri College of Engineering”

Dept. of ISE, Sapthagiri College of Engg. 21


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

example:
printf(“ Sapthagiri College of Engineering”);

output: Sapthagiri College of Engineering

COMMON OPERATIONS
OPERATIONS PERFORMED ON CHARACTER STRINGS:
STRINGS

1. Reading and Writing strings.


2. Combining Strings together.
3. Copying one string to another.
4. Comparing strings for equality.
5. Extracting a portion of a string.

DECLARING AND INITIALIZING STRING VARIABLES

C does not support strings as a data type. However, it allows us to represent


strings as character arrays.

DECLARING AN CHARACTER ARRAYS


Syntax:
char string_name[size];

the size determines the number of characters in the string_name.

Example:
char city[20];
char name[30];

COMPILE TIME INITIALIZATION OF CHARACTER ARRAY

• Character array may be initialized when they are declared. C permits a


character array to be initialized in either of the following two forms:

char city[5]=”INDIA”;
char city[5]={‘I’,’N’,’D’,’I’,’A’,’\0’};

• C also permits us to initialize a character array without specifying the


number of elements.
char string[ ] = {‘g’,’o’,’o’,’d’,’\0’};

Dept. of ISE, Sapthagiri College of Engg. 22


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

• 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

• the following declaration is Illegal.


char str2[3] =”good”; //compile time error
• Note that we cannot separate the initialization from declaration.
char str3[5];
str3=”good”; //illegal inialization
Example:
#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}

output:
Greeting message: Hello

READING STRINGS FROM TERMINAL


TERMINAL

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.

Dept. of ISE, Sapthagiri College of Engg. 23


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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.

The address array is created in the memory as shown below


B a n g a l o r e \0 ? ? ? ?

note that the unused locations are filled with garbage.

Note 3: we can also specify the field width using the form %ws in the scanf
function

Example:
char name[10];
scanf(“%5s”,name);

Input string RAM will be stored as:


R A M \0 ? ? ? ? ? ? ?

Input string KRISHNA will be stored as:


K R I S H \0 ? ? ? ? ?

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.

Dept. of ISE, Sapthagiri College of Engg. 24


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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.

USING getchar and gets FUNCTION:


FUNCTION

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");

Dept. of ISE, Sapthagiri College of Engg. 25


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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:

C supports another character handling function putchar to output the values of


character variables.

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’);
}

Dept. of ISE, Sapthagiri College of Engg. 26


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

GETS AND PUTS FUNCTION:


You can use gets() function to read a line of string. And, you can use puts() to
display the string.

#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); // read string
printf("Name: ");
puts(name); // display string
return 0;
}

OUTPUT:

Enter name: Tom Hanks


Name: Tom Hanks

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:

Dept. of ISE, Sapthagiri College of Engg. 27


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

WRITING STRING TO SCREEN

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

3.9 ARITHMETIC OPERATIONS ON CHARACTERS

C allows us to manipulate characters the same way we do with numbers

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;
}

Dept. of ISE, Sapthagiri College of Engg. 28


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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();
}

Dept. of ISE, Sapthagiri College of Engg. 29


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

3.10 COMPARISON OF TWO STRINGS WITHOUT USING BUILT IN


FUNCTION

#include<stdio.h>
#include<conio.h>

void main()
{

char string1[5],string2[6];
int i;
clrscr();
printf("\nEnter the string1 value: ");
gets(string1);

printf(" \nEnter the String2 value: ");


gets(string2);

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();

Dept. of ISE, Sapthagiri College of Engg. 30


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

3.11 STRING HANDLING FUNCTIONS

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];

printf("Enter the first string\n");


gets(a);

printf("Enter the second string\n");


gets(b);

strcat(a,b);

printf("String obtained on concatenation is %s\n",a);

Dept. of ISE, Sapthagiri College of Engg. 31


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

return 0;

strcmp() Function:
Function:

syntax:
strcmp(s1,s2)

Compare two strings lexicographically. Return a negative value if s1<s2; 0 if s1


and s2 are equal or identical; and a positive value if s1>s2.
#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
nter 1st string: sudha
Enter 2nd string:sudha
Strings are equal

Dept. of ISE, Sapthagiri College of Engg. 32


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

strcpy() Function:

syntax:
strcpy(s1,s2);

copy string s2 to string s1

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.

Dept. of ISE, Sapthagiri College of Engg. 33


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

Syntax:

char *strncpy( char *dest, const char *src, size_t n )

Parameters: This function accepts two parameters as mentioned above and


described below:

• src: The string which will be copied.


• dest: Pointer to the destination array where the content is to be copied.
• n: The first n character copied from src to dest.
#include <stdio.h>
#include <string.h>
int main()
{
char src[] = "geeksforgeeks";

// The destination string size is 14.


char dest[14];

// copying n bytes of src into dest.


strncpy(dest, src, 14);
printf("Copied string: %s\n", dest);

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];

strcpy(src, "This is source");


strcpy(dest, "This is destination");

strncat(dest, src, 4);

printf("Final destination string : |%s|", dest);

Dept. of ISE, Sapthagiri College of Engg. 34


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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;

// Find first occurence of s2 in s1


p = strstr(s1, s2);

// Prints the result


if (p) {
printf("String found\n");
printf("First occurrence of string '%s' in '%s' is '%s'", s2, s1, p);
} else
printf("String not found\n");

return 0;
}

output:
String found
First occurrence of string 'for' in 'GeeksforGeeks' is 'forGeeks'

Dept. of ISE, Sapthagiri College of Engg. 35


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

3.12 SEARCHING TECHNIQUES


TECHNIQUES

More often we will be working on large amount of data. It may be necessary to


determine whether a particular item is present in that large amount of data. The
process of finding a particular element in the large amount of data is called as
searching.

There are 2 types of Searching techniques

1. Linear Search
2. Binary Search

Linear Search:

A linear search also called as sequential search is a simple searching technique. In


this technique we search for a given specific element called as key element in the
large list of data in sequential order (one after another) from first element to last
element. If the key element is present in the list of data then search is successful.
Otherwise, search is unsuccessful.

/*
* 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;

int i, keynum, found = 0;


int array[30];

printf("Enter the number of elements ");


scanf("%d", &num);

printf("Enter the elements one by one \n");


for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}

printf("Enter the element to be searched ");


scanf("%d", &keynum);

Dept. of ISE, Sapthagiri College of Engg. 36


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

/* Linear search begins */


for (i = 0; i < num ; i++)
{
if (keynum == array[i] )
{
found = 1;
break;
}
}
if (found == 1)
printf("Element is present in the array at position %d",i+1);
else
printf("Element is not present in the array\n");
}

output:
Enter the number of elements 6
Enter the elements one by one
4
6
1
2
5
3

Enter the element to be searched 6

Element is present in the array at position 2

Binary Search Technique:

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.

Advantage: very efficient searching technique.


Disadvantage: Array elements should be in sorted.

Dept. of ISE, Sapthagiri College of Engg. 37


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

#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");

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


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

printf("Enter value to Search\n");


scanf("%d", &key);

low = 0;
high = n - 1;

while (low <= high)


{
mid = (low+high)/2;

if (key == arr[mid])
{
flag=1;
break;
}

if (key > arr[mid] )


low = mid + 1;

Dept. of ISE, Sapthagiri College of Engg. 38


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

if (key < arr[mid])


high = mid - 1;
}
if ( flag==1)
printf("%d found at location %d.\n", key, mid+1);
else
printf(" %d is Not found! \n", key);
return 0;
}
Output:

Enter number of elements


5
Enter integer numbers in ascending order
14
15
16
17
18
Enter value to Search
16
16 found at location 3.

3.13 SORTING TECHNIQUES

The process of arranging the elements in the ascending order or


descending order is the sorting.

BUBBLE SORT (SINK SORT):


SORT):

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-


based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order. This algorithm is not suitable for
large data sets as it average and worst case complexity are of O(n2) where n is the
number of items.
example:

A 50 40 30 20 10

1ST PASS 2ND PASS 3RD PASS 4TH PASS


50 40 40 40 40 30 30 30 20 20 10
40 50 30 30 30 40 20 20 30 10 20
30 30 50 20 20 20 40 10 10 30 30
20 20 20 50 10 10 10 40 40 40 40
10 10 10 10 50 50 50 50 50 50 50

Dept. of ISE, Sapthagiri College of Engg. 39


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

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;
}

printf("\nArray after sorting: ");


for(i=0;i<n;++i)
printf("%d ",a[i]);

return 0;
}

Output

Enter the size of array: 4


Enter the array elements: 3 7 9 2

Array after sorting: 2 3 7 9

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..

Dept. of ISE, Sapthagiri College of Engg. 40


ARRAYS, STRINGS,SEARCHING AND SORTING MODULE 3 Sudarsanan D

#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]);

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


{
for(j=i+1; j<n; j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("After sorting is:");
for(i=0; i<n; i++)
printf("%d\t",a[i]);
getch();
}

Dept. of ISE, Sapthagiri College of Engg. 41

You might also like