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;
}
Output-
strcmp(str1, str2) = 1
strcmp(str1, str3) = 0
Check the explanation of the program step-by-step.
- Include header files The first two lines of the program tell the compiler to include two important header files:
stdio.h
andstring.h
. These files contain functions that the program needs to work properly. - Define the
main
function Themain
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 (()
). - 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
, andstr3
) and initialize them with strings. We also declare an integer variable calledresult
, which we will use later to store the result of the string comparison. - Compare strings using
strcmp
Now we get to the interesting part of the program, where we use thestrcmp
function to compare the three strings we declared earlier.strcmp
is a function from thestring.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 comparestr1
andstr2
, and thenstr1
andstr3
. We store the result of each comparison in theresult
variable. - Print the result Finally, we print the result of each comparison using the
printf
function. We use a format string to print the value ofresult
for each comparison. - 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.