Understanding C++ Code “Get the number of digits in an int”












9














I am having trouble understanding how exactly this code works.



int length = 1;
int x = 234567545;
while ( x /= 10 )
length++;


It is supposed to count the number of digits in the int variable. I dont get how the while loop is working. Does the loop just go to zero and stop by default. Also why is the length starting at 1. Thank you for your time.










share|improve this question




















  • 1




    Zero means false. Think about that regarding how that loop ends. The final iteration (where x < 10 is true), will break the loop, but not account for that final digit, thus the starting point of 1 requirement.
    – WhozCraig
    4 hours ago








  • 6




    Step through your program with a debugger and watch the value of the x variable. BTW, /= means x = x / 10.
    – Thomas Matthews
    4 hours ago






  • 2




    As an aside: a simpler way to get the number of digits for a positive number is ceil(log10(x)).
    – duskwuff
    4 hours ago
















9














I am having trouble understanding how exactly this code works.



int length = 1;
int x = 234567545;
while ( x /= 10 )
length++;


It is supposed to count the number of digits in the int variable. I dont get how the while loop is working. Does the loop just go to zero and stop by default. Also why is the length starting at 1. Thank you for your time.










share|improve this question




















  • 1




    Zero means false. Think about that regarding how that loop ends. The final iteration (where x < 10 is true), will break the loop, but not account for that final digit, thus the starting point of 1 requirement.
    – WhozCraig
    4 hours ago








  • 6




    Step through your program with a debugger and watch the value of the x variable. BTW, /= means x = x / 10.
    – Thomas Matthews
    4 hours ago






  • 2




    As an aside: a simpler way to get the number of digits for a positive number is ceil(log10(x)).
    – duskwuff
    4 hours ago














9












9








9







I am having trouble understanding how exactly this code works.



int length = 1;
int x = 234567545;
while ( x /= 10 )
length++;


It is supposed to count the number of digits in the int variable. I dont get how the while loop is working. Does the loop just go to zero and stop by default. Also why is the length starting at 1. Thank you for your time.










share|improve this question















I am having trouble understanding how exactly this code works.



int length = 1;
int x = 234567545;
while ( x /= 10 )
length++;


It is supposed to count the number of digits in the int variable. I dont get how the while loop is working. Does the loop just go to zero and stop by default. Also why is the length starting at 1. Thank you for your time.







c++ while-loop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 4 hours ago









NathanOliver

88k15120184




88k15120184










asked 4 hours ago









VickTreeVickTree

663




663








  • 1




    Zero means false. Think about that regarding how that loop ends. The final iteration (where x < 10 is true), will break the loop, but not account for that final digit, thus the starting point of 1 requirement.
    – WhozCraig
    4 hours ago








  • 6




    Step through your program with a debugger and watch the value of the x variable. BTW, /= means x = x / 10.
    – Thomas Matthews
    4 hours ago






  • 2




    As an aside: a simpler way to get the number of digits for a positive number is ceil(log10(x)).
    – duskwuff
    4 hours ago














  • 1




    Zero means false. Think about that regarding how that loop ends. The final iteration (where x < 10 is true), will break the loop, but not account for that final digit, thus the starting point of 1 requirement.
    – WhozCraig
    4 hours ago








  • 6




    Step through your program with a debugger and watch the value of the x variable. BTW, /= means x = x / 10.
    – Thomas Matthews
    4 hours ago






  • 2




    As an aside: a simpler way to get the number of digits for a positive number is ceil(log10(x)).
    – duskwuff
    4 hours ago








1




1




Zero means false. Think about that regarding how that loop ends. The final iteration (where x < 10 is true), will break the loop, but not account for that final digit, thus the starting point of 1 requirement.
– WhozCraig
4 hours ago






Zero means false. Think about that regarding how that loop ends. The final iteration (where x < 10 is true), will break the loop, but not account for that final digit, thus the starting point of 1 requirement.
– WhozCraig
4 hours ago






6




6




Step through your program with a debugger and watch the value of the x variable. BTW, /= means x = x / 10.
– Thomas Matthews
4 hours ago




Step through your program with a debugger and watch the value of the x variable. BTW, /= means x = x / 10.
– Thomas Matthews
4 hours ago




2




2




As an aside: a simpler way to get the number of digits for a positive number is ceil(log10(x)).
– duskwuff
4 hours ago




As an aside: a simpler way to get the number of digits for a positive number is ceil(log10(x)).
– duskwuff
4 hours ago












5 Answers
5






active

oldest

votes


















19














There are three things that might be suspicious for you if you are a C++ beginner:



First thing might be operator /=, which combines an integral division (i.e. without remainder), with an assignment. So x /= 10 actually is the same as x = x / 10.



Second, each expression in C++ has - after having been evaluated - a value. For an assignment like (x = 0), the result is the value of x after the assignment, i.e. 0 in this case.



Third, a condition in C++ like if (x) ... has the same meaning as if(x != 0), i.e. it is false if x equals 0, and it is true if x is anything else but 0.



All together: while ( x /= 10 ) means assign x the value of an integral division by 10 and then compare the value to 0. If 0 is reached, the loop ends.



BTW: length starts with 1, because any number, even 0, comprises at least one digit.






share|improve this answer

















  • 4




    @downvoter: a comment would be very helpful, for me as well as for OP.
    – Stephan Lechner
    4 hours ago



















9














x /= 10 continuously divides x by 10, which will make it 0 eventually and cause the while loop to terminate due to 0 being interpreted as false (and any other value than 0 as true).



The reason it starts at length = 1 is because there is always at least 1 digit in the number: if x was from 0 to 9 inclusive, then x /= 10 would cause x to become 0 immediately, meaning nothing inside the loop would execute. Therefore, if length started at 0, it would never get to be incremented to 1 which would be wrong if x was a single digit large.



Manually calculating this example by hand:




  1. 234567545 / 10 = 23456754, which is true, so the while loop continues and length becomes 2.


  2. 23456754 / 10 = 2345675, true. length becomes 3.


  3. 2345675 / 10 = 234567, true. length becomes 4.


  4. 234567 / 10 = 23456, true. length becomes 5.


  5. 23456 / 10 = 2345, true. length becomes 6.


  6. 2345 / 10 = 234, true. length becomes 7.


  7. 234 / 10 = 23, true. length becomes 8.


  8. 23 / 10 = 2, true. length becomes 9.


  9. 2 / 10 = 0, false. The while loop stops with length equal 9.







share|improve this answer































    5














    The loop



    while (x /= 10) {
    length++;
    }


    will go until the result of x /= 10 evaluates to false, since 0 means false it will go until x /= 10 is 0. Integer division truncates, ensuring the condition will be reached.






    share|improve this answer





























      4














      Integer division will truncate the remainder, so continually dividing a number with integer division will inevitably result in zero.



      Dividing a number n by 10 while incrementing a counter i once for each time the resulting quotient (stored back into n) is not zero will result in the i containing the number of digits for the base-10 representation of n.






      share|improve this answer





























        3














        it helps to understand 2 parts:




        • what is "/="

        • when does the loop terminate


        Explain "/="



        this:



        x /= 10


        is the same as:



        x = x / 10


        Explain when the loop terminates



        the while loop terminates, when the condition is false. And 0 is equivalent to false.



        while (condition) {
        length++;
        }


        so x is, with every pass through the loop, divided by 10, until is is 0. That terminates the loop.



        so, the condition is 2 things at the same time:




        • it is a value, that is compared to 0. The loop continues until this
          evalues to 0.

        • it is an assignment: x gets a new value with every evaluation. It's divided by 10, so it converges to 0.






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54136717%2funderstanding-c-code-get-the-number-of-digits-in-an-int%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          19














          There are three things that might be suspicious for you if you are a C++ beginner:



          First thing might be operator /=, which combines an integral division (i.e. without remainder), with an assignment. So x /= 10 actually is the same as x = x / 10.



          Second, each expression in C++ has - after having been evaluated - a value. For an assignment like (x = 0), the result is the value of x after the assignment, i.e. 0 in this case.



          Third, a condition in C++ like if (x) ... has the same meaning as if(x != 0), i.e. it is false if x equals 0, and it is true if x is anything else but 0.



          All together: while ( x /= 10 ) means assign x the value of an integral division by 10 and then compare the value to 0. If 0 is reached, the loop ends.



          BTW: length starts with 1, because any number, even 0, comprises at least one digit.






          share|improve this answer

















          • 4




            @downvoter: a comment would be very helpful, for me as well as for OP.
            – Stephan Lechner
            4 hours ago
















          19














          There are three things that might be suspicious for you if you are a C++ beginner:



          First thing might be operator /=, which combines an integral division (i.e. without remainder), with an assignment. So x /= 10 actually is the same as x = x / 10.



          Second, each expression in C++ has - after having been evaluated - a value. For an assignment like (x = 0), the result is the value of x after the assignment, i.e. 0 in this case.



          Third, a condition in C++ like if (x) ... has the same meaning as if(x != 0), i.e. it is false if x equals 0, and it is true if x is anything else but 0.



          All together: while ( x /= 10 ) means assign x the value of an integral division by 10 and then compare the value to 0. If 0 is reached, the loop ends.



          BTW: length starts with 1, because any number, even 0, comprises at least one digit.






          share|improve this answer

















          • 4




            @downvoter: a comment would be very helpful, for me as well as for OP.
            – Stephan Lechner
            4 hours ago














          19












          19








          19






          There are three things that might be suspicious for you if you are a C++ beginner:



          First thing might be operator /=, which combines an integral division (i.e. without remainder), with an assignment. So x /= 10 actually is the same as x = x / 10.



          Second, each expression in C++ has - after having been evaluated - a value. For an assignment like (x = 0), the result is the value of x after the assignment, i.e. 0 in this case.



          Third, a condition in C++ like if (x) ... has the same meaning as if(x != 0), i.e. it is false if x equals 0, and it is true if x is anything else but 0.



          All together: while ( x /= 10 ) means assign x the value of an integral division by 10 and then compare the value to 0. If 0 is reached, the loop ends.



          BTW: length starts with 1, because any number, even 0, comprises at least one digit.






          share|improve this answer












          There are three things that might be suspicious for you if you are a C++ beginner:



          First thing might be operator /=, which combines an integral division (i.e. without remainder), with an assignment. So x /= 10 actually is the same as x = x / 10.



          Second, each expression in C++ has - after having been evaluated - a value. For an assignment like (x = 0), the result is the value of x after the assignment, i.e. 0 in this case.



          Third, a condition in C++ like if (x) ... has the same meaning as if(x != 0), i.e. it is false if x equals 0, and it is true if x is anything else but 0.



          All together: while ( x /= 10 ) means assign x the value of an integral division by 10 and then compare the value to 0. If 0 is reached, the loop ends.



          BTW: length starts with 1, because any number, even 0, comprises at least one digit.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 4 hours ago









          Stephan LechnerStephan Lechner

          26.7k21940




          26.7k21940








          • 4




            @downvoter: a comment would be very helpful, for me as well as for OP.
            – Stephan Lechner
            4 hours ago














          • 4




            @downvoter: a comment would be very helpful, for me as well as for OP.
            – Stephan Lechner
            4 hours ago








          4




          4




          @downvoter: a comment would be very helpful, for me as well as for OP.
          – Stephan Lechner
          4 hours ago




          @downvoter: a comment would be very helpful, for me as well as for OP.
          – Stephan Lechner
          4 hours ago













          9














          x /= 10 continuously divides x by 10, which will make it 0 eventually and cause the while loop to terminate due to 0 being interpreted as false (and any other value than 0 as true).



          The reason it starts at length = 1 is because there is always at least 1 digit in the number: if x was from 0 to 9 inclusive, then x /= 10 would cause x to become 0 immediately, meaning nothing inside the loop would execute. Therefore, if length started at 0, it would never get to be incremented to 1 which would be wrong if x was a single digit large.



          Manually calculating this example by hand:




          1. 234567545 / 10 = 23456754, which is true, so the while loop continues and length becomes 2.


          2. 23456754 / 10 = 2345675, true. length becomes 3.


          3. 2345675 / 10 = 234567, true. length becomes 4.


          4. 234567 / 10 = 23456, true. length becomes 5.


          5. 23456 / 10 = 2345, true. length becomes 6.


          6. 2345 / 10 = 234, true. length becomes 7.


          7. 234 / 10 = 23, true. length becomes 8.


          8. 23 / 10 = 2, true. length becomes 9.


          9. 2 / 10 = 0, false. The while loop stops with length equal 9.







          share|improve this answer




























            9














            x /= 10 continuously divides x by 10, which will make it 0 eventually and cause the while loop to terminate due to 0 being interpreted as false (and any other value than 0 as true).



            The reason it starts at length = 1 is because there is always at least 1 digit in the number: if x was from 0 to 9 inclusive, then x /= 10 would cause x to become 0 immediately, meaning nothing inside the loop would execute. Therefore, if length started at 0, it would never get to be incremented to 1 which would be wrong if x was a single digit large.



            Manually calculating this example by hand:




            1. 234567545 / 10 = 23456754, which is true, so the while loop continues and length becomes 2.


            2. 23456754 / 10 = 2345675, true. length becomes 3.


            3. 2345675 / 10 = 234567, true. length becomes 4.


            4. 234567 / 10 = 23456, true. length becomes 5.


            5. 23456 / 10 = 2345, true. length becomes 6.


            6. 2345 / 10 = 234, true. length becomes 7.


            7. 234 / 10 = 23, true. length becomes 8.


            8. 23 / 10 = 2, true. length becomes 9.


            9. 2 / 10 = 0, false. The while loop stops with length equal 9.







            share|improve this answer


























              9












              9








              9






              x /= 10 continuously divides x by 10, which will make it 0 eventually and cause the while loop to terminate due to 0 being interpreted as false (and any other value than 0 as true).



              The reason it starts at length = 1 is because there is always at least 1 digit in the number: if x was from 0 to 9 inclusive, then x /= 10 would cause x to become 0 immediately, meaning nothing inside the loop would execute. Therefore, if length started at 0, it would never get to be incremented to 1 which would be wrong if x was a single digit large.



              Manually calculating this example by hand:




              1. 234567545 / 10 = 23456754, which is true, so the while loop continues and length becomes 2.


              2. 23456754 / 10 = 2345675, true. length becomes 3.


              3. 2345675 / 10 = 234567, true. length becomes 4.


              4. 234567 / 10 = 23456, true. length becomes 5.


              5. 23456 / 10 = 2345, true. length becomes 6.


              6. 2345 / 10 = 234, true. length becomes 7.


              7. 234 / 10 = 23, true. length becomes 8.


              8. 23 / 10 = 2, true. length becomes 9.


              9. 2 / 10 = 0, false. The while loop stops with length equal 9.







              share|improve this answer














              x /= 10 continuously divides x by 10, which will make it 0 eventually and cause the while loop to terminate due to 0 being interpreted as false (and any other value than 0 as true).



              The reason it starts at length = 1 is because there is always at least 1 digit in the number: if x was from 0 to 9 inclusive, then x /= 10 would cause x to become 0 immediately, meaning nothing inside the loop would execute. Therefore, if length started at 0, it would never get to be incremented to 1 which would be wrong if x was a single digit large.



              Manually calculating this example by hand:




              1. 234567545 / 10 = 23456754, which is true, so the while loop continues and length becomes 2.


              2. 23456754 / 10 = 2345675, true. length becomes 3.


              3. 2345675 / 10 = 234567, true. length becomes 4.


              4. 234567 / 10 = 23456, true. length becomes 5.


              5. 23456 / 10 = 2345, true. length becomes 6.


              6. 2345 / 10 = 234, true. length becomes 7.


              7. 234 / 10 = 23, true. length becomes 8.


              8. 23 / 10 = 2, true. length becomes 9.


              9. 2 / 10 = 0, false. The while loop stops with length equal 9.








              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 3 hours ago









              Ghost

              1289




              1289










              answered 4 hours ago









              brothirbrothir

              964




              964























                  5














                  The loop



                  while (x /= 10) {
                  length++;
                  }


                  will go until the result of x /= 10 evaluates to false, since 0 means false it will go until x /= 10 is 0. Integer division truncates, ensuring the condition will be reached.






                  share|improve this answer


























                    5














                    The loop



                    while (x /= 10) {
                    length++;
                    }


                    will go until the result of x /= 10 evaluates to false, since 0 means false it will go until x /= 10 is 0. Integer division truncates, ensuring the condition will be reached.






                    share|improve this answer
























                      5












                      5








                      5






                      The loop



                      while (x /= 10) {
                      length++;
                      }


                      will go until the result of x /= 10 evaluates to false, since 0 means false it will go until x /= 10 is 0. Integer division truncates, ensuring the condition will be reached.






                      share|improve this answer












                      The loop



                      while (x /= 10) {
                      length++;
                      }


                      will go until the result of x /= 10 evaluates to false, since 0 means false it will go until x /= 10 is 0. Integer division truncates, ensuring the condition will be reached.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 4 hours ago









                      William MillerWilliam Miller

                      1,089116




                      1,089116























                          4














                          Integer division will truncate the remainder, so continually dividing a number with integer division will inevitably result in zero.



                          Dividing a number n by 10 while incrementing a counter i once for each time the resulting quotient (stored back into n) is not zero will result in the i containing the number of digits for the base-10 representation of n.






                          share|improve this answer


























                            4














                            Integer division will truncate the remainder, so continually dividing a number with integer division will inevitably result in zero.



                            Dividing a number n by 10 while incrementing a counter i once for each time the resulting quotient (stored back into n) is not zero will result in the i containing the number of digits for the base-10 representation of n.






                            share|improve this answer
























                              4












                              4








                              4






                              Integer division will truncate the remainder, so continually dividing a number with integer division will inevitably result in zero.



                              Dividing a number n by 10 while incrementing a counter i once for each time the resulting quotient (stored back into n) is not zero will result in the i containing the number of digits for the base-10 representation of n.






                              share|improve this answer












                              Integer division will truncate the remainder, so continually dividing a number with integer division will inevitably result in zero.



                              Dividing a number n by 10 while incrementing a counter i once for each time the resulting quotient (stored back into n) is not zero will result in the i containing the number of digits for the base-10 representation of n.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 4 hours ago









                              Govind ParmarGovind Parmar

                              7,17553055




                              7,17553055























                                  3














                                  it helps to understand 2 parts:




                                  • what is "/="

                                  • when does the loop terminate


                                  Explain "/="



                                  this:



                                  x /= 10


                                  is the same as:



                                  x = x / 10


                                  Explain when the loop terminates



                                  the while loop terminates, when the condition is false. And 0 is equivalent to false.



                                  while (condition) {
                                  length++;
                                  }


                                  so x is, with every pass through the loop, divided by 10, until is is 0. That terminates the loop.



                                  so, the condition is 2 things at the same time:




                                  • it is a value, that is compared to 0. The loop continues until this
                                    evalues to 0.

                                  • it is an assignment: x gets a new value with every evaluation. It's divided by 10, so it converges to 0.






                                  share|improve this answer




























                                    3














                                    it helps to understand 2 parts:




                                    • what is "/="

                                    • when does the loop terminate


                                    Explain "/="



                                    this:



                                    x /= 10


                                    is the same as:



                                    x = x / 10


                                    Explain when the loop terminates



                                    the while loop terminates, when the condition is false. And 0 is equivalent to false.



                                    while (condition) {
                                    length++;
                                    }


                                    so x is, with every pass through the loop, divided by 10, until is is 0. That terminates the loop.



                                    so, the condition is 2 things at the same time:




                                    • it is a value, that is compared to 0. The loop continues until this
                                      evalues to 0.

                                    • it is an assignment: x gets a new value with every evaluation. It's divided by 10, so it converges to 0.






                                    share|improve this answer


























                                      3












                                      3








                                      3






                                      it helps to understand 2 parts:




                                      • what is "/="

                                      • when does the loop terminate


                                      Explain "/="



                                      this:



                                      x /= 10


                                      is the same as:



                                      x = x / 10


                                      Explain when the loop terminates



                                      the while loop terminates, when the condition is false. And 0 is equivalent to false.



                                      while (condition) {
                                      length++;
                                      }


                                      so x is, with every pass through the loop, divided by 10, until is is 0. That terminates the loop.



                                      so, the condition is 2 things at the same time:




                                      • it is a value, that is compared to 0. The loop continues until this
                                        evalues to 0.

                                      • it is an assignment: x gets a new value with every evaluation. It's divided by 10, so it converges to 0.






                                      share|improve this answer














                                      it helps to understand 2 parts:




                                      • what is "/="

                                      • when does the loop terminate


                                      Explain "/="



                                      this:



                                      x /= 10


                                      is the same as:



                                      x = x / 10


                                      Explain when the loop terminates



                                      the while loop terminates, when the condition is false. And 0 is equivalent to false.



                                      while (condition) {
                                      length++;
                                      }


                                      so x is, with every pass through the loop, divided by 10, until is is 0. That terminates the loop.



                                      so, the condition is 2 things at the same time:




                                      • it is a value, that is compared to 0. The loop continues until this
                                        evalues to 0.

                                      • it is an assignment: x gets a new value with every evaluation. It's divided by 10, so it converges to 0.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited 4 hours ago

























                                      answered 4 hours ago









                                      Jörg BeyerJörg Beyer

                                      2,9611331




                                      2,9611331






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54136717%2funderstanding-c-code-get-the-number-of-digits-in-an-int%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Lallio

                                          Unable to find Lightning Node

                                          Futebolista