Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday 24 March 2019

The Interview Question Today#4(27-2-19)

Question:

Compute the sum of digits in all number from 1 to n.

Example:

Input: n = 10

Output:
Enter the Upper Limit 10
Sum of digits in numbers from 1 to 10 is 46


Solution:

Approach:

The solution is to go through every number x from 1 to n, and compute sum in x by traversing all digits of x. 

C program:


#include<stdio.h>
int sumOfDigits(int );

int sumOfDigitsFrom1ToN(int n)
{
    int result = 0; // initialize result
int x;
    for ( x = 1; x <= n; x++)
        result += sumOfDigits(x);

    return result;
}

int sumOfDigits(int x)
{
    int sum = 0;
    while (x != 0)
    {
        sum += x %10;
        x   = x /10;
    }
    return sum;
}

int main()
{
    int n;
    printf("Enter the Upper Limit");
    scanf("%d",&n);
    printf("Sum of digits in numbers from 1 to %d is %d",n,sumOfDigitsFrom1ToN(n));
    return 0;

}

Output:

Enter the Upper Limit 10

Sum of digits in numbers from 1 to 10 is 46

0 comments:

Post a Comment