C program to concatenate strings using pointers

 Ex: Write a C program to concatenate strings using pointers. How to write a C program to concatenate strings using pointers. C program to concatenate strings using pointers.



Input from user:

Enter first string:

codefor

Enter second string:

hunger


Expected output:

Concatenated string:

codeforhunger




  Step by step logic of the given program:


1. Accept two strings from user declare variables say str1 and str2.


2. Run while loop till end of first string:

while(*s1)

     {

  s1++;

     }


3. Run while loop till end of second string and inside the while loop copy second string to first string:

while(*s2)

        {

*s1=*s2;

s1++;

s2++;

}


4. After that end first string with NULL(\0).


5. Last, print concatenated string str1.




  C program to concatenate two strings using pointers:


#include<stdio.h>

#define max 100//declare max size 100

int main()

{

char str1[max],str2[max];

        /*declare pointers for str1 and str2*/

char *s1=str1,*s2=str2;

printf("Enter first string:\n");

gets(str1);

printf("Enter second string:\n");

gets(str2);

while(*s1)/*till end of the first string*/

{

s1++;/*point to the next character*/

}

while(*s2)/*till end of the second string*/

{

*s1=*s2;

s1++;

s2++;

}

/*Make sure that str1 end with NULL*/

    *s1='\0';

    printf("Concatenated string is:\n%s",str1);

return 0;

}



Above program shows the following output:


C program to concatenate strings using pointers



No comments:

Post a Comment

If you have any doubts, please discuss here...👇