The strangest thing happens.

Started by net2011, December 18, 2011, 03:17:54 AM

Previous topic - Next topic

net2011

Hi everyone. I am using version 6.5 and when only one of the conditions 1 through 4 should be true the statement under else is also executed for some reason. For example, when I run the following program

#include <stdio.h>

main()
{
   int x;

   printf("Choose a number: \n");
   printf("1.   capachino: \n");
   printf("2.   Tea/chai: \n");
   printf("3.   Mikatho: \n");
   printf("4.   no order sorry: \n");
   scanf("%d", &x);

   if(x == 1)
   {
      printf("Capachino is offered!\n");
   }
   if(x == 2)
   {
      printf("Tea/chai is offered!\n");
   }
   if(x == 3)
   {
      printf("Mikatho is offered!\n");
   }
   if(x == 4)
   {
      printf("No order, sorry.\n");
   }
   else
   {
      printf("Now I don't know what to do.\n");
   }
}

and let's say I enter number 4, the statement under else is also executed for some reason. Shouldn't everything but x == 4 be false? If so, why in the world would the statement under else be executed after choosing an option 1 through 4?

I had to include this if statement under else

if(x != 1 && x != 2 && x != 3 && x != 4)
     {
           printf("Now I don't know what to do.\n");
     }

and it fixed the problem but I don't think I should've had to do this. Can someone please tell me what is going on or what I am doing wrong? Thanks.

CommonTater

#1
What you have there is called the "dangling else" problem...  Which if statement does the else belong to?

The fix for that is with this construct...

#include <stdio.h>

main()
{
   int x;

   printf("Choose a number: \n");
   printf("1.   capachino: \n");
   printf("2.   Tea/chai: \n");
   printf("3.   Mikatho: \n");
   printf("4.   no order sorry: \n");
   scanf("%d", &x);

   if(x == 1)
   {
      printf("Capachino is offered!\n");
   }
    else if(x == 2)
   {
      printf("Tea/chai is offered!\n");
   }
   else if(x == 3)
   {
      printf("Mikatho is offered!\n");
   }
   else if(x == 4)
   {
      printf("No order, sorry.\n");
   }
   else
   {
      printf("Now I don't know what to do.\n");
   }
}


Alternatively you can use swtich()....


#include <stdio.h>

int main(void )
{
   int x;

   printf("Choose a number: \n");
   printf("1.   capachino: \n");
   printf("2.   Tea/chai: \n");
   printf("3.   Mikatho: \n");
   printf("4.   no order sorry: \n");
   scanf("%d", &x);
   switch (x)
    {
     case 1:
        printf("Capachino is offered!\n");
        break;
     case 2:
        printf("Tea/chai is offered!\n");
        break;
     case 3:
        printf("Mikatho is offered!\n");
        break;
      case 4 :
        printf("No order, sorry.\n");
        break;
      default :
        printf("Now I don't know what to do.\n");
   }

  return 0;
}




net2011

Thanks for the help common tater ! ! !

CommonTater