Explain the code

class GFG
{
static int dayofweek(int d, int m, int y)
{
int t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
y -= (m < 3) ? 1 : 0;
return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}

// Driver Program to test above function
public static void main(String arg)
{
int day = dayofweek(31, 8, 2010);
System.out.print(day);
}
}

Hello! I’ll run through the code step-by-step:

declares a function dayofweek which returns an integer, with the integer parameters: d, m, and y.

Creates a variable which stores a list of integers.

This is a ternary expression. This is similar to an if…else block, except it does it in one line. Essentially, the code checks to see if the parameter m is less than three. If it is, then the program will subtract 1 from y. Otherwise, nothing will be subtracted from y. (Subtract 0).

This returns the following expression: ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7

Click this to see what that expression does

y+y/4
Adds y to the result of dividing y by 4.
-y/100
Subtracts y divided by 100 from the above expression.
+y/400
Adds y divided by 400 to the result of the above expression.
+t[m-1]
Adds the value stored in t at the position of m minus 1 to the result of the above expression. (Remember an array’s index starts at 0.
+d
Adds d to the result of the above expression.
%7
Finds the remainder of diving the above result by 7.

Calls the main function which has special properties-it starts the execution of the program.

Calls the dayofweek function using the parameters: d=31, m=8, y=2010 in the variable day. Since the dayofweek function returns an integer, the variable is of type int as well.

Prints the value stored in the variable day to the console.

I hope this helps!

1 Like