Menu
Coddy logo textTech

Displaying Result

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

challenge icon

Challenge

Easy

The final step in our calculator program is to display the result in a nicely formatted way.

Complete your calculator program by:

  1. After calculating the result, add an empty line by using print("\n")
  2. Print the text "Calculation Summary:" on a new line
  3. On the next line, print the entire calculation in the format: "10.5 * 5.5 = 57.75" (adjust based on your actual operation and result)
  4. Make sure to use string interpolation to insert the values of firstNumber, operation, secondNumber, and result into the output string

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
  double? result;
  
  if (operation == '+') {
    result = firstNumber + secondNumber;
  } else if (operation == '-') {
    result = firstNumber - secondNumber;
  } else if (operation == '*') {
    result = firstNumber * secondNumber;
  } else if (operation == '/') {
    if (secondNumber == 0) {
      print("Error: Cannot divide by zero!");
      return;
    }
    result = firstNumber / secondNumber;
  }
  
  print("Result: $result");
  
  // Format and display the final result here
}

All lessons in Fundamentals