0% found this document useful (0 votes)
32 views30 pages

Module3 18cps23 SKC

The document discusses one-dimensional and two-dimensional arrays in C programming. It describes how to declare, initialize, read from, and write to single dimensional arrays. Examples of C programs that work with single dimensional arrays are provided.

Uploaded by

Sanjeet Shetty
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)
32 views30 pages

Module3 18cps23 SKC

The document discusses one-dimensional and two-dimensional arrays in C programming. It describes how to declare, initialize, read from, and write to single dimensional arrays. Examples of C programs that work with single dimensional arrays are provided.

Uploaded by

Sanjeet Shetty
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/ 30

SUB CODE: 18CPS13/23

MODULE-3
 ARRAYS
 ONE-DIMENSIONAL ARRAY
 TWO-DIMENSIONAL ARRAY
 CHARACTER ARRAY AND STRINGS
 SEARCHING ALGORITHMS
o LINEAR SEARCH
o BINARY SEARCH
 SORTING ALGORITHMS
o BUBBLE SORT
o SELECTION SORT
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

MODULE-III
ARRAYS AND STRINGS
3.1 Arrays
 An Array is a special and powerful data structure and it is used to store, process and print large
amounts of data.
 “An array is a collection of similar type of items (elements) stored sequentially
(continuously) one after the other in memory”.

Ex: 1. int A[5] ; // Array of 5 Integers

A[0] 10
A[1] 20
A[2] 30
A[3] 40
A[4] 50

 The Elements in the Array A can be accessed using the common name A, but with different
index.
 The Element ‘10’ is called 0th Element and it can be accessed using the Subscript 0 (called Index
‘0’) along with name of the array ‘A’.

2. char B[5]; //Array of 5 Characters

B[0] ‘A’
B[1] ‘r’
B[2] ‘r’
B[3] ‘a’
B[4] ‘y’
3. float C[5]; //Array of 5 floats

C[0] 12.56
C[1] 234.20
C[2] 215.60
C[3] 322.50
C[4] 123.45

 An ‘Index’ is also called as Subscript ([ ]). It is used to indicate the position of an element in
the Array.
 An array is a fixed-size sequenced collection of elements of the same data type. It is simply a
grouping of like-typed data.
Basic Properties of the Arrays
1. All the elements in an array should be of the same data type.

Santosh K C, CSE Dept. BIET, DVG 2


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
2. The elements are stored continuously in the memory. (For example, in the array char B[5] , if the
first address is 1000 then the data is stored contiguously in the addresses 1000, 1001, 1002 and
so on).
3. The Subscript (index) of first item is always zero.
4. Each element of an array is accessed using the name of the Array, but with different subscript.
5. The Index of the Array is always an Integer number can’t be float.
Ex: a [1] or a [5].
a [1.5] is an Error.

3.2 Classification of Arrays


1. Single Dimensional Array
2. Multi-Dimensional Array

3.2.1 Single Dimensional Array


Definition:
Single dimensional array (One-dimensional array) is a linear list consisting of related
data items of same data type and in the memory, all the data items are stored contiguously
in memory locations one after the other.
Or
An array with one index is called as Single dimensional array (One-dimensional array)

Declaration of Single dimensional arrays


 As we declare the variables before they are used in a program, an array must also be declared
and defined before it is used using following syntax.
 Syntax
data_type array_name[size];

Where,
data_type: data type can be int, float, char etc.
array_name: name of the array which is a valid C variable.
size: it is the number of elements in the array.
Complete declaration ends with Semicolon.
Ex: int Marks[5];
Declares Marks as an array consisting of 5 elements of integer data type.
Ex: int Marks[5];

1000 35 Marks[0]
data type array_name 1002 45 Marks[1]
1004 65 Marks[2]
1006 55 Marks[3]
char name[5]; 1008 75 Marks[4]

Memory location Array name

 5 memory locations are reserved. sizeof(int) is 2 bytes, 2*5=10 bytes are reserved.
 5 memory locations are reserved. sizeof(char) is 1 bytes 1*5=5 bytes are reserved.
Santosh K C, CSE Dept. BIET, DVG 3
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Initialization of Single dimensional arrays
 Once an array is declared it must be initialized with some values using Initialization.
“Process of assigning the values to the individual elements of an array is called as
Initialization of an array”.

Syntax: data_type array_name[size]={v1,v2,-----,vn};

data_type: it can be int, float, char etc.


array_name: it is the name of the array.
size: it is the number of elements in the array.
v1,v2,-----,vn are the values and should be enclosed within ‘{‘ and ‘}’ separated by commas.

Ex: 1. int a[5] = {10, 20, 30, 40, 50};


 The compiler allocates 5 memory locations and these locations are initialized with the integer
values in the order specified.

a[0] 10
a[1] 20
a[2] 30
a[3]
40
a[4]
50
2. int a[5] = {10, 20};

10 20 0 0 0
a[0] a[1] a[2] a[3] a[4]
 When the numbers of initial values are lesser than declared array size then those many elements
will be initialized and other memory locations are automatically initialized to 0’s, in case of
numeric arrays.
 It is ‘partial array initialization’.

3. int a[ ] = {10, 20, 30, 40, 50};

Size not specified


 If we have not specified the size then the compiler will calculate the size of the array based on
the number of initial values.
4. char a[6] = {‘A’, ‘r’, ‘r’, ‘a’, ‘y’, ‘\0’};

A r r a y \0
a[0] a[1] a[2] a[3] a[4] a[5]

5. char b[ ] = “COMPUTER”; //String Initialization


C O M P U T E R \0

Null character at the end of the string

Santosh K C, CSE Dept. BIET, DVG 4


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Reading/Writing Single dimensional arrays
 We can easily read and write the array elements using for loop.
 Reading the elements of an array from the keyboard can be done using for loop and
“scanf( )” function.
 Writing/Displaying the elements of an array to the screen can be done using for loop and
“printf( )” function.

 C code or C instruction to read ‘n’ elements of an array is shown below:


for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
 C code or C instruction to display/write ‘n’ elements of an array is shown below:

for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}

Example C programs of Single dimensional array


1. Write a C Program to read n items from keyboard and display them on the monitor.
#include<stdio.h>
void main( )
{
int n,a[10],i;
printf(“Enter the size of array:”); Output:
scanf(“%d”,&n); Enter the size of array:
printf(“Enter the array elements:\n”); 5
for(i=0;i<n;i++) Enter the array elements:
{ 12345
scanf(“%d”,&a[i]); Entered elements are:
} 1
printf(“\nEntered elements are:\n”); 2
for(i=0;i<n;i++) 3
{ 4
printf(“%d\n”,a[i]); 5
}
}

2. Write a C program to find the sum and average of n array elements.


#include<stdio.h>
void main( )
{
int n,a[10],i,sum=0;
float avg=0;
printf(“Enter the number of elements in the array:”);
scanf(“%d”,&n);
printf(“Enter the array elements:\n”);

Santosh K C, CSE Dept. BIET, DVG 5


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
for(i=0;i<n;i++)
{ Output:
scanf(“%d”,&a[i]); Enter the size of array:
} 3
for(i=0;i<n;i++) Enter the array elements:
{ 12
sum=sum+a[i]; 34
} 50
avg=sum/n; Sum= 96
printf(“Sum=%d\n Average=%f”,sum,avg); Average =32
}
3. Write a C program to find the largest of ‘n’ numbers in the array.
#include<stdio.h>
void main( )
{
int n,a[20],i,large=-1; Output:
printf(“Enter the size of array:\n”); Enter the size of array:
scanf(“%d”,&n); 5
printf(“Enter the array elements:\n”); Enter the array elements:
for(i=0;i<n;i++) 10
{ 20
scanf(“%d”,&a[i]); 30
} 40
for(i=0;i<n;i++) 50
{ The largest number in the
if(a[i]>large) array is= 50
{
large=a[i];
}
}
printf(“The largest number in the array is=%d\n”,large);
}
4. Write a C program to print the smallest of ‘n’ numbers in the array.
#include<stdio.h>
void main( )
{
int n,a[20],i,small=9999; Output:
printf(“Enter the number of elements in the array:\n”); Enter the size of array:
scanf(“%d”,&n); 5
printf(“Enter the array elements:\n”); Enter the array elements:
for(i=0;i<n;i++) 10
{ 20
scanf(“%d”,&a[i]); 30
} 40
for(i=0;i<n;i++) 50
if(a[i]<small) The largest number in the
{ array is= 10
small=a[i];
}
printf(“The smallest number in the array is=%d”,small);
}
Santosh K C, CSE Dept. BIET, DVG 6
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
3.2.2 Two dimensional arrays (Multi-dimensional arrays)
 Arrays which are specified with 2 subscripts (2 set of square brackets [ ][ ]) are called 2-
dimensional arrays.
 Arrays with two or more dimensions are called Multi-dimensional arrays.
 In 2-Dimensional Array, the first index indicates the ‘row size’( the number of rows) and
second index indicates the ‘column size’( the number of columns).
Ex: int a[10][10]; //Two-dimensional array
int b[3][4][5]; //Three-dimensional array

Declaration of Two-dimensional arrays


 As we declare the variables before they are used in a program, an array must also be declared
before it is used using the following syntax.
Syntax:
data_type array_name [row_size][col_size];

data_type: It can be int, float, char etc.


array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.
Semicolon is must at the end.

 The size used during declaration of the array is useful to reserve the specified memory locations.

Ex: int a [2][4]; a[0][0] a[0][1] a[0][2] a[0][3]


col_size Col.0 Col.1 Col.2 Col.3
Row 0
Data type row_size
Row 1

Array name a[1][0] a[1][1] a[1][2] a[1][3]

 The array ‘a’ is a 2-dimensional array with 2 rows and 4 columns. This declaration informs the
compiler to reserve 8 locations (2*4=8 locations, 2*8=16 bytes in total) continuously one after
the other.

Initialization of 2-dimensional arrays


 As we initialize a variable to the required value, we can initialize the individual elements of the
array during initialization.
Syntax

data_type array_name[row_size][col_size]={
{a1,a2,-----,an},
{b1,b2,-----,bn},
……………...,
{z1,z2,-----,zn}
};

Santosh K C, CSE Dept. BIET, DVG 7


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
data_type: It can be int, float, char etc.
array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.
a1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2nd row and so on.

Ex: 1. int a[4][3]= {{11,22,33}, {44,55,66},{77,88,99},{10,20,30} };


The array has 4 rows and 3 columns.
Columns

0 1 2
0 11 22 33
1
44 55 66
Rows 2
3 77 88 99
10 20 30

2. int a[4][3]= {
{11,22},
{33,4},
{55,66},
{77,88}
};
The array has 4 rows and 3 columns.
Columns

0 1 2
0 11 22 0
1 //This is a partial array initialization
33 44 0
Rows 2
3 55 66 0
77 88 0

Reading/Writing Two dimensional arrays


 To read the 2-dimensional array, we have to use two for loops along with scanf(), where the
outer for loop indicates the number of rows to be read and the inner for loop indicates the
number of columns to be read.

 To read the ‘n’ array elements of Two dimensional array:


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}

Santosh K C, CSE Dept. BIET, DVG 8


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

 To write/print the 2-dimensional array elements, we have to use two for loops along with
printf(), where the outer for loop indicates the number of rows to be printed and the inner for
loop indicates the number of columns to be printed.

 To print the ‘n’ array elements of Two dimensional array:


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
printf(“\n”);
}

Example Programs:
1. Write a C Program to read and print 2-dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n;
printf(“Enter the number of Rows and Columns of the Array:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the Array elements:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:
{ Enter the number of Rows and
scanf(“%d”,&a[i][j]); Columns of the Array:
2 2
}
Enter the Array elements:
} 1
printf(“Entered array elements are:\n”); 2
for(i=0;i<m;i++) 3
{ 4
for(j=0;j<n;j++) Entered array elements are:
{ 1 2
printf(“%d\t”,a[i][j]); 3 4
}
}
printf(“\n”);
}
}

Santosh K C, CSE Dept. BIET, DVG 9


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
2. Write a C program to add 2 matrices A and B and store sum in C.
#include<stdio.h>
void main( )
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]); Output:
} Enter the size of matrix:
} 2 2
printf(“Enter the elements of Matrix B:\n”); Enter the elements of Matrix A:
for(i=0;i<m;i++) 1 2
{ 3 4
for(j=0;j<n;j++) Enter the elements of Matrix B:
{ 5 6
scanf(“%d”,&b[i][j]); 7 8
} The Resultant Matrix C is:
} 6 8
for(i=0;i<m;i++)
10 12
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“The Resultant Matrix C is:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}

3. Write a C program to find the largest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n,big=-1;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)

Santosh K C, CSE Dept. BIET, DVG 10


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
} Output:
} Enter the size of matrix:
for(i=0;i<m;i++) 2 2
{ Enter the elements of Matrix A:
for(j=0;j<n;j++) 10 20
{ 30 40
if(a[i][j]>big) The largest element is: 40
{
big=a[i][j];
}
}
}
printf(“The largest element is:%d\n”,big);
}

4. Write a C program to find the smallest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n,small=9999;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:
{ Enter the size of matrix:
2 2
scanf(“%d”,&a[i][j]);
Enter the elements of Matrix A:
} 10 20
} 30 40
for(i=0;i<m;i++) The largest element is: 10
{
for(j=0;j<n;j++)
{
if(a[i][j]<small)
{
small=a[i][j];
}
}
}
printf(“The smallest element is:%d\n”,small);
}

Santosh K C, CSE Dept. BIET, DVG 11


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
3.3 STRINGS
 “A string is a sequence of characters enclosed within double quotes”.
or
 “String is an array of characters and terminated by NULL character which is denoted by ‘\0’.

 A string is stored as a sequence of characters in an array terminated by ‘\0’ (NULL character).


Ex: Consider the String “DAVANGERE”.
 This string is stored in the form of an array as shown below:

D A V A N G E R E \0 Null character
0 1 2 3 4 5 6 7 8 9

3.3.1 Declaring String variables


 A string is declared like an array of characters.

Syntax: char string_name[size/length];

Where,
char: data type used to declare the strings or characters.
string_name: It specifies the name of the given string.
size: The size or maximum length (number of characters including ‘\0’) of the string is specified in
square brackets.

 Length of the String: The ‘length’ is the number of characters stored in the string up to but not
including the null character.

Example
1. char name[21];
 Size of the string is 21, means that it can store up to 20 characters plus one null character.

2. char str[10];
 Size of the string is 10, means that it can store up to 10 characters plus one null character.

3.3.3 Initializing the Strings


 We can initialize an array of characters (Strings) in the declaration itself.

Examples:
1. char a[9]={‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’, ‘\0’};
 The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized
with the characters in the order specified.

a C O M P U T E R \0
0 1 2 3 4 5 6 7 8
Santosh K C, CSE Dept. BIET, DVG 12
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
2. char b[10]={‘R’, ‘A’, ‘M’, ‘A’, ‘\0’};
 The compiler allocates 10 memory locations ranging from 0 to 9 and these locations are
initialized with the characters in the order specified. The remaining locations are automatically
initialized to null-characters as shown below:

b R A M A \0 \0 \0 \0 \0 \0

0 1 2 3 4 5 6 7 8 9

3. char b[ ]={‘C’, ‘O’, ‘M’, ‘P’, ‘U’, ‘T’, ‘E’, ‘R’, ‘\0’};
 For this declaration, the compiler will set the array size to the total number of initial values. i.e.
9. The characters will be stored in these memory locations in the order specified as shown below:

b C O M P U T E R \0
0 1 2 3 4 5 6 7 8

4. char b[ ]= “COMPUTER”;
 Here, the string length is 8 bytes. But string size is 9 bytes. So, the compiler reserves 8+1
memory locations and these locations are initialized with the characters in the order specified.
The string is terminated by ‘\0’ by the compiler.

b C O M P U T E R \0
0 1 2 3 4 5 6 7 8

3.4 String Input / Output Functions


3.4.1. Token-Oriented I/O functions
 The Input/Output operations performed by scanf() and printf() functions are called token-
oriented Input/Output.

Reading a String using scanf( )


 It is possible to read a string using “scanf()”.
 The conversion specification for reading a string using scanf() is “%s”.
 The scanf() function stops reading characters when it finds the first white space character (
spaces, tabs and new line characters).

Example: char name[20];


printf(“Enter the name:”);
scanf(“%s”, name);

Printing a String using printf( )


 The ‘printf()’ function prints the given string (all the characters but not the null character).
 The printf() conversion specification for a string variable is “%s”.
Example: char name[20];
printf(“Enter the name:\n”);
scanf(“%s”, name);
printf(“The entered name is:%s”, name);
Santosh K C, CSE Dept. BIET, DVG 13
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Output: Enter the name:
Rama
The entered name is:
Rama

Example C Program: Write a C program to read and display a string using scanf() and
printf().
#include<stdio.h>
void main()
{ Output:
char str[20]; Enter your name:
printf(“Enter your name:\n”); Bapuji
scanf(“%s”,str); Entered name is:
printf(“Entered name is:%s\n”,str); Bapuji
}

3.4.2. Line-Oriented I/O functions


 The Input/Output operation performed by gets() and puts() functions are called line-oriented
Input/Output.
 The prototypes for these functions are in “string.h”.
 This type of I/O functions processes entire line (string with white spaces). Hence these are called
line-oriented I/O.

Reading a String using gets( )


 gets() function is used to read a sequence of characters (string) with spaces in between.
 The ‘gets()’ function allows us to read an ‘entire line’ of input including whitespace characters.
Syntax
gets(string);
Example: char name[20];
printf(“Enter the name:”);
gets(name);

Printing a String using puts( )


 ‘puts()’ function is used for printing the given strings.
 Whenever we want to display a sequence of characters stored in memory locations on the screen,
then puts() function can be used.
Syntax
puts(string);

Example: char name[20];


printf(“Enter the name:\n”); Output:
gets(name); Enter the name:
Abdul Kalam
printf(“The entered name is:\n”);
Entered name is:
puts(name); Abdul Kalam

Santosh K C, CSE Dept. BIET, DVG 14


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

3.5 String Manipulation Functions


 The standard library ‘string.h’ contains many functions for the string manipulation.

Si.No String Functions Description of each function

1. strlen(str) Returns length of the string str

2. strcpy(dest,src) Copies the source string src to destination string dest

3. strncpy(dest,src,n) Copies n characters of the source string src to destination


string dest

4. strcat(s1,s2) Append string s2 to string s1

5. strncat(s1,s2) Append first n characters of string s2 to string s1

6. strcmp(s1,s2) Compare two strings s1 and s2

7. strncmp(s1,s2,n) Compare n characters of two strings s1 and s2

8. strrev(string) Reverse the given string

9. strupr(string) Used to convert the string to uppercase

10. strlwr(string) Used to convert the string to lowercase

1. strlen(str) and sizeof(): The length and size of a string


 The ‘strlen()’ function can be used to find the length of the string in bytes.
 This function calculates the length of the string up to but not including the ‘null character’.

Syntax
length=strlen(str);
Where,
‘str’ is a string.
‘length’ is an integer representing the length of ‘str’ in bytes excluding the null character.

Example: Write a C program to demonstrate the usage of strlen().


#include<stdio.h>
#include<string.h>
void main()
{
char str[10]= “hello”;
int length;
length=strlen(str);
printf(“Length of the string is=%d\n”,length);
}

Santosh K C, CSE Dept. BIET, DVG 15


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Output: Length of the string is=5

 The ‘sizeof’ operator can be used to determine the size of a declared string.

Syntax
sizeof(str);
Where,
‘str’ is a string.

Example: Write a C program to demonstrate the usage of sizeof().


#include<stdio.h>
#include<string.h>
void main()
{
char str1[25]= “RAMA”;
printf(“Size of string is=%d”,sizeof(str));
}
Output: Size of string is= 25

Example: Write a C program to find the length of string without using strlen() function.
#include<stdio.h>
#include<string.h>
void main()
{
char str[];
int length=0; Output:
printf(“Enter the string\n”); Enter the string
gets(str); Good morning
while(str[length]!=’\0’) Length of the string is=12
{
length ++;
}
printf(“Length of the string is=%d\n”, length);
}

2. strcpy ( ): String Copy

Syntax strcpy(dest,src);

Where,
dest: it is the destination string
src: it is the source string.

 The ‘strcpy()’ function copies the contents of source string src to destination string dest
including ‘\0’.
 The strcpy() function copies characters from the source string to the destination string until it finds
null character.
Santosh K C, CSE Dept. BIET, DVG 16
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

Example: Write a C program to demonstrate the usage of strcpy().


#include<stdio.h>
#include<string.h>
void main()
{
char src[10]= “string”,dest[10];
strcpy(dest,src);
printf(“The Source String=%s\n The Destination String=%s”,src,dest);
}
Source
Output: The Source String =string s t r i n g \0
The Destination String =string

s t r i n g \0

Destination

Example: Write a C program to copy string without using strcpy() function.


#include<stdio.h>
#include<string.h>
void main()
{
char src[100],dest[100];
int i; Output:
printf(“Enter the string\n”); Enter the string
gets(str); rahul
for(i=0; str1[i]!=’\0’; i++) copied string is= rahul
{
str2[i] = str1[i];
}
str2[i]=’\0’;
printf(“copied string is=%d\n”, str2);
}

3. strncpy(dest,src,n): String Number Copy

Syntax
strncpy(dest,src,n);

Where,
dest: it is the destination string.
src: it is the source string.
n: n is the number of characters to be copied into destination string.

Santosh K C, CSE Dept. BIET, DVG 17


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
 ‘strncpy()’ function is used to copy ‘n’ characters from the source string src to the
destination string dest.

Examples: Write a C program to demonstrate the usage of strncpy().


#include<stdio.h>
#include<string.h>
void main()
{
char src[10]= “Computer”, dest[10];
strncpy(dest,src,3);
printf (“The Source String=%s\n The Destination String=%s”,src,dest);
}

Output: The Source String=Computer


The Destination String= Com

src C o m p u t e r \0

0 1 2 3 4 5 6 7 8 9

dest C o m

0 1 2 3 4 5 6 7 8 9

4. strcat(s1,s2): String Concatenate(Joining two strings together)

Syntax
strcat(s1,s2);
Where,
s1: It is the first string
s2: It is the second string
 The ‘strcat()’ function is used to concatenate or join the two strings.
 The ‘strcat()’ function copies all the characters of string s2 to the end of string s1. The
NULL character of string s1 is replaced by the first character of s2.

Example: Write a C program to demonstrate the usage of strcat().


#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”;
strcat(s1,s2);
printf(“The concatenated String=%s”,s1);
}

Santosh K C, CSE Dept. BIET, DVG 18


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Output:
The concatenated String=GoodMorning.
s1
G o o d \0
0 1 2 3 4 5 6 7 8 9 10 12 13 14
s2

M o r n i n g \0

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
s1
G o o d M o r n i n g \0
0 1 2 3 4 5 6 7 8 9 10 12 13 14

Example: Write a C program to demonstrate string concatenation without using strcat().


#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”, s3[20];
int k,i;
for (i=0; s1[i]!=’\0’; i++)
{
s3[i] = s1[i];
k = k +1;
}
for (i=0; s2[i]!=’\0’; i++)
{
s3[i] = s2[i];
k = k +1;
}
s3[k] = ‘\0’;
printf(“The concatenated String=%s”,s3);
}

5. strncat(s1,s2,n)- String Number Concatenate

Syntax strncat(s1,s2,n);
Where,
s1: It is the first string
s2: It is the second string
n: It is the number of characters of string s2 to be concatenated.

 The ‘strncat()’ function is used to concatenate or join n characters of string s2 to the end of
string s1.
Santosh K C, CSE Dept. BIET, DVG 19
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Example: Write a C program to demonstrate the usage of strncat().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”;
strncat(str1,str2,4);
printf(“The concatenated String=%s”,str1);
}
Output: The concatenated String=GoodMorn.

s1
G o o d \0
0 1 2 3 4 5 6 7 8 9 10 12 13 14
s2

M o r n i n g \0

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
s1
G o o d M o r n \0
0 1 2 3 4 5 6 7 8 9 10 12 13 14

6. strcmp(s1,s2): String Compare

Syntax
strcmp(s1,s2);

Where,
s1: It is the first string.
s2: It is the second string.

 This function is used to compare two strings.


 The comparison starts with first character of each string. The comparison continues till the
corresponding characters differ or until the end of the character is reached.
 The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
2. If s1 is greater than s2, a positive value is returned.
3. If s1 is less than s2, then the function returns a negative value.

Santosh K C, CSE Dept. BIET, DVG 20


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

Example:
1.
s1 c a r \0

s2 c a t \0
strcmp(s1,s2);
 “car” and “cat” are different strings. The characters ‘r’ and ‘t’ have different ASCII values. It
returns negative value since ASCII value of ‘r’ is less than the ASCII value of ‘t’.

2.
s1 c a r \0

s2 c a r \0
strcmp(s1,s2);
 Since both the strings are same, the function returns 0.
3.
s1 c a t \0

s2 c a r \0
strcmp(s1,s2);
 “cat” and “car” are different strings. The characters ‘t’ and ‘r’ have different ASCII values. It
returns positive value since ASCII value of ‘t’ is greater than the ASCII value of ‘r’.

Example: Write a C program to demonstrate the usage of strcmp().


#include<stdio.h>
#include<string.h>
void main()
{
char s1[10]=”Hello”;
char s2[10]=”Hey”;
if(strcmp(s1,s2)==0)
printf(“The two strings are identical”);
else
printf(“The two strings are not identical”);
}

Example: Write a C program to compare two strings without using strcmp().


#include<stdio.h>
#include<string.h>
void main()
{ int i;
Santosh K C, CSE Dept. BIET, DVG 21
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
char s1[10]=”Hello”;
char s2[10]=”Hey”;
len1 = strlen(s1);
len2 = strlen(s2);
if (strlen(s1) != strlen(s2))
printf(“The two strings are different”);
else{
for (i=0; s1[i]!=’\0’; i++)
{
if(s1[i]!=s2[i])
printf(“strings are different”);
break;
}
}
printf(“The two strings are identical”);
}

7. strncmp(s1,s2,n): String Number Compare

Syntax strncmp(s1,s2,n);
Where,
s1: It is the first string.
s2: It is the second string.
n: It is the number of characters to be compared.
 This function is used to compare first n number of characters in two strings.
 The comparison starts with first character of each string. The comparison continues till the
corresponding characters differ or until the end of the character is reached or specified numbers of
characters have been tested.
 The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
2. If s1 is greater than s2, a positive value is returned.
3. If s1 is less than s2, then the function returns a negative value.
Example: Write a C program to demonstrate the usage of strcmp().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[10]=”Hello”;
char s2[10]=”Hey”;
if(strcmp(s1,s2,2)==0)
printf(“The first two characters in the strings are identical”);
else
printf(“The first two characters in the strings are not identical”);
}

Santosh K C, CSE Dept. BIET, DVG 22


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
3.6 Basic Algorithms
3.6.1 Searching Algorithms
 The process of identifying or finding a particular record or element is called searching. This can be
implemented using array. Here we have two searching techniques.
1. Linear Search: linear search or sequential search is a method for finding an element within a list. It
sequentially checks each element of the list until a match is found or the whole list has been
searched.
 Linear search is usually very simple to implement, and is practical when the list has only a few
elements, or when performing a single search in an unordered list.
 A simple approach is to do linear search:
 Start from the leftmost element of arr[] and one by one compare j with each element of arr[].
 If j matches with an element, return the index number.
 If j doesn’t match with any of elements, return -1 or element not found in an arr[].

Example: C Program to search the ‘key’ element in an array using linear search algorithm.
#include <stdio.h>
void main()
{
int array[100], key, i, n;

printf("Enter number of elements in array\n");


scanf("%d", &n); Output:
printf("Enter elements of array\n"); Enter number of elements in
for (i = 0; i < n; i++) array:
scanf("%d", &array [ i ] ); 5
Enter elements of array
100
printf("Enter a number to search\n"); 25
scanf("%d", &key); 35
30
for (i = 0; i < n; i++) 56
{ Enter a number to search:
if (array[i] == key) 30
30 is present at location 4
{
printf("%d is present at location %d.\n", key, i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array.\n", key);
}
Santosh K C, CSE Dept. BIET, DVG 23
C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

2. Binary Search:
 Binary search is a fast searching algorithm. This search algorithm works on the principle of divide
and conquers.
 Binary search works on sorted arrays. Binary search begins by comparing the middle element of the
array with the target value. If the target value matches the middle element, its position in the array is
returned. If the target value is less than the middle element, the search continues in the lower half of
the array. If the target value is greater than the middle element, the search continues in the upper half
of the array.

How Binary Search Works?


 For a binary search to work, it is mandatory for the target array to be sorted. The following is our
sorted array and let us assume that we need to search the location of value 31 using binary search.

First, we shall determine half of the array by using this formula −


mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

 Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that
the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have a
sorted array, so we also know that the target value must be in the upper portion of the array.

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2

 Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.

Santosh K C, CSE Dept. BIET, DVG 24


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
 The value stored at location 7 is not a match; rather it is more than what we are looking for. So, the
value must be in the lower part from this location.

 Hence, we calculate the mid again. This time it is 5.

 We compare the value stored at location 5 with our target value. We find that it is a match.

 We conclude that the target value 31 is stored at location 5.


 Binary search halves the searchable items and thus reduces the count of comparisons to be made to
very less numbers.

Example: C Program to search key elements in array using binary search algorithms.
#include<stdio.h>
void main()
{
int n, i, arr[50], key, first, last, middle;
Output:
printf("Enter total number of elements :");
Enter number of
scanf("%d",&n);
elements in array:
printf("Enter array elements:\n");
5
for (i=0; i<n; i++)
Enter elements of array
{
10
scanf("%d",&arr[i]);
25
}
35
printf("Enter a number to find :");
50
scanf("%d", &key);
65
first = 0;
Enter a number to
last = n-1;
search:
while (first <= last)
65
{ middle = (first+last)/2;
65 is present at location 5
if ( arr[middle] == key)
{
printf("%d found at location %d\n", key, middle+1);
break;
}
else if ( arr[middle] < key)
{
first = middle + 1;
}

Santosh K C, CSE Dept. BIET, DVG 25


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
printf("Not found! %d is not present in the list.",key);
}
}

3.6.2 Sorting Algorithms


 A sorting algorithm is an algorithm that puts/arrange the elements of a list in a certain order. Order
may be numerical (increasing/decreasing) or alphabetical form. Here we have two different sorting
algorithms.

1. Selection sort
 Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based
algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted
part at the right end.
 Initially, the sorted part is empty and the unsorted part is the entire list.
 The smallest element is selected from the unsorted array and swapped with the leftmost element, and
that element becomes a part of the sorted array.
 This process continues moving unsorted array boundary by one element to the right. This algorithm
is not suitable for large data sets.
How Selection Sort Works?
 Consider the following depicted array as an example.

 For the first position in the sorted list, the whole list is scanned sequentially. The first position where
14 is stored presently, we search the whole list and find that 10 is the lowest value.

 So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list,
appears in the first position of the sorted list.

Santosh K C, CSE Dept. BIET, DVG 26


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
 For the second position, where 33 is residing, we start scanning the rest of the list in a linear manner.

 We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.

 After two iterations, two least values are positioned at the beginning in a sorted manner.

 The same process is applied to the rest of the items in the array. Following is a pictorial depiction of
the entire sorting process –

Santosh K C, CSE Dept. BIET, DVG 27


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23
Example: C Program to sort given array elements using selection sort algorithm.
#include<stdio.h>
int main()
{
int i, j, n, temp, a[25],min;

printf("enter the size of array: ");


scanf("%d", &n);
Output:
printf("Enter the array elements: "); Enter the size of array:
for(i=0; i< n; i++) 5
scanf("%d", &a[i]); Enter elements of array
100
for(i=0;i<n;i++) 25
{ 35
min=i; 30
for(j=i+1;j<n;j++) 56
{ Sorted elements:
if( a[j] < a[min] ) 25
{ 30
min = j ; 35
} 56
} 100
temp = a [ i ];
a [ i ] = a [ min ];
a [ min ] = temp;
}
printf("Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
}

2. Bubble Sort.
 Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
 Bubble sort algorithm starts by comparing the first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first
element is greater than second then, you need to swap the elements but, if the first element is
smaller than second, you mustn't swap the element.
 Then, again second and third elements are compared and swapped if it is necessary and this
process go on until last and second last element is compared and swapped. This completes the
first step of bubble sort.
 If there are n elements to be sorted then, the process mentioned above should be repeated n-
1 times to get required result. But, for better performance, in second step, last and second last
elements are not compared because; the proper element is automatically placed at last after first
step. Similarly, in third step, last and second last and second last and third last elements are not
compared and so on.

Santosh K C, CSE Dept. BIET, DVG 28


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

Example: C Program to sort the given array elements using Bubble sort Algorithm.
#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n); Output:
printf("Enter the array elements: "); Enter the size of array:
for(i=0;i<n;++i) 5
scanf("%d",&a[i]); Enter elements of array
for(i=1;i<n;++i) 30
for(j=0;j<(n-i);++j) 25
35
if(a[j]>a[j+1])
10
{ 56
temp=a[j]; Sorted elements:
a[j]=a[j+1]; 10
a[j+1]=temp; 25
} 30
35
printf("\nArray after sorting: ");
56
for(i=0;i<n;++i)
printf("%d ",a[i]);
}

Santosh K C, CSE Dept. BIET, DVG 29


C PROGRAMMING FOR PROBLEM SOLVING(CPPS) Module-3 18CPS13-23

ASSIGNMENT QUESTIONS

1. What is array? Explain the properties of array with examples.


2. Explain the declaration and initialization of 1-D array with example.
3. Write a c program to find the largest element in the given string using array.
4. Explain the declaration and initialization of 2-D array with example.
5. Write a c program to perform matrix multiplication using 2 –D array.
6. Define string? Explain the declaration and initialization of strings with example.
7. Explain any 5 string Manipulation functions with examples.
8. Write a C Program to find length of string without using strlen().
9. Write a C Program to copy of strings without using strcpy().
10. Write a C Program to compare two strings without using strcmp().
11. Write a C Program to concatenate two strings without using strcat().
12. Write a C Program to search the ‘key’ element in an array using linear search algorithm.
13. Write a C Program to search the ‘key’ element in an array using binary search algorithm.
14. Write a C Program to sort the given array elements using Selection sort algorithm.
15. Write a C Program to sort the given array elements using Bubble sort algorithm.
16. Write a C program, which reads your name from the keyboard and outputs a list of ASCII codes,
which represents your name.
17. Write a C program, which read a string and rewrite it in the alphabetical order. For ex- the word
CORONA should be written as ANOROC

Santosh K C, CSE Dept. BIET, DVG 30

You might also like