Janine McDaniel Janine McDaniel - 6 months ago 17
Java Question

Java: Print array elements

I need to print the array elements in increments of 10 each line...

import java.util.*;

public class Array {

public static void main(String args[]) {
double alpha[] = new double[50];

//Initialize the first 25 elements of the array (int i=0; i<25; i++)//
for(int i = 0; i < 25; i++) {
alpha[i]= i * i;
}

//Initialize the last 25 elements of the array (i=25; i<50; i++)//
for(int i = 25; i < 50; i++) {
alpha[i]= 3 * i;
}

//Print the element of the array
System.out.println ( "The values are: " );

for (int i = 0; i < 50; i++) {
System.out.println ( alpha[i] );
}

//Print method to display the element of the array
void print(double m_array[]) {
for(int i =1; i <= m_array.length; i++) {
System.out.print(m_array[i-1] +" ");
if(i%10==0)
System.out.print("\n");
}
}
}
}


I'm assuming this if statement is my problem...if it is exactly what am I missing I tried the printf but that didn't work...

Answer
public class Array {

    public static void main(String args[]) {
        double alpha[] = new double[50];

        // Initialize the first 25 elements of the array (int i=0; i<25; i++)
        for (int i = 0; i < 25; i++) {
            alpha[i] = i * i;
        }

        // Initialize the last 25 elements of the array (i=25; i<50; i++)
        for (int i = 25; i < 50; i++) {
            alpha[i] = 3 * i;
        }

        System.out.println("The values are: ");

        // Print the element of the array
        print(alpha);

    }

    // Print method to display the element of the array
    private static void print(double m_array[]) {
        for (int i = 1; i <= m_array.length; i++) {
            System.out.print(m_array[i-1] + " ");
            if (i % 10 == 0) {
                System.out.println();
            }
        }
    }
}

Output:

The values are:

0.0 1.0 4.0 9.0 16.0 25.0 36.0 49.0 64.0 81.0

100.0 121.0 144.0 169.0 196.0 225.0 256.0 289.0 324.0 361.0

400.0 441.0 484.0 529.0 576.0 75.0 78.0 81.0 84.0 87.0

90.0 93.0 96.0 99.0 102.0 105.0 108.0 111.0 114.0 117.0

120.0 123.0 126.0 129.0 132.0 135.0 138.0 141.0 144.0 147.0

Comments