In this tutorial you will learn about the C Program to Concatenate Two Strings and its application with practical example.
C Program to Concatenate Two Strings
In this tutorial, we will learn to create a C program that will Concatenate Two Strings in C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Using Strings in C Programming.
What is a string?
As we all know, the string is a collection of characters, symbols, digits, and blank spaces. In strings, only one variable is declared which can store multiple values.
What is Concatenation?
Concatenation means to join two different words i.e. multiple Strings into a single string value.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking input string 1 and 2 from the user. 3. Concatinating the string from the taken variable. 4. Printing the result string. 5. End the program. |
Program to Concatenate Two Strings:-
First will take the input string one from the user. Then we will take a second-string from the user and now we will concatenate that two stings. And at last, will print the resultant string.
Using the below program example.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/* C Program to Concatenate Two Strings */ #include <stdio.h> int main() { //Declaring the required variables for the program. char string1[20]; // declaration char array1 char string2[20]; // declaration char array2 int i=0,j=0; // integer variables declaration char *str1; // of char pointer declaration char *str2; // char pointer declaration str1=string1; str2=string2; //Taking Input From the user printf("Enter the first string\n"); scanf("%s",string1); printf("\nEnter the second string\n"); scanf("%s", string2); while(string1[i]!='\0') { ++str1; i++; } while(string2[j]!='\0') { *str1=*str2; str1++; str2++; j++; } printf("The concatenated string is %s",string1); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- string1[20] = it will hold the string value.
- string2[20] = it will hold the string value.
- i = it will hold the integer value.
- j = it will hold the integer value.
- *str1 = pointer type variable 1.
- *str2 = pointer type variable 2.
Input strings from the user.
While loop body for concatenating the strings using the pointers and printing the concatenated string.