From the special function called void main, we’ve seen how we can call other functions. However, these functions can go on to call other functions, and those functions can call yet more functions. This is how programs start to get their structure, by separating one large problem out into smaller problems, and solving these smaller problems with functions. The void main function then acts as if it solves the large problem by delegating the work to other functions and combining the results.
Let’s write a program that will take as input a number, named ‘n’, then tell you whether n is prime (a prime number is a number that can only be divided by 1 and itself without leaving a remainder). We can do this by looping from all the numbers from 2 to n, and checking whether n divided by that number leaves a remainder.
bool isPrime(int n)
{
int i = 2;
while( i < n )
{
if( n % i == 0 ) return false
i = i + 1;
}
return true; //If the program gets here then n must be prime
}
Write a program that will ask for a number, then tell you if that number is prime.
The only prime which is also an even number is 2. So we can speed the program up a little by first checking whether the number is even.
bool isEven(int n)
{
if( n % 2 == 0 ) return true;
return false;
}
Then we can call this function from the function isPrime(), before we start looping:
bool IsPrime(int n)
{
if( isEven(n) && n != 2 ) return false;
etc..
}
Add a function to check whether a number is even, and use it to speed up the function which checks whether a number is prime.
Modify the program so that it inputs 2 numbers, A and B, and outputs how many numbers between a and b are prime.