Hi,
I wrote a program which seemed very simple, a switch case nested in a while cicle. The compiler is not giving any error message, and yet when it's running, it starts an endless serie of loops and I do not understand, why.Here the code
#include<stdio.h>
int main ()
{
  
  int id;

  float value1 = 0;
  float value2 = 0;
 
  
  printf("Please enter the id number - 1 to 2 - to end\n");
	      scanf("%d",&id);
		while(id<=3)
		{
		  switch(id)
		  {
		  case 1:
		    value1 = 10 * 10;
		    printf("Value1 is: %f\n",value1);
		    break;
		    
		  case 2:
		    value2 = 20 * 20;
		    printf("Value2 is: %f\n",value2);
		    break;
		  
		  default:
		    printf("Wrong input\n");
		    break;
		  }
		}
		
      return 0;
}
Anyone knows the problem?

Thank you very much!!

Bye, bye

Fab2

Try something like below

#include<stdio.h>
int main ()
{
  
  int id = 0;

  float value1 = 0;
  float value2 = 0;
 
  
	while(id<=3)
	{
	 	printf("Please enter the id number - 1 to 2 - to end\n");
	      	scanf("%d",&id);
	  switch(id)
	  {
	  case 1:
	    value1 = 10 * 10;
	    printf("Value1 is: %f\n",value1);
	    break;
	    
	  case 2:
	    value2 = 20 * 20;
	    printf("Value2 is: %f\n",value2);
	    break;
	  
	  default:
	    printf("Wrong input\n");
	    break;
	  }
	}
		
      return 0;
}

You could try initializing all variables to zero like the above post.

Comments
Why do you think the above post was made, Mr. Obvious?

You could try initializing all variables to zero like the above post.

No. I think the point that gerard4143 was making was that the user is asked for input outside the while loop in the original code. This will definitely result in either the while loop never getting executed, or it will execute forever, since the user is never asked again for a new value of id . So if id <= 3 returns true the first time, it will always do so and the loop will run indefinitely. In gerard4143's revised code, the user is asked for a new value of id on each iteration of the while loop, so when it's checked at the start of the loop, it can have been changed by the user to a value that will exit the loop.

Initializing variable to known values is generally a good idea, but it's not the source of the infinite loop in this case.

This article has been dead for over six months. Start a new discussion instead.