Character Input Output using scanf and printf

In this tutorial, we will understand how to receive characters from the user using the scanf() function, and how to display them on the screen using the printf() function.


Using the scanf and the printf Functions

In our previous tutorials, we learned about two important functions: scanf() and printf(). These functions help us interact with the user and display information on the screen.

To receive different types of input from the user, we use the scanf() function. For example, if we want to get an integer from the user, we use %d as the format specifier. Here’s an example:

int var;
scanf("%d", &var);

In this code, the scanf() function will wait for the user to enter an integer, and then it will store that value in the variable named ‘var’.

Similarly, if we want to receive a single character from the user, we use %c as the format specifier. Here’s an example:

char c;
scanf("%c", &c);

In this case, the scanf() function will wait for the user to enter a character, and it will store that character in the variable named ‘c’.

Now, let’s say we want to display a character on the screen. We can easily do that using the printf() function. Here’s an example:

printf("%c", c);

In this code, the printf() function will display the character stored in the variable ‘c’ on the screen. The format specifier %c tells printf() that we want to print a character.

Remember to use the correct format specifier (%c) when printing a character using printf().


Program to Count the Number of Characters in a Line

Imagine we want to create a program that counts how many characters the user enters in a single line. We want the counting to stop as soon as the user presses the “Enter” or “Return” key, which produces a newline character. To achieve this, we can use loops to repeatedly check for new characters until we encounter the newline character.

This is our first introduction to loops in the program, so let’s take a moment to understand what loops are.

A loop is a way to repeat a specific piece of code multiple times.

For instance, in the example program below, the while loop will run two times in total, resulting in the word “Hello” being printed twice.

#include <stdio.h>

int main() {
    int i = 2;
    while(i > 0) {
        printf("Hello\n");
        i = i - 1;
    }
    return 0;
}

Output:

Hello
Hello

Now, let’s understand why we got the output mentioned above by learning how the while loop works. The basic syntax of a while loop in C is as follows:

while(condition) {
    // statements
} 

The while loop starts with the keyword “while” followed by parentheses. Inside the parentheses, we provide a conditional statement. As long as the conditional statement evaluates to a non-zero value (which is considered as true in C), the statements within the curly braces will be executed repeatedly. When the conditional statement evaluates to zero, the loop stops running.

In our example, the value of i is initially 2, and the condition i > 0 (i.e., 2 > 0) is true. Therefore, the printf statement will be executed, printing "Hello" on the screen, and then i is decremented by 1. This means that i becomes 1. The condition is checked again. Since i is still greater than 0, "Hello" is printed again, and i is decremented once more. This time, i becomes 0, and the condition evaluates to false because i is now equal to zero, which is not greater than zero. As a result, the while loop terminates, and the output is "Hello” printed twice.

Now that we understand how the while loop works, we can proceed to write our program.

The following program counts the number of characters entered by the user.

#include <stdio.h>
int main()
{
    int count = 0;
    char ch;
    scanf("%c", &ch);
    while(ch != '\n') {
        count = count + 1;
        scanf("%c", &ch);
    }
    printf("There are a total of %d characters in the line entered by you.", count);
    return 0;
}

Output:

If the user input is “I love C programming,” the output will be “There are a total of 20 characters in the line entered by you,” which is correct. Let’s understand how we got this output by understanding the logic of our program.

First, we declare and initialize a variable called count to zero. This variable will store the number of characters entered by the user. In the next line, we declare a variable called ch of type char, which will be used to store each character entered by the user.

The scanf function outside the while loop is used to receive the first character from the user. It allows the user to enter the first character, which is ‘I’ in our example. This input is stored in the variable ch using the scanf function.

Next, the while loop is executed. The loop will continue running until the newline character (‘\n’) is received. Since the variable ch holds the character ‘I’, the condition ch != '\n' is true, and the statements inside the body of the while loop will be executed. First, the count variable is incremented by 1, making count equal to 1. Then, the scanf function is used to receive the next character from the user, which is a whitespace character in our example. As long as the condition inside the parentheses is true, we will continue to receive characters from the user. According to our example, the count variable will end up with a value of 20.

After the while loop, the printf function is used to display the number of characters on the screen, resulting in the output mentioned above.


Try it yourself

Question

Can you determine the output of the following program? (Assume that the user input is “C programming language”)

#include <stdio.h>

int main()
{
    int count = 0;
    char ch;
    scanf("%c", &ch);
    while(ch != '\n') {
        count++;
        scanf(" %c", &ch);
    }
    printf("count = %d", count);
    return 0;
}
count = 22
count = 20
Loop will never terminate
None of the above
explanation

Notice that the format string of the scanf function inside the while loop starts with a blank space. In scanf, a blank space means “skip zero or more whitespace characters.” This means that not only blank spaces within the string will be skipped, but the newline character will also be skipped. As a result, the variable ch will never receive a newline character. Therefore, the while loop will never stop executing.



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.