Nik
Nik

Reputation: 11

If else errors in C

guys, I need help I'm new in programming and I have problems with the if-else statement

I tried deleting every "paragraph" that contains the word else/else if and it worked only for the if "paragraph" though(obviously cuz the others aren't there)

float w,l,r,pi,rec,tri,cir; char shape;

printf("What shape is the desired calculated area?\n");
scanf("%c",&shape);

    if(shape=='R')
    printf("width: ");
    scanf("%f",&w);
    printf("length: ");
    scanf("%f",&l);
    rec=w*l;
    printf("\nThe area for the rectangle is %.2f Cm2\n",rec);

    else if(shape=='C')
    printf("radius: ");
    scanf("%f",&r);
    pi=3.142;
    cir=pi*r*r;
    printf("\nThe area for the rectangle is %.2f Cm2\n",cir);

    else if(shape=='T')
    printf("width: ");
    scanf("%f",&w);
    printf("length: ");
    scanf("%f",&l);
    tri=1/2*w*l;
    printf("\nThe area for the rectangle is %.2f Cm2\n",tri);

    else
    printf("You must choose one type of shape using R C T only and only digits are allowed afterwards");

I got a message which is [Error] parse error before `else' for every line that contains the word else. Further reading of the error message says error: ‘else’ without a previous ‘if’. Any help would be appreciated

Upvotes: 0

Views: 1005

Answers (1)

J CHEN
J CHEN

Reputation: 494

using {} if your line more than one when you use "if" like

if(shape=='R'){
    printf("width: ");
    scanf("%f",&w);
    printf("length: ");
    scanf("%f",&l);
    rec=w*l;
    printf("\nThe area for the rectangle is %.2f Cm2\n",rec);
}

if(shape=='R')
printf("width: ");
scanf("%f",&w);
printf("length: ");
scanf("%f",&l);
rec=w*l;
printf("\nThe area for the rectangle is %.2f Cm2\n",rec);

Will be like below in compiler

if(shape=='R'){
    printf("width: ");
}
scanf("%f",&w);
printf("length: ");
scanf("%f",&l);
rec=w*l;
printf("\nThe area for the rectangle is %.2f Cm2\n",rec);

Upvotes: 2

Related Questions