Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
2.57/5 (3 votes)
See more:
Hey everyone, I'm new to programming. I recently wrote a program to convert from decimal to binary in c++ and just want some better opinions if it is properly written. Excuse my ignorance in advance in c++ and other programming languages, just want to know if this code is decently written.

Well here it is:

-IN BINARY.H-
C++
class ntb {
public:
    void num_to_bin() {
        std::cin>>convte;
        recur(convte);
        go_back();
        return ;
    }

    void recur(int convte) {
        if(convte == 0) {
            return;
        }
        recur(convte/2);
        std::cout<<convte % 2;

    };

    void go_back() {
        while(convte > 0 ) {
            std::cout<<""<<std::endl;
            num_to_bin();
        };
    };

private:
    int convte;
};
ntb Binary_Convert;


-IN MAIN.CPP -
C++
#include <iostream>
#include "binaryC.h"

int main()
{
    Binary_Convert.num_to_bin();
}
Posted
Updated 16-Sep-14 15:59pm
v2
Comments
George Jonsson 16-Sep-14 22:00pm    
First you need to learn how to format the code so it is readable.
I did it this time.

Well, there are a few issues in your code, and this is without even trying if it works.


  1. Use comments to explain what you are doing.
  2. When you come back three weeks from now and look at your code, you will scratch your head and wonder how you where thinking. (Learned that the hard way)

  3. Variable naming

  4. Do not use the same variable name for member variables and local variables or as parameters. It can be very confusing.
    Also use descriptive names. convte is not exactly self describing.

  5. Variable initialization
  6. Always, always initialize your variables with an initial value.
    C++
    int convte;
    int convte = 0;

    One reason for this is that in the Debug mode variables are initialized to NULL or zero, but that is not the case in Release mode.
    I spent some time once trying to find the bug in the code below:
    C++
    for (int i; i < 5; i++)
    {
        // In Release mode the code inside the loop was never executed.
        // In Debug mode it worked fine.
    }


  7. Circular function calls
  8. One of the more serious problems in your code is that you inside num_to_bin call go_back that calls num_to_bin.

  9. Usage of UI specific methods
  10. By using cin inside the method num_to_bin() you limit the re-usability of your class. What if you want to use this class in a graphical interface?
    It is better to use an in-parameter.
    C++
    int main()
    {
        int input = 0;
        std::cin >> input;
        Binary_Convert.num_to_bin(input);
    }

    The same applies to the usage of cout. Better to use a return value or an out-parameter.

  11. Spaces are not evil (in the right places)
  12. Spaces increase readability of your code.
    C++
    std::cout << convte % 2;

    is more readable than
    C++
    std::cout<<convte % 2;

  13. Bracket positioning { }
  14. I find this style
    C++
    void go_back() 
    {
        while(convte > 0 )
        {
            std::cout << "" << std::endl;
            num_to_bin();
        };
    };

    more readable than this
    C++
    void go_back() {
        while(convte > 0 ) {
            std::cout<<""<<std::endl;
            num_to_bin();
        };
    };

    But this is more a matter of taste. The most important thing is to be consistent throughout your code.


The code you have written can be done in one method.
I just changed your recursive method a bit
C++
int Int2BinaryString(int iNumber, char* szOutput, int iLength)
{
    // If the input string is not initialized return -1 as error code
    if (szOutput == NULL)
        return -1;

    // Break condition for the recursion
    if (iNumber == 0)
        return 0;

    Int2BinaryString(iNumber / 2, szOutput, iLength);

    // The position of the character to add is the same as the current length of the string
    int iPosition = strlen(szOutput);
    
    // If the position exceeds the length of szOutput, return the number of characters required.
    if (iPosition >= iLength)
        return iPosition + 1;

    // Set the current position to one or zero
    szOutput[iPosition] = (iNumber % 2 == 0) ? '0' : '1';
}

int main()
{
    char szBinary[10] = ""; // Needs to be initialized to empty string.
    int result = Int2BinaryString(7, szBinary, sizeof(szBinary));
    if (result == 0)
        std::cout << szBinary << std::endl;
    else
        std::cout << "Error code: " + result + std::endl;
}


As an end note.
No, your code is not very well written.
But if you want to learn, you can.
 
Share this answer
 
v6
Comments
[no name] 19-Sep-14 19:06pm    
I've revised my code. Care to check it again if i post it in the comment section down here?
George Jonsson 20-Sep-14 1:44am    
Nah. Don't post code in comments. It is hard to read.
And I think you need to get a good programming book and learn the basics.
Or look at resources online.
[no name] 20-Sep-14 20:17pm    
I am just a little discouraged and it really isn't from you, but is something wrong with my style (like naming , spaces , and brackets) or something more serious like not knowing what goes where ( i mean that by function calling, using the right keywords , etc). I do have a programming book, and do study it and learn by example, but in your perspective, do i even qualify for basic level or am i not even there yet? I am so sorry for bothering you, it's that this is stuck in the back of my head and i have been studying it for about 4 months now .
George Jonsson 21-Sep-14 1:08am    
Well, it takes time to learn programming and you will make many mistakes on the way. You will learn a lot from these mistakes and understand why different programming patterns are to prefer in different situations.

When it comes to style you would get different answers from every programmer, left to their own devices. That is why there exist some common rules and most companies have a set of internal rules. The reason is that it is easier for all programmers within the company to read and debug each others code.

How long have you been programming and what level do you think you are on?
[no name] 21-Sep-14 11:48am    
It's not even a year i have been programming, matter of fact, I started a little less than 4 months ago. I am not sure what level i am on honestly, I still think I am a beginner or maybe not even that. All in all , thank you so much for your feedback ,it really is appreciated.
These are some tips to improve your code:

Descriptive Names: First of all, try to name your variable, class and method names descriptively. For instance, ntb isn't a very good name. Instead try to name the class some thing like "NumberToBinaryConverter".

Document your code: You should document your code to show people what your methods, functions do and why they exist. For example,
C++
/**
 *   This function accepts input from the console and calls the recur function.
 */
void num_to_bin() {
  std::cin>>convte;
  recur(convte);
  go_back();
  return ;
}

The comment above the method is the documentation associated with the method. There are these tools like doxygen that generate HTML files containing your code documentation.

Try to Follow a Naming Convention: I can see inconsistent naming style in your code. Use a style to name your variables. For example, I use this style,
1) PascalCase for class and function names.
2) camelCase for variable names.
As my style is more suitable for C#, I encourage you to follow the Google C++ style. You follow any style but be consistent with it. But when you work on old projects, follow the convention used there.

Use Spaces Wherever Possible: Use of enough space is not bad and can improve code readability. For example,
C++
std::cout << "Hello, world" << std::endl;

is better than
C++
std::cout << "Hello, world" << std::endl;

That being said, overwhelming spaces aren't that good. For example,
C++
window . DoSomeThing ( 10 , 12 , 30 , 20 ) ;

can hurt your eyes.

Brace Placement Style: As in the case of naming convention, you must be consistent with style of brace placement. Your first file uses Java style while your second file uses the ANSI style. You should have used any one of these styles.

I can also see the weird semicolon after the closing braces. While the C++ compiler allows the semicolon, that is not necessary.

Avoid Global Variables: Never use global variables. I see no reason for why you declared the global variable Binary_Convert. Instead, why not use a local variable,
C++
int main()
{
  ntb n;
  n.num_to_bin();
}

Now, the object n will get destroyed when it reaches the end of the scope. But with global variables the object will remain in memory until your program exits. See this page.

Declare a Constructor and a Destructor: Your class ntb should have a constructor that initializes the fields during construction. Something like this would be fine,
C++
ntb() {
  this->convte = 0;
}

A destructor should be declared if your class has pointer members to delete the data pointed by them. I don't know how familiar you are with pointers. If you're unfamiliar with pointers and references, you should learn them; they're so important to understand programming.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900