Below is a program to copy string using strcoy() function with step-by-step explanation.
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = “C programming”;
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}
Output-
C programming
Step-by-step explanation of a program.
- Include header files The program starts by including two important header files:
stdio.handstring.his needed for input-output operations, whilestring.his needed for string manipulation functions. - Declare variables The program declares two character arrays named
str1andstr2, each with a length of 20 characters.str1is initialized with the string “C programming”, whilestr2is left uninitialized. - Copy
str1tostr2usingstrcpyThestrcpyfunction from thestring.hlibrary is used to copy the contents ofstr1intostr2. Thestrcpyfunction takes two arguments: the destination string (str2in this case), and the source string (str1in this case). After thestrcpyfunction is called,str2will contain the same string asstr1. - Print the result The
putsfunction is used to print the contents ofstr2to the console. Theputsfunction takes one argument: the string to be printed (str2in this case). - End the program The
returnstatement at the end of the program returns a value of0to the operating system, indicating that the program has executed successfully.
Overall, this program demonstrates how to copy a string using the strcpy function in C. The strcpy function can be useful when you need to make a copy of a string in memory, or when you need to manipulate a string without affecting the original.
Once you have written the code, you can compile and run it using a C compiler, such as GCC, on your computer. The program will then display output on the screen when executed.
For more information about C programming join our course of C programming.