Home > other >  Why does entering the char 'T' not return the total of the array?
Why does entering the char 'T' not return the total of the array?

Time:01-23

I'm a beginner and trying to use an array to calculate the total number of hours someone spent working on the CS50 course over a variable number of weeks. However when it prompts to enter the char T, the program ends and it doesn't calculate the total.

#include <cs50.h>
#include <stdio.h>

int main (void)
{
    int weeks = get_int("Weeks taking CS50: ");

    int hours [weeks];
    for (int i=0; i < weeks; i  )
    {
        hours[i] = get_int("WK %i Number of hours: ",i);
    }
    char output;
    do
    {
        output = get_char("Enter T for total hours, A for average hours per week: ");
    } while (output != 'T' && output != 'A');

    int total =0;
    for (int i=0; i < weeks; i  )
    {
        total  = hours [i];

        if (output == 'T')

        return total;
    }
}

I've tried putting the if statement first but then the total is incorrect - comes out to something like 21782. I'm assuming the issue is in the second for loop - I will eventually make it calculate the average too but first I would like the total to work

CodePudding user response:

In this for loop

for (int i=0; i < weeks; i  )
{
    total  = hours [i];

    if (output == 'T')

    return total;
}

in the first iteration of the loop the program at once exits due to this if statement

    if (output == 'T')

    return total;

If you want to output the value of total then write for example

if ( output == 'T' )
{
    int total = 0;

    for ( int i = 0; i < weeks; i   )
    {
        total  = hours[i];
    }

    printf( "total = %d\n", total );
}

Pay attention to that you should declare variables in minimum scope where they are used.

Or if you want to append your code for the selection 'A' then the code can look like

int total = 0;

for ( int i = 0; i < weeks; i   )
{
    total  = hours[i];
}

if ( output == 'T' )
{
    printf( "total = %d\n", total );
}
else
{
    printf( "average = %d\n", total / weeks );
}

CodePudding user response:

You never print the total. You return total - and you also do it inside the first iteration of the loop, meaning that total will be the same as hours[0].

You need to printf the result and also move it after the loop:

    // ...

    int total = 0;
    for(int i = 0; i < weeks; i  ) {
        total  = hours[i];
    }

    if(output == 'T')
        printf("Total: %d\n", total);
    else
        printf("Average: %d\n", total / weeks);

  • Related