Education

Scanf in c – The Basics of C Programming – Computer

Scanf in c

Scanf in c

The scanf function permits you to take input from standard input the case of us, which is usually the keyboard. The Scanf in c function is able to do many tasks, but is not reliable because it can’t deal with human error very efficiently. For simple programs, it’s sufficient and easy to use.

The most basic use to scanf is as follows:

scanf("%d", and b);

The program will interpret an integer value which the user inputs via the keyboard (%d is used for integers, like printf, and it is necessary to declare b as an integer) and insert that value into the b.

The scanf function employs the same placeholders for printf.

  • int makes use of the %d
  • float employs the %f
  • char employs the %c
  • string of characters (discussed in a future post) make use of the %s

It is necessary to put the letters & before the variable in scanf. The reason for this will become evident once you are familiar with points. It’s easy to lose the symbol and sign, and if you do, your program will most likely fail when you try to run it.

In general, it’s ideal to use scanf, like this — to read one keystroke. Make multiple scanf calls to read different values. In every real program you’ll be using the functions gets or Fgets functions to read lines of text at one time. You will then “parse” the text to identify its data. The reason you do that is so that you can find mistakes in the input and take care of them as you see best.

The functions of printf and scanf may require some practice before you are completely able to comprehend them However, once you have mastered them, they can be very useful.

Try This!

Modify the program to ensure that it can accept three values instead of just two and adds all three values together:

#include <stdio.h>

int main()
{
    int a, b, c;
    printf("Enter the first value:");
    scanf("%d", &a);
    printf("Enter the second value:");
    scanf("%d", &b);
    c = a + b;
    printf("%d + %d = %d\n", a, b, c);
    return 0;
}

It is also possible to delete the b variable from the initial line in this program to observe what the compiler does if you do not declare the variable. Remove a semicolon, and then observe what happens. Remove any braces. Take out one of the parentheses that are next to the primary function. Create each error on its own and test the code through the compiler and observe what happens. When you simulate errors similar to these, you will be able to learn about the different compiler errors and this makes your mistakes more easy to identify in the event that you attempt to make them real.

Most Popular

To Top