206k views
5 votes
1. For the following code:

int myFunction(int n) {
int x = n * 2;
int y = (x + 1) % 3;
return y - x;

What does myFunction(4) evaluate to?

User TobiX
by
5.3k points

1 Answer

6 votes

The answer should be
-8.

In most programming languages, lines of code are read from the top to the bottom of the file. Let's start by analyzing this function from top to bottom.

In the first line we see a function definition and we can see that it has one parameter. This parameter is called
n and is a variable that can store integers.

  • int myFunction(int n)

We are told in the question that the integer number
4 should be assigned to this parameter.

  • myFunction(4)

Therefore, in this code block, we can place the integer
4 wherever we see the parameter
n.

In the next step, we are greeted by a variable
x and some arithmetic operations appear.

  • int x = n * 2;
  • int x = 4 * 2;
  • int x = 8;

We will do the same steps for our next variable,
y. In this question, the % operator is a sign that returns us the remainder from the quotient.

  • int y = (x+1) % 3;
  • int y = (8+1) % 3;
  • int y = 9 % 3;
  • int y = 0;

In the last step, we will calculate the value that the function will return, which depends on the value of two variables. Since we know the value of these two variables, we can finish analyzing the question by substituting them.

  • return y - x;
  • return 0 - 8;
  • return -8;
User EJZ
by
5.8k points