cant figure out whats wrong with my program

+1 vote
asked Nov 15 by amal k (130 points)
i'm trying to run the program but it keep saying floating point exception(core dumped) i dont know whats wrong

#include <stdio.h>

int main()
{
    int age [4];
    int i=0;
    int total =0, gt=0, nt=0;
    float avg=gt/nt;
    int salary[4];
    int j=0;
    float totalsal=0;
    char gender[4];
    int k=03;
    int numF=0;
    int numM=0;
    int rank;
    int id;
    int bonus=0;
    printf("enter the age of 4 employees:\n");
    while(i<4)
    {
        scanf("%d", &age[i]);
        total+=age[i];
        if(age[i]>=30)
        {
            gt+age[i];
            nt++;
            
        }
        i++;
    }
    printf("------------------------------\n");
    printf("average age of all employees <older than or equal to 30 is %.2f\n", avg);
    printf("employees total age is %d\n", total);
    printf("------------------------------\n");
    printf("salary of each employee:\n");
    while(j<4);
    {
        scanf("%d", salary[j]);
        if(salary[j]<=2500)
        {
            totalsal+=(salary[j]-(salary[j]*.03));
        }
        else if (salary[j]>2500 && salary[j]<=4000)
        {
            totalsal+=(salary[j]-(salary[j]*.07));
            
        }
        j++;
    }
    printf("------------------------------\n");
    printf("total salary of employees is: %.2f\n", totalsal);
    fflush(stdin);
    while(k<4)
    {
        printf("enter the gender <F or M> of employees %d :",k+1);
        scanf("%c", &gender[k]);
        if(gender[k]=='f')
            numF++;
        else
            numM++;
        printf("\n");
        k++;
        fflush(stdin);
        
        
    }
    printf("------------------------------\n");
    printf("there are %d female employees in the company\n", numF);
    printf("\n");
    printf("there are %d male employees in the company\n", numM);
    printf("------------------------------\n");
    printf("what is the rank of the company?:");
    scanf("%d", &rank);
    printf("\n");
    printf("what is the ID of the company?:");
    scanf("%d", &id);
    printf("\n");
    printf("the company ID + %d", id);
    printf("    ");
    printf("rank = %d", rank);
    printf("    ");
    if(rank==1)
     bonus=15;
    else if (rank==2)
     bonus=10;
    else
     bonus=0;
    printf("bonus = %d", bonus);
    printf("------------------------------\n");
    printf("student name: nnn\n");
    printf("section:03\n");
    printf("student ID:nnn\n");
    printf("semester: Fall 2020\n");
    
}

1 Answer

0 votes
answered Nov 18 by Peter Minarik (12,220 points)

Compile your code

When you compile your code (try to run it) the compiler tells you if there are any errors or warnings. In your case, there is no error (that prevents compilation), but there is a very important warning that warns you about memory corruption:

main.c:39:17: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]

So the compiler just told you that you're supposed to provide a pointer, but you provided just a value.

To fix this, get the address (use the & -- address of -- operator) of the element in the array:

scanf("%d", &salary[j]);

Do not divide by zero

Your "Floating point exception" happens due to division by zero. Depending on what school of mathematics you study the result may be invalid -- making no sense -- or infinite (positive or negative). In most lower level programming languages, it's the first (invalid operation).

This use due to the following lines:

int total = 0, gt = 0, nt = 0;
float avg = gt / nt;

As you can see, you initialize your values gt and nt to be zero. Then calculate avg as the division of the two, which leads to the zero division error.

What you should do is calculate avg after you're done setting gt and nt. This is after your first while loop and before you print out the "average age of all employees".

Also, consider the case when there are no employees older than 30 years. Then you'd end up with zero division again, despite our best effort.

In this case, you'd need to set avg conditionally, whether or not we have anyone older than 30 years:

printf("------------------------------\n");
if (nt > 0)
    printf("average age of all employees older than or equal to 30 is %.2f\n", (float)gt / nt);
else
    printf("There are no employees who are at least 30 years old.\n")
printf("employees total age is %d\n", total);
printf("------------------------------\n");

Float vs int

When you divide two integral numbers, the result is also an integral number. E.g. 3 / 2 = 1 (not 1.5) as both 3 and 2 are integral numbers. To make a float division, you have to tell the compiler that you're dealing with floats. This is by using floating point literals (3.0 / 2.0 = 1.5) or telling the compiler to cast a variable to a float:

(float) gt / nt

As we could see this in the above code.

Typo in the code

One of your line contains a typo, but unfortunately it's a valid code, so there are no warnings about that (well, not with this warning level anyway):

gt + age[i];

Probably you meant

gt += age[i];

right?

Infinite loop

You accidentally made an infinite loop:

while (j < 4);
{
    // ...
}

Please note the semicolon at the end of the line of the while key word. This tells the compiler that the body of the while loop is not the intended part below, but an empty statement. Remove the semicolon.

Reading single characters

It is a good idea indeed to flush the stream before trying to read a single character from it. However, your loop was a bit funny, as you initialized k to be 3 not 0.

Also, back to the original matter, you want to ignore any whitespace before the character, so you'd better do

scanf(" %c", &gender[k]);

instead.

Also, for future improvements, you could check if the m/f indicator is lower or upper case and accept both. Another improvement could be to check if this indicator is f/m or something else (error case).

Loops with known number of steps

I've noticed you often have loops where we know how many times it repeats the code instructions. You use a while loop:

int i = 0;
while (i < 4)
{
    // body
    i++;
}

, but often it's easier to use a for loop instead:

for (int i = 0; i < 4; i++)
{
    // body
}

The changes

Below is the code with my changes. Please, pay attention to the TODO sections:

#include <stdio.h>

int main()
{
    int age [4];
    int total = 0, gt = 0, nt = 0;
    int salary[4];
    float totalsal = 0;
    char gender[4];
    int numF = 0;
    int numM = 0;
    int rank;
    int id;
    int bonus=0;
    printf("enter the age of 4 employees:\n");
    for (int i = 0; i < 4; i++)
    {
        scanf("%d", &age[i]);
        total += age[i];
        if (age[i] >= 30)
        {
            gt += age[i];
            nt++;
        }
    }
    printf("------------------------------\n");
    if (nt > 0)
        printf("average age of all employees older than or equal to 30 is %.2f\n", (float)gt / nt);
    else
        printf("There are no employees who are at least 30 years old.\n");
    printf("employees total age is %d\n", total);
    printf("------------------------------\n");
    printf("salary of each employee:\n");
    for (int i = 0; i < 4; i++)
    {
        printf("%d: ", i + 1);
        scanf("%d", &salary[i]);
        if(salary[i] <= 2500)
        {
            totalsal += salary[i] - salary[i] * 0.03;
        }
        else if (salary[i] > 2500 && salary[i] <= 4000)
        {
            totalsal += salary[i] - salary[i] * 0.07;
        }
        // TODO: What happens if salaries are lower then 2500 or greater than 4000? It's not summarised.
        //       Handle these cases
    }
    printf("------------------------------\n");
    printf("total salary of employees is: %.2f\n", totalsal);
    fflush(stdin);
    for (int i = 0; i < 4; i++)
    {
        printf("enter the gender <F or M> of employees %d: ", i + 1);
        scanf(" %c", &gender[i]);
        if (gender[i] == 'f' || gender[i] == 'F')
            numF++;
        else if (gender[i] == 'm' || gender[i] == 'M')
            numM++;
        else
        {
            // TODO: Handle error case, wrong gender tag
        }
        printf("\n");
        fflush(stdin);
    }
    printf("------------------------------\n");
    printf("there are %d female employees in the company\n", numF);
    printf("\n");
    printf("there are %d male employees in the company\n", numM);
    printf("------------------------------\n");
    printf("what is the rank of the company?:");
    scanf("%d", &rank);
    printf("\n");
    printf("what is the ID of the company?:");
    scanf("%d", &id);
    printf("\n");
    printf("the company ID + %d", id);
    printf("    ");
    printf("rank = %d", rank);
    printf("    ");
    if (rank==1)
        bonus = 15;
    else if (rank==2)
        bonus = 10;
    else
        bonus = 0;
    printf("bonus = %d\n", bonus);
    printf("------------------------------\n");
    printf("student name: nnn\n");
    printf("section:03\n");
    printf("student ID:nnn\n");
    printf("semester: Fall 2020\n");
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...