Cout change the variable value

In the main function,if i call the cout << answer << "\n";,
the final answer will be change.Can someone explain to me why this happen ?

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
  #include <iostream>

	using namespace std;

int Even(int *num){

	return (*num)/2;
}


int Odd(int *num){

	return 3*(*num)+1;
}

int Cycle (int num){
		int cycle;

		while (num != 1){
	
		if( num%2 == 0 ){  
			
			num= Even(&num) ;
		
		}else{

			num = Odd(&num) ;
		}
	
	  	cycle++;
	}
		return  cycle+1 ;
}

  

int main(){
	
 	int num1,num2,max=0,answer;

	cin>>num1;
	cin>>num2;

	for(int i = (num1 < num2 ?  num1 : num2) ; i<=num2 ; i++ ){
	
		answer = Cycle(i);
		
//Here is the PROBLEM
		cout << answer << "\n";
 
		if(max < answer){
			max = answer;
		}
		
	}
	
	cout <<"Final Answer "<< max <<"\n" ;
 
  return 0;
}


Output without cout Final Answer 68

Output with cout Final Answer 20
Last edited on
(Ah, the Collatz conjecture.)
Not sure why it's not working, but I don't think cout is the problem. Why are you passing pointers to your Even and Odd functions? sizeof(int) is either smaller then or equal to sizeof(void*).
Actually,i try to understand the concept of pointer.I also try a different version of code which i pass the value without using the pointer.Unfortunately,the answer remain the same.Any thought ?
When I compile your code my compiler tells me "warning: ‘cycle’ may be used uninitialized in this function".
Finally,I know the answer.I should initialize the cycle variable value.Thx for helping me.
Topic archived. No new replies allowed.