Menu
Coddy logo textTech

Performing Calculation

Part of the Fundamentals section of Coddy's Dart journey — lesson 90 of 94.

challenge icon

Challenge

Easy

Now that we have two numbers and an operation, we can perform the calculation.

Update your calculator program to:

  1. Create a variable named result with type double? (nullable double) to store the result of the calculation
  2. Use if-else statements to perform the appropriate calculation based on the operation:
    • If operation is '+', set result to firstNumber + secondNumber
    • If operation is '-', set result to firstNumber - secondNumber
    • If operation is '*', set result to firstNumber * secondNumber
    • If operation is '/', check if secondNumber is 0
  3. If attempting division by zero, print exactly: "Error: Cannot divide by zero!" and use the return statement to exit the function
  4. For all valid calculations, set the result variable appropriately
  5. Print "Result: " followed by the result value

Try it yourself

void main() {
  print("Welcome to the Simple Calculator!");
  
  // Declare and initialize number variables
  double firstNumber = 10.5;
  double secondNumber = 5.5;
  
  // Print the numbers
  print("First number: $firstNumber");
  print("Second number: $secondNumber");
  
  // Declare and validate the operation variable
  String operation = "*";  // Can be +, -, *, or /
  
  // Check if operation is valid
  if (operation != '+' && operation != '-' && operation != '*' && operation != '/') {
    print("Invalid operation. Using addition (+) as default.");
    operation = '+';
  }
  
  print("Operation: $operation");
  
  // Perform the calculation here
}

All lessons in Fundamentals