1

Im a programming student and im having alot of trouble with this question:

"complete a static method multiplesOf which takes two int parameters, number and count. The method body must return an int array containing the first count multiples of number. For example,

multiplesOf(5, 4) should return the array { 5, 10, 15, 20 } multiplesOf(11, 3) should return the array { 11, 22, 33 } multiplesOf(1, 15) should return the array { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }

You must not use System.out.print or System.out.println in your method."

This is my current code:

public static void main(String[] args) {
    multiplesOf(5,4);
}

public static int[] multiplesOf (int number, int count) {
    int[] a = new int[count];
    a[0]= number;
    for(int i = 0; i<count; i++) {
        a[i] = (a[i]*count);
    }
    return a;
}

Ive been trying to figure out why the array "a" still only has the values 0,1,2,3

1
  • 1
    What does a[i] = (a[i]*count); do? Commented Jan 13, 2017 at 6:21

5 Answers 5

2

Try:

public static int[] multiplesOf(int number, int count) {
  int[] a = new int[count];
  for(int i = 1; i <= count; i++) {
    a[i - 1] = number * i;
  }
  return a;
}
Sign up to request clarification or add additional context in comments.

Comments

1
a[0] = number;
for(int i = 1; i<count; i++)
{
      a[i] = (i+1)*number;
}

2 Comments

ah yeah you were faster :D but I think when I see all the wrong answers I can let the answer stay here :) I will upvote you
Pretty shocking really
1

try this

        public static int[] multiplesOf (int number, int count)
        {
            int[] a = new int[count];
            a[0] = number;
            for(int i = 1; i<count; i++)
            {
              a[i] = number * (i + 1);
            }
            return a;
          }

output

[5, 10, 15, 20]

Comments

0
    public static int[] multiplesOf(int number, int count) {
    int[] a = new int[count];
    for (int i = 0; i < count; i++) {
        a[i] = (number * (i+1));
    }
    return a;
}

use this

5 Comments

As OP says "You must not use System.out.print or System.out.println in your method."
must not use System.out.print or System.out.println in your method.
SOP isn't required; the array is supposed to just be returned, not printed.
i was just checking by printing..now changes are made.
Post you output then
0
 public static int[] multiplesOf (int number, int count) {
     int[] a = new int[count];
     for(int i = 1; i<=count; i++) {
         //a[i-1] beacuse we started iterating array at i=1
         a[i-1] = (i*number); 
     }
     return a;
}

multiplesOf(5, 4) returns -> the array { 5, 10, 15, 20 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.