C Program to concatenate two strings

Category: C Program

C Program to concatenate two strings using loop or strcat string function in C language. How to concatenate two strings in C language. Logic to concatenate two strings. 1. using loop 2. strcat string function

1. C Program to concatenate two strings using loop

#include <stdio.h>

void main()
{
  char str1[100], str2[50];
  int i=0, j;

  printf("Enter first string: ");
  gets(str1);
  printf("Enter second string: ");
  gets(str2);

  while (str1[i] != '\0')
    i++;

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

  str1[i] = '\0';

  printf("After concatenation: %s", str1);
}

2. C Program to concatenate two strings using strcat function

#include <stdio.h>
#include <string.h>

void main()
{
  char str1[100], str2[50];
  int i=0, j;

  printf("Enter first string: ");
  gets(str1);
  printf("Enter second string: ");
  gets(str2);

  strcat(str1, str2);

  printf("After concatenation: %s", str1);
}

Output

Enter first string: pro
Enter second string: coding
After concatenation: procoding

Recommended Posts