BU CAS CS 113
Introduction to Computer Science II with Intensive C
Fall 1997


Getting started: Variables and printf()
Last Modified: Mon Nov 17 00:30:49 1997

I found most of this on the web and modfied it a bit for our class. It covers the basics of simple programs in C: basic structure, variables and output. In particular, there is a section on printf() at the end.

Another look at hello.c

#include <stdio.h>

int main(void){

}

How does it work?

You probably want to know what you just did? You can obviously figure out how to make it say This program is useless instead of Hello World, but you probably want to know what are the rest of the lines for.

#include <stdio.h>

is a compiler directive. This line has nothing to do with what your program does, it is strictly for the compiler.  By including stdio.h we include the STandardD Input Output library. We will include it in almost all our programs. The # tells the compiler that this line is a compiler directive. include tells it to include a file (since this is the first chapter I'll go ridiculously slow and explain things like what include does even though it is blatantly obvoius that include will include a file!) and <stdio.h> is the name of that file.

int main(void){

is the name of a function. All programs must have a main function, it is where the program starts. int is short for integer. The int before main means when this function is done, it will return an integer. (void) is the parameters which the function takes. To pass parameters to the main function you type something after the program name. pkunzip quake.zip passes quake as a parameter to pkunzip. The { tells the compiler where the code for the function actually starts. Since it is void our program wont expect any input.

printf("Hello World\n");

is pretty self explanitory. It prints Hello World on the screen. The \n you will notice doesn't show up on the screen. \n is translated into a new line code. What if you want to put In C \n means new line on screen? Just use a double \ to print a \ character. The code to do that would be printf("In C \\n means new line");

return 0;

is what the function returns. In this case it means our program will return 0 to the operating system. When the operating system gets recives a 0 after the program has run it knows that nothing went wrong. If there is an error in your program, such as not enough memory, you should return a number different than zero to the operating system to indicate that you abnormally ended the program. A lot of compilers don't require you to return a zero, but it is part of the ANSI standard so its good practice to return a value.

For every open bracket you use, you need to use one to close it. Thats what the final } is for. You will also notice that every line has a ; at the end. This tells the compiler that it is the end of the line. If you leave a ;out your program will not compile.

You now know how to program C!  Well sort of, all you can do is write messages, but you have to start somewhere!

Variables

Variables are the most important tool a programmer has. They are used to keep track of things like points in a games, lives left, or height of the player on the screen. There are eleven built in variable types. They are char, int, short, long, float, double, and long double. By default they are signed, which means they can hold both positve and negative numbers. The other four variable types are just repeats of those (execpt for float, double, and long double), but can not hold any negative numbers.  They are creativly called unsigned variables. The advantages of unsigned numbers is they can hold numbers of twice the magnatude. For example an unsigned char can hold numbers 0 to 255 (for a total of 256 different values) but a signed char can hold numbers -128 to 127 (for a total of 256 different values). We won't use int because it is not very good for portable code. Different compilers,or even the same compiler in different situations, treat int as either a 16bit number (short) (65536 different values) or a 32bit number (long) (4,294,967,295 different values).

For those without much math education yet, an integer is any whole number. If you wanted a running game where the player had to run 1.98 kilometres but used ints to keep track of the distance, the 1.98 would get truncated (not rounded, like real numbers are) to 1 which would make the course much shorter! If you need decimal places use a floating point number.

Variables can be given any name you want such as x, Points, or Time_Left. Variables are case sensitive in C. Therefore Points, points, POINTS, PoiNTS, and pOInts are all different variables. The first character of a variable name must be a letter (a-z or A-Z). After that you can add any number of letters, numbers, or underscores ( _ is an underscore) as you feel is appropriate.

Here is what variables can hold:

long double and int are compiler dependant so caution must be used if using them in settings where portability is important.

The last thing about variables.  They must be declared either as arguments (parameters) of functions, or at the top of a block of code. This means that typically all declarations come at the beginning of functions, before the code for the body of the function. You can not just add a variable in the middle of your function when you need it. This is a difference between C and C++

I am sure you want to see an example of this right about now to explain everything you just read. Lets pretend we needed to figure out the average of 9 and 2, but our brains didn't work and we couldn't find a calculator.

#include <stdio.h> /* you know the meaning of this */

int main(){ /* and this */

}

This is the first C shortcut you will learn, instead of typing (void) for functions that won't be taking in any parameters you can just type () such as main() rather than main(void).

Try to guess what everything does and then compile it.

When you compile this you will get 9 as your answer (the / means divide, like a fraction). As you can see the compiler knows BEDMAS (for those who haven't learned BEDMAS, it's a way to remember the proper order to do math in. You do start at the left and work right doing brackets, then starting again at the left and do exponents, then start again at the left and do division or multiplication, then finally work through again doing addition or substaction.) Therefore 5+9/2 is the same as 5+(9/2), not (5+9)/2 which is how we would compute the average.

To find the real average of 5 and 9 we have to add it before we divide by 2. The proper line should be average=(5+9)/2;

And of course, the type must be a floating point type if we want to allow for fractional parts, in which case we need a line like average=(5+9)/2.0;

and the appropriately changed declaration of average.

The %i in the printf statment is simular to the \n. It tells the compiler to replace that with an integer which will be given after the ",. There can be more than one integer such as printf("%i*%i=%i",3,7,3*7).

That was very short, but it should be enough for you to know what a variable is. As you can see it was declared or created before any of our code that actually did anything. Now its time to move to bigger and better things.

You will probably find it useful to have a table of the printf conversion characters (things like %i) so here it is.

Character Input Output
d Integer signed decimal integer

eg. 23242

i Integer signed decimal integer

eg. 23242

o Integer unsigned octal integer

eg. 55312

u Integer unsigned decimal integer

eg. 23242

x Integer unsigned hexadecimal integer (with a,b,c,d,e,f)

eg. 5aca

X Integer unsigned hexadecimal integer (with A,B,C,D,E,F)

eg. 5ACA

f Floating Point signed value of the form [-]dddd.dddddd

eg. 2342.123000

e Floating Point signed value

eg. 2.324212e+004

g Floating Point signed value in either e or f form, based on given value and precision. Trailing zeros and the decimal point are printed if necessary.

eg. 23242.1

E Floating Point Same as e; with E for exponent
G Floating Point Same as g; with E for exponent if e format used
c Character Single character
s String Pointer Prints charcters until a null-terminator is reached or prescision is reached
% none Prints the % character

printf also allows for formatting codes that allow for allignment of data into tables or collumns. We will learn more of these later, but here are a few common examples.

printf("%5d",n);
printf("%8f",x);
printf("%8.2f",x);
The first of these prints the integer value n using at least 5 spaces. If the number is too short, extra blanks are added. The second line does the same but for a floating point number using at least 8 spaces. The last one prints the floating point number using at least 8 spaces exactly two of which come after the decimal point. This is useful for printing, for example, amounts of money. The justification is right, for left justification use negatives, as in %-5d.