How to compare ASCII values in C?
#include<stdio.h> int main() { int num = 65; // ASCII value of 'A' char ch = 'B'; // ASCII value of 'B' if(num == ch) { printf("The values are equal\n"); } else { printf("The values are not equal\n"); } return 0; }
How to compare ASCII values in C?Explain:
Certainly! Let’s go through the code step by step to explain its functionality:
#include<stdio.h>
: This line is a preprocessor directive that tells the compiler to include the standard input/output library, which provides functions likeprintf()
andscanf()
.int main()
: This line defines the main function, which is the entry point of the program. It returns an integer value (in this case, 0) to indicate the execution status of the program.int num = 65;
: This line declares an integer variable namednum
and initializes it with the value 65. In ASCII, 65 corresponds to the character ‘A’.char ch = 'B';
: This line declares a character variable namedch
and assigns it the value ‘B’. In ASCII, ‘B’ corresponds to the integer value 66.if(num == ch) { ... } else { ... }
: This line begins an if-else statement. It compares the value ofnum
withch
using the==
operator, which checks for equality.printf("The values are not equal\n");
: Ifnum
andch
are not equal, this line is executed. It uses theprintf()
function to print the message “The values are not equal” to the console.return 0;
: This line indicates the end of themain()
function and returns the value 0 to the operating system, indicating successful execution of the program.
To summarize, the code compares the ASCII value of the integer num
(65) with the ASCII value of the character ch
(‘B’, which corresponds to 66). Since these values are not equal, the program will output “The values are not equal” to the console.