Upload
bertram-mason
View
212
Download
0
Embed Size (px)
Citation preview
CSCI 130
Chapter 2
Program Components
• main()• #include• Variable Definition• Function Prototype• Program Statements• Function Call• Function Definition• Comments
main()
• Required in every program– Under normal circumstances:
• program starts at first statement in main
• program ends at last statement in main
– Ex:• void main() {
• printf(“Hello World”);
• }
#include
• Instructs C compiler to add contents of another file during compilation
• #include statements at top of file
• Usually called header files (.h)– Some supplied with compiler
• Never modified
– Some user defined• Can be modified
Example of #include
• Library function– #include <stdio.h>– greater than, less than indicate library function
• User defined function– #include “myfile.h”– quotation marks indicate user-defined function– if not in same directory as main file, need to
specify the path
Variable Definition
• Variable - name assigned to a data storage location
• Must define a variable before it can be used
• Definition informs compiler of:– variable name– type of data
• Ex:– int a;– char a, b, c;
Program Statements
• These statements do the ‘Real’ work
• One per line, end with semi-colon
• Statements perform various functions:– input/output
• write to screen/file/printer• accept from screen/file
– call functions– perform calculations– other
The Function Call
• ‘Calling a function’– asking compiler to execute a function outside of
the main() function
• Ex:– printf(“Hello World”);– doReset()– c = product(a,b)
Function Definition
• A function:
• is a self contained block of code
• performs a specific task
• A function may be:– a library function
• printf()
– a user defined function• doMultiply()
Example of a function, and a function call
• Function:• int doMultiply(int x, int y) {
• return(x*y);
• }
• Function call:• ...programming statements…
• c = doMultiply(3,6);• …programming statements...
Comments
• When in doubt - Comment!!!• No effect on program execution
• Any text can be stored in a comment
• May take up part of a line, a whole line, more than one line
• Do not be stingy with Comments!!!
Examples of Comments
• Comments may use one line, part of a line, or more than one line:– /*A single line*/
– for (int x; x<10; x++) /*start of a loop*/
– /*Comments can span multiple lines– as well*/
Philosophy
• You never have too many comments• Too few comments may:
– cost you points in this class– cost you friends on the job– cause grey hairs
• Use comments when the logic is fresh in your mind
• Crucial to program maintenance