954,202 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Using loop functions

When using loop functions or statements which loop statement do you prefer to use that would be easy for a beginner like me to use:
The do while loop, for loop, or while loop. I ask because I am to re-write my code from using the If statement to using one of the stated loop functions into my code. I am writing a coke machine program, I haven't started re-writing it yet I wanted to know which one of the stated loop functions would be practical for a beginner like me to use. If you need to see my code here it is. It is written in If statements, I haven't started on the loop functions yet.

#include <stdio.h>
 
int main()
{
  char drinkchoice;    
  float insert;    
  float money = 1.00;   
  float totalinsert;    
  
  
 printf("\nHow much do you wish to insert: ");   
 scanf("%f", &insert);                       
 
 
 
 
 if(totalinsert < money)                       
 {
  printf("Please insert more money: ");
  scanf("%f", &insert);
  totalinsert = insert + totalinsert;
 }
 
 if(totalinsert < money)
 {
  printf("Please insert more money: ");
  scanf("%f", &insert);
  totalinsert = (insert + totalinsert);
 }
 
 if(totalinsert < money)
 {
  printf("Please insert more money: ");
  scanf("%f", &insert);
  totalinsert = (insert + totalinsert);
 }
 
 if(totalinsert < money)
 {
  printf("Please insert more money: ");
  scanf("%f", &insert);
  totalinsert = (insert + totalinsert);
 }
 
 if(totalinsert == money)        
  {
   printf("\nWhat would you like.");  
   printf("\nPress 1 for coke\nPress 2 for sprite\nPress 3 for  drpepper: ");
   scanf("%c", &drinkchoice);
   totalinsert = (totalinsert == insert);
          getchar();
          }
 
  
  
  if(drinkchoice == '1')      
  {
  printf("here is you coke");
  scanf("%c", &drinkchoice);
  getchar();
  }
  if(drinkchoice == '2')
  {
  printf("here is your sprite");
  scanf("%c", &drinkchoice);
  getchar();
  }
  if(drinkchoice == '3')
  {
  printf("here is your dr pepper");
  scanf("%c", &drinkchoice);
  getchar();
  }
  
  
  
 
 
 getchar();
 return 0;
 
 
}
jlb_2_99
Newbie Poster
6 posts since May 2007
Reputation Points: 10
Solved Threads: 0
 

Short answer would be to have a while loop controlled by the totalinsert and money variables

while( totalinsert < money)
{
   /* ask for money here, add it to total insert */
}
/* you get here when you have enough totalinsert */
jim mcnamara
Junior Poster
180 posts since May 2004
Reputation Points: 62
Solved Threads: 10
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You