Ascii Name
QUESTION DESCRIPTION
Write a program which reads your name from the keyboard and outputs a list of ASCII codes, which represent your name
TEST CASE 1
INPUT
SRMUNIVERSITY
OUTPUT
OUTPUT
The ASCII values of the string are:
83 82 77 85 78 86 69 82 83 73 84 89
Solution :
#include <stdio.h>
int main(){
char input_str[1000];
scanf("%s",input_str); // taking input
printf("The ASCII values of the string are:\n"); // print mandatory line
for(int i=0;input_str[i]!='\0';i++){
printf("%d ",(int)(input_str[i])); // convert and print in the same line
}
return 0;
}Problem Description
You need to write a program that reads a string (name) from the keyboard and outputs the ASCII values of each character in that string.
Solution Approach
To achieve this:
- Read the input string from the user.
- Convert each character in the string to its corresponding ASCII value.
- Print the ASCII values in a formatted manner.
Detailed Explanation
Input Handling:
scanf("%s", input_str);reads the input string from the user. This function reads a string until it encounters a whitespace or newline.Output Header:
printf("The ASCII values of the string are:\n");prints a header to indicate the output format.Character Processing:
- The
forloop iterates through each character of the string.input_str[i] != '\0'checks if the current character is not the null terminator (end of the string).(int)(input_str[i])converts the character to its ASCII value andprintf("%d ", ...)prints it.Formatting:
- The ASCII values are printed in a single line, separated by spaces.
Edge Cases and Considerations
- Empty Input: If the input string is empty, the output will just be the header line with no ASCII values.
- Long Strings: Ensure that the array size
input_stris large enough to handle the input string.Conclusion
The provided C code effectively converts each character of a string to its ASCII value and prints it in a formatted manner. It uses basic string operations and formatted output to achieve the task.