Home > Mobile >  How can I fix this code and print the output
How can I fix this code and print the output

Time:11-27

I just started C programming , My code doesn't work properly . can you help me? This is my code :

#include <stdio.h>
int main(){
   int n,sum=0,a;
   scanf("%d", &n);
     while (n!=0)
   { a=n%10;
    sum=sum a;
      n=n/10;
   }
   printf("%d",&sum);
   return 0;
}

CodePudding user response:

You should remove "&" from your printf statement. In C, using & before a variable name means you are referencing that variable's address location. When printing, placing %d indicates the variable you will pass into the print statement will be a number in decimal format, and the return type of &sum does not match this.

If you replace &sum with sum, you will be properly referencing the value of sum instead of its address, which matches the expected type for %d. Replacing your printf statement will give you this code:

#include <stdio.h>
int main(){
    int n,sum=0,a;
    scanf("%d", &n);
    while (n!=0)
    { 
        a=n%10;
        sum=sum a;
        n=n/10;
    }
    printf("Sum of digits: %d", sum);
    return 0;
}

CodePudding user response:

You are not supposed to use & before sum in your printf.

  •  Tags:  
  • c
  • Related