Home > Software design >  Times Table array using methods
Times Table array using methods

Time:03-07

I'm pretty new to coding and have been set a challenge of creating an method that prints out a times table array.

My code is as follows...

public class TimesTableArray

{
 public static void main(String[] args)
 {
 int size = 12;
 int number = 5;

 int [] timesTable = getTimesTable(size, number);
 printArray(timesTable);
 }
 
 
 private static int [] getTimesTable(int size, int number)
 {
     int[] timesTable = new int[size];
     
     for (int i = 1; i < (size); i  )
     {
         timesTable[i-1]  = number * i;
     }
     return timesTable;
 } 

 
 
 private static void printArray(int [] integerArray)
 {
     for(int i = 0; i < integerArray.length; i  ) 
    {
        System.out.println(integerArray[i]);
    }
 }
 
}

I get the following output...

5
10
15
20
25
30
35
40
45
50
55
0

I need the 12th item to read 60, not 0. I know it's to do with the index reads from 0 to 11, but I don't know how to amend my code to make this so.

Please could someone help and guide me on how to do this?

Many thanks

CodePudding user response:

You have a classic "off by one" error.

If you start at 1, then you INCLUDE the size, and have to subtract one to get the Index:

 for (int i = 1; i <= size; i  )
 {
     timesTable[i - 1]  = number * i;
 }

If you start at 0, then you EXCLUDE the size, and have to add one when you multiply:

 for (int i = 0; i < size; i  )
 {
     timesTable[i]  = number * (i   1);
 }

You're going to have people swear up and down that one is correct and the other is wrong. This is down to preference. Do what "makes sense" to you.

CodePudding user response:

In the population loop, you are iterating from 1 rather than 0 but you do not offset the terminal condition. I would rewrite you loop to follow the standard pattern rather than trying to bake in the offset. So...

for (int index = 0 ; index < size ;   index) { ... }

This will allow the index to line up naturally in the assignment. Apply the offset in the calcuation.

timesTable[index] = number * (index   1);

So you get...

private static int[] getTimesTable(int size, int number) {
  int[] timesTable = new int[size];
  for (int i = 0; i < size; i  ) {
    timesTable[i]  = number * (i 1);
  }
  return timesTable;
} 

CodePudding user response:

You are having an off-by-one error. Since you want to have an array of 12 answers, starting with 1, your loop range has to be from 1 to 12 inclusive. Therefore:

 private static int [] getTimesTable(int size, int number)
 {
     int[] timesTable = new int[size];
     
     for (int i = 1; i <= (size); i  )
     {
         timesTable[i-1]  = number * i;
     }
     return timesTable;
 } 

The reason why your last index was zero, is because numeric array indexes are initialized to zero after instantiation (new int[size]).

  • Related