Title: Elements of a C Program
1Elements of a C Program
ECOR 1606 - Problem Solving and Computers
Carleton University Department of Systems and
Computer Engineering
2Elements of a simple program
- Comments
- meant for the human reader
- ignored by the compiler
- can be placed anywhere in the program
- two methods for comments
- / ignore everything in between /
- // ignore until the end of the line
3Elements of a simple program
- Include directives
- include ltfilenamegt
- tells compiler to read the specified header file
- enables optional features
- permits access to library functions
- examples of standard header files
- iostream cin, cout
- cmath pow(), exp(), sin(), sqrt( )
- cstdlib rand(), qsort(), getcwd( )
4Elements of a simple program
- Main function
- tells the compiler that your actual program
starts here - basically, this is the name of the function that
the operating system calls to begin running your
program - this function must be called main
5Elements of a simple program
- Declarations
- specifies the names and types of variables that
will be used - examples
- int x
- double y
6Elements of a simple program
- Executable Statements
- the actual instructions for the algorithm
- examples
- cout ltlt "Hello, World!"
- x 10 y
- z sqrt(17.2)
7Hello, World! Program
/ Print "Hello, World!", then exit.
/ include ltiostreamgt // for cout using
namespace std int main() cout ltlt "Hello,
World!" ltlt endl system("PAUSE") return
0
8Average Value Program
comment
/ Read in three numbers and print their
average value / include ltiostreamgt using
namespace std int main() double
value1, value2, value3, average cout ltlt
"Enter three numbers " cin gtgt value1 gtgt
value2 gtgt value3 average (value1
value2 value3) / 3 cout ltlt "The
average is " ltlt average ltlt endl
system("PAUSE") return 0
include directives
declarations
main function
print prompt
read values
calculate average
print result
9User Window
- Program output (shown here in black) the
content of the output stream produced by the
statements of the form cout ltlt . . . - Program input (shown here in red) the content of
the input stream entered by the user and
processed by the statements cin gtgt . . .