Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Please Help me fix my code

+1 vote
asked Nov 2, 2020 by Hammad (130 points)
#include<iostream>

using namespace std;

main(){

int number;

cout<<"Please enter the number between 0 to 30: ";

cin>>number;

if(0>=number>=10)

{

cout<<"Blue";

}

else if (11>=number>=20)

{

cout<<"Red";

}

else if (21>=number>=30)

{

cout<<"Green";

}else

cout<<"It is not a correct colour option.";

}

if number is 0 - 10 print blue

if number is 11- 20 print red

if number is 21-30 print green else

it is not a correct colour option

2 Answers

0 votes
answered Nov 5, 2020 by Saksham Rajput (140 points)
TRY THIS :
#include <iostream>

using namespace std;

int
main ()
{


  int number;

  cout << "Please enter the number between 0 to 30: ";

  cin >> number;

  if (0 <= number && number <= 10)

    {

      cout << "Blue";

    }

  else if (11 <= number && number <= 20)

    {

      cout << "Red";

    }

  else if (21 <= number && number <= 30)

    {

      cout << "Green";

    }
  else
    {
      cout << "It is not a correct colour option.";

    }

  return 0;
}
0 votes
answered Nov 5, 2020 by Peter Minarik (86,900 points)

Problem #1

Your logic is wrong. There aren't any numbers that would be "0>=number>=10" i.e. less or equal to 0 but at the same time greater or equal to 10. The correct logic would be to look for a number that is at least 0 but not larger than 10 (0 <= number <= 10).

The same apply for the rest of the checks.

Problem #2

In many programming languages you cannot exactly use the same expressions as you'd use in mathematics. To tell the C compiler you want to check if a number is at least 0 and is no more than 10 then you have to describe this with two conditions combined together with an and (&&) operator:
0 <= number && number <= 10

Correct Code

#include <iostream>
using namespace std;

main()
{
    int number;
    cout << "Please enter the number between 0 to 30: ";
    cin >> number;
    if (0 <= number && number <= 10)
    {
        cout << "Blue";
    }
    else if (11 <= number && number <= 20)
    {
        cout << "Red";
    }
    else if (21 <= number && number <=30)
    {
        cout << "Green";
    }
    else
    {
        cout << "It is not a correct colour option.";
    }
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...