-5
#include<stdio.h>

int sum_digit(int);

int main()
{
    int a;
    printf("Enter no. for which we want the sum of digits\n");
    scanf(" %d", &a);
    printf("Some of digit %d", sum_digit(a));
    return 0;
}

int sum_digit(int num)
{
    int sum = 0;
    while(num > 0);
    {
        sum = sum + num % 10;
        num = num / 10;
    }
}

When I run this code it asks for value but as I hit enter it gets stuck. Not able to understand why it is not producing any results.

Is this the problem of whites spaces with scanf?

3 Answers3

3

While loops (as well as for loops and if statements), in the typical use cases, don't have a semicolon at the end. That being said, you have an extra semicolon at the end of the line: while(num > 0);. Remove the semicolon for the expected behavior.

As pointed out in comments, the function int sum_digit(int) will result in an undefined behavior because it doesn't return anything. Add return sum; at the end of the function to fix that.

Here's the final code:

#include<stdio.h>

int sum_digit(int);

int main()
{
    int a;
    printf("Enter no. for which we want the sum of digits\n");
    scanf(" %d", &a);
    printf("Some of digit %d", sum_digit(a));
    return 0;
}

int sum_digit(int num)
{
    int sum = 0;
    while(num > 0)
    {
        sum = sum + num % 10;
        num = num / 10;
    }
    return sum;
}

Using a semicolon at the end can be useful sometimes.

PajLe
  • 791
  • 1
  • 7
  • 21
3

Your code has two issues:

  1. while(num > 0); - There is a semicolon ; after the loop condition, which results in that the loop´s body won´t be treated as loop body - the while loop will just constantly proof the condition and as num does not change, the loop goes infinitely.

  2. The function sum_digit() does not return anything.

    Thus, To use printf("Some of digit %d", sum_digit(a)); invokes undefined behavior.

    return sum; at the end of sum_digit().


Note: If you use GCC, the -Wall option had showed you warnings for both.

1

Your while loop is infinite. You need to remove the semi-colon. A while loop looks like this

while(condition) {
    statement(s);
}

Your while loop does nothing, but keeps running if num>0

RetardedHorse
  • 148
  • 1
  • 7