[prog] switch statement

Jacinta Richardson jarich at perltraining.com.au
Thu Dec 16 15:35:00 EST 2004


The if statement isn't required, and personally I'd leave it out.  This 
can be done with the following changes:

> #include <iostream>
> using namespace std;
> 
> int main() {
> 	
> 	//define variables
> 	int  product; // product to be ordered
> 	int  quantity;//quantity to be ordered
> 	double price;
> 	double totalSales;
> 		
> 		
> 	// Get input from user
> 		
> 	do {
> 		product = 0;
> 		//order product desired by product number
> 		cout << "Enter the product number (enter 0 to end): ";
> 		//receive product number
> 		cin >> product;
> 			
> 				
> 		//begin switch statement, define prices of product by number
> 		switch ( product) {
> 			case 0:
> 				break;
> 					
> 			case 1:
> 				price = 2.98;
> 				break;
> 						
> 			case 2:
> 				price = 4.50;
> 				break;
> 						
> 			case 3:
> 				price = 9.98;
> 				break;
> 						
> 			case 4:
> 				price = 4.49;
> 				break;
> 					
> 			case 5:
> 				price = 6.87;
> 				break;
> 						
> 			default:
> 				cout << "INCORRECT NUMBER ENTERED. PLEASE TRY AGAIN. \n";
				continue;  /* Restart the loop */
> 						
> 		}
> 				

		// If we reach here, we must have valid input.
> 		//order quantity of product desired
> 		cout << "Enter the quantity of this product you wish to order: ";
> 		//receive quantity
> 		cin >> quantity;
> 					
> 		//calculate total
> 		totalSales += quantity * price;
> 					
>	}while (product != 0);
> 			
> 	cout << "The total sales in dollars is: " << totalSales;
> 			
> 	return 0;
> }

My rationalisation for this is that if you go and add another case in, 
you don't have to update the if statement.  It also assists in avoiding 
the case where you have cases 1-5 and 7, 9, but 6 and 8 are invalid (for 
some spurious reason).

This should always work unless I've forgotten something about calling 
continue for a loop from a switch statement....

All the best,

    Jacinta

-- 
    ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
     `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
     (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
   _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
  (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |




More information about the Programming mailing list