Trouble with algorithm

Hi guys I'm having trouble understanding how i = 5,I actually wrote the algorithm myself which is pretty funny,anyway in the for loop i will run less than size-1 lets say I use the word hello the size will be 5, but the outer for loop will only execute three times and i will only be incremented 3 times so how is it that when both the for loops finish I ends up being 5,I thought it would be 3?

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  void uniqueLetters(const char* str,int size){

       char* newstr = new char[size+1];
       int newSize = 0;
       bool duplicate = false;
       int i = 0;

       for(i; i < size-1; i++){

        for(int j = i+1; j < size; j++){

            if(str[i] == str[j]){

                duplicate = true;
                break;
            }
        }
        if(!duplicate){

            newstr[newSize] = str[i];
            newstr[newSize+1] = '\0';
            newSize++;
        }
        duplicate = false;
       }

       cout << i << endl; // PRINTS 5

       int b = i-1;

       while(b > 0){
            
        if(str[b] == str[i]){

            break;
        }
        b--;
       }
       newstr[newSize] = str[i];
       newstr[newSize+1] = '\0';

       cout << " hello " << newstr << endl;
}
Last edited on
Hello adam2016,

Given "size" a value of 5 the outer for loop will run from zero to three as it should. When "i" equals four the condition fails because four is not less than four. The for loop will only use the elements of the array from zero to three, but the value if "i" will always be one more than you used when the loop is finished.

At line 27 the program prints 4 as it should. The full output I get is:

4
 hello helo 



I guess that is what you are looking for.

Hope that helps,

Andy
thanks Andy,I never knew i got incremented until it was less than the size,I learn something new everyday =)

Last edited on
Topic archived. No new replies allowed.