C Program to Concatenate Two Strings

In this post, we will learn how to concatenate two strings using the C Programming language.

Concatenation, in the context of programming, is the process of joining two strings together. For example: two strings hello and world after concatenation becomes helloworld.

We will be writing a manual logic to concatenate two strings.

So, without further ado, let’s begin this tutorial.

C Program to Concatenate Two Strings

// C Program to Concatenate Two Strings
#include <stdio.h>
int main(){
    char first[25], second[25];
    int i, j;
    
    // Asking for input
    printf("Enter the first string: ");
    scanf("%s", first);
    printf("Enter the second string: ");
    scanf("%s", second);
    
    // Concatenating two strings
    i = 0;
    while (first[i] != '\0'){
        i++;
    }
    for (j = 0; second[j] != '\0'; ++j, ++i){
        first[i] = second[j];
    }
    first[i] = '\0';
    
    // Displaying output
    printf("After concatenation: %s", first);
    return 0;
}

Output

Enter the first string: Coding
Enter the second string: Broz
After concatenation: CodingBroz

How Does This Program Work ?

    char first[25], second[25];
    int i, j;

In this program, we have declared some char data type variables and some int data type variables.

    // Asking for input
    printf("Enter the first string: ");
    scanf("%s", first);
    printf("Enter the second string: ");
    scanf("%s", second);

Then, the user is asked to enter the first and the second string.

    i = 0;
    while (first[i] != '\0'){
        i++;
    }

This is used to store the length of the first string in the i variable.

    for (j = 0; second[j] != '\0'; ++j, ++i){
        first[i] = second[j];
    }

This loop statement concatenates the second string at the end of the first string.

    // Displaying output
    printf("After concatenation: %s", first);

Finally, the string after concatenation is displayed on the screen using printf() function.

Conclusion

I hope after going through this post, you understand how to concatenate two strings using C Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *