Arrays and Loops


Collapse Content

Arrays help keep data organized, and their real power comes through when you are able to write a little code that can go through every element in an array. Instead of repeating code for each element, you just say:

for each element in array
do something

To go through an array in code, you can use an index variable to keep track of your position in the array, and increment it to get through the whole array. The For Loop works particularly well for such purposes:

//create array
int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8 };

//print each element in array
for(int i = 0; i < array1.length; i = i+1){
  System.out.println(array1[i]);
}

This would print:

1
2
3
4
5
6
7
8

Similarly, you can setup the initial data in an array with a for loop (Hover over code for more info.):

  int[] array2 = new int[8];
  for(int i = 0; i < array2.length; i = i+1){
    array2[i] = i+1;
  }

This would create an array like above: {1, 2, 3, 4, 5, 6, 7, 8}

You can now see how a loop can find the largest number in an array:

static int getLargestNumber(int[] numbers){
    int largest = 0;
    for(int i=0; i < numbers.length; i = i+1){
      if(numbers[i] > largest){
        largest = numbers[i];  
      }
     }
  return largest;
  }

The numbers are stored in an array named numbers. i is used to go through the array one number at a time and every numbers[i] is compared with largest to see which is larger. largest will be assigned any larger value, so after going through the array, it will have the largest value.

These examples showed how for loops can be used to setup the data in arrays, to do something to each element in an array and to search through arrays. Now you can try your own for loops to solve the following challenge.

Challenge

You will be given an array of numbers ar. Print each number in the array in the order it appears, unless the number is a multiple of 3. If a number is a multiple of 3, print no3 instead. (Make sure to print everything in a given array on the same line.)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • Hint 2: remember to print the empty char for both if and else :)

  • why am i getting errors in the boilerplate code :\

  • forgot the curly brackets haha :P

  • if(numbers[i] > largest){
    largest = numbers[i];

    }

    Shouldn't be numbers[i] < largest ?

  • How to print on one line everything, I am having issues with that.

  • Ehh, just use System.out.print(); instead of System.out.println(""); You didn't mention it earlier :(

  • //What´s wrong with my Code??
    //PLZ help I don´t get any further...
    //blessed
    import java.util.*;
    class Main{
    static void doStuff(int[] ar){
    for(int i=0; i<=ar.length;i++){

    cont...
  • @Andreas, we will be running a membership option for people to get help with their errors. Meanwhile, here's some tips: You don't need to create a new array, just print the items in the given array. To print "no3", just type System.out.print("no3");

  • How should I do?
    when i run this code, the compiler return the error message:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

    cont...
  • Someone please post the answer so I can see what I am doing wrong. :/

  • @jordan, I would suggest starting by printing the array, and then move on to modifying it for multiples of 3. The code at the top of the page shows how to print an array, though you'll want print instead of println.

  • package Testpac;

    import java.util.Scanner;

    public class Maon_Test
    {

    public static void main(String[] args) 
    {
        Scanner sc=new Scanner(System.in);
    
    cont...
  • CORRECT:

    for(int i = 0; i < ar.length; i = i+1)
    {

    if (ar[i]%3==0){
        System.out.print("no3");
        } else{
            System.out.print(" "+ar[i]);
        }
    

    }

  • Does anyone have any idea what boilerplate code means?

  • @Prashant, in these challenges, it's just standard code that is included to process the input for you. I.e. it sets up the variables or arrays and passes them to the method doStuff().

  • another simple solution using for each :
    for (int element : ar)
    {
    if (element%3 == 0) System.out.print("no3 ");
    else System.out.print(element+" ");
    }

  • I'm just wondering whether or not you have a guide for using streams?

  • Sorry these tutorials are focused on the basics of Java for beginners, so we don't cover that.

Contact Us
Sign in or email us at [email protected]