C Program to Concatenate Two Strings Using strcat

cprogramming-Logo
C Programming Examples
C String Programs
C Loop Programs
C Function Programs
C Array Programs
C Integer Number Programs
C File I/O Programs

This C program is used to concatenate strings by using strcat() function.

Program to Concatenate Strings using strcat()

Program:
#include <stdio.h>
#include <string.h>

int main()
{
    char a[100], b[100];
    
    printf("Enter the first string\n");
    gets(a);
    
    printf("Enter the second string\n");
    gets(b);
    
    strcat(a,b);
    
    printf("String obtained on concatenation is %s\n",a);
    
    return 0;

}
Program Output:

string-concatenation-c

Explanation:

This program is used to concatenate two given strings as a single set of strings using the function strcat(). So first of all, you have to include the stdio header file using the "include" preceding # which tells that the header file needs to be process before compilation, hence named preprocessor directive. Also, you have to include the string.h header file. The string.h header classifies one variable type, one macro, and various functions to manipulate arrays of characters within your program.

Then you have to define the main() function and it has been declared as an int as it is going to return an integer type value at the end of the program. The inside the main() function, you have to take two character arrays name as a[] and b[] having 100 consecutive memory location. You have to use the printf() function for displaying the message - "Enter the first string" to the screen. The statement gets(a); will fetch a set of characters the form of a string and store them in the array a[]. Similarly another printf for displaying the second message - "Enter the second string" and so the second string will also get fetched from the keyboard using gets() and stored in character array b[]. Then comes the use of strcat() which is abbreviated as string concatenation, and is having syntax as: char *strcat(dest, src), where 'dest' defines the destination array (here in this program 'a'), which should contain a string and should be larger for containing the concatenated resulting string.

'src' also contains a string (here in this program 'b') for appending and should not overlap the dest string. And lastly the return 0; statement is used to return an integer type value back to main().


Scroll Back to Top