0

I was wondering if it's possible to use a loop to fill and array without prompting the user for input? I have to design a program to fill an array of size 6 with multiples of 7. The specification doesn't say anything about prompting the user, and it says 'Use a loop to fill the array' so I can't hard code the numbers in. Of the multiples of 7 , I need to print out which ones can be divided by 3 exactly.

Is it possible to fill the array without an input from the user? My code is below...

import java.util.Scanner;
/**
 * Created by IntelliJ IDEA.
 * Date: 26/02/2015
 * Time: 15:25
 * UPDATE COMMENT ABOUT PROGRAM HERE
 */
public class Array7Mult
{
   public static void main(String[] args)
   {

      int multipleSeven [] = new int[6];
      final int HOWMANY=6,DIVIDE=3;
      Scanner keyboard = new Scanner(System.in);


      for(int count=0;count<HOWMANY;count++)
      {
         System.out.println("Please enter a multiple of 7 below..");
         multipleSeven[count]=keyboard.nextInt();
      }//for


      System.out.println("The multiples of seven that can be divided by 3 are..");

      for(int count=0;count<HOWMANY;count++)
      {

         if (multipleSeven[count] % DIVIDE == 0)
         {

            System.out.println(multipleSeven[count]);
         }//if
      }//for

   }//main
}//class
2
  • 1
    Why do you need a user input to populate an array? Just use a loop to populate each element in the array with something like: multipleSeven[count]=count*7; Commented Mar 1, 2015 at 14:34
  • int multipleSeven [] is discoraged use int[] multipleSeven for the declaration. Commented Mar 1, 2015 at 15:00

2 Answers 2

1

Yes ofcourse. Say you want to populate an array by a variable which is incremented by one per index. Say variable i (so we use the same variable that's instantiated in the loop).

for(int i = 0; i < arr.length; i++)
    arr[i] = i;

Simple as that. You may ofcourse create a global variable and add it into the array within the boundaries of the loop and manipulate its value within the loop too.

int a = 0;

for(int i = 0; i < arr.length; i++) {
     arr[i] = a;
     a += 10;
}

If you want to increment the value as a multiple of seven, you can simple use the first example and instead of doing arr[i] = i do arr[i] = i*7

Sign up to request clarification or add additional context in comments.

Comments

0

Use

for(int count=0;count<HOWMANY;count++)
    multipleSeven[i]=(i+1)*7;

Instead of

for(int count=0;count<HOWMANY;count++)
{
    System.out.println("Please enter a multiple of 7 below..");
    multipleSeven[count]=keyboard.nextInt();
}

To fill the array multipleSeven with values 7,14,21,28,35,42.

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.