/* Lab 1: Example 1: Using C functions
Objectives:
a. To review C++ programming structure
b. To understand how functions can be used for modular and structured programming exercise
*/
//include standard input/output libraries
#include
using namespace std;
//declare a function prototype: check_prime with integer parameter; returns a flag of integer type (you just need to mention type; no type return means "void" return
int check_prime(int num);
//main function without any parameter; returns an integer
int main(){
//declare variables number and flag as integer types
int number,flag;
//print "Enter a number: " in the standard output console
cout << "Enter a number: ";
//input/scan the number from the standard input console, i.e. keyboard
cin >> number; //Notice the direction arrows have changed from cout, meaning from console input to variable address directly.
//call the check_prime function with number as the parameter; the function will return flag indicating whether it is prime or not
flag=check_prime(number);
//if flag is 1, the number is not prime
if(flag==1){
cout << "Number " << number << " is not prime";
}
//otherwise, the number is prime
else{
cout << "Number " << number << " is prime";
}
//return from the main with 0 value
return 0;
}
//define the check_prime prototype here; has to be in the same format - except that since you are defining the function you will need enclosing {}s
int check_prime(int num) /* User-defined function to check prime number*/
{
//declare two integer types: i and flag - flag initialised to 0
int j,flag=0;
//run a loop from 2 to half of the number and check to see if it produces zero remainder when dividing the "number" - if it does it is not prime (there are better algorithms!)
for(j=2;j<=num/2;++j){
if(num%j==0){
flag=1;
break; //break statement skips the rest of the iterations in the loop
}
}
//return the flag value back to the caller
return flag;
}