Module - 4

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Introduction to C Programming (BESCK104E)

Module-4
TWO – DMENSIONAL 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
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.

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.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 1


Introduction to C Programming (BESCK104E)

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

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 2


Introduction to C Programming (BESCK104E)

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;i++)
{
scanf(“%d”,&a[i][j]);
}
}

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

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 3


Introduction to C Programming (BESCK104E)

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++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Entered array elements are:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,a[i][j]);
}
}
printf(“\n”);
}
}

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 4


Introduction to C Programming (BESCK104E)

Output:
Enter the number of Rows and Columns of the Array:
22
Enter the Array elements:
1
2
3
4
Entered array elements are:
1 2
3 4

OPERATIONS ON TWO-DIMENSIONAL ARRAYS


We can perform the following operations on a two- dimensional array:
Transpose: Transpose of a m x n matrix A is given as a n x m matrix B where, Bi,j = Aj,i

Sum Two matrices that are compatible with each other can be added together thereby storing the
result in the third matrix. Two matrices are said to be compatible when they have the same
number of rows and columns. Elements of the matrices can be added by writing: Ci,j = Ai,j + Bi,j

Difference Two matrices that are compatible with each other can be subtracted thereby storing
the result in the third matrix. Two matrices are said to be compatible when they have the same
number of rows and columns. Elements of the matrices can be subtracted by writing: Ci,j = Ai,j -
Bi,j

Product Two matrices can be multiplied with each other if the number of columns in the first
matrix is equal to the number of rows in the second matrix. Therefore, m X n matrix A can be
multiplied with a p x q matrix if n = q.
Elements of the matrices can be multiplied by writing:
Ci,j = Σ Ai,k Bj,k for k=1 to k<n.

Write a program to transpose a 3 x 3 matrix.


#include <stdio.h>

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 5


Introduction to C Programming (BESCK104E)

#include <conio . h>


int main ()
{
int i, j, mat [3] [3], transposed_mat [3] [3] ;
clrscr ();
printf ("\n Enter the elements of the matrix" );
printf ("\n **************************" );
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf ("\n mat [%d] [%d] = ",i, j);
scanf ("%d", &mat [i] [j] );
}
}
printf ("\n The elements of the matrix are ");
printf ("\n **************************" );
for (i=0; i<3; i++)
{
printf ("\n");
for (j=0 ; j<3; j++)
printf ("\t mat [%d] [%d] = %d", i, j,mat [i] [j] );
}
for (i=0 ; i<3; i++)
{
for (j =0; j<3; j++)
transposed_mat [i] [j] = mat [j] [i];
}
printf ("\n The elements of the transposed matrix are ");
printf ("\n **************************" );
for (i=0 ; i<3; i++)

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 6


Introduction to C Programming (BESCK104E)

{
printf ("\n");
for (j=0; j<3; j++)
printf ("\t transposed_mat [%d] [%d]=%d", i, j, transposed_mat [i][j]);
}
return 0;
}
Output
Enter the elements of the matrix
**************************
123456789
The elements of the matrix are
**************************
123
456
789
The elements of the transposed matrix are
147
258
369

Write a C program to add 2 matrices A and B and store sum in C.


#include<stdio.h>

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 7


Introduction to C Programming (BESCK104E)

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]);
}
}
printf(“Enter the elements of Matrix B:\n”);
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];
}
}
printf(“The Resultant Matrix C is:\n”);
for(i=0;i<m;i++)
{

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 8


Introduction to C Programming (BESCK104E)

for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
Output
Enter the size of matrix: 2 2
Enter the elements of Matrix A:
1 2
3 4
Enter the elements of Matrix B:
5 6
7 8
The Resultant Matrix C is:
6 8
10 12

Implement Matrix multiplication and validate the rules of multiplication.


# include <stdio.h>
#include<conio.h>
int main()
{
int a[10][10], b[10][10], c[10][10];
int m , n , p , q , i ,j , k;
printf("\n Enter the order of the matrix A :");
scanf("%d %d", &m , &n);
printf("\n Enter the order of the matrix B :");
scanf("%d %d",&p,&q);
if(n == p)

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 9


Introduction to C Programming (BESCK104E)

{
printf("\n Enter the elements of Matrix A \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < n ; j++)
scanf("%d", &a[i][j]);
}
printf("\n Enter the elements of matrix B \n");
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] += a[i][k] * b[k][j];
}
}
}
printf("\n MATRIX A \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < n ; j++)
{
printf(" %d \t", a[i][j]);
}

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 10


Introduction to C Programming (BESCK104E)

printf("\n")
}
printf("\n MATRIX B \n");
for(i = 0 ; i< p ; i++)
{
for(j = 0 ; j < q ; j++)
{
printf(" %d \t", b[i][j]);
}
printf("\n");
}
printf("\n MATRIX C \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < q ; j++)
{
printf(" %d \t", c[i][j]);
}
printf("\n");
}
}
else
printf("Matrix multiplication is not possible");
getch();
return 0;
}

TWO-DIMENSIONAL ARRAYS FOR INTER-FUNCTION COMMUNICATION

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 11


Introduction to C Programming (BESCK104E)

There are three ways of passing parts of the two- dimensional array to a function (process). First,
we can pass individual elements of the array. This is exactly same as passing the elements of a
lD array. Second, we can pass a single row of the 2D array. This is equivalent to passing the
entire ID array to a function. This has already been discussed in the previous section. Third, we
can pass the entire 2D array to the function. Refer Figure which shows the three ways of using
two-dimensional arrays for inter-function communication.

Passing a Row
A row of a 2D array can be passed by indexing the array name with the row number. When we
send a single row of a two-dimensional array, then the called function receives a one-
dimensional array. Figure illustrates how a single row of a 2D array is passed to the called
function

main ( ) // Calling Function


{
int arr [2] [3] = ( (1, 2, 3), (4, 5, 6));
func (arr [1] ) ;
}
void func (int arr []) // Called Function
{
int i;
Calling function
for (i=0; i<5; i++)

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 12


Introduction to C Programming (BESCK104E)

Figure 11.34
printf (" %d", arr [i] * 10) ;
}
Passing the Entire Array
To pass a 2D array to a function, we use the array name as the actual parameter. (The same we
did in case of a 1D array). However, the parameter in the called function must indicate that the
array has two dimensions.

MULTIDIMENSIONAL ARRAYS
A multidimensional array in simple terms is an array of arrays. Like we have one index in a 1D
array, two indices in a 2D array, in the same way we have n indices in an, n-dimensional array or
multi dimensional array. Conversely, an n-dimensional array is specified using n indices. An n-
dimensional m1 X m2 X m3 X ... mn, array is a collection m1 * m2 *m, * m3…… mn elements. In a
multidimensional array, a particular element is specified by using n subscripts as A [I 1] [I2]
[I3] . ..In], where,
I1 <= M1, I2< = M2, I3 <= M3, . In <= Mn
A multidimensional array can contain as many indices as needed and the requirement of the
memory increases with the number of indices used. However, practically Speaking we will
hardly use more than three indices in any program. Figure shows a three-dimensional (3D) array.
The array has three pages, four rows, and two columns.

STRINGS

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 13


Introduction to C Programming (BESCK104E)

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

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.

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

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 14


Introduction to C Programming (BESCK104E)

The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are initialized
with the characters in the order specified.

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:

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:

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.

String Input / Output Functions


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


Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 15
Introduction to C Programming (BESCK104E)

 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);
Output: Enter the name: Rama
The entered name is: Rama

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

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 16


Introduction to C Programming (BESCK104E)

Write a program to display a string using printf ( ).


#include <stdio.h>
#include <conio.h>
main ( )
{
char str [ ] = “Introduction to C”;
clrscr ( );
printf (“\n |%s|", str);
printf (“\n |%20s|", str);
printf (“\n |%-20s|", str);
printf (“\n |%.4s|", str);
printf ("\n |%20.4s|", str);
printf (“\n |%-20.4s|", str);
getch ( );
return 0;
}
Output
|Introduction to C|
| Introduction to C|
|Introduction to C|
|Intr|
| Intr|
|Intr |

Write a program to read and display a string.


#include <stdio.h>
#include <conio.h>
main ( )
{
char str [50] ;
printf ("\n Enter the string: ");

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 17


Introduction to C Programming (BESCK104E)

scanf ("%s", str) ;


clrscr ( );
printf ("\n |%s|", str);
printf ("\n |%20s|", str);
printf ("\n |%-20s|", str);
printf (“\n |%.4s|", str);
printf ("\n |%20.4s|", str);
printf ("\n |%-20.4s|", str);
getch( );
return 0;
}
Output
Enter the string:
|Introduction|
| Introduction|
|Introduction |
|Intr|
| Intr|
|Intr |

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.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 18


Introduction to C Programming (BESCK104E)

 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”);
gets(name);
printf(“The entered name is:\n”);
puts(name);
Output:
Enter the name:
Abdul Kalam
Entered name is:
Abdul Kalam

The sprintf() Function


The library function sprintf ( ) is similar to printf ( ). The only difference is that the formatted
output is written to a memory area rather than directly to a standard output (screen). The sprintf
() function is useful in situations when a formatted string in a memory has to be transmitted over
a communication channel or to a special device.
The syntax of sprintf () can be given as
int sprintf (char * buffer, const char * format [, argument ,...] );

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 19


Introduction to C Programming (BESCK104E)

Here, buffer is the place to store the resulting string from using the function. The argument
command is an ellipsis so you can put as many types of arguments as you want. Finally, the
format is the string that contains the text to be printed. The string may contain format tags.
#include < stdio.h>
main ( )
{
Char buf [100];
int num = 10;
sprintf (buf, “ num = %3d”, num);
}

STRING TAXONOMY
In C, we can store a string either in fixed-length format or in variable length format as shown I
figure

Figure: String Taxonomy


Fixed-length string When storing a string in a fixed- length format, you need to specify an
appropriate size for the string variable. If the size is too small, then you will not be able to store
all the elements in the string. On the other hand, if the string size is large, then unnecessarily
memory space will be wasted.
Variable-length string A better option is to use a variable-length format in which the string can
be expanded or contracted to accommodate the elements in it. For example, if you declare a
string variable to store the name of a student. If a student has a long name say 20 characters, then

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 20


Introduction to C Programming (BESCK104E)

the string can be expanded to accommodate 20 characters. On the hand, a student name has only
5 characters, then the string variable can be contracted to store only 5 characters. However, to
use a variable-length string format you need a technique to indicate the end of elements that are a
part of f the string. This can be done either by using length-controlled string or a delimiter.
Length-controlled string In a length-controlled string. you need to specify the number of
characters in the string. This count is used by string manipulation functions to determine the
actual length of the string variable.
Delimited string In this format, the string is ended with a delimiter. The delimiter is then used to
identify the end of the string. For example, in English language every sentence is ended with a
full-stop. Similarly, in C we can use any character such as comma, semicolon, colon, dash, null
character, etc. as the delimiter of a string, However, the null character is the most commonly
used string delimiter in the C language.

STRING OPERATIONS
In this section, we will learn about different operations that are performed on character arrays.
Length
The number of characters in the string constitutes the length of the string. For example,
LENGTH ("C PROGRAMMING IS FUN") Will return 20. Note that even blank spaces are
counted as characters in the string. LENGTH(0) = 0 and LENGTH (' ') = 0 because both the
strings do not contain any character and the ASCII code of \0 is zero. Therefore, both the strings
are empty and of zero length.
Algorithm to calculate length of a string
Step 1: [INITIALIZE] SET I = 0
Step 2: Repeat Step 3 while STR[I] != ‘\0’
Step 3: SET I =I+1
[END OF LOOP]
Step 4: SET LENGTH = I
Step 5: END

In this algorithm, I is used as an index of the string STR. to traverse each and every character of
STR we increment the value of I. Once the null character is encountered, the control jumps out

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 21


Introduction to C Programming (BESCK104E)

of the while loop and initializes LENGTH with the value of I. This is because the number of
characters in the string constitutes its length.

Write a program to find the length of a string.


#include <stdio.h>
#include <conio.h>
int main ()
{
char str [100] , i= 0, length;
clrscr ();
printf ("\n Enter the string :") ;
gets (str) ;
while (str [i] != ‘\0’)
i++;
length = i;
printf ("\n The length of the string is :%d", length);
getch ();
}
Output
Enter the string: HELLO
The length of the string is: 5

Converting Characters of a String into Upper Case


We have already seen that in memory the ASCII codes are stored instead of the real value. The
ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97 to 123. So if
we have to convert a lower case character to upper case, then we just need to subtract 32 from
the ASCII value of the character.
Algorithm to convert characters of a string into upper case
Step1: [Initialize] SET I=0
Step 2: Repeat Step 3 while STR[I] != ‘\0’
Step 3: IF STR [I] > 'a' AND STR[I] < ‘z’

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 22


Introduction to C Programming (BESCK104E)

SET Upperstr [I] = STR[I] – 32


ELSE
SET Upperstr [I] = STR[I]
[END OF IF]
[END OF while LOOP]
Step 4: SET Upperstr [I] = ‘\0’
Step 5: EXIT

In the algorithm, we initialize I to zero. Using as the index of STR. we traverse each character
from Steps 2 to 3. If the character is already in upper case, then it s copied in the Upperstr string
else the lower case character is converted into upper case by subtracting 32 from its ASCII value.
The upper case character is then stored in Upperstr. Finally, when all the characters have been
traversed a null character is appended to the Upperstr (as done in Step 4).

Write a program to convert characters of a string to upper case


#include <stdio.h>
#include <conio.h>
int main ()
{
char str [100] , upper_str [100];
int i=0, j=0;
clrscr ();
printf(\n Enter the string:");
gets (str);
while (str [i]!= "\0")
{
if (str [i] >="a" && str [i] <="z ")
upper_str [j] = str [i] -32;
else
upper_str [i] = str[i];
i++; j++;

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 23


Introduction to C Programming (BESCK104E)

}
Upper_str [j] = "\O";
printf ("\n The string converted into upper case is : ");
puts (upper_str) ;
return 0;
}
Output
Enter the string: hello
The string converted into upper case is: HELLO

Converting Characters of a String into Lower Case


We have already seen that in memory the ASCII codes are stored instead of the real value. The
ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z ranges from 97 to 123. So if
we have to convert a upper case character to lower case, then we just need to add 32 to ASCII
value.
Algorithm to convert characters of a string into lower case
Step1: [Initialize] SET I=0
Step 2: Repeat Step 3 while STR[I] != ‘\0’
Step 3: IF STR [I] > 'A' AND STR[I] < ‘Z’
SET Lowerstr [I] = STR[I] + 32
ELSE
SET Lowerstr [I] = STR[I]
[END OF IF]
[END OF while LOOP]
Step 4: SET Lowerstr [I] = ‘\0’
Step 5: EXIT

In the algorithm, we initialize I to zero. Using as the index of STR. we traverse each character
from Steps 2 to 3. If the character is already in upper case, then it s copied in the Lowerstr string
else the upper case character is converted into lower case by adding 32 to its ASCII value. The

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 24


Introduction to C Programming (BESCK104E)

lower case character is then stored in Lowerstr. Finally, when all the characters have been
traversed a null character is appended to the lowerstr (as done in Step 4).

Write a program to convert characters of a string to upper case


#include <stdio.h>
#include <conio.h>
int main ()
{
char str [100] , lower_str [100]:
int i=0, j=0;
clrscr ();
printf(\n Enter the string:");
gets (str);
while (str [i]!= "\0")
{
if (str [i] >="A" && str (i] <="Z ")
lower_str [j] = str [i] +32;
else
lower_str [i] = str[i];
i++; j++;
}
lower_str [j] = "\O";
printf ("\n The string converted into lower case is : ");
puts (lower_str) ;
return 0;
}
Output
Enter the string: HELLO
The string converted into upper case is: hello

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 25


Introduction to C Programming (BESCK104E)

Concatenating Two Strings to form a New String


If S1 and S2 are two strings, then concatenation operation produces a string which contains
characters of S1 followed by the characters of S2.
Algorithm to concatenate two strings
Step 1: Initialize I=0 and J=0
Step 2: Repeat Step 3 to d while I <= LENGTH(str1)
Step 3: SET new_strl[J] = strl [I]
Step 4: Set I=I+l and J=J+1
[END of Step 2]
Step 5: SET I=0
Step 6: Repeat Steps6 to 7 while I <= LENGTH (str2)
Step 7: SET new_ str [J] = str1[I]
Step 8: Set I = I+l and J= J+1
[END OE step 5]
Step 9: SET new_str [J] =’\0’
Step l0: EXIT
In this algorithm, we first initialize the two counters I and J to zero. To concatenate the strings,
we have to copy the contents of the first string followed by the contents of the second string in a
third string, new_str. Steps 2 to 4 copy the contents of the first string in the new_str. Likewise,
Steps 6 to 8 copy the contents of the second String in the new str. After the contents have been
copied a null character is appended at the end of the new str.

Write a program to concatenate two strings.


#include <stdio.h>
#include <conio.h>
int main ()
{
char str1 [100] , str2 [100] , str3 [100] ;
ínt i=0, j=0;
clrscr ( );
printf ("\n Enter the first string :") ;

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 26


Introduction to C Programming (BESCK104E)

gets (str1) ;
printf ("\n Enter the second string : ");
gets (str2) ;
while (str1 [i] != ‘\0’)
{
str3 [j] = str1 [i];
i++;
j++;
}
i = 0;
while (str2 [i] != ‘\0’)
{
str3 [j]= str2 [i] ;
i++;
j++;
}
str3 [j] = ‘\0’;
printf ("\n The concatenated string is:") ;
puts (str3) ;
getch ();
return 0;
}
Output
Enter the first string : Hello,
Enter the second string: How are you?
The concatenated string is: Hello, How are you?
Appending Strings
Appending one string to another involves copying the contents of the source string at the end of
the destination string. For example, if S1 and S2 are two strings, then appending S1 to S2 means
we have to add the contents of S1 to S2. Here S1 is the source string and S2 is the destination

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 27


Introduction to C Programming (BESCK104E)

string. The appending operation would leave the source string S1 unchanged and the destination
string S2 = S2 + S1.
Algorithm to append two strings
Step 1: (Initialize] SET I =0 and J=0
Step 2: Repeat Step 3 while Dest_Str [I] != ‘\0’
Step 3: SET I+I+1
[END OF LOOP]
Step 4: Repeat Steps 5 to 7 while Source Str [J]!= ‘\0’
Step 5: Dest_Str [I] = Source_Str[J]
Step 6: SET I =I+1
Step 7: SET J=J+1
[END OF LOOP]
Step 8: SET Dest_Str[J] = ‘\0’
Step 9: EXIT
In this algorithm, we first traverse through the destination string to reach its end, i.e., reach the
position where a null character is encountered. The characters of the source string are then
copied in to the destination string starting from that position. Finally, a null character is added to
terminate the destination string.
Write a program to append a string to another string
#include <stdio. h>
#include <conio.h>
main ( )
{
char Dest_Str [100] , Source_Str [50] i
int i = 0, j = 0;
clrscr( );
printf ("\n Enter the source string : ");
gets (Source_Str) ;
printf ("\n Enter the destination string:");
gets (Dest Str);
while (Dest_Str [i] != ‘\0’)

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 28


Introduction to C Programming (BESCK104E)

i++;
while (Source_Str [j] != ‘\0’)
{
Dest_Str [i] = Source_Str [j] ;
i++;
j++;
}
Dest_Str (i] = ‘\0';
printf ("\n After appending, the destination string is: ");
puts (Dest_Str) ;
getch ();
return 0;
}
Output
Enter the source string: How are you?
Enter the destination string: Hi,
After appending, the destination string is: Hi, How are you?

Comparing two strings


If S1 and S2 are two strings then comparing two strings will give either of these results:
(a) SI and S2 are equal
(b) S1> S2, when in dictionary order S1 will come after S2
(c) S1< S2, when in dictionary order S1 precedes S2
To compare the two strings, each and every character is compared from both the strings. If all the
characters are same then the two strings are said to be equal.

In this algorithm, we first check whether the two strings are of same length. If not, then there is
no point in moving ahead as it straightaway means that the two strings are not same. However, if
the two strings are of the same length, then we compare character by character to check if all the
characters are same. If yes, then variable SAME is set to 1 else if SAME = 0, then we check
which string precedes the other in dictionary order and print the corresponding message.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 29


Introduction to C Programming (BESCK104E)

Algorithm to compare two strings


Step 1: [Initialize] SET I=0, SAME =0
Step 2 : SET Lenl = Length (STR1), Len2 = Length (STR2)
Step 3: IF len1 != len2, then
Write "Strings Are Not Equal "
ELSE
Repeat while I<Len1
IF STR1 [I] == STR2 [I]
SET I =I+1
ELSE
Go to Step 4
[END OF IF]
[END OF LOOP]
IF I =Len1, then
SET SAME = 1
Write "Strings are equal"
[END OF IF]
Step 4: IF SAME = 0, then
IF STR1 [I] > STR2 [I], then
Write "String1 is greater than String2”
ELSE IF STR1 [I] < STR2 [I], then
Write "String2 is greater than String1"
[END OF IF]
[END OF IF]
Step 5: EXIT

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 30


Introduction to C Programming (BESCK104E)

Write a program to compare two strings.


#include <stdio.h>
#include <conio.h>
#include <string.h>
main()
{
char strl [50] , str2 [50];
int i = 0, lenl = 0, len2 = 0, same = 0;
clrscr();
printf ("\n Enter the first string : ");
gets (strl);
printf ("\n Enter the second string : ");
gets (str2) ;
lenl = strlen(strl);
len2 = strlen (str2);
if (lenl == len2)
{
while (i < lenl)
{
if (str1 [i] == str2 [i])
i++;
else break;
}
if (i == len1)
{
same= l;
printf ("\n The two strings are equal”);
}
}
if (lenl ! =len2)
printf(\n The two strings are not equal");

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 31


Introduction to C Programming (BESCK104E)

if (same == 0)
{
if (strl[i] >str2 [i])
printf (\n String1 is greater than string2);
else if (strl [i] <str2 [i] )
printf (“\n String2 is greater than string1” ):
}
getch ():
return 0;
}
Output
Enter the first string: Hello
Enter the second string: Hello
The two strings are equal

Reversing a String
If S1 = "HELLO", then reverse of S1 = "OLLEH". To reverse a string we just need to swap the
first character with the last, second character with the second last character, and so on.
Algorithm to reverse a string
Step l: [Initialize] SET I=0, J= Length (STR)
Step 2: Repeat Step 3 and 4 while I< Length (STR)
Step 3: SWAP (STR(I), STR(J))
Step 4: SET I =I+1, J=J-1
[END OF LOOP]
Step 5: EXIT
In Step 1, I is initialized to zero and J is initialized to the length of the string STR. In Step 2, a
while loop is executed until all the characters of the string are accessed. In Step 3, we swap the ith
character of STR with its jth character. (As a result, the first character of STR will be replaced
with the last character, the second character will be replaced with the second last character of
STR, and so on). In Step 4, the value of I is incremented and J is decremented to traverse STR in
the forward and backward direction, respectively.

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 32


Introduction to C Programming (BESCK104E)

Write a program to reverse the given string.


#include <stdio.h>
#include <conio.h>
#include <string.h>
int main ()
{
char str [100] , reverse_str [l00] , temp;
int i = 0, j = 0;
clrscr ( ) ;
printf ("\n Enter the string: ");
gets (str);
j=strlen (str) -1;
while (i<j)
{
temp = str [j] ;
str [j] = str[il ;
str [i] = temp ;
i++;
j--;
}
printf ("\n The reversed string is: ") ;
puts (str);
getch ();
return 0;
}
Output
Enter the string: Hi there
The reversed string is: ereht iH

Mr. Sandeep S H, Asst. Prof, Dept. of ME., GMIT, Dvg. Page 33

You might also like