Add and Subtract with Integers
Not Started

We’re going to do some math in this course. I already know your heart rate increased - but don't worry this will be easy. We’re going to build software that does basic addition and subtraction. This is where Integers and Doubles really shine! You got this!

Imagine we’re asked to build software for a restaurant. In this specific scenario, a customer has ordered a sandwich and a drink. We’ll need to write code that will calculate the total price of the meal.

Apex supports the arithmetic operators + and - which allow for addition and subtraction of Integers.

Let’s set up the basic cost of each item first. This part you should feel comfortable with already:

Integer sandwichPrice = 7; Integer drinkPrice = 2; Integer totalPrice; //this is what we’re trying to figure out

Our goal here is to set totalPrice as the sum of sandwichPrice and drinkPrice. Here’s how we do that using the + operator:

Integer sandwichPrice = 7; Integer drinkPrice = 2; Integer totalPrice = sandwichPrice + drinkPrice; // totalPrice is now set to 9

Since sandwichPrice is referencing 7 and drinkPrice is referencing 2 - we’re able to sum them up using the + operator and set the totalPrice variable.

The restaurant is running a promotion where they’re giving everyone 2 off their purchase. How generous! We’ll need to subtract 2 from the totalPrice:

Integer sandwichPrice = 7; Integer drinkPrice = 2; Integer discount = 2; Integer totalPrice = sandwichPrice + drinkPrice - discount;

Alternatively, we could do the math by referencing the Integer values directly:

Integer sandwichPrice = 7; Integer drinkPrice = 2; Integer totalPrice = sandwichPrice + drinkPrice - 2;

You’re not required to use variables, but it’s a good practice to do so. In this example, it’s hard to know for certain why 2 is being subtracted. Without variables, we're left with “magic numbers”. Those sound cool, but they're a red flag. We should always know what the numbers in our software represent.

Here are some more examples of addition and subtraction:

Integer result = 7 + 3; // Evaluates to 10 Integer result2 = result + 5; // Evaluates to 15 Integer subtractionResult = result2 - 4; // Evaluates to 11 Integer subtractionResult2 = 10 - 5; // Evaluates to 5 Integer goNuts = result + result2 + subtractionResult + subtractionResult2; // 10 + 15 + 11 + 5 -> goNuts evaluates to 41

Challenge

You're provided two variables productACost and productBCost. Create a variable named productTotal to calculate the sum of the two variables.