Concatenate Two Strings in C Program

What we are going to see through this article is we will see in detail about Concatenate Two Strings in C Program. Modifying strings is an important programming skill. Concatenation involves appending one string to the end of another string.

Concatenate Two Strings in C Program

Concatenate Two Strings in C

In the following program user would be asked to enter two strings and then the program would concatenate them.

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

  // store length of s1 in the length variable
  length = 0;
  while (s1[length] != '\0') {
    ++length;
  }

  // concatenate s2 to s1
  for (j = 0; s2[j] != '\0'; ++j, ++length) {
    s1[length] = s2[j];
  }

  // terminating the s1 string
  s1[length] = '\0';

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

  return 0;
}

Execution of the Program

length = 0;
  while (s1[length] != '\0') {
    ++length;

After that concatenate s1 and s2 using for loop. The result is stored in s1 string. We can terminate the s1 value to get the output.

// concatenate s2 to s1
  for (j = 0; s2[j] != '\0'; ++j, ++length) {
    s1[length] = s2[j];
  }

  // terminating the s1 string
  s1[length] = '\0';

Read Also;Divide Two Numbers in C Program

Output

After concatenation: programming is awesome

Final Words

What we learned through this article is that we clearly know Concatenate Two Strings in C Program. you benefit everyone who shared this article with their friends.

Leave a Comment