String : Store Larger Numbers & Count Number Of Digits
String: Store Large Number
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 :
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char num[1000];
- scanf("%s", num);
- printf("The number is %s\n", num);
- return 0;
- }
| 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 :-
- #include <stdio.h>
- int main()
- {
- long long n;
- n = 12345; //you can use scanf()
- long long r, q = n, count = 0;
- while(q > 0){
- r = q % 10;
- q = q / 10;
- count++;
- }
- printf("%lld has %lld digits", n, count);
- reutrn 0;
- }
Output: 12345 has 5 digits
Using sorting, we can solve it easily in this way:-
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char num[] = "12345";
- long long len = strlen(num); // To use strlen() function, we have to use <string.h>
- printf("%s has %lld digits", num, len);
- return 0;
- }
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!



No comments