Complementary task for topic: 1
M Nemeth · 2023-08-29 15:21:04.605220'
scanf: char
scanf: char
Task: Determine the ASCII value of a character:
Write a C program that prompts the user to enter a character using scanf() and determines its ASCII value. Display the ASCII value using printf().
Hint: You need to use %c to scan characters
Solution
#include
int main() {
char character;
printf("Enter a character: ");
scanf(" %c", &character);
int asciiValue = character;
printf("The ASCII value of the character %c is %d.\n", character, asciiValue);
return 0;
}
Explanation
In this example, the program uses printf() to prompt the user to enter a character. The scanf() function is used to scan the input from the user and store it in the character variable. Note the space before %c in scanf to consume any leading whitespace characters before reading the character. The program determines the ASCII value of the character by assigning it to an int variable asciiValue, which automatically converts the character to its corresponding ASCII value. Finally, it uses printf() to display the ASCII value in the specified format.