I seem to be getting this runtime error with my C code. What am I missing?? Here
ID: 670027 • Letter: I
Question
I seem to be getting this runtime error with my C code.
What am I missing?? Here is the code
#include <stdio.h>
/* function returning the Area of a rectangle */
float Area(float length, float width)
{
return length*width;
}
/* function returning the Perimeter of a rectangle */
float Perimeter(float length, float width)
{
return 2*(length+width);
}
int main ()
{
/* variable definition: */
float length, width, Results;
int menuSelect;
length = 1;
// While a positive number
while (length > 0)
{
printf ("Enter length and width of rectangle : ");
scanf("%f", &length);
scanf("%f", &width);
if (length > 0)
{
printf ("Enter 1 to calculate Area, 2 to Calculate Perimeter : ");
scanf("%d", &menuSelect);
if (menuSelect == 1)
{
// Call the Area Function
Results = Area(length, width);
printf("Area of rectangle is %f ",Results);
}
else if (menuSelect == 2)
{
// Call the Perimeter function
Results = Perimeter(length, width);
printf("Perimeter of rectangle is %f ",Results);
}
else printf("Invalid menu item, only 1 or 2 is accepted ");
}
}
return 0;
}
Explanation / Answer
Program modified and tested. Modifications to the program have appropriate comments in the same line of code.
Modified Program is working perfectly and is pasted below:
#include <stdio.h>
/* function returning the Area of a rectangle */
float Area(float length, float width)
{
return length*width;
}
/* function returning the Perimeter of a rectangle */
float Perimeter(float length, float width)
{
return 2*(length+width);
}
int main ()
{
/* variable definition: */
float length, width, Results;
int menuSelect;
length = 1;
// While a positive number
//while (length > 0) --Not Required, so commented
//{ --Not Required, so commented
printf ("Enter length and width of rectangle: "); //colon modified appropriately
scanf("%f", &length);
scanf("%f", &width);
//if (length > 0) --Not Required, so commented
//{ --Not Required, so commented
printf ("Enter 1 to calculate Area, 2 to Calculate Perimeter: "); //colon modified appropriately
scanf("%d", &menuSelect);
if (menuSelect == 1)
{
// Call the Area Function
Results = Area(length, width);
printf("Area of rectangle is %f ",Results);
}
else if (menuSelect == 2)
{
// Call the Perimeter function
Results = Perimeter(length, width);
printf("Perimeter of rectangle is %f ",Results);
}
else printf("Invalid menu item, only 1 or 2 is accepted ");
//} --Not Required, so commented
//} --Not Required, so commented
return 0;
}