HI,

Following is a program to calculate resistance. Can u please tell me how to make the program loop again using a 'While' statement or is there anyother way to loop the progam. Now my program runs once. Suppose if i enter wrong values, it should not terminate but rather it should ask the user to input the values again.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void print_codes(void);
double decode_char(char code);
main()

{
  char code1,code2,code3;
  double resistance;
  double color1,color2,color3;
  int flag;

  /*print codes and prompt for user input*/


  print_codes();
  printf("\n\n\tEnter three codes");

  /*Read three character codes*/


  code1= getchar();
  code2 = getchar();
  code3 = getchar();

  /*Decode each charcter code*/

  color1 = decode_char (code1);
  color2 = decode_char(code2);
  color3 = decode_char(code3);

  /* check wheterh codes are legal*/
  if (color1 == -999.0 || color2 == -999.0 || color3 == -999.0)


  printf("\n\n\tBad code -- cannot compute resistance\n");



  /*if codes were legal, compute and print resistance in ohms.*/
  else
  {

  resistance = (10.0 * color1 + color2) * pow(10.0,color3);

  printf("\n\n Resistance in ohms:\t%f\n",resistance);


  }



  }






  /* This function prints a menu of color codes to guide the user in entering input*/

  void print_codes(void)

  {
    printf("\n\n\tThe colored bands are coded as follows:\n\n\t");
    printf("COLOR\t\t\tCODE\n\t");
    printf("--------\t\t\t-------\n\n");
    printf("\tBlack----------->B\n");
    printf("\tBrown----------->N\n");
    printf("\tRed  ----------->R\n");
    printf("\tOrange---------->O\n");
    printf("\tYellow---------->Y\n");
    printf("\tGreen----------->G\n");
    printf("\tBlue--- -------->E\n");
    printf("\tViolet---------->V\n");
    printf("\tGray ----------->A\n");
    printf("\tWhite----------->W\n");

    }

    double decode_char(char code)

    {
      switch(code) {
       case 'B':
        return 0.0;
    case 'N':
        return 1.0;
        case 'R':
        return 2.0;
        case 'O':
        return 3.0;
        case 'Y':
        return 4.0;
        case 'G':
        return 5.0;
        case 'E':
        return 6.0;
        case 'V':
        return 7.0;
        case 'A':
        return 8.0;
        case 'W':
        return 9.0;
        default:
         return -999.0;
         }

         }

Thanks again for your support

Edited 3 Years Ago by happygeek: fixed formatting

move all the code that is in main into a different function -- just rename main() to something else. Then create a new main() what has a loop that calls that function

int some_function()
{
   // blabla

   return < 0 to end program, or non-0 to continue >
}

int main()
{
    while( some_function() != 0)
          ;
    return 0;
}
This article has been dead for over six months. Start a new discussion instead.