Thread: work calculator and arrays

  1. #1
    Registered User
    Join Date
    Sep 2020
    Posts
    9

    work calculator and arrays

    hi,

    i have to program i work calculator which prompts the user for the days and then ask how many hours the person worked a day.
    the expected output is:

    The program calculates the total hours worked during
    a specific period and the average length of a day.


    How many days: for example i put 3
    Enter the working hours for day 1: x
    Enter the working hours for day 2: x
    Enter the working hours for day 3: x


    Total hours worked: xx.x
    Average length of day: x.x
    Hours entered: x.x x.x x.x

    theres also a hint:It is easiest to implement the program using an array with 30 elements.

    what does it mean? array to what?, im new to arrays and cant find any help or examples with that kind of program, even though i understand how arrays work. i dont get what does that mean. do i have to link for example dailyhoursday[0] to 6.6 hrs and dailyhoursday[1] to 8.6 etc?

    thanks for help

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,294
    So you've posted this twice - in C# and C forums.
    Which do you want to keep?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    456
    Quote Originally Posted by xways View Post
    hi,

    theres also a hint:It is easiest to implement the program using an array with 30 elements.

    what does it mean? array to what?,
    To calculate an average you need a list of numbers. The simplest form of list is an array. In C we usually need to keep the count of items in the array in a separate variable. Unlike high level languages the "array" is really just a memory buffer.

    The assignment doesn't say whether days not worked are to be counted as zero hours. And it isn't clear why you need 30 elements. This looks like the number of days in a month, except that not all months are 30 days long. So questions to ask. But these changes should be easy to make once you have a skeleton working.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  4. #4
    Registered User
    Join Date
    Sep 2020
    Posts
    9
    Quote Originally Posted by Salem View Post
    So you've posted this twice - in C# and C forums.
    Which do you want to keep?
    Ye, i realized little later i posted it in the wrong section and i used the report button, to tell that what went wrong, also i changed the question since, that wasnt what i was struggling with.

    Quote Originally Posted by [COLOR=#000000
    Malcolm McLean[/COLOR];1298013]
    To calculate an average you need a list of numbers. The simplest form of list is an array. In C we usually need to keep the count of items in the array in a separate variable. Unlike high level languages the "array" is really just a memory buffer.

    The assignment doesn't say whether days not worked are to be counted as zero hours. And it isn't clear why you need 30 elements. This looks like the number of days in a month, except that not all months are 30 days long. So questions to ask. But these changes should be easy to make once you have a skeleton working.
    im familiar with calculating the average, i got already the code that asks me how many days and when i enter like 3, it will ask me three times, how much hours on day 1...2..3 with a for loop. But as far as i can understand/imagine, it should store each day of hours in a array so day1: 6 hrs into [0] day2.. hrs into [1] etc. although i could just sum up all hours as a float and get days/(float)dailyhrs as average.. im confused if thats possible to add and store each entered day into one array.. im not getting help from the teachers either for that..

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,294
    You already seem to be able to describe in words what needs to happen.

    So given a loop like
    for ( day = 0 ; day < number_of_days ; day++ )

    and an array like
    int hours_worked_each_day[30];

    see what you can come up with.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Sep 2020
    Posts
    9
    hey salem,
    yes i know kinda like what to do, but im not succeeding to add each hours to days with an array, beside i think it has to be float hours_worked_each_day, since im adding also 6.5 hours, no!? still didnt get real clear with those ints doubles and floats yet. i think i have to do something like
    float hours_worked_each_day[30];
    and then a loop to go like that linked with the days i entered:
    how many hours on day 1: 6.5 (saving into array 0)
    how many hours on day 2: 8.4 (saving into array 1)
    but i dont know how to... i try hard to understand arrays, but this example i couldnt find in internet, its always defined how many and what numbers are in already, without scanning for input to add. sorry, i have just hard time understanding that and im so confused. dont know even if thats the right approach to solve that.
    thanks so far for reply

    edit:
    i finally found something maybe useful what i think i was looking:
    How To Store Multiple String Values In An Array Using C Programming - YouTube
    what you guys think
    Last edited by xways; 09-28-2020 at 01:58 AM.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,294
    Spending hours on google trying to find 5 minute videos of watching someone type (badly) isn't going to substitute for the physical act of actually trying to write code yourself.

    Start small, forget the array.
    Just see if you can do a single printf("How many days") and scanf to read a number.

    You don't have to write the whole code in a single edit.
    You don't even have to think about the whole code in a single edit.
    You just have to break the problem down into smaller achievable steps.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,883
    You need to make and test each part of your code bit by bit. If something does not work, you can fix it in isolation.

    If you have a question about any stage you'll need to say what you tried, what you expected to happen, and what actually happened.


    Step 1 - Can I get all of the required info from the user?
    * As Salem said, scanf/printf...
    * Start with just one input into one variable, make sure that there are no unexpected things when reading integers/floats

    Step 2 - Can you fill an array a fixed amount of times?
    * Create an array with 2 elements - Can you get 2 inputs and put them into an array?
    * Can you then create a larger array of 4 elements and populate that array?

    Step 3 - Can you then work out how to put a variable amount of elements into a fixed size array?
    * First use a variable to change the amount of days you enter
    * Then use the value of "days"
    * What is the maximum amount of days your array can hold? Can you think of a way to stop not putting in too many days?

    Step 4 - Can I do the calculation?
    * Start with known values (3 days, 1.0h, 2.0h, 3.0h) - Single variables at first, and then an array.
    * Use a lot of printf to see if your calculation is working as you expect
    * Can I then use the array and values from earlier?

    Step 5 - Present data
    Fact - Beethoven wrote his first symphony in C

  9. #9
    Registered User
    Join Date
    Sep 2020
    Posts
    9
    hey,

    thanks for the informal input, guys. to write this code, i need to use arrays and thats were step 2 and step 3 are neccesairy for me to understand, since that is stopping me to finish the code at all. this youtube video just gave me the format to write that lines that will add input to the array, since i couldnt find it anywhere else, but now i found examples all over x). i will post the code here once im done and maybe you can see, if theres something that i could have done much easier.

  10. #10
    Registered User
    Join Date
    Sep 2020
    Posts
    9
    someone wrote:
    yeah, I understand. It take a lot of works indeed. Great you find it in YouTube and by the way, thanks for keeping us posted
    somehow it wont show anymore, maybe deleted.

    So i tried more and more, but i just couldnt get it worked, something in the code is wrong ofc.
    Since im stuck with that exercise for almost a week and dont do any progress, i decided to skip that for now and do the next chapter and will return to that, once im further, maybe even learn that problem throughout the next chapters. this code i post now, is just the last thing i worked on and changed things around, so it might not even do anything, before i managed to get something atleast, like getting the daily hours into an array, but the compiler didnt like the total += dailyhours line. it told me over and over again:
    invalid operands to binary + (have 'float' and 'float *')|, and if i managed that problem, it didnt sum up the total with dailys and so far..
    but as i said, i will post once i got it, may just take a while. thanks for having been active in that thread happy coding guys

    Code:
    
    
    Code:
    #include <stdio.h>
    
    
    	int main(){
    
    
        float days, daily[30], total = 0, avg;
        int i;
    
    
    	printf("How many days:");
        scanf("%f", &days);
    
    
        for (i = 1; i <= days; ++i){
    	printf("Enter the working hours for day %d:", i);
    	scanf("%f", &daily[i]);
    	total += daily[i];
        printf("\n%f", daily[i]);
        }
        return 0;
    }
    Last edited by xways; 10-01-2020 at 04:18 AM.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,294
    Not sure what compiler you're using, or where "invalid operands to binary + (have 'float' and 'float *')|" came from.

    But the code you posted compiles and runs.
    Code:
    $ gcc -Wall main.c
    main.c: In function ‘main’:
    main.c:7:39: warning: unused variable ‘avg’ [-Wunused-variable]
         float days, daily[30], total = 0, avg;
                                           ^
    $ ./a.out 
    How many days:3
    Enter the working hours for day 1:22
    
    22.000000Enter the working hours for day 2:33
    
    33.000000Enter the working hours for day 3:44
    
    44.000000$
    OK, so the input/output formatting is a little off, but that's easy enough to fix by putting \n in the right places.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User
    Join Date
    Sep 2020
    Posts
    9
    Quote Originally Posted by Salem View Post
    Not sure what compiler you're using, or where "invalid operands to binary..
    [QUOTE=Salem;1298122]Not sure what compiler you're using, or where..[/code]

    I use codeblocks and ye, this code didnt gave an error since as i mentioned i played around alot and then let it be in a state, i just was to tired to rework the code, to repeat this error, but it came when i did something like sum = sum+dailyhours;

    so tonight i finally got that program working, doing exactly what it was supposed to do, with the right output. feelsgoodman, all these days and hours from morning till night paid off.. was painful but necessairy to keep trying. im actual thankful, no one gave me the answer, since im supposed to solve problems in future on my own as a programmer xd. but now i could see how you would have done it/what i have could done much better,easier etc if u like, let me know
    i have an example solution from the school now, so i might post that afterwards, when some ppls posted something first.
    thats my code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        int i, j, enthrs, days;
        float dhrs[30], avg = 0, sum = 0;
    
    
            printf("The program calculates the total hours worked during\na specific period and the average length of a day.\n\n");
    
    
            printf("How many days:");
            scanf("%d", &days);
            for(i = 1; i <= days; i++)
            {
                printf("Enter the working hours for day %d:", i);
                scanf("%f", &dhrs[i-1]);
            }
    
    
            for(j = 0; j < i; j++)
            {
                sum = sum+dhrs[j];
                avg = sum/days;
            }
                printf("\nTotal hours worked: %.1f\n", sum);
                printf("Average length of day: %.1f\n", avg);
                printf("Hours entered: ");
                for(enthrs = 0; enthrs < days; enthrs++)
            {
                printf("%.1f ", dhrs[enthrs]);
            }
    
    
        return 0;
    }

    good night for now x)

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,082
    Your indentation could be more consistent, and generally it is unnecessary to have more than one blank line in a function body. For example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        int i, j, enthrs, days;
        float dhrs[30], avg = 0, sum = 0;
    
        printf("The program calculates the total hours worked during\na specific period and the average length of a day.\n\n");
    
        printf("How many days:");
        scanf("%d", &days);
        for(i = 1; i <= days; i++)
        {
            printf("Enter the working hours for day %d:", i);
            scanf("%f", &dhrs[i-1]);
        }
    
        for(j = 0; j < i; j++)
        {
            sum = sum+dhrs[j];
            avg = sum/days;
        }
    
        printf("\nTotal hours worked: %.1f\n", sum);
        printf("Average length of day: %.1f\n", avg);
        printf("Hours entered: ");
        for(enthrs = 0; enthrs < days; enthrs++)
        {
            printf("%.1f ", dhrs[enthrs]);
        }
    
        return 0;
    }
    A few thoughts:
    • You don't actually need i, j, and enthrs. Just i will do because it is clear that it is a loop/array index. Usually if you see both i and j, it is because you have a nested loop/2D array. This way, you also avoid what you did in the second for loop: you used j < i as the condition, but you should have used j < days instead as it would be clearer.
    • You allocated 30 elements for dhrs, but some months have 31 days, and while unusual under decent labour conditions, it is possible for someone to work all 31 days of such a month. If you're just going for 30 days rather than a month, then it might be good to incorporate this in the prompt for how many days, e.g., "How many days (max 30):".
    • Related to the previous point, instead of using the magic number 30, you could use #define to make it a named constant.
    • You should check the return value of scanf to check that the read was successful. Related to this, you should check that the input for days and the working hours are valid.
    • You don't need to compute the average on each iteration of the second loop: just compute the sum, and then after the loop you compute the average.
    Last edited by laserlight; 10-05-2020 at 06:23 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Sep 2020
    Posts
    9
    hey laserlight!
    thanks for input.
    yes, i usually do clean up the spaces and so on, to have a nice to look and easy to read code. i was just to tired and happy that i got it working and the school accepted that code online immediately so i just copy&paste it here. im also not allowed to change any printf text, since the site wont accept any differences in letters/space/line etc, it must be srict the same, but i get what you mean.

    to your points:
    1. do you mean, i dont need those 3 to write that same kind of outcome?
    2. the hint from school was its easier to use an array with 30 elements, also its actually dailyhours not days, even the school had this in the code written.
    3. define 30 with array? how would that work? and why?
    4.ye if that program was up to me, id implement that, but im 2 far behind the time schedule, so i rather waste no time on that.
    5.agree, didnt realise avg was in a loop, after polishing id be probably somewhere else.

    are there other commands, which would have made this code even smaller and more efficient?
    well ye, studying the example code after i submitted, i could have left out avg, enthrs and j.
    they use i twice, on the later lines, pretty useful to dispose the first i index, if everything is summed up by then :O.
    coding is so interessting xd
    Last edited by xways; 10-06-2020 at 01:52 PM.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,082
    Quote Originally Posted by xways
    1. do you mean, i dont need those 3 to write that same kind of outcome?
    As you found out from reading the "model answer" given to you, indeed you don't need all three, just one. Basically, your first loop reads in values to the array, your second loop computes the sum of values in the array, and your third loop prints the values in the array. So what's important is the array (and hence its name) and where you start (0) and end (days), rather than the name of the index variable that is used for the iteration.

    Quote Originally Posted by xways
    2. the hint from school was its easier to use an array with 30 elements, also its actually dailyhours not days, even the school had this in the code written.
    Then you should ask your school: why 30? Why not 10, or 50? This should have been specified in the requirements.

    Quote Originally Posted by xways
    3. define 30 with array? how would that work? and why?
    You would put this somewhere before the main function, after the includes:
    Code:
    #define MAX_NUM_DAILYHOURS 30
    Then to declare the array:
    Code:
    float dhrs[MAX_NUM_DAILYHOURS];
    As for why: so that readers will know what the 30 means, and you can use it in multiple places such that should you want to change the value, you just change the #define rather than having to do a possibly error-prone search and replace (possibly error-prone because you might get mixed up with 30 used for another purpose).

    Quote Originally Posted by xways
    are there other commands, which would have made this code even smaller and more efficient?
    You can compute the sum while reading the values, but while that would technically make the code smaller and more efficient, it reduces what we call "separation of concerns", i.e., that each part of your code is responsible for that one thing that it is concerned with. It makes no real difference to you now, but as you write bigger and bigger programs and modify them, you'll find that separation of concerns will allow you to write components that are more easily tested and debugged, and so you can have more confidence that your code works. It can also make it easier to understand your code, and allow you to reuse components better, e.g., instead of always having to write a loop to sum values, you might be able to call a function that you have already written.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. work calculator question
    By xways in forum C# Programming
    Replies: 2
    Last Post: 09-27-2020, 02:48 PM
  2. How to work with 2d arrays and an image file?
    By klee87 in forum C Programming
    Replies: 1
    Last Post: 06-03-2013, 10:58 PM
  3. simple printing calculator in C doesn't work
    By Pierre Hardy in forum C Programming
    Replies: 6
    Last Post: 02-10-2012, 02:03 PM
  4. Arrays of Pointers, how do they work?
    By yougene in forum C Programming
    Replies: 10
    Last Post: 11-16-2007, 07:58 PM
  5. Arrays failing to work
    By Bri Rock in forum C Programming
    Replies: 4
    Last Post: 06-14-2004, 06:34 PM

Tags for this Thread