Accepting user input from the console in a C program

Hey there!

Welcome to ClearUrDoubt.com.

In this post, we will look at a C program to accept user input from the console and print it back on the console.

Here is the C program:

 

Output:

 

 

 

 

 

 

 

 

Let’s go through each line and explore the details.

These lines declare the datatypes of the variables. the variables a, b and c are declared as an integer, a floating point, and a char array type respectively.

 

Like “printf()” function, “scanf()” is also an inbuilt function defined in “stdio.h”. this function will read the input entered on the console by the user and stores the value in the memory location pointed by the corresponding argument. Here “a” is a variable and “&a” denotes the memory location it points to. Similarly “b” and “&b”, “c” and “&c” denote variables and their memory locations.

The “%d”, “%f” & “%s” are called Control Strings in C language. They denote integer, floating point, and character string datatypes respectively.

The format of a Control String:

%[width][.precision][modifier]type

width:  specifies the number characters it has to read/write

precision: specifies the number of characters that need to be printed after the precision

modifier:  specifies the additional info on the type i.e., if the type is an integer (%i or %d) the applicable modifiers are [h, l]. %hd denotes it is a short int and %ld denotes it is a long int.

 

We are going to print the user input values on the console using Control Strings in the printf() method. As shown in the output, the control string “%.2f”, will print only two decimal points after the precision by rounding up the value.

 

We have covered the explanation of other lines in the below post. Happy Learning.!! 🙂

“Hello World..!” program in C

Please leave a reply in case of any queries.

Leave a Reply

Your email address will not be published.