program to merge two strings in c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], result[200];
printf("Enter the first string: ");
gets(str1);
printf("Enter the second string: ");
gets(str2);
strcpy(result, str1);
strcat(result, str2);
printf("The merged string is: %s\n", result);
return 0;
}
Explanation
Include the necessary header files:
stdio.h
for input/output operations andstring.h
for string manipulation functions.Define the main function which is the entry point of the program.
Declare three character arrays:
str1
,str2
, andresult
. These arrays will store the first string, second string, and the merged string, respectively. The sizes of these arrays are set to 100 characters, but you can adjust them as per your requirements.Prompt the user to enter the first string using the
printf
function.Use the
gets
function to read the first string from the user and store it in thestr1
array. Note thatgets
is not a safe function to use as it may cause buffer overflow. It is recommended to usefgets
instead.Prompt the user to enter the second string using the
printf
function.Use the
gets
function to read the second string from the user and store it in thestr2
array.Use the
strcpy
function from thestring.h
library to copy the contents ofstr1
intoresult
. This will initializeresult
with the first string.Use the
strcat
function from thestring.h
library to concatenatestr2
toresult
. This will append the second string to the end ofresult
.Print the merged string using the
printf
function.Return 0 to indicate successful program execution.