0

I am trying to output arrays using enhanced for loop. I want it to be printed as;

a[0] = 5, a[1] = 8, ... and so on.

This is my code;

int[] a = {5, 8, 10, 24, 45};

        for(int i=0 ;i <= 4; i++) {
             for(int  enhancedfor : a) {
                 System.out.print("a[" + i + "] = " + enhancedfor + ", ");
 }
}

I actually want, once it outputs value of a[0], instead of again going for same loop, it should go to first for statement , and then second ...

Any help guys ?

1
  • That means you don't actually want a loop inside your outer loop. Loops are for repeating actions. If you want to stop after one action, you don't use a loop. Apr 28, 2015 at 16:49

4 Answers 4

1

If you want to print

a[0] = 5, a[1] = 8, ... and so on.

Then you dont need inner loop.Just do

for(int i=0 ;i <= 4; i++)
    System.out.print("a[" + i + "] = " + a[i]+ ", ");   
0
1

It is not possible to find the present index in an enhanced for loop (there are workarounds but generally it's not worthwile). Either way, you are having two for loops at the moment, while really it should be one. So, you should pick between the ordinary for loop and using the index, or using the enhanced for loop and dropping the index.

So either

int[] a = {5, 8, 10, 24, 45};
for(int i = 0; i < 5; i++) {
    System.out.print("a[" + i + "] = " + a[i] + ", ");
}

or

int[] a = {5, 8, 10, 24, 45};
for(int i : a) {
    System.out.print(i + ", ");
}

If you really, really want to, you can introduce a variable that you increment at every print such that you still can print the current index.

0
  1. There is a way that can be used to output the answer. See the code:

    Integer[] a = {5, 8, 10, 24, 25};
    
    for(int loop:a){
        System.out.print("a[" + Arrays.asList(a).indexOf(loop) +"] = " + loop + ", ");
    }
    

    But for this to work just import java.util.Arrays.
    Try it.

  2. Now there is also another way to get the desired output using enhanced for loop:

    int[] a = {5, 8, 10, 24, 45};
    int c,  i;
    c = i = a.length;
    
    for (int temp:a) {
        int x = c - i;
        System.out.print("a[" + x +"] = " + temp + ", ");
        i -= 1;
    }
    

This should do it. It will just use the array length feature and use it for convenience.

1
  • 3
    This will only work if the array has distinct entries
    – SamYonnou
    Apr 28, 2015 at 17:38
0
public class Forloop {

    public static void main(String[] args) {
        // TODO code application logic here
        int fl=0,sl=0;

        for(int i =0;i<=3;i++)
        {
            fl=fl+i;

            for( int k=0;k<=2;k++)
            {
                sl=sl+k;
            }
        }
        System.out.println("Sum="+(fl+sl));
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.