2 Replies - 285 Views - Last Post: 14 May 2013 - 09:51 PM Rate Topic: -----

#1 ThatsSoShaneka  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 13-April 12

Switch within a Do While statement question

Posted 13 May 2013 - 11:21 AM

Basically I'm having some trouble getting this code to work the way it should. This is the question:

Write a C program that repeatedly asks the user to enter an integer number.
If the number is negative then the program should print out the message “BYE” and stop
If the number is either 0 or 1 then it should print out “VERY LOW”
If the number is either 2 or 3 it should print out “LOW”
If the number is either 4 or 5 it should print out “MEDIUM”
If the number is either 6 or 7 it should print out “HIGH”
If the number is either 8 or 9 it should printout “VERY HIGH”
Any other number should cause the program to output the message “Input a value between 0 and 9 only”
Use a switch statement inside the loop to select the appropriate message to print.

Here is the code I've got so far:

#include <stdio.h>

int main()
{
	int num;

		do
		{
		printf("Enter a value: \n");
		scanf(" %i", &num);
		}
		while (num >= 0);
		{
			switch (num)
			{
				case 0 : 
				case 1 : printf("VERY LOW\n");
						break;
				case 2 :
				case 3 : printf("LOW\n");
						  break;
				case 4 :
				case 5 : printf("MEDIUM\n");
						  break;
				case 6 :
				case 7 : printf("HIGH\n");
						  break;
				case 8 :
				case 9 : printf("VERY HIGH\n");
						  break;
				default : printf("Input a value between 0 and 9 only\n");
			}
		}
			
	printf("BYE\n");
	
	return 0;
}


When I run the program and input a positive number nothing happens and it just asks me to enter another value repeatedly, but doesn't display the relevant messages in the switch statement. Then if I input a negative number it displays the message 'Input a value between 0 and 9' and 'BYE' then it stops.

Is This A Good Question/Topic? 0
  • +

Replies To: Switch within a Do While statement question

#2 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3549
  • View blog
  • Posts: 10,993
  • Joined: 05-May 12

Re: Switch within a Do While statement question

Posted 13 May 2013 - 12:11 PM

Your do-while loop starts at line 7 and ends at line 12. When the while condition on line 12 is satisfied, it loops back to line 7.
Was This Post Helpful? 1
  • +
  • -

#3 buffalobill  Icon User is offline

  • D.I.C Head

Reputation: 21
  • View blog
  • Posts: 188
  • Joined: 08-July 08

Re: Switch within a Do While statement question

Posted 14 May 2013 - 09:51 PM

Another way of saying what Skydiver has said is:
Place the switch statement inside the loop.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1