Article



Jun
20
2013

C Programming – Ch: 007 – Receiving Inputs in C

Babu
Posted 1 years 153 days ago ago by Babu     
  • Currently 0.00/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  
 


Receiving Inputs in C

In the previous chapter, we created a simple interest calculator. We assigned the values 1000, 5 and 3.5, to principle amount, number of years and rate of interest respectively. Every time you run the program, you get the same value for simple interest. If we wanted to calculate the simple interest for a different set of values, then we had to make changes to the code and recompile it.

There wasn’t any way a user can calculate the simple interest for a different set of values without changing code and recompiling it. If a program has to be useful to others, then it should ask them to enter the values using their keyboard and calculate the simple interest for the user supplied values.

So far in this course, you have learned to send output to the computer’s screen by printing data using printf() function. Let me show you how to receive input from the users using scanf() function.

In this chapter, let us enhance our simple interest calculator program by allowing the user to key in Principle amount, number of years and rate of interest.

scanf()

scanf() function is a counter-part of the printf() function. While the printf() outputs the values to the screen, scanf() receives the values from the keyboard.

scanf() is another built in function provided by the standard input output library <stdio.h>, to read standard input from the keyboard and to store it in previously declared variables. The format for using scanf() function is

scanf("format specifier", variable);

The format specifier tells scanf() how to treat the incoming data.

Sample: 007_01.c : Enhanced simple interest calculator below. Execute it and try it. Remove the line numbers before executing the program.

 

   1: // Name: 007_01.c
   2: // Description: Sample demonstrating scanf().
   3: //              Extension of simple interest calculator to accept user input.
   4:  
   5: #include "stdio.h"
   6: main()
   7: {
   8:     int principleAmt = 0;
   9:     int NoOfYears = 0;
  10:     float rateOfInterest = 0, simpleInterest = 0;
  11:  
  12:     //Accepting Data
  13:     printf("Enter the Principle Amount : ");    // Principle Amount prompt
  14:     scanf("%d", &principleAmt);                  // read an integer
  15:  
  16:     printf("Enter the Loan duration : ");       // Loan duration prompt
  17:     scanf("%d", &NoOfYears);                     // read an integer
  18:  
  19:     printf("Enter the Rate of Interest : ");    // Principle Amount prompt
  20:     scanf("%f", &rateOfInterest);                // read an floating point number
  21:  
  22:     simpleInterest = (principleAmt * NoOfYears * rateOfInterest) / 100;
  23:  
  24:     //Printing Variable contents
  25:     printf("\n\nYou entered \nPrincipleAmt = %d\nNoOfYears = %d\nrateOfInterest = %f\n\n", principleAmt, NoOfYears, rateOfInterest);
  26:     printf("The simple interest is %f.\n", simpleInterest);
  27: }

The comments in lines 1-3 states the name and description of the program.

You can notice the changes in the following lines of code compared to the earlier version.

   8:     int principleAmt = 0;
   9:     int NoOfYears = 0;
  10:     float rateOfInterest = 0, simpleInterest = 0;

All the four variables are declared and initialized together. Two variables are of type integer and the remaining two are of type float. The lines 8 & 9 could have also been combined as below

   8:     int principleAmt = 0, NoOfYears = 0;
   9:     
  10:     float rateOfInterest = 0, simpleInterest = 0;

The lines from 13 to 20 prompt the user to enter data and also reads & stores the data into its respective variables.

 

  12:     //Accepting Data
  13:     printf("Enter the Principle Amount : ");    // Principle Amount prompt
  14:     scanf("%d", &principleAmt);                  // read an integer
  15:  
  16:     printf("Enter the Loan duration : ");       // Loan duration prompt
  17:     scanf("%d", &NoOfYears);                     // read an integer
  18:  
  19:     printf("Enter the Rate of Interest : ");    // Principle Amount prompt
  20:     scanf("%f", &rateOfInterest);                // read an floating point number

Line 13 prints the literal “Enter the Principle Amount : ” (without double quotes) on the screen and positions the cursor at the end of the line. This message is known as a prompt, since it tells the user to take a specific action.

The next statement on line 14 uses scanf to obtain a value from the user. The scanf function reads from the standard input, which is usually the keyboard.

As you can see, it takes 2 arguments.

First one is the format specifier, which indicates the type of data that should be input by the user. In this line %d format specifier (which you have used even in the previous chapter as well) indicates that the data should be an integer and the value entered by the user will be converted into an integer. Because of this conversion, its also known as conversion specifier. The % symbol is treated by the scanf and printf (as you saw in previous chapter) as a special character that begins a format specifier.

Second argument is the variable. The variable name is prefixed with an ampersand (&) which is an ‘Address of’ operator. It gives the location number used by the variable in memory. In other words, the ampersand, when prefixed to a variable name tells scanf the address (or location) in the memory which has been allocated to the variable principleAmt. When we say &principleAmt, we are informing scanf() the memory location where the value supplied by the user has to be stored. It then stores the value entered by the user in that memory location. Don’t break your head and try to find the reason for using this ampersand. I will cover them in detail later on in this course while covering pointers.

Note: If you forget to prefix the ampersand operator to the variable name, it will not always result in any compile time errors, but it will cause problems with memory access during program execution.

When the computer executes the scanf statement on line 14, it waits for the user to enter a value for the variable principleAmt. Once the user responds by typing an integer, it waits for the Enter key to be pressed, which indicates the end of input. It then assigns the integer value to the variable principleAmt.

printf() and scanf() functions facilitate interaction between the computer and the user. Since this interaction resembles a dialogue, its known as interactive computing or conversational computing.

The same steps repeat for the set next of printf and scanf statements from line 16 to 20. However, one change that is to be noticed here is the use of %f as the first argument, which indicates the data should be a floating point number since the variable rateOfInterest is of float type.

As with printf() function, we can use a single scanf() to read data into multiple variables as in the code below:

scanf("%d %d %f",&principleAmt, &NoOfYears, &rateOfInterest); 

Notice, first argument includes a set of 3 format specifiers as per the variables and then it follow with the set of variables all prefixed with ampersand.

Note: You can use a space, a tab or a new line character to separate the values for each of these variables and indicate the completion with a enter key press. Space is created using the spacebar, tab using the Tab key and new line using the Enter key.

  22:     simpleInterest = (principleAmt * NoOfYears * rateOfInterest) / 100;
  23:  
  24:     //Printing Variable contents
  25:     printf("\n\nYou entered \nPrincipleAmt = %d\nNoOfYears = %d\nrateOfInterest = %f\n\n", principleAmt, NoOfYears, rateOfInterest);
  26:     printf("The simple interest is %f.\n", simpleInterest);

The remaining statements have not changed from the previous version.

The statement on line 22 calculates the simple interest and assigns the result to variable simpleInterest using the assignment operator =.

Line 25 uses the printf() function and prints the values entered by the user with the new line characters as specified within the printf() function. The printf() on line 26 displays the simpleInterest.

Good Programming Practice:

  • Declare all the variables at the top of the function.
  • Separate the variable declarations & other statements in a function with one blank line to emphasize where the declarations end and the statements begin.
  • Place spaces on either side of an operator, which makes the operator stand out and makes the program more readable.
  • Leaving a space after each comma (,) makes it easier to read the arguments and the program as a whole.

Common Errors while programming:

  • In an assignment statement, the calculation part or the constant should always be on the right hand side of the = operator.
  • Forgetting one or both the double quotes surrounding the format control string in a printf() or scanf().
  • Forgetting the % symbol before the format specifier in printf() or scanf() statements.
  • Forgetting to prefix ampersand (&) before the variable names in a scanf() statement when its required and prefixing an ampersand when its not required.
  • Having escape sequence outside the double quotes surrounding the format control string in a printf() or scanf() functions.
  • Having more or less number of expressions whose values are to be printed or acquired by printf() or scanf() functions respectively.
  • Placing the comma that is supposed to separate the format control string from the expressions inside a format control string itself.
  • Using incorrect format specifiers to read data using scanf() function.

Leave Your Comments