user3663862
user3663862

Reputation: 11

Run a program multiple times in C

I am a newbie to programing, so excuse my ignorance. And I didn't get the answer properly here in this site. It can be my searching incapability. In C I've written a code which is running fine. But I want to run the code as many time as the user wishes it to. That means, suppose after executing the Triangle area problem, user can run the program again and again. What needs to be done here? Here is the code:

#include <stdio.h>
#include <conio.h>
main()
{     

      char a;
      int base, hight, radius, length, width;
      float area, pi=3.14;
      printf("\n\tEnter T to execute the area of Triangle"
      "\n\tEnter R to execute the area of Rectangle"
      "\n\tEnter C to execute the area of Circle\n\t\n\t\n\t\n\t\n\t");
      a=getche();
      printf("\n\t\n\t\n\t\n\t");
      if(a=='T' || a=='t'){
                 printf("You want to know the Area of a Triangle."
                 "\n\tEnter your triangles Base: ");
                 scanf("%d", &base);

                 printf("\n\tEnter your triangles Hight: ");
                 scanf("%d", &hight);

                 printf("\n\tThe base is %d and the hight is %d." 
                 "So the area of your triangle is: \n\n\t\t\t\t", base,hight);

                 area= .5*base*hight;
                 printf("%f", area);
      }

       else if(a=='R' || a=='r'){
                 printf("You want to know the Area of a Rectangle."
                 "\n\tEnter your rectangles Length: ");
                 scanf("%d", &length);

                 printf("\n\tEnter your rectangles Hight: ");
                 scanf("%d", &hight);

                 printf("\n\tThe length is %d and the hight is %d." 
                 "So the area of your Rectangle is: \n\n\t\t\t\t", length,hight);

                 area= length*hight;
                 printf("%f", area);
     }

      else if(a=='C' || a=='c'){
                 printf("You want to know the Area of a Circle."
                 "\n\tEnter your circles Radius: ");
                 scanf("%d", &radius);

                 printf("\n\tThe Radius is %d." 
                 "So the area of your Circle is: \n\n\t\t\t\t", radius);

                 area= pi*radius*radius;
                 printf("%f", area);
      }else{
            printf("Invalid Input");
      }


      getch();

}

Upvotes: 1

Views: 3162

Answers (1)

Codor
Codor

Reputation: 17595

Introduce a boolean variable, say repeat. Then set up an infinite loop with do and while that repeats as long as repeat is true. After the calculation, ask the user if he or she would like to continue; the result could be read with scanf. Then, set repeat accordingly, which means that the infinite loop is terminated as soon as repeat gets false.

Upvotes: 5

Related Questions