Home > Enterprise >  How to use loop in an if else statement in C Programming
How to use loop in an if else statement in C Programming

Time:07-06

I need to construct an algorithm that reads the membership type and item price. The output will be the amount to pay after discount. The program allows both lowercase and uppercase character input and will prompt user to reenter membership type if code entered is invalid.

The membership works as following: Platinum - P - 30% Gold - G - 20% Silver - S - 10% Non-member - X - 0%

I manages to get an output when the membership is inserted correctly (P,G,S or X). However when a wrong character is inserted, I am not sure how to repeat the program until I get the correct output...



int main()
{
   
    
    printf("Suria Supermarket");
    
    char membershipType;
    char membershipTypeTwo;
    float itemPrice;
    
    
    char membershipType2;
    float itemPrice2;
    
    printf("\nEnter membership type (S or G or P, X for non-member): %c", membershipType);
    scanf("%c", &membershipType);
    
    printf("Enter item price (RM): ",itemPrice); 
    scanf("%f",&itemPrice);
    
    
   float discountedAmount;
   float discountedAmount2;
       
    if(membershipType=='s') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 10\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.1));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
        
    }
    else if(membershipType=='S') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 10\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.1));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
        
    } 
    else if(membershipType=='g') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 20");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.2));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='G') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 20");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.2));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='p') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 30");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.3));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='P') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 30");
        printf("\n");
        discountedAmount = ((itemPrice)-(itemPrice*0.3));        
        printf("Discounted Price: RM %1.2f", discountedAmount);
    } 
    else if(membershipType=='x'){
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 0");
        printf("\n");      
        printf("Discounted Price: RM %1.2f", itemPrice);
    }
        else if(membershipType=='X') {
        printf("\n");
        printf("Item Price: RM %1.2f", itemPrice);
        printf("\n");
        printf("Membership Type: %c",membershipType);
        printf("\n");
        printf("Discount (%%): 0");
        printf("\n");      
        printf("Discounted Price: RM %1.2f", itemPrice);
    }
    else {
        printf("Invalid code, please enter again.");
        printf("\n");
        printf("\n");
        if(membershipTypeTwo!='s','S','g','G','p','P','x','X');
        
        printf("Enter membership type (S or G or P, X for non-member): %c",membershipTypeTwo);
        scanf("%c%*c",&membershipTypeTwo);
        printf("Enter item price (RM): ",itemPrice); 
        scanf("%f",&itemPrice);
        
            
}

       return 0;

}```

CodePudding user response:

Instead of large if-else ladders use switch statement

switch(toupper((unsigned char)membershipType))
{
    case 'P':
    /* ... */
    break;
    case 'G':
    /* ... */
    break;
    default:
        print("Wrong membership type\n");
    break;
}

CodePudding user response:

Write a loop to read the input value, exiting only when there's a match or an error condition on the input stream.

As a bit of a labor-saver, you can put all the valid membership types into a string like "PGSX" and use the strchr library function to see if the entered value is part of the string, rather than explicitly checking against each possible character. You can also use the toupper or tolower functions to convert the input to one of the other case for comparisons.

/**
 * These headers are necessary for the code below.
 */
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
...
/**
 * Create a flag to tell us if we need to keep scanning
 * for input.
 */
bool done = false;
...
while ( !done )
{
  /**
   * Stores the number of items read from scanf.
   */
  int itemsRead;

  /**
   * Create a string with the valid input characters.
   */
  const char *membershipTypeList = "PGSX";

  printf( "\nEnter membership type..." );
  /**
   * The leading blank in the " %c" format string
   * tells scanf to skip over any leading whitespace
   * so you don't accidentally pick up a newline from
   * a previous entry.
   *
   * scanf returns the number of items successfully
   * read and assigned, or EOF on end-of-file or 
   * error.  A return value of 1 means we read *something*;
   * we then compare that against the values in the 
   * membershipTypeList string.  If strchr returns
   * NULL, the the character wasn't in the string
   * and we prompt the user to try again.  A return 
   * value of 0 means we had a matching failure, 
   * which almost never happens with %c because 
   * it will match any printing character.  A
   * return value of EOF means scanf either saw
   * and end of file condition or an error on
   * the input stream.
   */
  if ( (itemsRead = scanf( " %c", &membershipType )) == 1 )
  {
    /**
     * You can assign the result of a comparison
     * to an int or boolean variable.  If this
     * looks too weird for you, you can replace 
     * it with:
     *
     *    if ( strchr(...) != NULL )
     *      done = true;
     */
    done = strchr( membershipTypeList, 
      toupper( membershipType ) ) != NULL;

    if ( !done )
       printf( "\nThat wasn't a valid membership type, try again..." );
  }
  else if ( itemsRead == 0 )
  {
    printf( "\nMatching failure on input, try again..." );
  }
  else
  {
    done = true;
  }
}
/**
 * Check to see if we exited the loop because
 * a problem with the stream
 */
if ( feof( stdin ) || ferror( stdin ) )
{
  fprintf( stderr, "Error on input stream, exiting...\n" );
  exit( -1 );
}

/**
 * Process membershipType as normal
 */

Welcome to handling interactive input in C. It's usually a pain in the butt.

  • Related