Calculate the total area and volume occupied by a cylinder.
Correct or not?

#include <stdio.h>

#include <math.h>



int main()

{

float At, V, r, h;



printf("\n ===========Calculate the total area and volume occupied by a cylinder============\n");

printf("\n the base radius.......: ");

scanf("%f", &r);

printf("\n Cylinder height.: ");

scanf("%f", &h);



At = ((2 * M_PI * r * r) + (2 * M_PI * r * h));

V = (M_PI * r * r * h);



printf("\n Area = %f", At);

printf("\n Volume = %fnn"\n, V);

printf("\n");



}

Dani AI

Generated

The formulas in the original post are essentially correct: total surface area = lateral area + two bases, and volume = base area × height. The posted program will compute those values, but it contains a small syntax error in the volume printf and a few robustness/usability issues that cause crashes or incorrect behavior on bad input.

Key practical points (aligned with earlier replies):

  • was right to flag scanf as risky: it easily leaves the input stream in a bad state and can mis-handle non-numeric input.
  • 's suggestion to use meaningful names (for example radius, height, surface_area, volume) improves readability and maintenance.
  • provided a good direction: validate input, loop for repeated calculations, and separate concerns into functions.
  • is correct that the math is fine once input/printing bugs are fixed.

Portability and numeric tips:

  • Prefer double for geometry calculations (math functions use double and give better precision than float).
  • M_PI is not guaranteed by ISO C; compute PI portably with acos(-1.0) or define a named constant.

Minimal examples (portable snippets):

Compute PI and the results:

double PI = acos(-1.0);
double surface = 2.0 * PI * radius * (radius + height);
double volume  = PI * radius * radius * height;

Safer input pattern (parse a line and convert):

char buf[128];
if (fgets(buf, sizeof buf, stdin)) {
    char *end;
    double r = strtod(buf, &end);
    if (end == buf || (*end != '\n' && *end != '\0')) { /* invalid input */ }
}

Additional suggestions: reject non-positive radius/height, print results with consistent formatting (e.g. printf("%.6f\n", value);), and add small unit tests or example inputs to confirm behavior. These small changes make the program compile reliably, handle bad input gracefully, and produce reproducible results.

Recommended Answers

All 5 Replies

Besides the fact that scanf is dangerous, it looks ok.

Were you having any problems with it?

Yes.
Suggestion: give your variables a mainingful name. Instead of At use something like surface

Some next steps:

  1. validate and 'crash proof' input

  2. loop for more input until no more input desired

  3. break up program into jobs using functions

This little demo revision of your code my give you some more ideas ...

/* cylinderAreaVol.c */

#include <stdio.h>
#include <ctype.h> /* re. tolower */

#define MY_PI 3.1415926536

/* forward function declarations / function prototypes */

/* pass in prompt and min val to accept */
float takeInFltMin( const char* msg, float min ) ;

void calAndShow( float, float ) ;

char takeInChar( const char* msg ) ;
int more() ;



int main()
{
    do
    {
        float radius, height;

        printf("\n========Total surface area and "
                   "volume of a cylinder========\n");

        radius = takeInFltMin( "\nThe base radius.......: ", 0 );
        height = takeInFltMin( "\nCylinder height.......: ", 0 );

        calAndShow( radius, height );
    }
    while( more() );

    return 0;
}



/* loop until user takes in a valid int ... after prompt(s) ...  */
/* int here is also checked and accepted iff in  range >= min */
float takeInFltMin( const char* msg, float min )
{
    float goodVal = 0, val = 0;

    while( !goodVal )
    {
        /* show prompt for input ...
           fflush( stdout) ensures prompt displayed right NOW
        */
        printf( msg ); fflush( stdout );

        /* Note logic below ...

           if scanf returns 1 below means ...
           ***there WAS ONE***
           good int data presented at first in input stream

           then ... if getchar() == '\n'
           ***that means that '\n' WAS the VERY NEXT CHAR***

           which means no space or other chars entered there
           before a '\n' char was entered ...
           so ... ***WAS good float*** data presented
           i.e. no 'junk' was entered by user 'by accident'
                (after int data was entered and before '\n' pressed)
        */

        if( scanf( "%f", &val ) == 1 && getchar() == '\n' )
        {
            goodVal = 1; /* Ok ... so far ... so good ... */
        }
        else
        {
            printf( "\nDecimal input only here please ...\n" );
            while( getchar() != '\n' ) ; /* flush stdin ... */
        }

        /* NOW check if input val was in the desired range min <= val */

        if( goodVal && ( val < min ) )
        {
            goodVal = 0; /* reset to 'false' since val NOT in desired range */
            printf( "\nValid input only in range %f...\n", min );
        }

    } /* end while ... */

    return val;
}

char takeInChar( const char* msg )
{
    char chr;
    printf( msg ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' ) while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}
int more() /* defaults to 'true'/'yes'/'1' ... unless 'n' or 'N' entered */
{
    if( tolower( takeInChar( "\nMore (y/n) ? " )) == 'n' ) return 0;
    /* else ... */
    return 1;
}

void calAndShow( float r, float h )
{
    float surfaceArea = 2 * MY_PI * r* ( h + r );
    float volume = MY_PI * r * r * h;

    printf( "\nFor radius = %.2e and height = %.2e ...\n", r, h );

    printf( "Cylinder surface area = %.2e\n", surfaceArea );

    printf( "Cylinder volume       = %.2e\n", volume );
}

Oops ... see/use the following instead (to take in a float)

(I had modified the code from a student example I gave years ago ... an example for integer 'take in' ... and missed changing a few comments (and things) re. the float version ...)

/*
    Prompt and loop until user takes in a valid float.
    The float val input here is also checked and accepted
    iff in  range >= min
*/
float takeInFltMin( const char* msg, float min )
{
    float val = 0;
    int isGoodVal = 0;
    while( ! isGoodVal )
    {
        /* show prompt for input ...
           fflush( stdout) ensures prompt displayed right NOW
        */
        printf( msg ); fflush( stdout );

        /* Note logic below ...

           if scanf returns 1 below means ...
           ***there WAS ONE***
           good float data presented at first in input stream

           then ... if getchar() == '\n'
           ***that means that '\n' WAS the VERY NEXT CHAR***

           which means no space or other chars entered there
           (after float val) before a '\n' char was entered ...
           so ... ***WAS good float*** data presented
           i.e. no 'junk' was entered by user 'by accident'
           (after int data was entered and before '\n' pressed)
        */

        if( scanf( "%f", &val ) == 1 && getchar() == '\n' )
        {
            isGoodVal = 1; /* Ok ... so far, so good */
        }
        else
        {
            printf( "\nDecimal input only here please ...\n" );
            while( getchar() != '\n' ) ; /* flush stdin ... */
        }

        /* NOW check if input val was in the desired range min <= val */

        if( isGoodVal && ( val < min ) )
        {/* reset to 'false' since val NOT in desired range */
            isGoodVal = 0; 
            printf( "\nValid input only in range %f...\n", min );
        }

    } /* end while ... */

    return val;
}

everything is correct what problem u got in this. coding is correct, post problem if have

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.