CrazyEngineers
  • Explain this C Code: Calculate Sun of 5 digits

    gsk_ssit

    Member

    Updated: Oct 26, 2024
    Views: 965
    /* To calculate sum of five digits*/
    int num,a,n;
    int sum=0;
    system("cls");
    printf("Enter a five digit number\n");
    scanf("%d",&num);
    a=num%10;
    n=num/10;
    sum=sum+a;
    a=n%10;
    n=n/10;
    sum=sum+a;
    a=n%10;
    n=n/10;
    sum=sum+a;
    a=n%10;
    n=n/10;
    sum=sum+a;
    a=n%10;
    sum=sum+a;
    printf("The sum of the five digits of %d is %d\n",num,sum);
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Kaustubh Katdare

    AdministratorJan 28, 2013

    Which part of the above do you find difficult to understand? I think it is the part where it says -

    a= num%10;
    n= num/10;

    Am I right?

    First part of understanding the code would be to understand what the % operator does.
    Are you sure? This action cannot be undone.
    Cancel
  • Anoop Kumar

    MemberJan 28, 2013

    Check this out simpler program:

    int num,sum=0;
    printf("Enter a number\n");
    scanf("%d",&num);
     
    while(num >0){
             
                sum=sum+num%10;
                num=num/10;
             
            }
     
    printf("The sum of the digits of %d is    %d\n",num,sum);
    It will return you sum of any digit number.
    % operator is also called as modulo, That means it will return the reminder of operation.
    ps: I wrote this program in java. I hope it good in syntax wise for C.
    Are you sure? This action cannot be undone.
    Cancel
  • Jeffrey Arulraj

    MemberJan 30, 2013

    It does not find sum of 5 numbers But it finds the sum of the digits of a five digit number
    Are you sure? This action cannot be undone.
    Cancel
  • ashwin sarangula

    MemberJan 30, 2013

    it would be good if we use for loop in this program
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register