A for() loop in a for() loop

Posts 1–10 of 10 · Page 1 of 1
A for() loop in a for() loop
Can be closed, I'm an idiot
Brackets are your friends.
Code:
    int numbers[] = { 1, 1, 2, 4, 4, 5, 7, 8, 8, 9 };
    int i, j;
    
    for(i=0; i<10; i++)
    {
    for(j=i+1; j<10; j++)
    {
    if(numbers[i] == numbers[j]) 
    cout << "Duplicate values are: " << numbers[i] << endl;
    }
    }
Brackets aren't needed here, i just don't understand how these for loops work.
I'm pretty damn sure you need brackets... and even if you don't you should add them anyway, it makes it easier for people to read your code.

But anyway I see your problem. Your making j = i +1. You should make j=0. That was say the second for loop will be able to look through the entire array to find a match for element [i].
you can also add cout statement to make it more clear.
Code:
    int numbers[] = { 1, 1, 2, 4, 4, 5, 7, 8, 8, 9 };
    int i, j;
    
    for(i=0; i<10; i++)
    {
      cout << "i is now" << i <<endl;
        for(j=i+1; j<10; j++)
              {
                cout << "j is now" << j <<endl;
               if(numbers[i] == numbers[j]) 
               cout << "Duplicate values are: " << numbers[i] << endl;
              }           
    }
Quote Originally Posted by why06 View Post
I'm pretty damn sure you need brackets... and even if you don't you should add them anyway, it makes it easier for people to read your code.

But anyway I see your problem. Your making j = i +1. You should make j=0. That was say the second for loop will be able to look through the entire array to find a match for element [i].
lol read my question, the code works fine but i simply dont understand how it works
Quote Originally Posted by BooYa View Post
lol read my question, the code works fine but i simply dont understand how it works
So you don't know how a for loop works?
Code:
for(int i = 0/*Init I as 0*/; i<10/*if I is below 10*/;i++/*increment it*/)
Hmm never mind... I just didn't understand how the second for loop would work inside the first and why j was set to i+1, but i understand now after trying those cout statements from laka
Ok...if you want me to... and thanks lalakiljip.
Posts 1–10 of 10 · Page 1 of 1
This thread is closed for replies.

Similar Threads

Tags for this Thread

Talk with us