Intro + Seeking Help

Hello, I'm a new member here. I've recently decided to learn a programming language (C++) in hopes of keeping myself entertained with something that can both, keep me busy, and help me find employment in the near future.

I have a small amount of experience with C programming, but that was long ago. I'm not a university student anymore, so I'm not looking for help getting a good grade, I'd just like to understand this language better.

Here is the code that I have written that turns decimal into binary.


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
61
62
63


#include <iostream>
#include <cmath>

int main(int argc, const char * argv[])
{
    using namespace std;
    double number;
    
    cout<<"Type in your number"<<endl;
    cin>>number;
    
   
    
    while(number>1 && number !=3)
    {
        
        double num1;
        double num2;
        double num3;
        
        num2=(number/2);
        num3=floor(num2);
        num1= fmod(number, 2.0);
       // cout<<num2<<endl; //check if works
       // cout<<num3<<endl; //check if works
       // cout<<num1<<endl; //check if works
       
        number=num3;
       
        if(num1==1 && number>1)
        {
            cout<<"1";
        }
        else if (num1==0 && number>1)
        {
            cout<<"0";
        }
        else if (num1==0 && number==1)
        {
            cout<<"0";
        }
    }
   
    if(number==1)
    {
        cout<<"1";
    }

    if(number==0)
    {
        cout<<"0";
    }
    if(number==3)
    {
        cout<<"11";
    }
    cout<<endl;
    
    return 0;
    
}


I've ran tests on it, and it now seems to display the correct answer, backward. I figure that in order to have it display in the correct order, I'll have to first save the output as a string, and then reverse that string. The problem is that I don't know how to do either, and I don't even know where to start. I realize I've used a lot of "if", "else if" statements, so any advice or comments as to whether this is an acceptable manner of programming in C++ would be much appreciated.

Thank you.
Last edited on
There's a lot of repetition in the code that doesn't seem to be necessary. For example, like 32, 36, and 40. Those number == or > conditions don't need to be there, because they're already taken care of by your while loop.

Stylistically, one liners don't need brackets, aka
1
2
3
4
5
6
7
8
9
if( blah )
{
    stuff;
}

// is the same as 

if( blah2 )
    stuff2;


Also take advantage of spaces. cout << endl; looks much better than this: cout<<endl; (especially when coding late at night or with poor lighting conditions).

As for addressing your actual question of output, take a look at vectors
http://www.cplusplus.com/reference/vector/vector/

If you're not worried about space allocation, you could do what you mentioned, in storing your output into a vector, then using some good ol' logic, output the reverse of that string (you'll need to start with the maximum size of the vector that you're dealing with, using the built-in ".size()" function.
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


#include <iostream>
#include <cmath>

int main(int argc, const char * argv[])
{
    using namespace std;
    double number;
    
    cout << "Type in your number" << endl;
    cin >> number;
    
   
    
    while(number > 1 && number !=3)
    {
        
        double num1;
        double num2;
        double num3;
        
        num2=(number/2.0);
        num3=floor(num2);
        num1= fmod(number, 2.0);
       
        number=num3;
       
        if(num1 == 1)
            cout << "1";
        
        else if (num1 == 0)
            cout << "0";
    }
   
    if(number == 1)
        cout << "1";

    if(number == 0)
        cout << "0";
    
    if(number == 3)
        cout << "11";
    
    cout << endl;
    
    return 0;
    
}

   


Just to clarify, this is what you meant with regards to line 32,36, and 40, correct? I'm about to read up on the other stuff you listed to see if I can figure it out. Thanks.
Knowledge of C would suffice to understand this snippet:

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
#include <iostream>

void do_print_binary( unsigned int number )
{
    if( number == 0 ) return ; // no more binary digits to be printed

    if( number < 2 ) std::cout << number ;
    else
    {
        do_print_binary( number/2 ) ; // print the leading binary digits
        std::cout << number%2 ; // after that, print the last binary digit
    }
}

void print_binary( unsigned int number )
{
    if( number == 0 ) std::cout << "0\n" ; // special case to take care of zero

    else
    {
        do_print_binary(number) ;
        std::cout << '\n' ;
    }
}

int main()
{
    std::cout << "Type in a non-negative number: " ;

    unsigned int number ;
    std::cin >> number ;

    print_binary(number) ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>//This Program only capable of handling Positive digits
using namespace std;
int main()
{
    long dec,rem,i=1,sum=0;
    cout<<"Enter the decimal to be converted:";
    cin>>dec;
    do
    {
        rem=dec%2;
        sum=sum + (i*rem);
        dec=dec/2;
        i=i*10;
    }while(dec>0);
    cout<<"The binary of the given number is:"<<sum<<endl;
    cin.get();
    cin.get();
 
    return 0;
}
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
#include <iostream>//modified version

using namespace std;
int main()
{
    long dec,rem,i=1,sum=0;
    cout<<"Enter the decimal to be converted:";
    cin>>dec;
    if(dec<=0){
        cout << "Invalid Number!\tEnter a positive number Please\n";
        exit(0);
    }
    do
    {
        rem=dec%2;
        sum=sum + (i*rem);
        dec=dec/2;
        i=i*10;
    }while(dec>0);
    cout<<"The binary of the given number is:"<<sum<<endl;
    cin.get();
    cin.get();
 
    return 0;
}
Last edited on
Stylistically, one liners don't need brackets

In my opinion, that's poor advice. Many, many times, I've seen bugs introduced in code, because someone didn't put brackets around a single-line block, and then went and added extra lines to the block, forgetting to add braces. Frex:

1
2
if (x > 10)
    std::cout << "x is too big";


gets changed to:

1
2
3
4
bool x_is_too_big = false;
if (x > 10)
    std::cout << "x is too big";
    x_is_too_big = true;


I'm sure you can see the obvious bug in there.

IMHO, it's much better practice to code defensively, putting in the brackets even for a single-line block, to reduce the chance if accidentally introducing bugs.

EDIT: If you're really obsessed with saving screen space, something like:

if (x > 10) std::cout << "x is too big";

as JLBorges did, is safer, too.
Last edited on
Wow, the multiply by 10 (i*10) to reorient the numbers in the correct manner is an extremely simple (but extremely genius) solution. And here I was breaking my head, trying to build a mountain out of a molehill. Thanks a lot for your help!

This is also the first time I've come across the do/while loop. I think I have some reading to do.
@MikeyBoy Yeah you're right on that one. I guess I'm just used to see stuff like return (a > b ) ? a : b; which, if written regularly, would take at least 2 or 3 lines depending on how you wrote it. And I typically keep those ternary ops written as is, so I don't confuse myself when I go back and look at it later.

Also since you mentioned it, @OP, here's a basic breakdown of the loops:

For: used when you want to step through a data structure one by one, usually seen with integers or with pointers.

While: used when you want something to keep looking when a certain condition still holds true, like while the mouse hovers across the link, show the menu.

Do-while: guaranteed to execute your code once, but otherwise functions the same as the While loop.

A note on the do-while: it is absolutely guaranteed, provided nothing is done to impede it, that the code inside the do-while block will execute at least once. So if you screwed up your while condition, and was supposed to be true instead of false, you'd see the results of your creation once through before your computer burns down on you.
> the multiply by 10 (i*10) to reorient the numbers in the correct manner is an extremely simple (but extremely genius) solution

Not only simple, but also simplistic. (The range is severely limited).
I'm surprised nobody has done any bit manipulation, which seems like the most natural approach to me given that values are already stored in a binary representation.

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
// http://ideone.com/d3dKes
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>

using value_type = unsigned long long;

std::string as_binary(value_type value)
{
    std::ostringstream os;

    if (value == 0)                         // no bits set
        os << value;
    else
    {
        // set mask's left-most bit.
        value_type mask = 
            value_type{1} << (std::numeric_limits<value_type>::digits - 1);

        while ((mask & value) == 0)         // skip leading 0 bits
            mask >>= 1;                     // shift our set bit to the right

        while (mask)
        {
            os << ((mask & value) ? 1 : 0);
            mask >>= 1;
        }
    }

    return os.str();
}

int main()
{
    for (value_type i = 0; i < 33; ++i)
    {
        std::cout << std::setw(2) << i;
        std::cout << " = ";
        std::cout << std::setw(6) << as_binary(i) << '\n';
    }
}
Topic archived. No new replies allowed.