-2

I need to count down to 0. I am only printing 0 to the screen. How can I print all the count-down characters to the screen? Below is the code I am using right now.

#include <stdio.h>
#include <iostream>
using namespace std;

class Solution {
public:
    int num;
    int numberOfSteps (int num) 
    {
      while (num != 0)
      {
        if (num % 2 == 0)
          {
            num = num / 2;
            cout << num;
          }
        else
        {
            num = num - 1;
            cout << num;
        }
    }

    }
};
int main () {
    int num;
    Solution myObj;
    cin >> num;
    cout << myObj.num;
    }

2 Answers2

1

You're passing the num to std::cout. You are also not calling numberOfSteps(...) anywhere in your code.

Replacing the line with cout << myObj.numberOfSteps(num); fixes the problem, but a tidier solution would be as follows:

#include <stdio.h>
#include <iostream>

void countDown (int num) {
    while (num != 0) {
        if (num % 2 == 0) {
            num = num / 2;
            std::cout << num << std::endl;
        } else {
            num = num - 1;
            std::cout << num << std::endl;
        }
    }
}

int main () {
    int num;
    std::cin >> num;
    countDown(num);
}

Class is not necessary as there is no state and the function is void since it does not return anything.

Roy
  • 3,027
  • 4
  • 29
  • 43
  • [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/430766) – bitmask Apr 08 '20 at 00:41
  • Thanks iop45. After changing to: ```myObj.numberOfSteps(num);``` and adding endl at each cout I got the output I wanted. – Ryan Dunnion Apr 08 '20 at 01:03
0

I am revisiting this question and have created a simpler solution than my original post:

    #include <iostream>

    using namespace std;

    int num;

    int main()
    {
    cout << "Please enter the number you would like to count down to zero : ";
    cin >> num;

        while (num > 0)
        {
            cout << num << endl; 
            num--;
        }

    cout << "The number is now zero.";
    return 0;
    }