AP Computer Science A : Pre-Conditions

Study concepts, example questions & explanations for AP Computer Science A

varsity tutors app store varsity tutors android store

Example Questions

Example Question #1 : Pre Conditions

USING FUNCTIONS

Consider the following C++ code to perform the following subtraction:

9 - 6:

 

#include <iostream>

using namespace std;

int main() {

int total = 0;

cout << "This code performs the following math operation: 9 - 6 = ";

total = sub(6,9);

cout << total;

}

 

int sub(int num1, int num2) {

return (num2 - num1);

}

 

Is there anything wrong with the code?

Possible Answers:

The arguments in total should be flipped. Such as: total = sum(9,6);

The code is missing the math library. It should have

#include

The function prototype is missing.

There is nothing wrong with this code.

Correct answer:

The function prototype is missing.

Explanation:

Taking a look at each answer, we can see that the order of the arguments passed in the sub function is correct because of the fact that num1 is being subtracted from num2. Also, for simple math operations there isn't a need to include the math library. Lastly, any operation can be done within a function or in main; there is no wrong method however, creating and using functions makes the code in main() easier to read and cleaner.

Now within main(), when the sub() function is called the function has not been defined; meaning that it is not within the scope. This means that we should place the function prototype before main() so that when the function is called, the compiler know that there's a function called sub() that takes in two integer parameters and returns an integer. Therefore this addition will fix our scope issue.

 

#include <iostream>

using namespace std;

int sub(int num1, int num2); //This addition is the function prototype

int main() {

int total = 0;

cout << "This code performs the following math operation: 9 - 6 = ";

total = sub(6,9);

cout << total;

}

 

int sub(int num1, int num2) {

return (num2 - num1);

}

 

Note: Another fix to this issue, is placing the functions right before main(). Although this method is not particularly recommended because it makes main() harder to find, people still use it. The following is an example of fixing the issue by placing the function before main(). Note that the function prototype is not needed when using this method:

 

#include <iostream>

using namespace std;

 

int sub(int num1, int num2) {

return (num2 - num1);

}

 

int main() {

int total = 0;

cout << "This code performs the following math operation: 9 - 6 = ";

total = sub(6,9);

cout << total;

}

 

Learning Tools by Varsity Tutors