Introduction
In this lab, you will learn how to use the strcmp() function in C language to compare two strings and perform different operations based on the comparison result.
Compare String Using Conditional Statements
In this lab, you will learn how to compare strings using conditional statements.
Create a file named
conditional-statements.cand open it in WebIDE.Copy the following code into the file:
#include <stdio.h> #include <string.h> void main(){ int n1, n2, result; char operator[10]; printf("Enter first number: "); scanf("%d",&n1); printf("Enter second number: "); scanf("%d",&n2); printf("Enter operation name (add or sub): "); scanf("%s",operator); if(strcmp(operator,"add") == 0) result = n1 + n2; else if(strcmp(operator,"sub") == 0) result = n1 - n2; else result=0; printf("The result is : %d\n\n\n",result); }Save the file.
Compile the code using the following command in the terminal:
gcc conditional-statements.c -o conditional-statementsRun the compiled program using the following command:
./conditional-statementsEnter the first number when prompted and press enter.
Enter the second number when prompted and press enter.
Enter the operation name (
addorsub) when prompted and press enter.The program will compare the entered operation name to perform either addition or subtraction based on the comparison result.
The program will then display the result.
Summary
After completing this lab, you will be able to compare strings using conditional statements in C and perform different operations based on the comparison result.



