Search code examples
cbignum

How can I input very large numbers(more than 200 digits) in C?


I want to input very large numbers in C.And I also want to calculate the sum of its digits.Is there a way to input very large numbers?

Here is my Code.

#include<stdio.h>
main() {
    int sum=0,rem;
    int a;
    printf("Enter a number:-");
    scanf("%d",a);
}

Solution

  • You probably don't want to load all those 200 digits into memory. When all you want to calculate is the sum of the digits, then all you need during your program is some accumulator variable storing the sum of the digits so far. The type of this variable can be int, because 200 * 9 <= INT_MAX will always be true in conforming implementations of C.

    #include <stdio.h>
    
    int main(void) {
        int accumulator = 0;
        int read_result;
    
        printf("Enter a number:-");
    
        while (1) {
            read_result = fgetc(stdin);
    
            if ('0' <= read_result && read_result <= '9') {
                accumulator += read_result - '0';
            } else {
                break;
            }
        }
    
        printf("The sum of the digits is %d", accumulator);
    
        return 0;
    }