If u wanna code her, You must feel her!

String : Store Larger Numbers & Count Number Of Digits


String: Store Large Number


Did you know that one of the most important limitations in C Programming or C++ Programming Language is we cannot use numbers larger than 10^19?

Whatever, you knew it or not, now you do. So what can we do to overcome this limitation so that we can store a number greater than that range?

Suppose, we need to scan a 100 digit number and print it. So, how do we do it? Here comes the concept of STRING!

Let's see a simple code :

  1.     #include <stdio.h>
  2.     #include <string.h>
  3.  
  4.     int main()
  5.     {
  6.         char num[1000];
  7.         scanf("%s", num);
  8.         printf("The number is %s\n", num);
  9.         return 0;
  10.     }

 Input:
11111111111111111111111111111111111111111111111111111111111111

Output:
11111111111111111111111111111111111111111111111111111111111111

So, here we go! Scanning the number as a string, we can store bigger numbers in this way! But What is the largest number we can store in a string?

  • A String can store around 10^7 characters (varies from version to version of the language). So you can store a 10^7 digit number in a string! Can you imagine the number which has 10^7 digit number in a string? Like the biggest number you can store is 999......999(10^7 nines!). So string is very much helpful for storing very large numbers while usinf long long/ unsigned long long , we can use upto 18 digit numbers.

How many digits are there in a number?

  • We can write a code for this in 2 ways:-
    • Using Modular Arithmetic (if the number is less than 10^19)
    • Using String
Well, if you wanna count how many digits are there in a number using modular arithmetic, you have to do it like this :-

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.     long long n;
  6.     n = 12345; //you can use scanf()
  7.     long long r, q = n, count = 0;
  8.     while(> 0){
  9.         r = q % 10;
  10.         q = q / 10;
  11.         count++;
  12.     }
  13.     printf("%lld has %lld digits", n, count);
  14.     reutrn 0;
  15. }
  16.  

Output: 12345 has 5 digits

 Using sorting, we can solve it easily in this way:-

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main()
  5. {
  6. char num[] = "12345";
  7. long long len = strlen(num); // To use strlen() function, we have to use <string.h>
  8. printf("%s has %lld digits", num, len);
  9. return 0;
  10. }
        
Output: 12345 has 5 digits

So, feel free to use string!

Now let me ask you a question - How will you find out the number of digits of a very large number if there are leading zeros at the beginning?

I am leaving this on you. If you write a code and if your code produces correct input then Welcome! But if you get stuck, leave a comment explaining where you got stuck. I'll help. Thank You!

Happy Coding!

No comments

Theme images by enot-poloskun. Powered by Blogger.