5

I am a begginer and this is my first question. I've scoured the net for answers and I am coming up short. Any help any of you can provide will put a smile on my face!!

I am writing a program that loops over two arrays simultaneously. These are char arrays cast from user defined strings so they will likely be different lengths. Below is how things are currently set up in my code.

for(int i = 0; i < charArray1.length; i++)
    {   
        char keyChar = charArray1[i];
        char messageChar = charArray2[i];
    }

Considering the example above. lets say that:

charArray1 = {'A','B','C','D'} and
charArray2 = {'1','2','3','4','5','6','7}

Currently this scenario tosses me an out of bounds exception, as it should. What I'd like to see happen is for a loop to return to the start of charArray1 while another loop continues to the end of charArray2.

If I were to print this it might look something like below.

A1, B2, C3, D4, A5, B6, C7

Any help would be greatly appreciated. I've been at this for a while now.

dmitrivada
  • 51
  • 1
  • 3

5 Answers5

6

The number of iterations you want from your loop is the length of the longest array. You can get that with Math.max(charArray1.length, charArray2.length);

Then you want to get the array item at index i, but cycling around when it passes the array's length. You can get that with arr[i%arr.length].

In combination:

int m = Math.max(charArray1.length, charArray2.length);
for (int i = 0; i < m; ++i) {
    char keyChar = charArray1[i%charArray1.length];
    char messageChar charArray2[i%charArray2.length];
}

Edit:

The modulo operator (a%b) gives you the amount left over after dividing a by b.

For instance, with b=3:

a   a%3
0    0
1    1
2    2
3    0
4    1
5    2
...

You can see that if a and b are integers with a>=0 and b>0, then a%b will always be in the range:

0 <= a%b < b

which is the range of acceptable indexes for an array of length b.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • This worked perfectly, thank you! Though in pursuit of understanding this stuff instead of merely pasting it, can you explain to me what the modulus operator is doing here? Thanks again. – dmitrivada Dec 23 '14 at 17:03
  • tells you the remainder of the division operation – jgr208 Dec 23 '14 at 17:05
  • Thanks jgr208. I understand what it does. I am seeking to understand it's purpose here in the code and how it relates to the iteration through the arrays index. – dmitrivada Dec 23 '14 at 17:09
  • @dmitrivada I've added some info to my post about what the modulo is doing. – khelwood Dec 23 '14 at 19:18
  • @khelwood Thanks for the update. I did the math with the modulo and immediately understood what it was doing. I'm not sure I would have figured that out on my own. Thanks a ton, all of you, for helping me out with this problem. – dmitrivada Dec 27 '14 at 06:34
0

What you need to do is make a for loop inside a for loop

for(int i = 0; i < charArray2.length; i++)
    {   
        for(int j = 0; j < charArray1.length; j++)
            char keyChar = charArray1[j];
        char messageChar = charArray2[i];
    }

This loops over the inside loop and once it reached the end loops over again until the end of charArray2 is reached at which point the outter for loop will terminate thus exiting the loop. There are other ways to do this but this is one ways that makes it easier for a beginner like you to understand.

Then if you want it to print out A1,B2,... exactly without two for loops you can do the following. Two for loops not be the best way to go if you are dealing with a large set of numbers since two for loops are n^2 while an if statement is just a constant like 1 i think.

int max = Math.max(charArray1.length, charArray2.length);
int j = 0;
for (int i = 0; i < max; ++i) {
    if(j==charArray1.length)
      j = 0;
    else
      j++;
    char keyChar = charArray1[j];
    char messageChar charArray2[i];
}
jgr208
  • 2,896
  • 9
  • 36
  • 64
  • @CyberneticTwerkGuruOrc how is this wrong? it loops over the inside of the array the small array then after it is done loops over the array again with the next letter. so it would be A1 A2 A3....B1 B2... and so on – jgr208 Dec 23 '14 at 16:27
  • @khelwood what do you not understand about the answer? – jgr208 Dec 23 '14 at 16:31
  • He wants A1 B2 C3 D4 A5 B6 D7. You've misunderstood the question. – ajb Dec 23 '14 at 16:38
  • @ajb he said **might** look like that. He then goes on to say he wants it in two loops. – jgr208 Dec 23 '14 at 16:39
  • No, no, no, no. He thinks he wants it in two loops, but he's a beginner trying to do something a little different from the usual textbook stuff, so it's understandable that he's not sure how to do it. It's up to us to show him how to produce the output he wants (in one loop), not to show him how to produce a totally different output. – ajb Dec 23 '14 at 16:42
  • @ajb but he said that might be the output, so thus it is ambiguous what one can assume from that. You might think hey he wants it exactly like that where I think hey he means he wants it to look like it would if it was through two for loops. Thus, maybe both of us are right and neither is wrong? – jgr208 Dec 23 '14 at 16:43
0

Have a second variable j to keep track of the indexing for the smaller array.

//charArray1 = {'A','B','C','D'}
//charArray2 = {'1','2','3','4','5','6','7}

int j = 0;
for(int i = 0; i < charArray2.length; i++)
{   
    char keyChar = charArray1[j];

    j++;
    if(j == charArray1.length)
        j=0;

    char messageChar = charArray2[i];
}

Here's a test run

This assumes charArray2 will always be the longest array. If you expect this to be untrue, just do a check prior entering loop

You can also do fancy stuff with the % operator, but I prefer this approach because it's more readable for newcomers.

0

You want to loop until the end of the longest array, so you pick the max of the two lengths as your loop's exit condition.

Then, you can loop the two arrays at the same time by using the modulo for the indexes, in such a way you can not throw an index out of bounds exception: when i becomes grater then the bounds of an array, with the modulo (%) operator you restart from the beginning of that array.

for (int i = 0; i < Math.max(charArray1.length,charArray2.length); i++) {
   char keyChar = charArray1[i%charArray1.length];
   char messageChar = charArray2[i%charArray2.length];
}

This will work independently of which array will be the larger.

WoDoSc
  • 2,598
  • 1
  • 13
  • 26
0

There's no rule that says the index of a for loop has to be an index into any array. Here's an approach that uses a counter and two separate array indexes:

int totalCount = Math.max(charArray1.length, charArray2.length);
int i = 0;
int j = 0;
for (int count = 0; count < totalCount; count++) {
     char keyChar = charArray1[i++];
     if (i >= charArray1.length) {
         i = 0;
     }
     char messageChar = charArray2[j++];
     if (j >= charArray2.length) {
         j = 0;
     }
     // code that outputs the two characters, or whatever
}

This will work regardless of which array is longer, and it doesn't rely on %.

ajb
  • 31,309
  • 3
  • 58
  • 84