Down25
Down25

Reputation: 55

Infinite Loop in C when inputting char

The following C program goes into an infinite loop when the user inputs a char for their choice of shape and inputs a char as the length of the shape. For example when ask to choose a shape if they input any char like s or [ it goes into an infinite loop samething when putting in the value of the length or radius.

#include <stdio.h>
int main()
{
 float area_of_circle, radius, area_of_rectangle, length, width, 
 area_of_triangle, 
 base, height;
 const float PI =  3.14159265358979323846 ;
 int choice;

do
{
    printf("Choose a shape to calculate it's area:\n"
       "1. Rectangle\n"
       "2. Triangle\n"
       "3. Circle\n"
       "4. Exit\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    switch (choice)
    {
        case 1:
            printf("Enter the length of the rectangle: ");
            scanf("%f", &length);
            while (length <= 0)
            {
                printf("Invalid length. Please enter a positive number: ");
                scanf("%f", &length);
            }
            printf("Enter the width of the rectangle: ");
            scanf("%f", &width);
            while(width <= 0)
            {
                printf("Invalid width. Please enter a positive number: ");
                scanf("%f", &width);
            }
            area_of_rectangle = length * width;
            printf("The area of the rectangle is: %.2f\n", area_of_rectangle);
            break;

        case 2:
            printf("Enter the base of the triangle: ");
            scanf("%f", &base);
            while(base <= 0)
            {
                printf("Invalid base. Please enter a positive number: ");
                scanf("%f", &base);
            }
            printf("Enter the height of the triangle: ");
            scanf("%f", &height);
            while(height <= 0)
            {
                printf("Invalid height. Please enter a positive number: ");
                scanf("%f", &height);
            }
            area_of_triangle = 0.5 * base * height;
            printf("The area of the triangle is: %.2f\n", area_of_triangle);
            break;

        case 3:
            printf("Enter the radius of the circle: ");
            scanf("%f", &radius);
            while(radius <= 0)
            {
                printf("Invalid radius. Please enter a positive number: ");
                scanf("%f", &radius);
            }
            area_of_circle = PI * radius * radius;
            printf("The area of the circle is: %.2f\n", area_of_circle);
            break;

        case 4:
            printf("Exiting the program...\n");
            break;
        default:
            if(choice <= 1 || choice >= 5)
            printf("Invalid choice. Please try again.\n");
            break;
    }
} while (choice != 4);

return 0;}

Upvotes: 1

Views: 69

Answers (0)

Related Questions