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.h
andstring.h
is needed for input-output operations, whilestring.h
is needed for string manipulation functions. - Declare variables The program declares two character arrays named
str1
andstr2
, each with a length of 20 characters.str1
is initialized with the string “C programming”, whilestr2
is left uninitialized. - Copy
str1
tostr2
usingstrcpy
Thestrcpy
function from thestring.h
library is used to copy the contents ofstr1
intostr2
. Thestrcpy
function takes two arguments: the destination string (str2
in this case), and the source string (str1
in this case). After thestrcpy
function is called,str2
will contain the same string asstr1
. - Print the result The
puts
function is used to print the contents ofstr2
to the console. Theputs
function takes one argument: the string to be printed (str2
in this case). - End the program The
return
statement at the end of the program returns a value of0
to 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.