if-else Statements

AP Computer Science A· difficulty 2/5

if (g >= 90) grade = 'A';
if (g >= 80) grade = 'B';
if (g >= 70) grade = 'C';

Why does a 95 produce grade 'C'?

  • A

    char cannot hold a grade

  • B

    g must be a String

  • C

    All ifs run; later assignments overwrite earlier ones. Use else if.

    check_circle
  • D

    Nothing is wrong

Explanation

Independent ifs all execute; with g=95 every condition is true, so the last assignment ('C') wins. Chain with else if for mutual exclusion.

Want 10 more like this — adaptive to your weak spots?

Related questions