Why it doesn't work as expected...

Hi all,
I am new in C++.
I tried to get the result like this:
(n, i)
0, 0
1, 0
2, 0
..
..
16,0 -----------------// reset here when n is 16
-----------------//multiply by 2 to n (i.e. 16*2)
-----------------//increase i by one
0, 1
1, 1
2, 1
....
....
32, 1 -----------------// reset here when n is 32
-----------------//multiply by 2 to n (i.e. 32*2)
-----------------//increase i by one
0, 2
1, 2
2, 2
....
....
64, 2 -----------------// reset here when n is 64
-----------------//multiply by 2 to n
-----------------//increase i by one
……
……

0, 6
1, 6
.....
.....
.....
.....
1024, 6 ...............//end the program here


******//And program is as: //******

void count(int, int);
int main()
{
int w=16, i=0;
count(w, i);
return 0;
}

void count(int w, int i)
{
int *wPtr;
wPtr = &w;
while (*wPtr<=1024)
{
for (int n=0; n<=*wPtr; n++)
{
cout<<" i = "<<i<<endl;
cout<<" n = "<<n<<endl;
if (n==*wPtr)
{
*wPtr = (*wPtr) * 2;
cout<<"reset w here"<<endl;
if (i<=7){
++i;
count(w, i);
}
}
}
}
}

**********//When I run this program the value of i increases even after it reaches 7 and *wPtr is 1024.**********//

What is the mistake here?
Last edited on
You get your recursion abit mixed up.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void count(int w, int i)
{
  int *wPtr;
  wPtr = &w;
  while (*wPtr<=1024)
  {
  for (int n=0; n<=*wPtr; n++)
  {
    cout<<" i = "<<i<<endl;
    cout<<" n = "<<n<<endl;
    if (n==*wPtr)
    {
      *wPtr = (*wPtr) * 2;
      cout<<"reset w here"<<endl;
      if (i<=7){
        ++i;
        count(w, i);
        break;
      }
    }
  }//end for
  break;
  }//end while
}//end count 
Hi sohguanh,
Thanks a lot. Yes, now it works perfectly. But, I didn't understand the uses of "break" in the program that you added. Could anybody please explain me how these two "break" works?
break means break out of the innermost loop containing the break.

In your case, the first break break outside of the for loop. The second break break outside of the while loop.
Topic archived. No new replies allowed.