From 5ba54311d69af3203ad43fcadbb41ec4fdcc3f8d Mon Sep 17 00:00:00 2001 From: siva200 <66561566+siva200@users.noreply.github.com> Date: Sat, 13 Jun 2020 18:34:33 +0530 Subject: [PATCH] m2-e2-t5.cpp --- .../m2-t2-e5.cpp | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/m2-diving-into-c-programming/m2-code challenges - solution/m2-t2-e5.cpp b/m2-diving-into-c-programming/m2-code challenges - solution/m2-t2-e5.cpp index bc2a603..bf95368 100644 --- a/m2-diving-into-c-programming/m2-code challenges - solution/m2-t2-e5.cpp +++ b/m2-diving-into-c-programming/m2-code challenges - solution/m2-t2-e5.cpp @@ -3,15 +3,22 @@ int main() { - long num; // User might enter a very large integer number. - int ctr = 0; // The counter variable ‘ctr’ will count the digits. + long num; + long num=764; + + + int ctr=1; printf("Enter a number: "); scanf("%ld", &num); - while (num > 0) { + while (num > 0) + while (764> 0) + { + + num /= 10; + 764 /=10; ctr++; - num /= 10; // num = num / 10; } printf("Total number of digit(s) is %d", ctr); @@ -20,13 +27,13 @@ int main() { } /* Explanation: -Let us assume ‘num’ = 764. +Let us assume ‘num’ = 764. -The while loop will be executed until ‘num’ becomes 0. Let’s see what happens in while loop with each iteration. +The while loop will be executed until ‘num’ becomes 0. Let’s see what happens in while loop with each iteration. At the end of the 1st Iteration: ctr = 1 num = num / 10 = 764 / 10 = 76 -Dividing 764 by 10 is 76.4. Since ‘num’ is of the type ‘int’, it cannot hold a decimal value. Therefore, the value after the decimal is removed and only 76 is stored in the variable ‘num’. This is again the concept of implicit type conversion. +Dividing 764 by 10 is 76.4. Since ‘num’ is of the type ‘int’, it cannot hold a decimal value. Therefore, the value after the decimal is removed and only 76 is stored in the variable ‘num’. This is again the concept of implicit type conversion. At the end of the 2nd iteration: ctr = 2 Num = num / 10 = 76 / 10 = 7 @@ -34,7 +41,7 @@ At the end of the 3rd iteration: ctr = 3 num = num / 10 = 7 / 10 = 0 -Therefore, ctr = 3 which means the number of digits in the ‘num’ was originally 3. +Therefore, ctr = 3 which means the number of digits in the ‘num’ was originally 3. */