Call us at 0700-922-6559 or Click here

Write a program to compare a string.

Below is a program to compare a string in C language with step-by-step explanations.

#include <stdio.h>

#include <string.h>

int main() {

  char str1[] = “abcd”, str2[] = “abCd”, str3[] = “abcd”;

  int result;

  // comparing strings str1 and str2

  result = strcmp(str1, str2);

  printf(“strcmp(str1, str2) = %d\n”, result);

  // comparing strings str1 and str3

  result = strcmp(str1, str3);

  printf(“strcmp(str1, str3) = %d\n”, result);

  return 0;



strcmp(str1, str2) = 1

strcmp(str1, str3) = 0

Check the explanation of the program step-by-step.

  1. Include header files The first two lines of the program tell the compiler to include two important header files: stdio.h and string.h. These files contain functions that the program needs to work properly.
  2. Define the main function The main function is the starting point of the program. It’s where the program begins and where it ends. This function is defined as returning an integer (int) value and taking no arguments (()).
  3. Declare variables In this part of the program, we declare the variables we need to store the strings and the result of the comparison. We declare three character arrays (str1, str2, and str3) and initialize them with strings. We also declare an integer variable called result, which we will use later to store the result of the string comparison.
  4. Compare strings using strcmp Now we get to the interesting part of the program, where we use the strcmp function to compare the three strings we declared earlier. strcmp is a function from the string.h header file that compares two strings and returns an integer value that indicates whether the strings are equal or not. In this program, we first compare str1 and str2, and then str1 and str3. We store the result of each comparison in the result variable.
  5. Print the result Finally, we print the result of each comparison using the printf function. We use a format string to print the value of result for each comparison.
  6. End the program The last line of the program is return 0;, which ends the program and returns a value of 0 to the operating system. This indicates that the program executed successfully.

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 *