Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Using Switch statement (http://www.go4expert.com/forums/using-switch-statement-t2279/)

Ubha 18Dec2006 10:05

Using Switch statement
 
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

shabbir 18Dec2006 10:32

Re: Using Switch statement
 
What are the values of kilo and meters you are entering.

DaWei 18Dec2006 11:36

Re: Using Switch statement
 
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?

Ubha 18Dec2006 19:42

Re: Using Switch statement
 
values of kilo and meters are floating like 65.2 and 1.7

shabbir 18Dec2006 21:17

Re: Using Switch statement
 
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.

Ubha 18Dec2006 22:04

Re: Using Switch statement
 
yes when q=22 i want to print "Underweight" . how to do this using switch statement.

DaWei 18Dec2006 22:38

Re: Using Switch statement
 
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;
}

Quote:

Originally Posted by output
Enter an integer: 7
Congratulations, you collect


Enter weight and height: 1000 3
q is 111
Give up the doughnuts, lardazz

Press ENTER to exit (sounds silly, I know


pradeep 19Dec2006 13:48

Re: Using Switch statement
 
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.

DaWei 19Dec2006 17:31

Re: Using Switch statement
 
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.


All times are GMT +5.5. The time now is 10:49.