Input and Variables
Problem:
Write a program that will ask the user to enter in two whole numbers. The program will then add the numbers together and show the user what they entered along with the sum of these two numbers.
How would we go about solving this problem?
- Learn about memory and variables
- Learn how to perform input
- Learn how to write an expression
Basic steps program must perform
For each program it is often good to outline what the steps of the program are. In this case our program must do the following
- Ask user for a number (output)
- read in a number (input)
- Ask user for another number (output)
- read in a second number (input)
- Print out what the two numbers are and their sum (output)
For steps # 1 and #3, we already know how to do this. it is just output like we saw in the hello world program. Below, is the beginning of our solution. The parts where we don't know how to code yet we put in as comments. We can then replace the comments once we know how to write the code.
#include <stdio.h>
int main(void){
printf("Please enter a number: ");
/*code to read in a number here*/
printf("Please enter another number: ");
/*code to read in another number here*/
/*print out result here*/
return 0;
}
For steps #2 and #4, we need to read in two numbers. To do so, we must have a place to put the numbers the user enters. We will need variables. The next part looks in detail at variables and how data is stored in computers.
Memory and Variables
Programs work with data and that data needs to be stored in the computer's memory. The most basic unit of storage for data is a bit. A single bit stores either a 0 or a 1. In other words using just 1 bit, we can store one of two possible values. Clearly a single bit doesn't store much information. However, if we use 2 bits, the number of possible values that can be held doubles to 4 values (00, 01, 10, and 11). If we use 3 bits, we double the number of possible values to 8 (000, 001, 010, 011, 100, 101, 110, and 111). For each bit we add, we double the the number of possible values. With 8 bits, we can hold up to 256 different values. With 32 bits we can hold over 4 billion different values.
8 bits makes up a single byte. In memory, each byte has a unique address, a number that indicates the byte's location in memory. A byte is the smallest addressable unit.
In C, when we want to store a piece of data, we create a variable. A variable is a reserved spot in memory that your program has given a name to. That is, when you create a variable you are essentially reserving a spot in memory and giving that spot a name. In C, variable has both a data type and a name. The data type lets the computer know how much memory has been reserved for the variable and how to interpret that memory. The name allows us to access the data stored in that spot.
Data Types
In C, each variable has to have a data type. The data type of a variable serves two purposes.
- Determine the amount of storage (how many bytes of memory) needed for a variable.
- Determine how to interpret the bits that are stored.
The first of these is quite straight forward. A single byte can only hold 256 different values (256 different patterns of 0's and 1's over 8 bits). So if we wanted to store numbers for example, we can hold 256 different values only (like 0 to 255 for example). To store more, we need more memory. So different data types will reserve different amounts of memory. For example, an variable with data type of int is 32 bits (4 bytes). This variable can hold 4billion+ different patterns of 0's and 1's. Thus, it can hold 4billion+ different whole numbers.
The second purpose of a data is in interpretation of 0's and 1's. As stated earlier, 32 bits will give you 4billion+ distinct patterns of bits. If each pattern corresponds to a single value, the variable can hold one of 4billion+ values. But how do we know what value each pattern represents? Here, the data types actually tell us how the bits will be interpreted. For example, if the data type is an int, the numbers will range from:
-2147483648 to 2147483647
31 of the bits will be used to store the number and one bit will be used to store the sign.
If the data type was: unsigned int (whole numbers all positive), the numbers would range from:
0 to 4294967295
In other words, all 32 bits would be used to represent the number.
Another data type named float is also 32 bits. A float uses the 32 bits completely differently. Some of the bitsstores a value that represents the mantissa, the other bits store an exponent. Think of scientific notation:
1.234 X 10^3 == 1234
the mantissa is 1.234, the exponent is 3.
Using floats, you can store numbers that are well over 4 billion because the exponent can get really big. However, what you start losing is accuracy. 1.234 X 10^9 means 1,234,000,000. So the last 6 digits are 0. So while the number can get very big, the accuracy of the mantissa has a limitation. depending on what you are doing, this could be an issue.
An alternative to float is double. Like float, doubles also uses its bits store numbers using both a mantissa and an exponent. However a double is 64 bits (8 bytes) and thus, it can use a lot more bits store a mantissa and thus is more accurate.
data type | what it stores | size (number of bytes |
---|---|---|
char | a signed whole number between -128 to 127. char can be used to store the ascii value of a single whole number. | 1 |
int | a signed whole number between -2147483648 to 2147483647 | 4 |
float | a signed floating point number | 4 |
double | a signed floating point number | 8 |
Video
A summary video on data types:
https://www.youtube.com/watch?v=ip7y1vydzHsInput
To perform input, we first need to declare variables so that we can store what the user types.
To declare a variable, the syntax is:
datatype variablename;
datatype specifies what type of variable it is.
variablename is a unique identifier that the programmer makes up that is used to reference the variable.
The problem states that we are asking for a whole number, so the variable that we make to store the number should represent a whole number. In this case an int.
#include <stdio.h>
int main(void){
int input1;
int input2;
printf("Please enter a number: ");
/*code to read in a number here*/
printf("Please enter another number: ");
/*code to read in another number here*/
/*print out result here*/
return 0;
}
To read in a number we will make use of the scanf function. However, before we do this, we need to take a closer look at format strings.
Format Strings
In C, both printf and scanf requires a format string as its first parameter. This string lets us create output to a certain format or read in data that has a certain format.
The format string tells us either where the data for a specific variable should go or where in the string the data comes from with the use of format codes. A format code indicates the datatype of data we are dealing with.
For example, suppose I wanted to print out three whole numbers with dashes in the middle of them. The format would be:
<number> - <number> - <number>
So, to make a format string that looks like that we would use:
%d - %d - %d
The %d in the above, shows the compiler where to put the three numbers.
The format string needs a format code that will match what we are trying to read. For base 10 integers, you would use %d.
Similarly you can also use it to read out values that have a given format. For example, suppose you know the user will enter a number like: 123.45
And you wanted to put the 123 in one variable, and 45 in a different variable (as whole numbers). You could actually use your format string in a scanf to help you do this:
"%d.%d"
In other words, you expect a whole number, a period (decimal point) and another whole number.
The following shows format codes and their matching types:
format code | matching data type |
---|---|
%d | int (base 10 whole number) |
%f | float (floating point number) |
%lf | double (high precision floating point number) |
%c | character encoded as ascii |
There are also various ways to modify the formatting further. These modifications are not necessarily the same for printf and scanf. Please see the the reference links for further details.
scanf
int scanf ( const char * format, ... );
You can find details of it here: scanf reference
The scanf function is also part of the stdio library so we do not need to add any other includes.
Thus, the line to read in a value into the variable named input1 is:
scanf("%d",&input1);
The & character in front of input1 is the address-of operator. &input1 means address of input1. This will pass in the location of the input1 variable to the scanf function.
A similar scanf statement will read in input2.
The program now looks like this.
#include <stdio.h>
int main(void){
int input1;
int input2;
printf("Please enter a number: ");
scanf("%d",&input1);
printf("Please enter another number: ");
scanf("%d",&input2);
/*print out result here*/
return 0;
}
For the final statement we need to print out the variables input1 and input2 and their sum. This can be done in a single printf statment.
We know that printf accepts a format string as its first argument. If we want to put the values stored in variables or the results of an expression into the output, we simply need to add the appropriate format code into the format string. We then place the variables we wish to put into each format code following the format string, separating each with a comma.
So suppose we wanted to write:
<first number> + <second number> = <sum>
Our printf statement would look like this:
printf("%d + %d = %d\n",input1,input2,input1+input2);
Think of each %d as a blank. The value put into each blank is the value of the corresponding variable that follows the format string. Thus the value of input1 which is the first value after the format string is put into the first format code.
So, if we put all of this together, our final program will look like this:
#include <stdio.h>
int main(void){
int input1;
int input2;
printf("Please enter a number: ");
scanf("%d",&input1);
printf("Please enter another number: ");
scanf("%d",&input2);
printf("%d + %d = %d\n", input1, input2, input1+input2);
return 0;
}
Video
A summary video on the above program
https://www.youtube.com/watch?v=KdegBE_2Mms