Concatinating Two Strings

void main()
char a[25],b[25];
int i, j, k=1;
puts(“Enter the string A”);
puts(“Enter the string B”);


The program is about concatenating two string , the program successfully concatenates the strings but also prints some garbage value after the two string why so?

I think it is because you are running the loops upto 25 characters and not breaking at the end of the string. i would suggest just add a break inside the for loop to exit when you encounter ‘\0’

As @kcahdog pointed out correctly, the loops should not run for a fixed number of times. But, they should run until you encounter the '\0' character.

Concatenating two strings means, not just printing them out together. It means producing a string that contains the contents of the two given strings one after the another. Of course, for just printing, this is enough. But in case you need further processing, below is the code to concatenate two strings. The function takes two strings as arguments, and adds the second string to the end of the first. The first string is assumed to have enough memory allocated to accommodate the concatenated string.

void concatenate(char a[], char b[])
	int i, j;
	for (i = 0; a[i] != '\0'; ++i)
	for (j = 0; b[j] != '\0'; ++j)
		a[i++] = b[j];
	a[i] = '\0';

Of course, there are other ways (which are more efficient and optimized) to write this, but as a basic version, this will suffice.

For the above example, the main will look something like this.

int main()
	char a[63], b[63];
	concatenate(a, b);
	printf("%sn", a);
	return 0;