Not able to create loop with goto statement

52 Views Asked by At

Hey everyone I created this program to calculate the net amount a customer has to pay after the discount . It calculates the discount on either millcloth or handloom items. I tried to use goto to create a loop that terminates when you enter a choice that is neither handloom nor millcloth, but it terminates after just one iteration. How do I create a loop with goto that will terminate only when I enter the wrong alphabet?

// a clothes showroom has announced a discount on mill cloth and handloom items , wap using switch and if //stmts to compute the net amount to be paid by customer
#include<stdio.h>
float netmillcloth(float a)
{
    if(a>300)
    a-=0.10*a;
    else if(a>200)
    a-=0.075*a;
    else if(a>100)
    a-=0.05*a;
    
    return a;
}


float nethandloom(float a)
{
    if(a>300)
    a-=0.15*a;
    else if(a>200)
    a-=0.10*a;
    else if(a>100)
    a-=0.075*a;
    else 
    a-=0.05*a;
    
    return a;
}
int main()
{
    char item;
    float purchase_amt, net;     // net is amount to be paid after discount
    input:
        
        
        printf("Enter the type of item bought\nM for millcloth\nH for handllom items\nother key to end program\n");
        scanf("%c",&item);
        
        switch(item)
       {
            case 'M':
            case 'm':
                printf("\nenter purchase amount:");
                scanf("%f",&purchase_amt);
                net=netmillcloth(purchase_amt);
                break;
            case 'H':
            case 'h':
                printf("\nenter purchase amount:");
                scanf("%f",&purchase_amt);
                net=nethandloom(purchase_amt);
                break;
            default:
                goto stop;
        }

    
printf("\nThe final amount to be paid is:%f\n\n",net);
goto input;
stop:
    printf("\nEnd of program");
        
    
}

I used goto statement but it did not result in a loop

1

There are 1 best solutions below

0
gulpr On

It is because scanf leaves the '\n' in the buffer so the second loop reads it and switch goes to default:

Read the string cleaning the buffer.

int main()
{
    char item[10];
    float purchase_amt, net;     // net is amount to be paid after discount
    input:
        
        
        printf("Enter the type of item bought\nM for millcloth\nH for handllom items\nother key to end program\n");
        fgets(input, sizeof(input), stdin);
        switch(item[0])
        {
            /* ... */