Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to Concatenate two String

C Code Example — String Programs

ADVERTISEMENT

C Program to Concatenate two String

Objective

Write a C program to concatenate (join) two strings manually.

Algorithm / Approach

  1. Read two strings: a (the base string) and b (the string to append).
  2. Run a loop to find the end of the first string: while(a[i] != '\0') i++;.
  3. Run a second loop to copy characters from b into a starting at index i.
  4. After copying, append the null terminator: a[i] = '\0'.
main.c
#include<stdio.h>
int main( ) {
 char a[100],b[100];
 int i=0, j=0;
 printf("Enter 1st String : ");
 gets(a);
 printf("Enter 2nd String : ");
 gets(b);
 while(a[i] != '\0') {
  i++;
 }
 while(b[j] != '\0') {
  a[i]= b[j];
  i++; 
  j++;
 }
 a[i] = '\0';
 i=0;
 printf("After Concat : ");
 while(a[i] !='\0') {
 printf("%c",a[i]);
 i++;
 }
 return 0;
}

Expected Output

Enter 1st String : C Programming 
Enter 2nd String : Prowess
After Concat : C ProgrammingProwess

Explanation of the Program

  • Concatenation is the process of appending one string to the tail end of another string (mimicking the built-in strcat() function).
  • To do this, we first must find the exact memory index where the first string ends. We then start writing the second string's characters directly over the top of the first string's null terminator, expanding its length.

Complexity

Time Complexity O(n + m) - Where n is the length of first string and m is the length of the second.
Space Complexity O(1) - Assuming the first array has enough capacity.
ADVERTISEMENT