A Simple Sample of C

I l @ ve RuBoard

A Simple Sample of C

Let's take a look at a simple C program. (Figure 2.1 outlines a more extensive example.) This program, shown in Listing 2.1, serves to point out some of the basic features of programming in C. Before you read the upcoming line-by-line explanation of the program, read through Listing 2.1 to see if you can figure out for yourself what it will do.

Figure 2.1. Anatomy of a C program.
graphics/02fig01.jpg
Listing 2.1 A simple C program.
 #include <stdio.h> int main (void)               /* a simple program             */ {    int num;                  /* define a variable called num */    num = 1;                  /* assign a value to num        */    printf("I am a simple "); /* use the printf() function    */    printf("computer.\n");    printf("My favorite number is %d because it is first.\n",num);    return 0; } 

If you think this program will print some things on your screen, you're right! Exactly what will be printed might not be apparent, so run the program and see the results. First, use your favorite editor (or your compiler's favorite editor) to create a file containing the text from Listing 2.1. Give the file a name that ends in .c and that satisfies your local system's name requirements. You can use first.c , for instance. Now compile and run the program. If all went well, the output should look like this:

 I am a simple computer. My favorite number is 1 because it is first. 

All in all, this result is not too surprising, but what happened to the \n 's and the %d in the program? And some of the lines in the program do look strange . It's time for an explanation.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net