CP Unit V

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 19

UNIT-V COMPUTER PROGRAMMING

5.0 Introduction
The fundamental data types, namely char, int, float, and double are used to store only one
value at any given time. Hence these fundamental data types can handle limited amounts of data.

In some cases we need to handle large volume of data in terms of reading, processing and
printing. To process such large amounts of data, we need a powerful data type that would
facilitate efficient storing, accessing and manipulation of data items. C supports a derived data
type known as array that can be used for such applications.

Arrays
 An array is a fixed size sequenced collection of elements of the same data type.
 It is simply grouping of like type data such as list of numbers, list of names etc.

Types of Arrays
We can use arrays to represent not only simple lists of values but also tables of data in two or
three or more dimensions.
1. One – dimensional arrays(1-D)
2. Two – dimensional arrays (2-D)
3. Multidimensional arrays (n-D)

Some examples where arrays can be used are


1. List of temperatures recorded every hour in a day, or a month, or a year.
2. List of employees in an organization.
3. List of products and their cost sold by a store.
4. Test scores of a class of students
5. List of customers and their telephone numbers.

5.1 Array
An array is collection of homogeneous elements that are represented under a single variable
name.
(Or)
An array is collection of same data type elements in a single entity.
 It allocates sequential memory locations.
 Individual values are called as elements.

Declaration of One-Dimensional Array


Like any other variables, arrays must be declared before they are used. The general form of
array declaration is
Syntax
datatype array_name[size];

 The data type specifies the type of element that will be contained in the array, such as int, float, or
char or any valid data type.
 The array name specifies the name of the array.
 The size indicates the maximum number of elements that can be stored inside the array.
 The size of array should be a constant value.

For example
int marks[10]; //integer array

The above statement declares a marks variable to be an array containing 10 elements. In


C, the array index (also known as subscript) start from zero. i.e. The first element will be stored

1
UNIT-V COMPUTER PROGRAMMING
in marks[0], second element in marks[1], and so on. Therefore, the last element, that is the 10th
element, will be stored in marks[9].

Fig. memory representation of an array of


elements Examples
float temp[24]; //floating-point array
Declare the group as an array to contain a maximum of 24 real constants.

char name[10]; //character array


Declare the name as a character array (string) variable that can hold a maximum of 10
characters.

C array indices start from 0. So for an array with N elements, the index that last element is N-1

Valid Statements
 a = marks[0] + 10;
 marks[4] = marks[0] + marks[2];
 marks[2] = x[5] + y[10];
 value[6] = marks[i] * 3;

Example 1: A C program that prints bytes reserved for various types of data and space required
for storing them in memory using array.

#include<stdio.h>
int main()
{
char c[10];
int i[10];
float f[10];
double d[10];
printf("\nThe type char requires %d byte",sizeof(char));
printf("\nThe type int requires %d bytes",sizeof(int)); printf("\
nThe type float requires %d bytes",sizeof(float)); printf("\nThe
type double requires %d bytes",sizeof(double));
printf("\n%d memory locations are reserved for 10 character elements", sizeof(c));
printf("\n%d memory locations are reserved for 10 integer elements", sizeof(i));
printf("\n%d memory locations are reserved for 10 float elements", sizeof(f));
printf("\n%d memory locations are reserved for 10 double elements", sizeof(d));
return 0;
}

Output
The type char requires 1 byte
The type int requires 2 bytes
The type float requires 4 bytes
The type double requires 8 bytes
10 memory locations are reserved for 10 character elements
20 memory locations are reserved for 10 integer elements

2
UNIT-V COMPUTER PROGRAMMING
40 memory locations are reserved for 10 float elements
80 memory locations are reserved for 10 double elements

5.1.1 Accessing elements the array


To access all the elements from an array, we must use a loop. That is, we can access all
the elements of an array by varying the value of the subscript into the array. But note that the
subscript must be an integral value or an expression that evaluates to an integral value.

For example
int i ,marks[10];
for (i=0; i<10; i++)
printf(“%d”,marks[i]);

5.1.2 Storing Values in Array


When we declare an array, we are just allocating space for its elements; no values are
stored in the array. There are three ways to store values in an array.
1. Initialize the array elements during declaration.
2. Input values for individual elements from the keyboard.
3. Assign values to individual elements using assignment (=) operator.

Initializing Arrays during Declaration


When an array is initialized, we need to provide a value for every element in the array.
Arrays are initialized by writing:
type array_name[size]={list_of_values};
The values are written within curly brackets and every value is separated by a comma.

For example
int marks[5]={90,87,76,69,82};

While initializing the array at the time of declaration, the programmer may omit the size of the
array. For example,
int marks[]= {98, 97, 90};

3
UNIT-V COMPUTER PROGRAMMING
Input values from keyboard
An array can be filled by inputting values from the keyboard. In this method, a while or for loop
is executed to input the value for each element of the array. For example:

int i ,marks[10];
for (i=0; i<10; i++)
scanf(“%d”,&marks[i]);

Assigning Values to Individual Elements


The third way is to assign values to individual elements of the array by using the
assignment operator. Any value that evaluates to the data type as that of the array can be
assigned to the individual array element. A simple assignment statement can be written as
marks[3] = 100;
Here, 100 is assigned to the fourth element of the array which is specified as marks[3].

Example 2: Write a C Program to read and display N numbers using an array.


#include <stdio.h>
int main()
{
int i, n, arr[20];
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("\t %d", arr[i]);
return 0;
}

Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5

Example 3: Write a C Program to print the maximum and minimum element in the array.
#include <stdio.h>
int main()
{
int i, n, a[20], max, min;
printf("Enter the number of elements in the array :
"); scanf("%d", &n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
4
UNIT-V COMPUTER PROGRAMMING
printf("a[%d] = ",i);
scanf("%d",&a[i]);
}
max = min = a[0];
for(i=1;i<n;i++)
{
if(a[i]<min)
min = a[i];
if(a[i]>max)
max = a[i];
}
printf("\n The smallest element is : %d\n", min);
printf("\n The largest element is : %d\n", max);
return 0;
}

Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The smallest element is : 1
The largest element is : 5

5.2 Searching the Array elements


Searching means to find whether a particular value is present in an array or not. If the
value is present in the array, then searching is said to be successful and the searching process
gives the location of that value in the array. if the value is not present in the array, the searching
is said to be unsuccessful. There are two popular methods for searching the array elements:
1. Linear search
2. Binary search.

Linear Search
Linear search, also called as sequential search, is a very simple method used for searching
an array for a particular value. It works by comparing the value to be searched with every
element of the array one by one in a sequence until a match is found. It is mostly used to search
an unordered list of elements. For example, if an array a[] is declared and initialized as,
int a[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is
present in the array or not. If yes, then it returns the position of its occurrence. Here, POS = 3
(index starting from 0).

Example 4: Write a C Program to search an element in an array using the linear search
technique.
#include <stdio.h>
int main()
{
int a[100],n,i,key,flag=0;
printf("Enter number of elements:");
scanf("%d", &n);

5
UNIT-V COMPUTER PROGRAMMING
printf("Enter elements\n");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
printf("Enter an element to be searched:");
scanf("%d", &key);
/* linear search starts here */
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf("%d is found at position %d\n", key, i);
flag=1;
break;
}
}
if(flag==0)
printf("%d is not found\n",key);
return 0;
}

Output
Enter number of elements: 5
Enter elements
Enter a[0] = 14
Enter a[1] = 5
Enter a[2] = 23
Enter a[3] = 9
Enter a[4] = 15
Enter an element to be searched: 9
9 is found at position 3

Binary Search
Binary search is a searching algorithm that works efficiently with a sorted list.

Example 5: Write a C Program to search an element in an array using binary search.


#include <stdio.h>
int main()
{
int a[25],i,n,key,high,low,mid,flag=0;
printf("\n Enter the number of elements in the array:
"); scanf("%d", &n);
printf("\n Enter the elements\n");
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
printf("Enter the element to be searched: ");

6
UNIT-V COMPUTER PROGRAMMING
scanf("%d", &key);
low = 0, high = n-1;
while(high>=low)
{
mid = (low + high)/2;
if (a[mid] == key)
{
printf("\n %d is found at position %d", key, mid);
flag = 1;
break;
}
else if (a[mid]>key)
high = mid-1;
else
low = mid+1;
}
if (flag == 0)
printf("\n %d does not found in the array",
key); return 0;
}
Output
Enter the number of elements in the array: 5
Enter the elements
Enter a[0] = 11
Enter a[1] = 26
Enter a[2] = 32
Enter a[3] = 49
Enter a[4] = 68
Enter the element to be searched: 49
49 is found at position 3

5.3 Sorting
Sorting means arranging the elements of an array in specific order may be either ascending or
descending. There are different types of sorting techniques are available:
1. Bubble sort
2. Selection sort
3. Insert sort
4. Merge sort
5. Quick sort etc.

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly
steps through the list to be sorted, compares each pair of adjacent items and swaps them if they
are in the wrong order.

Example 6: C Program to implement Bubble Sort Technique


#include <stdio.h>
int main()
{
int a[100],n,i,j,temp;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter elements\n");

7
UNIT-V COMPUTER PROGRAMMING
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
/* bubble sort logic starts from here */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
if(a[i]>a[j]) //> for ascending order, < for descending order
{
temp=a[i]; Output
a[i] = a[j]; Enter number of elements: 5
a[j] = temp; Enter elements
} Enter a[0] = 14
} Enter a[1] = 5
printf("Sorted elements ....\n"); Enter a[2] = 23
for(i=0;i<n;i++) Enter a[3] = 9
printf("%3d",a[i]); Enter a[4] = 15
printf("\n"); Sorted elements ....
return 0; 5 9 14 15 23
}

Selection sort is a simple sorting algorithm. This sorting algorithm is in-place comparison based
algorithm in which the list is divided into two parts, sorted part at left end and unsorted part at
right end. Initially sorted part is empty and unsorted part is entire list.

Example 7: C program to implement Selection sort technique


#include <stdio.h>
int main()
{
int a[100],n,i,j,temp; Output
printf("Enter number of Enter number of elements: 5
elements:"); scanf("%d", &n); Enter elements
printf("Enter elements\ Enter a[0] = 5
n"); /* Read array elements Enter a[1] = 3
*/ for(i=0;i<n;i++) { Enter a[2] = 9
printf("Enter a[%d]=",i);
Enter a[3] = 7
scanf("%d", &a[i]); Enter a[4] = 2
} Sorted elements....
/* selection sort */ 2 3 5 7 9
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
min=j;
}
temp=a[i];

8
UNIT-V COMPUTER PROGRAMMING
a[i] = a[min];
a[min] = temp;
}
printf("Sorted elements ....\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
return 0;
}

5.4 Two Dimensional (2D) Arrays


There could be situations where a table of values will have to be stored. Consider a student table
with marks in 3 subjects.

Student Maths Physics Chemistry


Student #1 89 77 84
Student #2 98 89 80
Student #3 75 70 82
 The above table contains a total of 9 values.
 We can think this table as a matrix consisting of 3 rows and 3 columns.
 Each row represents marks of student # 1 in all (different) subjects.
 Each column represents the subject wise marks of all students.

 In mathematics, we represent a particular value in a matrix by using two subscripts such as Vij.
 th
Here V denotes the entire matrix, Vij refers to the value in i row and j column.
th

In the above table V23 refers to the value “80”. C allows us to define such tables of items by
using two-dimensional arrays.

Definition
A list of items can be represented with one variable name using two subscripts and such
a variable is called a two – subscripted variable or a two – dimensional (2D) array.

5.4.1 Declaring 2-D Array


A two-dimensional array is declared as:
data_type array_name[row_size][column_size];
For example, if we want to store the marks obtained by three students in three different
subjects, we can declare a two dimensional array as:
int marks[3][3];
The pictorial form of a two-dimensional array in memory is shown in Figure.

9
UNIT-V COMPUTER PROGRAMMING
5.4.2 Initializing Two- Dimensional Arrays
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in curly braces.
int table[2] [3] = {0,0,0,1,1,1};
This initializes the elements of first row to zero and the second row to one.
 This initialization can also be done row by row. The above statement can be equivalently written as

int table[2][3] = { {0,0,0}, {1,1,1} };


Commas are required after each curly brace that closes of a row, except in case of last
row.
 If the values are missing in an initializer, they are automatically set to zero.
Ex: int table [2] [3] = {
{1,1}, \\ 1 1 0
{2} \\ 2 0 0
};
 When all the elements are to be initialized to zero, the following short-cut method may be used.
int m[3][5] = { {0}, {0}, {0}};

 The first element of each row is explicitly initialized to zero while the other elements are
automatically initialized to zero.
 The following statement will also achieve the same result
int m[3][5] = { 0 };

5.4.3 Accessing the Elements of Two-dimensional Arrays


Since the 2D array contains two subscripts, we will use two for loops to scan the
elements. The first for loop will scan each row in the 2D array and the second for loop will scan
individual columns for every row in the array.

Example 8: Write a program to print the elements of a 2D array.


#include <stdio.h>
int main()
{
int a[3][3] = {12, 34, 56,32,89,23,44,67,99}; Output
int i, j; 12 34 56
for(i=0;i<3;i++) 32 89 23
{ 44 67 99
for(j=0;j<3;j++)
printf("%d\t", a[i][j]);
printf("\n");
}
return 0;
}

5.4.4 Operations on 2D Arrays


Example 9: Write a C program to print the transpose of a given matrix
#include <stdio.h> int rows, cols, i, j;
int main() /* read the size of a matrix */
{ printf("Enter number of rows and
int a[10][10],trans[10][10]; columns:");
10
UNIT-V COMPUTER PROGRAMMING
scanf("%d%d", &rows,&cols); /* {
Read the elements of matrix */ for(j=0;j<rows;j++)
printf("Enter elements of matrix\n"); printf("%3d",trans[i][j]);
for(i=0; i<rows;i++) printf("\n");
for(j=0; j<cols;j++) }
{ return 0;
printf("Enter a[%d][%d]=",i,j); }
scanf("%d",&a[i][j]);
} Output
/* Display the matrix A */ Enter number of rows and columns: 3
printf("The Matrix A\n"); 3 Enter elements of matrix Enter a[0]
for(i=0; i<rows;i++) { [0]=4
Enter a[0][1]=7
for(j=0; j<cols; j++) Enter a[0][2]=3
printf("%3d",a[i][j]); Enter a[1][0]=9
printf("\n"); Enter a[1][1]=5
} Enter a[1][2]=2
/* Change rows into columns and columns Enter a[2][0]=6
into rows */ Enter a[2][1]=1
for(i=0;i<cols;i++) Enter a[2][2]=8
{ The Matrix A
for(j=0;j<rows;j++) 4 73
trans[i][j] = a[j][i]; 9 52
/ printf("%3d",a[j][i]); 6 18
/ printf("\n"); Transpose of a given matrix
} 4 9 6
/* Display the transpose matrix */ 7 5 1
printf("Transpose of a given matrix\ 3 2 8
n"); for(i=0;i<cols;i++)

Example 10: Write a C program to perform addition or subtraction of two matrices


#include <stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int rows,cols,i,j;
printf("Enter number of rows and columns (between 1 and
10):"); scanf("%d%d",&rows,&cols);
/* read the elements of first matrix */
printf("Enter elements of first matrix\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&a[i][j]);
}
/* read the elements of second matrix */
printf("Enter elements of second matrix\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&b[i][j]);
}

11
UNIT-V COMPUTER PROGRAMMING
/* Display A and B matrices */
printf("The Matrix A\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%3d",a[i][j]);
printf("\n");
}
printf("The Matrix B\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%3d",b[i][j]);
printf("\n");
}
/*Add two matrices and print resultant matrix */
printf("The resultant matrix is\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
c[i][j]=a[i][j]+b[i][j]; // for subtract, use minus (-) instead of plus (+) sign
printf("%3d",c[i][j]);
}
printf("\n");
}

return 0;
}

Output
Enter number of rows and columns (between 1 and 10): 3 3
Enter elements of first matrix: 1 2 3 4 5 6 7 8 9
Enter elements of second matrix: 1 2 3 4 5 6 7 8 9
The matrix A
123
456
789
The matrix B
123
456
789
The resultant matrix is
2 4 6
8 10 12
14 16 18

Example 11: Write a C program to perform multiplication of two matrices


#include <stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];

12
UNIT-V COMPUTER PROGRAMMING
int m,n,p,q,i,j,k;
printf("Enter number of rows and columns of first matrix(between 1 and
10):"); scanf("%d%d",&m,&n);
printf("Enter number of rows and columns of second matrix(between 1 and 10):");
scanf("%d%d",&p,&q);
if(n==p)
{
/* Read the elements of first matrix */
printf("Enter elements of first matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
/* Read the elements of second matrix */
Print f("Enter elements of second matrix\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
}
/* Display A and B matrices */
printf("The Matrix A\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%3d",a[i][j]);
printf("\n");
}
printf("The Matrix B\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%3d",b[i][j]);
printf("\n");
}
/*multiply two matrices and print resultant matrix */
printf("The resultant matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0; /* Initializing resultant matrix elements to zero */
for(k=0;k<p;k++)
c[i][j] += a[i][k]*b[k][j];
printf("%3d",c[i][j]);
}

printf("\n");
}
}
else

13
UNIT-V COMPUTER PROGRAMMING
printf("Multiplication is not possible\n");
return 0;
}

Output
Enter number of rows and columns of first matrix (between 1 and 10):2 3
Enter number of rows and columns of second matrix (between 1 and 10):3 2
Enter elements of first matrix: 1 2 3 4 5 6
Enter elements of second matrix: 1 2 3 4 5 6
The Matrix A
1 2 3
4 5 6
The Matrix B
1 2
3 4
5 6
The resultant matrix is
22 28
49 64

5.5 Multi – Dimensional Array


A list of items can be represented with one variable name using more than two subscripts and
such a variable is called Multi – dimensional array.

Three Dimensional (3D) Array


A list of items can be represented with one variable name using three subscripts and such a
variable is called Three – dimensional (3D) array.
Syntax
data type array_name [size_of_2d_matrix][row_ size][column_ size];

Initializing 3D Array
Like the one-dimensional arrays, three-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.

int table[2][2][3] = {0,0,0,1,1,1,6,6,6,7,7,7};

This initializes the elements of first two dimensional (matrix) first row to zero’s and the second
row to one’s and second matrix elements are first row to six’s and the second row to seven’s.
 This initialization is done row by row.
 The above statement can be equivalently written as

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


we can also initialize a two – dimensional array in the form of a matrix as
shown. int a[2][3] = {
{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}
};
14
UNIT-V COMPUTER PROGRAMMING
5.6 Strings
The string in C programming language is actually a one-dimensional array of characters
which is terminated by a null character '\0'. Since string is an array, the declaration of a string is
the same as declaring a char array.

char string1[30];
char str2[7] = “String”;

The following declaration creates string named “str2” and initialized with value “String”. To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word.

Declaration and Initialization of Strings


The following declaration and initialization create a string consisting of the word "Hello".

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

Another way of Initialization is (shortcut for initializing string)


char greeting[] = "Hello";

Note: The C compiler automatically places the '\0' at the end of the string when it initializes the
array.

The terminating null (‘\0’) is important, because it is the only way the functions that work with
a string can know where the string ends.

Memory Representation of String


char greeting[] = "Hello";

/* Program to demonstrate printing of a Following program illustrates printing


string */ string using ‘\0’.
int main( ) int main( )
{ {
char name[ ] = “Vijayanand" ; char name[ ] = “Vijayanand" ;
int i = 0 ; int i = 0 ;
while ( i <= 9 ) while ( name[i] != ‘\0’ )
{ {
printf ( "%c", name[i] ) ; printf ( "%c", name[i] ) ;
i++ ; i++ ;
} }
return 0; return 0;
} }

And here is the output... And here is the output...


Vijayanand Vijayanand

15
UNIT-V COMPUTER PROGRAMMING
5.7 Standard Library String Functions
With every C compiler a large set of useful string handling library functions are provided.
For using these functions, we need to include the header file string.h

Function Use
strlen() Finds length of a string
strlwr() Converts a string to lowercase
strupr() Converts a string to uppercase
strcat() Appends one string at the end of another
strcpy() Copies a string into another
strcmp() Compares two strings
strchr() Finds first occurrence of a given character in a string
strstr() Finds first occurrence of a given string in another string
strrev() Reverses the given string

strlen() function
This function counts the number of characters present in a string. Syntax for strlen() function
is given below:
size_t strlen(const char *str);

The function takes a single argument, i.e, the string variable whose length is to be found,
and returns the length of the string passed.

Note: While calculating the length it doesn’t count ‘\0’.

Example 12: C program that illustrates the usage of strlen() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char str[ ] = "Henry" ;
int len1, len2 ;
len1 = strlen ( str ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nThe string %s length is %d", str, len1 ) ;
printf ( "\nThe string %s length is %d\n", "Humpty Dumpty",
len2 ) ; return 0;
}
Output
The string Henry length is 5
The string Humpty Dumpty length is 13

strcpy( ) function
This function copies the contents of one string into another. Syntax for strcpy() function is given
below.
char * strcpy ( char * destination, const char * source );
 Example
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.

16
UNIT-V COMPUTER PROGRAMMING
 If destination string length is less than source string, entire source string value won’t be copied into
destination string.
 For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and remaining 10
characters won’t be copied and will be truncated.

Example 13: C program that illustrates the usage of strcpy() function.


#include<stdio.h>
#include<string.h>
int main()
{
char source[ ] = "Sayonara" ;
char target[20]= "" ;
strcpy (destination, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s",
destination ) ; return 0;
}

Output
Source string = Sayonara
Destinnation string = Sayonara

strcat( ) function
It combines two strings. It concatenates the source string at the end of the destination string.
Syntax for strcat( ) function is given below.

char * strcat ( char * destination, const char * source );

For example, “Bombay” and “Nagpur” on concatenation would result a new string
“BombayNagpur”.

Example 14: C program that illustrates the usage of strcat() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char source[ ] ="Students!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", target ) ;
return 0;
}
Output
Source string = Students!
Destination string = HelloStudents!

strcmp( ) function
It compares two strings to find out whether they are same or different. The two strings
are compared character by character until there is a mismatch or end of one of the strings is
reached, whichever occurs first.

17
UNIT-V COMPUTER PROGRAMMING
If the two strings are identical, strcmp( ) returns a value zero. If they’re not identical, it
returns the numeric difference between the ASCII values of the first non-matching pairs of
characters.
Syntax for strcmp( ) function is given below.

int strcmp ( const char * str1, const char * str2

Return Value from strcmp()


Return Value Description
0 if both strings are identical (equal)
<0 if the ASCII value of first unmatched character is less than second.
>0 if the ASCII value of first unmatched character is greater than second.

Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example 15: C program that illustrates the usage of strcmp() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = Output
"Ferry" ; int i, j, k ; 0 4 -32
i = strcmp ( string1, "Jerry" ) ; j
= strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry
boy" ) ; printf ( "\n%d %d %d", i,
j, k ) ;
}

Example 16: Program for checking string’s palindrome property.


#include<stdio.h>
#include<string.h>
int main()
{ Output:
char str1[25],str2[25]; Enter a string: madam
int d=0; madam is palindrome
printf("\nEnter a string:");
gets(str1); Some other palindrome strings are:
strcpy(str2,str1); civic, dad, malayalam, mom,wow etc.
strrev(str1);
d= strcmp(str1,str2);
if(d==0)
printf("\n%s is
pallindrome",str2); else
printf("\n%s is not a pallindrome",str2);
return 0;
}

5.8 getchar() and putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer.
This function reads only single character at a time. You can use this method in the loop in case
you want to read more than one characters.

18
UNIT-V COMPUTER PROGRAMMING
The putchar() function prints the character passed to it on the screen and returns the
same character. This function puts only single character at a time. In case you want to display
more than one characters, use putchar() method in the loop. #include <stdio.h>

int main( )
{
int ch;
printf("Enter a character:");
ch=getchar();
putchar(ch);
return 0;
}

When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.

5.9 puts() and gets() functions


The gets() function reads a line or multiword string from stdin into the buffer pointed to by s
until either a terminating newline or EOF (end of file).

The puts() function writes the string s and a trailing newline to stdout.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string:");
gets( str );
puts("Hello!");
puts(str);
return 0;
}
Output
Enter a string: prasad Ch
Hello! prasad Ch

Difference between scanf() and gets()

S.No scanf() puts()


1 It reads single word strings It reads multi-word strings
2 It stops reading characters when it It stops reading characters when it
encounters a whitespace encounters a newline or EOF
3 Example: Prasad Example: Prasad ch

19

You might also like