Search code examples
cterminate

How to do this assignment in C? Part 2


The following prompts input for the radius and height, and uses those values to calculate the volume of a cylinder. How can I write this program so that it doesn't terminate when the user inputs a negative value for either radius of height? The range has to be 1-10 inclusive and no other prompts are allowed. The loop must be terminated only when something non-numeric is entered.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


float areaCirc(float r){
return (M_PI*r*r);
}

float volCyl(float r, float h){
return (areaCirc(r)*h);
}


int main(void) {
float r, h;
int k = 0;
float volume;
float avgh = 0;
float toth = 0;

do{
    float exit = scanf("%f%f", &r, &h);
    if (exit == 0) 
    {break;}
    if(r<=0 || r>10){
        printf("Invalid radius: %.2f\n",r);
    }
    if(h<=0 || h>10){
        printf("Invalid height: %.2f\n",h);
    }
    if(r>=0 && r<=10 && h>=0 && h <= 10){
    volume = volCyl(r,h);
    k = k++;
    printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
    toth = toth + h;
} }while(r>0 && h>0);
    avgh = toth/k;
    printf("Total Height: %.2f\n",toth);
    printf("Average Height: %.2f\n",avgh);

return EXIT_SUCCESS;
}

Solution

  • My specified range has to be 1 to 10 inclusive, without the negative values terminating the program, and no other prompts are allowed

    Modify your main function

    do{
        int ex = scanf("%f%f", &r, &h); //scanf returns int
    
       if (ex == 0)
        {break;}
        if(r<=0 || r>10){
            printf("Invalid radius: %.2f\n",r);
           continue;
        }
        if(h<=0 || h>10){
            printf("Invalid height: %.2f\n",h);
           continue;
        }
       // hence above conditions failed means you have given desired input
       // need not to check any conditions 
        volume = volCyl(r,h);
        k = k++;
        printf(" Cylinder %d radius %.2f height %.2f volume %.2f\n",k,r,h,volume);
        toth = toth + h;
       }while(r>0 && h>0);
    
      if(k>0) // check this other wise divide by zero will occur
        {
        avgh = toth/k;
        printf("Total Height: %.2f\n",toth);
        printf("Average Height: %.2f\n",avgh);
        }