You write a simple function like this.
return-type name (parameters) { computational instructions return return-value; }The return-type is the type of the result. For example, the return-type of the sqrt function is double. The name is the name of the function. Each parameter in the parameter list consists of a type and a name for the parameter, in that order. If there are two or more parameters, they are separated by commas.
For example, here is a function that takes in a real number (type double) and returns the square of that real number. If it is given 5.0, it returns 25.0.
double sqr(double x) { return x*x; }
Here is a function that returns the maximum of two integers.
int max(int a, int b) { int result; if(a > b) { result = a; } else { result = b; } return result; }
The maximum finding function can be written in a shorter form. Here it is.
int max(int a, int b) { if(a > b) return a; else return b; }
WARNING. You will have a tendency to try to write your functions without writing contracts first. This is very bad practice, and will cause you to spend more time writing your programs than if you write the contracts first. The contracts serve as guides to your work, and are critical aspects of the programming process. If you skip over them, you can count on difficulties.
///////////////////////////////////////// // min // ///////////////////////////////////////// // min(x,y) returns the smaller of x // // and y. // ///////////////////////////////////////// int min(int x, int y) { if(x < y) return x; else return y; }
///////////////////////////////////////////// // prime // ///////////////////////////////////////////// // prime(n) returns 1 if n is prime, and // // 0 if n is not prime. // ///////////////////////////////////////////// bool prime(int n) { if(n <= 1) return 0; else { int k = 2; while(k < n) { if(n % k == 0) return 0; k++; } return 1; } }
/////////////////////////////////////////////// // nextPrime // /////////////////////////////////////////////// // nextPrime(n) returns the smallest prime // // number that is greater than n. // /////////////////////////////////////////////// int nextPrime(int n) { int k = n+1; while(prime(k) == 0) k++; return k; }
/////////////////////////////////////////////// // PrintPrimes // /////////////////////////////////////////////// // PrintPrimes(n) prints the first n prime // // numbers, one per line. // /////////////////////////////////////////////// void PrintPrimes(int n) { int k,i; k = 2; i = 0; while(i < n) { cout << k << endl; i++; k = nextPrime(k); } }
/////////////////////////////////////////////// // main // /////////////////////////////////////////////// // Read a number n and print the first n // // primes. // /////////////////////////////////////////////// int main() { int n; cout << "How many primes shall I print? "; cin >> n; cout << "The first " << n << " prime numbers are:\n"; PrintPrimes(n); return 0; }