2 Replies - 639 Views - Last Post: 15 July 2012 - 02:56 AM Rate Topic: -----

#1 new_user2   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 15-July 12

Switch statement error, takes directly to default statemnet

Posted 15 July 2012 - 02:43 AM

#include <iostream>
using namespace std;
int main()
{
    int score;
    cout<<"enter score\n";
    cin>> score;
    
   
    
    switch (score) {
        case 1:
            if (score>=90 && score<=100) 
                cout<< "A\n";
            
            break;
        case 2:
            if (score>=80 && score<90)
            cout << "B";
            break;
        case 3:
            if (score>=70 && score<80)
            cout<< "C";
            break;
        case 4:
            if (score>=60 && score<70)
            cout<< "D";
            break;
        case 5:
            if (score>=0 && score<60)
            cout<<"F";
            break;
        default:
            cout <<"invalid input\n";
            break;
    }
    
    
    return 0;
}

This post has been edited by no2pencil: 15 July 2012 - 02:53 AM
Reason for edit:: Added code tags


Is This A Good Question/Topic? 0
  • +

Replies To: Switch statement error, takes directly to default statemnet

#2 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6338
  • View blog
  • Posts: 21,756
  • Joined: 05-May 12

Re: Switch statement error, takes directly to default statemnet

Posted 15 July 2012 - 02:50 AM

Put your code in [code] blocks.

In your text, you should also describe your problem, but I think I have a fairly good idea of what is happening based on your title line.

I suspect that for score you are entering a value like 50, and you are getting the "invalid input" message displayed. This is because the switch statement matches the value of score against the values after the case statements. Since your case statements only have values of 1, 2, 3, 4, and 5, the switch statement goes to the default clause.

This post has been edited by Skydiver: 15 July 2012 - 02:51 AM

Was This Post Helpful? 0
  • +
  • -

#3 no2pencil   User is online

  • Professor Snuggly Pants
  • member icon

Reputation: 6659
  • View blog
  • Posts: 30,982
  • Joined: 10-May 07

Re: Switch statement error, takes directly to default statemnet

Posted 15 July 2012 - 02:56 AM

case 1:
            if (score>=90 && score<=100) 
                cout<< "A\n";



In your above code segment, the switch case will execute the code if the variable score equals 1. Your code then check is score is greater than 90 & less than 100. This along will never be true because score would have to equal 1 to launch this segment of code.

A switch case is like having many if statements & only one else. The else would be default.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1