-8

So I'm trying to do a challenge called 3n+1, where I have to tell how many times the program has to multiply or divide until n=1 but I don't get any output from the program. Please help? p.s. I'm using C++ 14

#include <iostream>
using namespace std;
int n;
int d=0;
int main() {
    cin>> n;
    for(int i=n; i<=1;){
        if(n=1){
            cout<< d;
        }
        else if(n%2==0){
            d++;
            n/2;
        }
        else{
            d++;
            n*3+1;
        }
    }
    return 0;
}
  • You don't even have a `<<` operator in your code. – owacoder Sep 25 '15 at 00:31
  • `cout << d`, not `cout >> d`. Voting to close as a typo. – Sergey Kalinichenko Sep 25 '15 at 00:31
  • change cout>> to cout< – Les Sep 25 '15 at 00:33
  • you do not change or use i – Les Sep 25 '15 at 00:35
  • try stepping through your code with a debugger – Les Sep 25 '15 at 00:36
  • 1
    [Get a book and read it](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). There's a ridiculous number of trivial errors in this code. – T.C. Sep 25 '15 at 00:37
  • If you want to learn the ins and outs of developing on linux (which is where I recommend you start because you won't have to buy any software), take a look at this question: http://stackoverflow.com/questions/623040/c-development-on-linux-where-do-i-start – Wug Sep 25 '15 at 00:39
  • ok so i fixed the typo, but i still dont get an out put – Edwin Duong Sep 25 '15 at 00:51
  • Try inputting `0`. It is less than 1, so the loop starts. Then, `n=1` is true because it will set `n`'s value to 1 and evaluates as 1, which means true. As a result, `cout<< d;` will be executed and it will print many `0` in infinity loop without changing the value of `i`. – MikeCAT Sep 25 '15 at 00:55

1 Answers1

2

Possible fix:

#include <iostream>
using namespace std;
int main() {
    int n; // you don't need the values to be global
    int d=0;
    cin>> n;
    for(; ;){ // deleted i because it wasn't used
        if(n<=1){ // compare here, don't assign here
            cout<< d;
            break; // exit the loop
        }
        else if(n%2==0){
            d++;
            n=n/2; // please update n here
        }
        else{
            d++;
            n=n*3+1; // also please update n here
        }
    }
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70