Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

solve this for c, using #include studio.h In the song The Twelve Days of Christm

ID: 644855 • Letter: S

Question


solve this for c, using #include studio.h

In the song The Twelve Days of Christmas the singer gets 1 present on the first day , 1+2 presents on the second day, 1+2+3 presents on the third day, and so on. Write a program that prompts the user for the number of days, we will call it n, and then computes the total number of presents the singer would get if there were n days of Christmas. If a number less than 1 is entered, print an error message and stop the program [Note that answer below is 10 since ] 1 +1 + 2+ 1 +2 +3 = 10. ] Explain: Enter the number of days: 3 Total number of Presents: 10

Explanation / Answer

Answer:

Answer for day 2 is 4 Presents total, On day 12 I'll have received a total of 364. Formula that lets me input 12 and get 364.

On the first day, you get 1.

On the second day, you get 1 + 2.

On the third day, you get 1 + 2 + 3.

...

On nth day, you get 1 + 2 + 3 + ... + n.

The sum 1 + 2 + ... + n is n(n+1)/2. So the total number, T(N) is the sum of n(n+1)/2 for n in 1..N, where N is the number of days.

Now, n(n+1)/2 = n^2 / 2 + n / 2, and sum of n^2 for n in 1..N is N(N+1)(2N+1)/6, so you get:

T(N) = N(N+1)(2N+1)/12 + N(N+1)/4

     = N(N^2 + 3N + 2) / 6

Program:

class Presents
{
final static int DAYS_OF_XMAS = 12;
  
public static void main ( String[] args )
   {   
int total_presents = 0;
int daily_presents, day, increment;
  
for ( day=1; day <=DAYS_OF_XMAS; day++ )
       {
daily_presents = 0; /* each day the daily presents need to
be reset to 0 */
for ( increment = 1; increment <= day; increment++ )
               {
daily_presents += increment;
}

System.out.println( "Presents for day " + day + ": " +
daily_presents );
total_presents += daily_presents;
} // end outer for loop
System.out.println( "Total presents received on Christmas: " +
total_presents );
} // end main
} // end class