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

Unit 3

Uploaded by

srmarteru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views30 pages

Unit 3

Uploaded by

srmarteru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

INTRADUCTION TO PROGRAMMING UNIT-III

UNIT-III
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.
 A value in an array is identified by index or subscript enclosed in square brackets with
array name.
 The individual data items can be integers, floating point numbers, and characters and so
on, but they must be the same type and same storage class.
 Arrays can be classified into
(i) One-Dimensional arrays
(ii) Two-Dimensional arrays
(iii) Multi-Dimensional arrays

One Dimensional Array:


 For maintaining a list of items in C, we can declare an array with a single subscript like
a[i] .Such arrays with only a single subscript are known as one dimensional arrays.
 Common uses of one dimensional arrays are:
to maintain a list of numbers,
to maintain the list of marks,
to maintain a list of student names etc.

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

Page 1
INTRADUCTION TO PROGRAMMING UNIT-III

Fig. memory representation of an array of elements


1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
element element element element element element element element element element
marks[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

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

Storing Values in Array(or) Initialization of 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:
syntax
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};

Page 2
INTRADUCTION TO PROGRAMMING UNIT-III

 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};
 If the number of values in initializer-is less than the size of an array, only those many first
locations of the are assigned the values. The remaining locations are assigned zero.
Example: int a[9]={1, 2, 3, 4};

1 2 3 4 0 0 0 0 0

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8]

 If the number of values listed within initialize- list for an array is greater than the size of
the array, compiler raises error.
Example: int a[5]={1, 2, 3, 4, 5, 6, 7, 8, 9};
 If the static array is declared without initialize- list then all locations are set to zero.
Example: static int a[9];

0 0 0 0 0 0 0 0 0

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8]

 If the size is omitted in a 1-d array declaration, which is initialized, the compiler will
supply this value by examining the number of values in the initialize-list.
Example: int a[]={1, 2, 3, 4, 5, 6, 7, 8, 9};

1 2 3 4 5 6 7 8 9

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8]

 Array elements cannot be initialized selectively. An attempt initialize only 2nd location is
illegal.
Example: int a[6]={, 6]; is illegal.

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

Page 3
INTRADUCTION TO PROGRAMMING UNIT-III

Input values from keyboard (or) reading values to Array


 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.
 This method of reading initialization of values is called dynamic initialization or
initialization at run time
 For example:
int i ,marks[10];
for (i=0; i<10; i++)
scanf(“%d”,&marks[i]);

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

Page 4
INTRADUCTION TO PROGRAMMING UNIT-III

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

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:

Page 5
INTRADUCTION TO PROGRAMMING UNIT-III

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

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

Page 6
INTRADUCTION TO PROGRAMMING UNIT-III

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

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.
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");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);

Page 7
INTRADUCTION TO PROGRAMMING UNIT-III

}
/* bubble sort logic starts from here */
for(i=0;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("Sorted elements .... \n");
for(i=0;i<n;i++)
printf("%3d",a[i]);
printf("\n");
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
Sorted elements ....
5 9 14 15 23

Page 8
INTRADUCTION TO PROGRAMMING UNIT-III

Two Dimensional Arrays


 The array with two sub scripts termed as two dimensional array.
 2-d arrays are used in situation where a table of values needs to be stored in an array.
 These can be defined in the same fashion as in one dimensional array, except a separate
pair of square brackets is required for each subscript.
 Two pairs of square brackets required for two dimensional array and three pairs
required for three dimensional arrays and so on.
 Two dimensional arrays are stored in a row-column matrix, where the left index
indicates the row and the right indicates the column.
Declaring 2-D Array
A two-dimensional array is declared as:
data_type array_name[row_size][column_size];

Example: int a[3],[3];


Column numbers
1 2 3

1 a[0][0] a[0][1] a[0][2]

2 a[1][0] a[1][1] a[1][2]

3 a[2][0] a[2][1] a[2][2]

- a[0][0] refers to data item in the first row and first column.
-a[0][2] refers to data item in the first row and third column.
-a[2][3] refers to data item in the second row and third column.
-a[3][3] refers to data item in the third row and third column.

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

Page 9
INTRADUCTION TO PROGRAMMING UNIT-III

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

Input values from keyboard (or) reading values to 2d Array


Since the 2D array contains two subscripts, we will use two for loops to read the elements. The
first for loop will read each row in the 2D array and the second for loop will read individual
columns for every row in the array
 For example:
int i ,j ,a[10[10];
for (i=0; i<10; i++)
for(j=0;j<10;j++)
scanf(“%d”,&a[i][j]);
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.
 For example:
int i ,j ,a[10[10];
for (i=0; i<10; i++)
for(j=0;j<10;j++)
printf(“%d”,&a[i][j]);

Operations on 2d arrays:
Write a C program to perform addition or subtraction of two matrices
PROGRAM:

#include<stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
printf("enter the rows and columns for a & b matrices\n");
scanf("%d%d",&m,&n);
printf("Enter the First matrix->");
for(i=0;i<m;i++)
{
Page 10
INTRADUCTION TO PROGRAMMING UNIT-III

for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix->");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j]; // for subtract, use minus (-) instead of plus (+) sign
}
}
printf("\nThe Addition of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",c[i][j]);
}
return 0;
}
OUTPUT:
enter the rows and columns for a & b matrices
2
2
Enter the first matrix->1
2
3
4
Enter the second matrix->1
2
3
4
The Addition of two matrix is
2 4
6 8

Page 11
INTRADUCTION TO PROGRAMMING UNIT-III

Write a C program to perform multiplication of two matrices


PROGRAM:

#include<stdio.h>
#include<conio.h>
int main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q,k;
printf("enter the rows and columns for matrix a\n");
scanf("%d%d",&m,&n);
printf("enter the rows and columns for matrix b\n");
scanf("%d%d",&p,&q);
if ( n != p )
{
printf("matrix multiplcation is not possible");
}
else
{
printf("Enter the First matrix->");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix->");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++) ‘
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];

Page 12
INTRADUCTION TO PROGRAMMING UNIT-III

}
}
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<q;j++)
{
printf("%d\t",c[i][j]);
}
}
}
return 0;
}

OUTPUT:
Enter the rows and columns of matrix a
2
2
Enter the rows and columns of matrix b
3
2
Matrix multiplication is not possible

Enter the rows and columns of matrix a


2
2
Enter the rows and columns of matrix b
2
2
Enter the First matrix->1 2 3 4
Enter the Second matrix->1 2 3 4
The multiplication of two matrix is
7 10
15 22

Page 13
INTRADUCTION TO PROGRAMMING UNIT-III

Write a C program to print the transpose of a given matrix


#include <stdio.h>
int main()
{
int a[10][10],trans[10][10];
int rows, cols, i, j;
/* read the size of a matrix */
printf("Enter number of rows and columns:");
scanf("%d%d", &rows,&cols);
/* Read the elements of matrix */
printf("Enter elements of matrix\n");
for(i=0; i<rows;i++)
for(j=0; j<cols;j++)
{
printf("Enter a[%d][%d]=",i,j);
scanf("%d",&a[i][j]);
}
/* Display the matrix A */
printf("The Matrix A\n");
for(i=0; i<rows;i++)
{
for(j=0; j<cols; j++)
printf("%3d",a[i][j]);
printf("\n");
}
/* Change rows into columns and columns into rows */
for(i=0;i<cols;i++)
{
for(j=0;j<rows;j++)
trans[i][j] = a[j][i];
}
/* Display the transpose matrix */
printf("Transpose of a given matrix\n");
for(i=0;i<cols;i++)
{
for(j=0;j<rows;j++)
printf("%3d",trans[i][j]);
printf("\n");
}
return 0;
}

Page 14
INTRADUCTION TO PROGRAMMING UNIT-III

Output
Enter number of rows and columns: 3 3
Enter elements of matrix
Enter a[0][0]=4
Enter a[0][1]=7
Enter a[0][2]=3
Enter a[1][0]=9
Enter a[1][1]=5
Enter a[1][2]=2
Enter a[2][0]=6
Enter a[2][1]=1
Enter a[2][2]=8
The Matrix A
4 7 3
9 5 2
6 1 8
Transpose of a given matrix
4 9 6
7 5 1
3 2 8

Write a c program to find row average and column average of a table or matrix
#include<stdio.h>
int main()
{
int i, j, rows, columns, a[10][10];

printf("Please Enter Number of rows and columns : ");


scanf("%d %d", &i, &j);

printf("Please Enter the Matrix Row and Column Elements \n");


for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
scanf("%d", &a[rows][columns]);
}
}
AddColumns(a,i,j);
AddRows(a,i,j);
return 0;

Page 15
INTRADUCTION TO PROGRAMMING UNIT-III

}
void AddColumns(int arr[10][10], int i, int j)
{
int rows, columns, Sum = 0;
float Avg;
printf("THE AVERAGE OF EACH COLUMN OF GIVEN MATRIX IS\n");
for(columns = 0; columns < j; columns++)
{
Avg=0;
for(rows = 0; rows < i; rows++)
{
Sum = Sum + arr[rows][columns];
}
Avg=Sum/i;
printf("The average of %d Column Elements in a Matrix = %f \n",columns, Avg );
}
}
void AddRows(int arr[10][10], int i, int j)
{
int rows, columns, Sum = 0;
float Avg;
printf("THE AVERAGE OF EACH ROW OF GIVEN MATRIX IS\n");
for(rows = 0; rows < i; rows++)
{
Avg=0;
for(columns = 0; columns < j; columns++)
{
Sum = Sum + arr[rows][columns];
}
Avg=Sum/i;
printf("The average of %d row Elements in a Matrix = %f \n",rows, Avg );
}
}

OUTPUT

Please Enter Number of rows and columns : 3 3


Please Enter the Matrix Row and Column Elements
123
456
789

Page 16
INTRADUCTION TO PROGRAMMING UNIT-III

THE AVERAGE OF EACH COLUMN OF GIVEN MATRIX IS

The average of 0 Column Elements in a Matrix = 4.000000

The average of 1 Column Elements in a Matrix = 9.000000

The average of 2 Column Elements in a Matrix = 15.000000

THE AVERAGE OF EACH ROW OF GIVEN MATRIX IS

The average of 0 row Elements in a Matrix = 2.000000

The average of 1 row Elements in a Matrix = 7.000000

The average of 2 row Elements in a Matrix = 15.000000

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.
SYNTEX
datatype array_name [s1][s2][s3] ......... [sn];

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
datatype 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] = {
Page 17
INTRADUCTION TO PROGRAMMING UNIT-III

{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}
}
/* Program to accept the elements of a 3-d array and display them */
#include<stdio.h>
main()
{
int a[2][3][3], i, j k;
printf(“Enter the elements of matrix a of order 2*3*3(two tables of sizes 3*3) \n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
for(k=0;k<3;k++)
scanf(“%d”, &a[i][j][k]);
}
printf(“ The 3-d array a \n”);
for(i=0;i<2;i++)
{
printf(“a-table %d \n”, i+1);
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
printf(“%3d”, a[i][j][k]);
printf(“\n”);
}
printf(“\n”);
}
getch();
}

Page 18
INTRADUCTION TO PROGRAMMING UNIT-III

Strings In C
 In ‘C’ language the group of characters, digits and symbols enclosed within
quotation marks are called as strings
 otherwise strings are array of characters.
 Null character (‘\0’) is used to mark the end of the string.
 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.

V A H I N I \0

65512 65512 65512 65512 65512 65512 65512

Initialization of Strings
char name[ ]="VAHINI";
char name[]= {’V’, ‘A’ ,’H’ ,’I’ ,’N’ ,’I’,’\0’};
The characters of the string are enclosed within a pair of double quotes.
The initialization of NULL character is not essential because the C compiler inserts the
NULL (\0) character automatically at the end of the string.
Reading And Writing String
The '%s' control string can be used in scanf() statement to read a string from the terminal
and the same may be used to write string to the terminal in printf() statement.
char s[10];
scanf(“%s”,s);
printf(“%s”,s);
scanf() function can only read a string upto a single space character .
To read the string including space charecters we use functions like getchar(), gets()
i.e to read a line of text we use getchar() or gets() functions

Commom operations on strings:


 Reading and writing a string
 Combining or concatenation of two strings
 Copying one string to another
 Comparing strings for equality
 Finding length of a string
 Reverse the content of string
 etc

Page 19
INTRADUCTION TO PROGRAMMING UNIT-III

Programs On Common Operations On Strings:

Write A C Program To COMPARING Of Two Strings Without Using Library Functions

#include<stdio.h>
int main()
{
char s1[ 20], s2[20 ];
int i=0;
printf (“enter string 1”);
gets(s1);
printf (“enter string 2”);
gets(s2);
while((s1[i]==s2[i]) && s1[i]!=’\0’ && s2[i]!=’\0’)
{
i=i+1;
}

Page 20
INTRADUCTION TO PROGRAMMING UNIT-III

if(s1[i]==’\0’ && s2[i]==’\0’)


printf(“two strings are equal”);
else
printf(“two strings are not equal”);
return 0;
}

Output :
Enter string1 hello
Enter string2 hello
Two strings are equal.

Write A C Program To COPY content of one Strings to another string Without Using Library
Functions

#include<stdio.h>
int main()
{
char s1[ 20], s2[20 ];
int i=0;
printf (“enter string 1”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
s2[i]=s1[i];
}
s2[i]=’\0’;
printf(“copied string is %s”,s2);
return 0;
}

Output
Enter string 1 hello
Copied string is hello

Page 21
INTRADUCTION TO PROGRAMMING UNIT-III

Write A C Program To Find LENGTH Of A String Without Using Library Functions

#include<stdio.h>
int main()
{
char s1[ 20];
int i=0,length=0;
printf (“enter string 1”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
length=length+1;
}
printf(“length of string is %d”,length);
return 0;
}

Output
Enter string 1 hello
Length of string is 5

Write A C Program To Find REVERSE Of A String Without Using Library Functions

#include<stdio.h>
int main()
{
char s1[ 20];
int i=0,j,length=0;
printf (“enter string 1”);
gets(s1);
for(i=0;s1[i]!=’\0’;i++)
{
length=length+1;
}
i=0
j=length;
while(i<j)
{
temp=s1[i];
s1[i]=s1[j-1];
s1[j-1]=temp;

Page 22
INTRADUCTION TO PROGRAMMING UNIT-III

i++;
j--;
}
printf(“reverse of string is %s”,s1);
return 0;
}
Output
Enter string 1 hello
reverse of string is olleh

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 Syntax (or) Example Description

strcpy() strcpy(string1, string2) Copies string2 value into string1

strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1

strlen() strlen(string1) returns total number of characters in string1

strcat() strcat(string1,string2) Appends string2 to string1

strncat() strncat(string1, string2, 4) Appends first 4 characters of string2 to string1

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if string1>string2

strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by ignoring case (upper
or lower)

Page 23
INTRADUCTION TO PROGRAMMING UNIT-III

Function Syntax (or) Example Description

stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case (similar
to strcmpi())

strlwr() strlwr(string1) Converts all the characters of string1 to lower case.

strupr() strupr(string1) Converts all the characters of string1 to upper case.

strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to string1

strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of character 'b' in string1

strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of character 'b' in string1

strstr() strstr(string1, string2) Returns a pointer to the first occurrence of string2 in string1

strset() strset(string1, 'B') Sets all the characters of string1 to given character 'B'.

strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given character 'B'.

strrev() strrev(string1) It reverses the value of string1

Strlen() Function
This function counts the number of characters present in a string. Syntax for strlen() function is
given below:
int strlen(string);
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 : C program that illustrates the usage of strlen() function.

Page 24
INTRADUCTION TO PROGRAMMING UNIT-III

#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.
strcpy ( destination, source );
Example
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2

 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 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
Page 25
INTRADUCTION TO PROGRAMMING UNIT-III

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.
strcat ( destination, source );

For example, “Bombay” and “Nagpur” on concatenation would result a new string
“BombayNagpur”.
Example : 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.

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 ( str1, 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.

Page 26
INTRADUCTION TO PROGRAMMING UNIT-III

Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example : C program that illustrates the usage of strcmp() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
Example : Program for checking string’s palindrome property.
#include<stdio.h>
#include<string.h>
int main()
{
char str1[25],str2[25];
int d=0;
printf("\nEnter a string:");
gets(str1);
strcpy(str2,str1);
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;
}

strstr() Function
The strstr() function searches the given string in the specified main string and returns the
pointer to the first occurrence of the given string.
Syntax:
strstr(str, searchString)
str – The string to be searched.
searchString – The string that we need to search in string str

Page 27
INTRADUCTION TO PROGRAMMING UNIT-III

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


#include <stdio.h>
#include <string.h>
int main ()
{
const char str[20] = "Hello, how are you?";
const char searchString[10] = "you";
char *result;
result = strstr(str, searchString);
printf("The substring starting from the given string: %s", result);
return 0;
}
Output:
The substring starting from the given string: you?

Example : c program to count number of lines, words,characters in given text.


#include<stdio.h>
#include<string.h>
int main()
{
char str[25],;
int I,words=0,chars=0,lines=0;
printf("\nEnter text:");
while(1)
{
gets(str);
if(str[0]==’\0’)
break;
else
{
Words++;
for(i=0;str[i]!=’\0’;i++);
if(s[i]=’ ‘||s[i]=’\t’)
words++;
}
lines++;
chars=chars+strlen(str);
}
Printf(“characters=%d,words=%d,lines=%d”,chars,words,lines);
return 0;
}

Page 28
INTRADUCTION TO PROGRAMMING UNIT-III

Input/Output
These statements are used to Input/Output a single/group of characters from/to the
input/output devices. Here the user cannot specify the type of data that is going to be
input/output.
Input and Output Functions
(1) Unformatted Input/Output Statements:
Input Output
getc( ); putc( );
getchar( ); putchar( );
gets( ); puts( );
(2) Formatted Input/Output Statements:
Input Output
scanf( ); printf( );
fscanf( ); fprintf( );
getc() Function
This is used to accept a single character from the standard input to a character variable.
Syntax character variable=getc();
Description Character variable is the valid 'c' variable of the type of char data type
Example char c;
c=getc();
putc() Fucntion
This is used to display a single character in a character variable to standard output device.
Syntax putc (character variable);
Description Character variable is the valid 'c' variable of the type of char data type
Example char c;
putc(c);
gets & puts Function
The gets () function is used to read the string (string is a group of characters) from the
standard input device (keyboard).
The puts () function is used to display/write the string to the standard output device
(Monitor).
/* Program using gets() and puts() function */
#include<stdio.h>
main()
{
char stu_name[40];
puts("Enter Name:");

Page 29
INTRADUCTION TO PROGRAMMING UNIT-III

gets(stu_name); /* gets the character from keyboard */


puts("Print the Name:");
puts(stu_name);
}
Single Character I/P Function:
getchar(): getchar() is used to read a character from the terminal, the syntax is-
ch=getchar();
A Single character can be given to the computer using 'C' input library function getchar().
where, ch is a variable of char type. As a result of this, a character types at the terminal is
assigned to the variable ch. This can be used repeatedly to accept a line of characters.
Single Character I/O Function:
putchar() is the counterpart of getchar(). It is used to display a character on the monitor. It
takes the general form of putchar(ch);
which ch represents a variable type char or a character constant. It displays the character
stored in ch on the monitor. The putchar() function is used to display one character at a
time on the standard output device. This function does the reverse operation of the single
character input function.

Page 30

You might also like