Call us at 0700-922-6559 or Click here

Write a program to copy string using strcpy().

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;



C programming

Step-by-step explanation of a program.

  1. Include header files The program starts by including two important header files: stdio.h and string.h is needed for input-output operations, while string.h is needed for string manipulation functions.
  2. Declare variables The program declares two character arrays named str1 and str2, each with a length of 20 characters. str1 is initialized with the string “C programming”, while str2 is left uninitialized.
  3. Copy str1 to str2 using strcpy The strcpy function from the string.h library is used to copy the contents of str1 into str2. The strcpy function takes two arguments: the destination string (str2 in this case), and the source string (str1 in this case). After the strcpy function is called, str2 will contain the same string as str1.
  4. Print the result The puts function is used to print the contents of str2 to the console. The puts function takes one argument: the string to be printed (str2 in this case).
  5. End the program The return statement at the end of the program returns a value of 0 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.

Leave a Reply

Your email address will not be published. Required fields are marked *