cppbeginner10 minutes

Refactor a Simple Grade Calculator for Clarity

Improve the readability and structure of a basic C++ grade calculation function without changing its behavior.

Challenge prompt

You are given a function that calculates and returns a letter grade based on a numerical score. The current implementation works correctly but is hard to read and understand due to poor formatting and nested conditionals. Refactor the function to improve clarity and maintainability while keeping the same output for any input.

Guidance

  • Focus on simplifying nested conditionals where possible.
  • Use clear and consistent variable names and formatting.
  • Avoid redundant code and conditions.

Hints

  • Consider using else-if statements instead of multiple nested ifs.
  • Returning as soon as you determine the grade can reduce complexity.

Starter code

char calculateGrade(int score) {
    if(score >= 90) {
        return 'A';
    } else {
        if(score >= 80) {
            return 'B';
        } else {
            if(score >= 70) {
                return 'C';
            } else {
                if(score >= 60) {
                    return 'D';
                } else {
                    return 'F';
                }
            }
        }
    }
}

Expected output

Input: 85 -> Output: B Input: 72 -> Output: C Input: 59 -> Output: F

Core concepts

conditional statementscode readabilityrefactoringfunctions

Challenge a Friend

Send this duel to someone else and see if they can solve it.