Question about arrays

This is a discussion on Question about arrays within the C++ Programming forums, part of the General Programming Boards category; Hi, im making a program to convert any number to binary using the division method. Its just dividing the number ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    7

    Question about arrays

    Hi, im making a program to convert any number to binary using the division method. Its just dividing the number by 2 and saving the remainders (which will either 1 or 0 ).
    At first I tought of just printing out the remainder saved in the variable rem, but there were some problems with 1 digit numbers, and the remainders are not in the correct order. For example the remainders of 10 are: 0101, but this of course isnt 10 in binary, you would have to start with the las bit, and go backwards, so it would be 1010.
    So later i thought, why not putting the remainder inside an array? So thats what i did.
    heres what i wrote:
    Code:
    ...
    int rem[100];
    int i;
    int n;
    ...
    ...
    i = n;
    
    c = 0;
    
    while ( i > 2)
        {
              a = n / 2;
              rem[c] = n % 2;
              n = a;
              i--;
              c++;
              if ( n == 0)
              {
                   break;
              }
        }
    ok, here is my question: If the number is 10, there are 4 elements in the array (0101), but i cant know that the number is 10, because its the user who has input that number so i cant know how many elements have been used in my array. How can i program this thing to print in the screen all the elements of the array, without knowing how many elements are there ( i cant do this: cout<< rem[0]<<rem[1]...), and how can i reverse that order, so that the last element is the first one.

    Maybe its a stupid question, but im studying this for the first time

    waiting anxiously for your answer!! thanks in advance.
    Last edited by Pixie; 12-26-2007 at 05:48 PM.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    First, consider how you'd print the elements in normal order, forwards. If you know about for loops, you might come up with something like this:
    Code:
    for(int x = 0; x < digits; x ++) {
        std::cout << digit[x];
    }
    
    std::cout << std::endl;
    (If you don't know about for loops, it's time you did: http://www.cprogramming.com/tutorial/lesson3.html)

    With some thought, you can see that this will work backwards as well . . .
    Code:
    for(int x = digits - 1; x >= 0; x --) {
        // ...
    I'm not sure if that answers your question or not . . . .
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    7
    thanks, i will try that

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    How can i program this thing to print in the screen all the elements of the array, without knowing how many elements are there ( i cant do this: cout<< rem[0]<<rem[1]...), and how can i reverse that order, so that the last element is the first one.
    You can almost certainly determine how many elements are in the array. If the data entered by the user was read as a string, you can use strlen() on it, or the .length() member of C++ std::strings. It probably wasn't read as a number, but even if it was, you can do this, too.

    I think perhaps you'd be interested in looking at this program.
    Code:
    #include <iostream>
    #include <cstdlib>
    #include <string>
    
    int main() {
        std::string data, rev;
        
        while(std::getline(std::cin, data)) {
            std::cout << "==== Processing number \"" << data << '"' << std::endl;
            
            std::cout << "Printed forwards:  \"";
            for(int x = 0; x < data.length(); x ++) {
                std::cout << data[x];
            }
            std::cout << '"' << std::endl;
            
            // build a string, the reverse of data
            rev = "";
            for(int x = data.length() - 1; x >= 0; x --) {
                rev += data[x];
            }
            
            std::cout << "Printed backwards: \"" << rev << '"' << std::endl;
            
            std::cout << "Converted to decimal via strtol(): "
                << std::strtol(rev.c_str(), NULL, 2) << std::endl;
        }
        
        return 0;
    }
    Notes: strtol() is limited to the range of a long. If you want higher values, you'll have to do the addition yourself. It's not hard. Do it as you would do it on paper.

    Your compiler may warn you about "comparison between signed and unsigned integer expressions". This is because I used ints, a signed type, and std::string::length() returns an unsigned type. I didn't use an unsigned type because it messes up "x >= 0", and I didn't want the example to be too confusing . . . .
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    7
    wow nice program, very similar to what i want to do
    but the remainders are numbers, how can i convert numbers to strings?

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Well . . . you can convert a digit, from 0 to 9, to a character which can be stored in a char, by adding '0':
    Code:
    int number = 4;
    char character = number + '0';
    It doesn't work for 10 and above, though, because you can't store "10" in a character. It's two characters.

    You can convert a number with more than one digit into a char array, a C-style string. It's a little complicated and I'll leave the explanation to the FAQ: http://faq.cprogramming.com/cgi-bin/...&id=1043284385

    You can convert a character or a char array to a std::string very easily.
    Code:
    char c = '3';
    char str[] = "123";
    std::string one = c, two = str;
    // or
    std::string one2(c), two2(str);
    On a side note, you probably don't really need to convert the numbers to strings or characters or anything. You can just print them . . . .
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Registered User
    Join Date
    Dec 2007
    Posts
    7
    ok, i've done it with the for loop, but theres a little problem. This is what i wrote:

    Code:
    for (rev = c; c >= 0; c--)
        {
            cout<< rem[c];
        }
    the output, whatever number i put is always:
    rarenumer(binary numer);
    example:
    with 30:
    411110
    with 25:
    411001
    with 15:
    26873041111

    what do i have to do to print only the binary number? and why do the rare number always appear?

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Notice my code.
    Code:
    for(int x = data.length() - 1; x >= 0; x --) {
    I subtract 1. Here's why.

    With a string like "123", strlen() and .length() return 3, because that's how many characters are in the string. However, string[3] will give you the NULL, if it's there. If you want to print every character in the string, you have to start at 2, that is, length-1, and go until 0, inclusive. (Hence >= 0, not > 0.)
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Registered User
    Join Date
    Dec 2007
    Posts
    7
    it doesn't work.

    I think its better if a put all the code

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main(void)
    {
        int a, i, n, c, rev;
        int rem[100];
        
        cout<<"write a number: ";
        cin>> n;
        
        i = n;
        c = 0;
        
        cout<<"binary number: ";
        while ( i > 2)
        {
              a = n / 2;
              rem[c] = n % 2;
              n = a;
              i--;
              c++;
              if ( n == 0)
              {
                   break;
              }
        }
          
        cout<<endl;
        for (rev = c - 1; c >= 0; c--)
        {
            cout<< rem[c];
        }
            
        cout<<"\n"<<endl;
        system("pause");
        return 0;
    }

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    Quote Originally Posted by dwks View Post
    Notice my code.
    Code:
    for(int x = data.length() - 1; x >= 0; x --) {
    You can do a backwards loop like this with an unsigned type like std::size_t as follows:
    Code:
    for (std::size_t x=data.length(); x>0;) {
      --x;
      // rest of loop code
    }
    Note that the decrement has to be inside the loop body, at the beginning, not in the for statement, since "x>=0" is always true. The same trick works with backwards pointer/iterator loops to insure that an invalid pointer/iterator value is never assigned (which triggers UB). I'm not sure whether std::string::size_type is guaranteed to be the same as std::size_t, though from the following link it appears the corresponding guarantee holds with std::vector<T> if the standard allocator is used.

    http://www.thescripts.com/forum/thread130058.html

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,920
    Code:
        for (rev = c - 1; c >= 0; c--)
        {
            cout<< rem[c];
        }
    This should be:

    Code:
        for (rev = c - 1; rev >= 0; rev--)
        {
            cout<< rem[rev];
        }
    You should be using a counter variable and print from the index of the counter variable.
    Btw, in C++, you can get away with just int main() and not int main(void).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Dec 2007
    Posts
    7
    thanks to everybody. I've finally done it.

    instead of doing cout<<rem[rev] (which also worked thanks elysia ) i erased the rev variable and continued with the c variable:

    Code:
    for (c = c -1; c>= 0; c--)
    {
        cout<<rem[c];
    }
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question about arrays.
    By Kelvie in forum C++ Programming
    Replies: 3
    Last Post: 09-17-2007, 06:32 AM
  2. A question concerning character arrays
    By ellipses in forum C Programming
    Replies: 3
    Last Post: 03-08-2005, 08:24 PM
  3. Replies: 6
    Last Post: 04-26-2004, 11:02 PM
  4. Question about char arrays
    By PJYelton in forum C++ Programming
    Replies: 5
    Last Post: 10-21-2003, 01:44 AM
  5. Question about arrays?? PLease read..
    By foofoo in forum C Programming
    Replies: 3
    Last Post: 06-24-2002, 03:40 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21