The Components of a C Program
- A Short C Program
- The Program's Components
- A Review of the Parts of a Program
- Summary
- Q&A
- Workshop
Every C program consists of several components combined in a specific way. Most of this book is devoted to explaining these various program components and how you use them. To help illustrate the overall picture, you should begin by reviewing a complete (though small) C program with all its components identified. In this lesson you learn:
- The components of a short C program
- The purpose of each program component
- How to compile and run a sample program
A Short C Program
Listing 2.1 presents the source code for bigyear.c. This is a simple program. All it does is accept a year of birth entered from the keyboard and calculate what year a person turns a specific age. At this stage, don’t worry about understanding the details of how the program works. The point is for you to gain some familiarity with the parts of a C program so that you can better understand the listings presented later in this book.
Before looking at the sample program, you need to know what a function is because functions are central to C programming. A function is an independent section of program code that performs a certain task and has been assigned a name. By referencing a function’s name, your program can execute the code in the function. The program also can send information, called arguments, to the function, and the function can return information to the main part of the program. The two types of C functions are library functions, which are a part of the C compiler package, and user-defined functions, which you, the programmer, create. You learn about both types of functions in this book.
Note that, as with all the listings in this book, the line numbers in Listing 2.1 are not part of the program. They are included only for identification purposes, so don’t type them.
Input
Listing 2.1 bigyear.c - A Program Calculates What Year a Person Turns a Specific Age
1: /* Program to calculate what year someone will turn a specific age */ 2: #include <stdio.h> 3: #define TARGET_AGE 88 4: 5: int year1, year2; 6: 7: int calcYear(int year1); 8: 9: int main(void) 10: { 11: // Ask the user for the birth year 12: printf("What year was the subject born? "); 13: printf("Enter as a 4-digit year (YYYY): "); 14: scanf(" %d", &year1); 15: 16: // Calculate the future year and display it 17: year2 = calcYear(year1); 18: 19: printf("Someone born in %d will be %d in %d.", 20: year1, TARGET_AGE, year2); 21: 22: return 0; 23: } 24: 25: /* The function to get the future year */ 26: int calcYear(int year1) 27: { 28: return(year1+TARGET_AGE); 29: }
Output
What year was the subject born? 1963 Someone born in 1963 will be 88 in 2051.