We learned two numeric types:
int for whole numbers (including zero and negatives), and
float for numbers that can have decimal parts.
A variable is an identifier that stands for a location in memory where we can store a value of some type. You must declare all variables before they are used. A declaration looks like this:
That is, the type followed by the identifier, then semi-colon. If you have multiple identifiers of the same type, you can merge them in one declaration with commas:
int quiz3, quiz4, midterm;
float height, length;
Variables get their values from assignment statements, which use an equals sign:
quiz3 = 98;
quiz4 = 83;
height = 1.25;
width = 2.8;
However, unlike in mathematics, this equals sign is a one way street: it goes right-to-left. On the left side, there must be a variable name. The right side can be any expression that produces a value of the correct type.
quiz2 = 100 - 5;
midterm = quiz2 * 3;
length = height * 1.2;
Some of the operators that work on
float values or addition (
+), subtraction (
-), multiplication (
*), and division (
/). There are many more that we’ll learn as we go.
Finally, we want to be able to print these values on the screen. We know
printf can print text, but how does it retrieve the value of the variable? It uses format codes, which start with a percent sign.
%dmeans substitute next value as a (base ten) integer
%fmeans substitute next value as a (floating-point) real number
Here is how they work:
printf("The score is %d.\n", quiz2);
printf("The room is %f by %f.\n", length, width);
Try putting together all these elements into a full program you can run on your system. Below is an example. Predict what the program will output on paper first, and then run it, fix any syntax errors, and see if you were correct.
©2011 Christopher League · some rights reserved · CC by-sa