C Program to Concatenate Two Strings

In this example, you will learn to concatenate two strings manually without using the strcat() function.

To understand this example, you should have the knowledge of the following C programming topics:

As you know, the best way to concatenate two strings in C programming is by using the strcat() function. However, in this example, we will concatenate two strings manually.


Concatenate Two Strings Without Using strcat()

#include <stdio.h>
int main() {
    char s1[100] = "programming ", s2[] = "is awesome";
    int i, j;

    // length of s1 is stored in i
    for (i = 0; s1[i] != '\0'; ++i) {
        printf("i = %d\n", i);
    }

    // concatenating each character of s2 to s1
    for (j = 0; s2[j] != '\0'; ++j, ++i) {
        s1[i] = s2[j];
    }

    // terminating s1 string
    s1[i] = '\0';

    printf("After concatenation: ");
    puts(s1);

    return 0;
}

Output

After concatenation: programming is awesome

Here, the strings s1 and s2 and concatenated and the result is stored in s1.

It's important to note that the length of s1 should be sufficient to hold the string after concatenation. If not, you may get unexpected output.