C Program to Concatenate Two Strings without using Library Function

1. Introduction

In this guide, we will learn how to write a C program to concatenate two strings without using the library function.

2. Program Steps

The program endeavors to:

1. Take two strings from the user.

2. Traverse to the end of the first string.

3. Append each character from the second string to the first.

4. Display the concatenated string to the user.

3. Code Program

#include <stdio.h>  // Integrate the Standard I/O library

int main() {  // Commence main function

    char str1[100], str2[100];  // Arrays to store the two strings
    int i = 0, j = 0;  // Counters for string traversal

    // Obtain the strings from the user
    printf("Enter the first string: ");
    scanf("%s", str1);

    printf("Enter the second string: ");
    scanf("%s", str2);

    // Traverse to the end of the first string
    while (str1[i] != '\0') {
        i++;
    }

    // Copy characters of the second string to the end of the first string
    while (str2[j] != '\0') {
        str1[i] = str2[j];
        i++;
        j++;
    }

    str1[i] = '\0';  // Terminate the concatenated string with a null character

    // Display the concatenated string
    printf("Concatenated String: %s\n", str1);

    return 0;  // Terminate the program gracefully

}

Output:

Enter the first string: Hello
Enter the second string: World
Concatenated String: HelloWorld

4. Step By Step Explanation

1. #include <stdio.h>: This line incorporates the standard input/output library.

2. int main(): The execution of the C program starts from main() function.

3. Variable and Array Declaration:

- str1 and str2 are arrays devised to store the user's input strings.- i and j are counters, crucial for string traversal and concatenation.

4. User Input:

- Users are requested to input two strings using print.

- scanf reads and stores two strings in 'str1' and 'str2'.

5. Traversing and Concatenating:

- The first while loop traverses through str1 till its end (null terminator).

- Post this, a second while loop append each character from str2 to the tail of str1.

- Terminate the concatenated string with a null character.

6. Display Results: Display the concatenated string to the user.

Comments