1
votes

lets say you have an array that has the days of the week in it:

String days[]={"monday","tuesday","wednesday","thursday",
               "friday","saturday","sunday"};

Now lets say you have a array that keeps track of every number day of the year with an array made up of 366 elements.(1 extra for leap year).

Is it possible to write a loop or something that when done cycling through the days array, that it resets back to monday to keep so that the output looks something like:

Monday:1 Tuesday:2 Wednesday:3 Thursday:4 Friday:5 Saturday:6 Sunday:7 Monday:8 Tuesday:9 ect all the way to 366

2

2 Answers

4
votes

Just use the modulo operator (%):

for (int i = 1; i <= 366; i++) {
    System.out.format("%s:%d%n", days[(i - 1) % days.length], i);
}
0
votes

use modulo operation

int[] year = new int[366];

for(int i = 0 ; i < year.length ; i++) { // initialize the days
    year[i] = i;
}

String[] days = {"monday","tuesday","wednesday","thursday",
               "friday","saturday","sunday"};

for(int i = 0; i < year.length; i++) {
    System.out.println(days[i % (days.length)] + ":" + year[i]);
}

yields monday:0 tuesday:1 wednesday:2 thursday:3 friday:4 saturday:5 sunday:6 monday:7 tuesday:8 wednesday:9...