What is the error in this code ,it is giving me segmentation fault everytime?

Viewed 68

See this is what I have written, please review it and correct the code.

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int Sum(int x);
    int i,T;
    scanf("%d",&T);
    for(i=0;i<T;i++)
    {
        int a;
        scanf("%d",&a);
        printf("%d",Sum(a));
    }
    return 0;
}
int Sum(int x)
{
    int ans=0;
    ans = ans + x%10;
    x=x%10;
    Sum(x);
}

The code is to find sum of digits of a number.

2 Answers

Your Sum() doesn't return at all. Which cause stack overlflow, as this site's name said.

You probably want something like that:

#include <iostream>
using namespace std;

int Sum(int x)
{
    int ans=0;
    while(x > 0) {
        ans = ans + x%10;
        x=x/10;
    }
    return ans;
}
int main() {
    int i,T;
    scanf("%d",&T);
    for(i=0;i<T;i++)
    {
        int a;
        scanf("%d",&a);
        printf("%d",Sum(a));
    }
    return 0;
}
Related