C Program to Concat Two Strings without Using Library Function
Program : C Program to Concat Two Strings without Using Library Function
Program Statement :
In this C Program we have to accept two strings from user using gets and we have to concatenate these two strings without using library functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include<stdio.h> #include<string.h> void concat(char[], char[]); int main() { char s1[50], s2[30]; printf("\nEnter String 1 :"); gets(s1); printf("\nEnter String 2 :"); gets(s2); concat(s1, s2); printf("nConcated string is :%s", s1); return (0); } void concat(char s1[], char s2[]) { int i, j; i = strlen(s1); for (j = 0; s2[j] != '\0'; i++, j++) { s1[i] = s2[j]; } s1[i] = '\0'; } |
Output of Program :
1 2 3 |
Enter String 1 : Pritesh Enter String 2 : Taral Concated string is : PriteshTaral |
Explanation of Code :
Our program starts from main and we are accepting two strings from user using these following statements -
1 2 3 4 |
printf("\nEnter String 1 :"); gets(s1); printf("\nEnter String 2 :"); gets(s2); |
Inside the concate() function we are firstly calculating the size of first string.
1 |
i = strlen(s1); |
Now we are iterating 2nd string character by character and putting each character to the end of the 1st string.
Explanation of Program With Dry Run :
Step 1 : Input
1 2 |
s1 = "Pritesh" s2 = "Taral" |
Step 2 : Size of Strings
1 2 3 |
i = strlen(s1); = strlen("Pritesh"); = 7 |
Step 3 : Concatenating Strings
1 |
Last position of s1 = 7 |
First Character of the 2nd String will be stored at last Position of String 1. thus using for loop -
1 2 3 4 5 |
s1[7] = "T" s1[8] = "a" s1[9] = "r" s1[10] = "a" s1[11] = "l" |