public class Array {
public static void main(String args[]) {
int[] daysInMonth = new int[31];
for (int i = 0; i < 31; i ) {
System.out.println("Day of the month: " daysInMonth[i]);
}
}
}
I recognize that I could hard code the values for each day of the month. I could do: daysInMonth[0] = 1; for all of the values in the month, but would like to use a loop to do this instead for the sake of efficiency. How would I create a loop that would output "Days of the month: 1, Day of the Month: 2, etc?"
CodePudding user response:
If I understand you correctly, you don't need an array, just write i
in output and change loop parameters like that
for (int i = 1; i < 32; i ) {
System.out.println("Day of the month: " i);
}
CodePudding user response:
You could use the array length in iterating through the loop, since months have different lengths, and print i instead of an index [i] of your array.
int[] daysInMonth = new int[31];
for (int i = 0; i <= daysInMonth.length-1; i ) {
System.out.println("Day of the month: " (i 1));
}