Using Switch statement

Discussion in 'C' started by Ubha, Dec 18, 2006.

  1. Ubha

    Ubha New Member

    Joined:
    Dec 17, 2006
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    Dear all,

    I did this program using switch statement but it gives no result.

    Please help to code.
    Code:
    #include <stdio.h>
    #include <conio.h>
    int main(void)
    {
        int menu;
        float kilo,meters;
        int q,x;
    
        printf("enter in weight and height -->");
        scanf("%f %f", &kilo, &meters);
        q=kilo/(meters*meters);
        printf("Value of q is %d",q);
    
        switch (q)
            {
        case 1:
    	if (q<20)
    	printf("Underweight \n");
    	break;
    	case 2:
    	if (q>=20 && q<25)
    	printf("Healthy Weight \n");
    	break;
    	default: printf("Extremely Overweight \n");
    	}
    
        getch();
    }
    thankx
    Ubha
     
    Last edited by a moderator: Dec 18, 2006
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    What are the values of kilo and meters you are entering.
     
  3. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    You have the idea of the switch/case all wrong. You don't just number the cases with ordinals, such as "case 1:". The case is the value you want to test against, akin to "if (q == switchVariable". Your code won't enter the case block because q is not == 1, nor is it == 2. Remember that I told you the case value has to be a constant. That's why the switch is not as flexible as an if.

    Point 2: conio is not a standard library function; it raises issues of portability. Sometimes one has to forego portability. Not in this case. Simply use getchar () to pause. So the user has to hit the enter key? Big hootywahwah, who cares?
     
  4. Ubha

    Ubha New Member

    Joined:
    Dec 17, 2006
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    values of kilo and meters are floating like 65.2 and 1.7
     
  5. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    that means q=22 and so default string should be printed.

    About what DaWei is saying is also correct that when q is 1 in case 1: its not possible to satisfy the conditions.
     
  6. Ubha

    Ubha New Member

    Joined:
    Dec 17, 2006
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    yes when q=22 i want to print "Underweight" . how to do this using switch statement.
     
  7. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    Here is an example. Note that in the first example the case values are the values you are screening for. Remember that I stated that they must be constants. Expressions and variables do not work. This is one reason that switches aren't always the preferred method. Statements that the switch is more efficient are usually full of crap, also. Unless the compiler chooses to emit a jump table, you will find that the emitted machine code is virtually identical.

    The second example addresses your problem. Any use of a switch here is just contraindicated.

    Please note that the return of scanf is tested in every instance. You are asking your user for input that must be gathered AND CONVERTED. What if it doesn't convert? Your program will run off into the weeds and barf on its shoes, that's what. There is nothing to prevent your user from entering "a b", either in error, or maliciously. The rather expert bozos that wrote the utility functions almost always give them a return value. If you don't use it, you are not (yet) competent, much less an expert. In some situations you will need to resort to other functions to determine the exact cause of an error. feof () and ferror () come to mind.
    Code:
    #include <stdio.h>
    
    int utOh (char *troubleInRiverCity)
    {
        fprintf (stderr, "%s\n", troubleInRiverCity);
        return -1;
    }
    
    int main(void)
    {
        int menu;
        float kilo, meters;
        int q, x;
    
        printf ("Enter an integer: ");
        if (scanf ("%d", &q) != 1)
    	return utOh ("Bad input");
    
        switch (q)
        {
    	case 7: puts ("Congratulations, you collect\n\n");
    		break;
    	case 2: puts ("Woopsie, you crapped out\n\n");
    		break;
    	default: printf ("Your point is %d\n\n", q);
        }
    
        printf ("Enter weight and height: ");
        if (scanf ("%f %f", &kilo, &meters) != 2)
    	return utOh ("Bad input");
    
        q = kilo / meters * meters;
        printf ("q is %d\n" , q);
    
        if (q < 20) puts ("You are underweight\n");
        else if ((q >= 20) && (q < 25)) puts ("You are at a healthy weight\n");
        else puts ("Give up the doughnuts, lardazz\n");
    
        puts ("Press ENTER to exit (sounds silly, I know");
        rewind (stdin);
        getchar ();
    
        return 0;
    }
    
     
  8. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Impressively written code DaWei, there are a lot of things we can learn from you.
    Firstly, I didn't know that we could use scanf's return value like that.
    Secondly, I didn't know we could rewind the STDIN, i guess rewind (stdin) clears the screen, please explain this.
     
  9. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    The documentation for f/s/scanf clearly indicates that they return the number of items sucessfully read AND ASSIGNED, or, under certain conditions, EOF. That is why I recommend to novices that they read the documentation for functions that they use. Having programmed life-support equipment, I am fully aware of the actual criminal liability one may subject oneself to by indulging in sloppy coding practices, regardless of whether it is due to negligence or ignorance.

    The use of "rewind (stdin)" is more problematic. I use it to clear the input buffer so that the "getchar ()" won't terminate because of things left in the buffer by scanf (a very common occurrence). Some people use "fflush (stdin)", and it works on some compilers, but "fflush" is distinctly specified to work on output buffers, not input buffers.

    "rewind (stdin)" is a synonym for "fseek(stdin, 0L, SEEK_SET)". "fseek" is, of course, defined to work for both input and output files. There is a valid question about whether or not one can rewind a terminal (go back in the past? nahhhh). Most systems will rewind stdin by clearing the buffer. Others will generate an error. I would never use it in production code. It is there simply to make the getchar () work under the conditions stated above. The use of the getchar () is subject to question. It is simply there to keep the window open so that the user can see the results of the app. It is a characteristic of programs that they are SUPPOSED to terminate when they're done. The schlocky use of getchar () is just a way to make "done" contingent upon user input, in case the app was started by a tool (compiler/linker) or by double-clicking an icon. The sure way to keep the window open is to start the app from the command line. The window thus belongs to "cmd", not the app, and will still be there when the app terminates.

    C does not provide a reliable way to clear the input stream associated with stdin. C++ does. Unless you dink with stdin, it is a buffered stream. It does no good to programmatically dink with the put and get pointers for the stream because the buffer is filled by issuing a raw "read ()". There is nothing in the buffer to use or clear until the read terminates. This is conditioned on the detection of a newline. You can't know to dink with the pointers until a condition has been met that means you don't HAVE to dink with the pointers.

    Input between the standard stream (stdin) and the actual input device is obviously implementation specific. After all, the system may have a 10-key pad or some keyboard other than the type usually associated with a specific implementation such as the typical desktop PC. This means that for reliable performance, you deal with the implementation (in other words, portability goes out the window). This is not, de facto, a Bad Thang. No one expects code generated on their PC to be able to port directly to their automobile and control the fuel/air mixture. Portability has to be addressed sensibly.

    If one wants to absolutely and correctly deal with the keyboard in Windows, one uses the Windows Console API, which is a couple of implementation layers between standard C and the machine. For *nix, one would use implementation-specific features associated with unistd.h, termio.h, stuff of that ilk. For a mail sorter for the USPS, an intravenous infusion pump, or a Polaroid film battery tester/sorter, one would use something else entirely different for each case.

    For trivial examples, I use "rewind (stdin)", which has no effects regarding clearing the screen, incidentally. It may not work for every viewer of the thread. If not, ask, and a suitable other solution can be pursued.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice