int main()
{
...
}The "main" function looks just like a general function
Type name(parameters)
{
...
}
The "main" function is special because it is where the program start executing.
Functions are useful because they stop us typing the same code (with small changes) many times. They help us follow The DRY Principle (Don't Repeat Yourself).
THey are vital when you wish to share some code with other people -- either because you are working on the same project together, or because you want to sell or give away your code.
A function always needs to be tested by a different function to see if it produces the right result.
double abs(double x)
{
if( x >= 0) return x;
else return -x;
}
Example program [ 09multi.cpp ] containing a function to calculate the hypotenuse of a right triangle.
When you get a program working -- check to see if there are any repeated pieces of code. You can then put the code inside a function and give it a meaningful name. Then replace the repeated pieces by calls to the new function and test.
egrep "[0-9]+" homework.cpp
egrep "[^A-Za-z][0-9]+" homework.cpp(The "+" is understood by "egrep" but not "grep")
Notice that the semicolon ";" is an essential part of the return statement.
So if you are writing code for mathematicians and scientists then you can use tradition (short) varaibles. You can also spell out greek letters.
But if you are writing code that is for an accountant then use accounting words...
[ fun.cpp ] (use "void" functions that return nothing).
[ fun2.cpp ]
[ circ.cpp ]
[ funfun.cpp ]
. . . . . . . . . ( end of section cs201/09 Functions) <<Contents | End>>