Scanf exercise implementation
Exercise:
Write a Program which takes 6 characters (alphabets, numbers, and special characters) from the user and prints the ASCII codes of the entered characters.
First, create variables.
char c1, c2, c3, c4, c5, c6; //These are the variables to hold those characters.
After that, use the printf to send the message to the user.
printf(“Enter any 6 characters of your choice:”);
And after that, let’s use scanf to read the inputs. We are going to read 6 inputs, so 6 characters. The format specifier will be %c. Let’s give space after one format specifier. I mentioned the 6 format specifier here. After that &c1,&c2,&c3,&c4,&c5,&c6.
scanf(“%c %c %c %c %c %c”, &c1,&c2,&c3,&c4,&c5,&c6);
After that, let’s print the ASCII codes. ASCII code is a number, so which format specifier do you use to print a number. You can use %d (for signed integers) or %u(if it is unsigned). So, I can use %d or %u here, but I would use %u here because, anyway the codes are they are unsigned numbers.
Let me give \n at the beginning, type ASCII codes, and give the format specifier %u 6 times. After that, let’s print the value of these variables.
Printf(“\nASCII codes : %u,%u,%u,%u,%u,%u”,c1,c2,c3,c4,c5,c6);
The code is shown below.
#include<stdio.h> int main(void) { char c1,c2,c3,c4,c5,c6; printf("Enter any 6 characters of your choice :"); scanf("%c %c %c %c %c %c",&c1,&c2,&c3,&c4,&c5,&c6); printf("\nASCII codes : %u,%u,%u,%u,%u,%u",c1,c2,c3,c4,c5,c6); printf("\nPress enter key to exit the application \n"); while(getchar() != '\n') { //just read the input buffer and do nothing } getchar(); }
Output:
Enter any 6 characters of your choice, and I entered a space, b space, c space, d space, 1 space, and % sign. Press Enter key. It shows the ASCII codes of the entered characters(Figure 1). So, this is the correct result.
I want to give another assignment to you. So, modify this code. The output should be the same, but instead of using scanf use getchar().
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1