Printing Output

We got the code to compile, but if we run it, nothing happens. The answer is calculated, but the program does not yet show us the result.

We have already seen how we can print information to the screen in the hello.c program using printf(). We could put statements in this program like:

        printf("You have 57 shares of XYZ Corp.\n");

But this is rather inefficient. Suppose we buy more shares of XYZ stock. We must modify our program to change the number of shares we have AND we must remember to change the value in both places: the assignment, and the printf().

Printing data values with printf()

The string we are passing to printf() is called a format string. We can put whatever words we want to appear on the output there, as well as special characters to control the screen, such as the '\n'.

We can also put a conversion specifier into the format string to tell printf() to substitute a value at that point in the output. We must also, then, give printf() the value to be substituted. For example, to convert an integer to be printed, the conversion specifier is "%d", so the above printf() would be written:

        printf("You have %d shares of XYZ Corp.\n",shares);

To convert a float value to be printed, the specifier is "%f".

We can make these changes in a new file called stock1.c.

Going back to step 5, we try to compile and test the program again.

What went wrong?


[up] to Overview.