Question:
Help with java cumulative sum loops?
2010-10-24 02:41:48 UTC
Hello,
I'm currently working on a project for a class and can't seem to figure out the cumulative sum for loops...for the project we need to calculate the absolute day of the current date the birthday of the user. I'm just not exactly sure how to turn a date (like 3/27) into it's absolute day by using the for loop.... This is what I have so far:

public static int totalDays(int month, int day) {
int total = 0;
for (int i = 1; i <= month; i++) {
total += 31;
total += 28;
total += 31;
...
total += day;
System.out.print(month + "/" + day + " is day #" + total + "of 365!");
return total;


I know it's probably really wrong, but as I said, I really don't get it.... Could someone set me straight on how to use this type of for loop? Thank you!
Three answers:
Sayee
2010-10-24 03:00:02 UTC
You could do it like this assuming you don't worry about year (leap year)



int [] numOfDays = {31,28,31,30,31,30,31,31,30,31,30,31};

int total = 0;

for (int i = 0; i < month-1; i++) { //e.g. if it was 3/27 this loop will do till feb

total = total + numOfDays[i];

}

total = total + day; // then add number of days in march here



Done! :-D
Corey G
2010-10-24 14:56:29 UTC
In regards to Sayee's answer. Your answer is correct, however, I believe I know that the poster is taking CSE 142 at the University of Washington.Your answer (although it is right) is not allowed because this homework assignment is from week four and unfortunately, arrays are not yet mentioned in chapter 4. Thus, shes still trying to find the cumulative sum but isn't allowed to use interger arrays She's also not allowed to use the built in java methods (date and gregorianCalendar).



Well, the only other way I can think of, is using an if/else statement to get the right answer.. Like "if (month = 12){ sum = 31 + 28 + 31+30....up to month 12.

if (month = 5) { sum = 30+28+31 ....up to month 5. My assignment was slightly different (same concept, but different problem).



Julie, I also suggest the IPL in mary gates hall..2nd floor (i think). It's a great place where students who are currently taking introductory programming classes go for help. CSE TA's are there and are waiting to help people in need.
Andrew Jenks
2010-10-24 03:03:38 UTC
First off, don't use your birthday as a reference date... Like, really??

Secondly, it IS really wrong....

Thirdly, java is coffee. I don't know why you need the birthday date of coffee! Crazy lady.

Fourthly and finally, I don't think anyone could set you straight....... Sorry.



Hope I helped!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...