C program concatenate two strings without using string function

C program to concatenate two strings without using string function(strcat)

This C program is to concatenate two strings without using string function(strcat).For example str1=’code’ and str2=’dost’ then on concatenation the string would be ‘codedost’.

Logic

We first find the length of first string using the 1st while loop.Then we use another while loop and append the 2nd string to the first string,we start appending after the last character of 1st string.

Dry Run of the Program

Take input str1 and str2.Let us take str1=code and str2 =dost.

1st while loop

1st iteration while(str1[i]!=’\0′) i.e. while(str1[o]!=’\0′)

i++;  hence i=1;

2nd iteration while(str1[i]!=’\0′) i.e. while(str1[1]!=’\0′)

i++;  hence i=2;

3rd iteration while(str1[i]!=’\0′) i.e. while(str1[2]!=’\0′)

i++;  hence i=2;

4th iteration while(str1[i]!=’\0′) i.e. while(str1[3]!=’\0′)

i++;  hence i=3;

Now 1st while loop ends here as i=4 is null.

2nd while loop

1st iteration while(str2[j]!=’\0′)  i.e. while(str2[0]!=’\0′)

str1[i]=str2[j]; i.e. str1[4]=str2[0];  i.e. str1[4]=d;

j++; i.e. j=1

i++;  i.e. i=5

2nd iteration while(str2[j]!=’\0′)  i.e. while(str2[1]!=’\0′)

str1[i]=str2[j]; i.e. str1[4]=str2[1];  i.e. str1[5]=o;

j++; i.e. j=2

i++;  i.e. i=6

3rd iteration while(str2[j]!=’\0′)  i.e. while(str2[2]!=’\0′)

str1[i]=str2[j]; i.e. str1[4]=str2[0];  i.e. str1[6]=s;

j++; i.e. j=3

i++;  i.e. i=7

4th iteration while(str2[j]!=’\0′)  i.e. while(str2[3]!=’\0′)

str1[i]=str2[j]; i.e. str1[4]=str2[0];  i.e. str1[7]=t;

j++; i.e. j=4

i++;  i.e. i=8;

2nd while loop ends here as str2[4] is equal to null.

Hence we get output as codedost.

Program

#include<stdio.h>

void main()
{
  char str1[50],str2[50];
  static int i=0;
  int j=0;
  printf("\nEnter First String\n");
  gets(str1);
  printf("\nEnter Second String\n");
  gets(str2);
  while(str1[i]!='\0')
  {
    i++;
  }

  while(str2[j]!='\0')
  {
    str1[i]=str2[j];
    j++;
    i++;
  }
  str1[i]='\0';
  printf("\nConcatenated String is %s",str1);
}

Output

Share Me!