15 September

Types

We learned two numeric types: int for whole numbers (including zero and negatives), and float for numbers that can have decimal parts.

Variables

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:

int quiz2;
float width;

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;

Operators

Some of the operators that work on int and float values or addition (+), subtraction (-), multiplication (*), and division (/). There are many more that we’ll learn as we go.

Format strings

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.

Here is how they work:

printf("The score is %d.\n", quiz2);
printf("The room is %f by %f.\n", length, width);

Practice

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.

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>

int main()
{
int a,b;
float f, g;
f = 3.8;
g = f - 5.2;
printf("%f,%f", f, g);
return 0;
}

©2011 Christopher League · some rights reserved · CC by-sa