Home / Programs / Concatenate Two Strings Without Using strcat()
🚀 Programming Example

Concatenate Two Strings Without Using strcat()

👁 539 Views
💻 Practical Program
📘 Step Learning

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

  • C Arrays
  • C Programming Strings
  • C for Loop

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.

💻 Program Code

#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;
}
                        

🖥 Program Output

After concatenation: programming is awesome
                            

📘 Explanation

Here, two 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.