C program to print sum of the digits of the number

Solution with out using functions(Using For Loop)

Solution with out using functions(Using While Loop)

Solution using functions without passing arguments

Solution using functions and by passing arguments



C program to print sum of the digits of the number(Using For Loop)

Solution : Without using function
Program/Source Code

#include <stdio.h>

int main()
{
    int n,s=0,d;
    printf("Enter any no ");
    scanf("%d",&n);
    for(;n>0;)
    {
        d=n%10;
        s=s+d;
        n=n/10;
    }
    printf("Sum of digits = %d",s);
    return 0;
}

Output:

Enter any no 236
Sum of digits = 11



C program to print sum of the digits of the number(Using While Loop)

Solution : Without using function
Program/Source Code

#include <stdio.h>

int main()
{
    int n,s=0,d;
    printf("Enter any no ");
    scanf("%d",&n);
    while(n>0)
    {
        d=n%10;
        s=s+d;
        n=n/10;
    }
    printf("Sum of digits = %d",s);
    return 0;
}

Output:

Enter any no 1234
Sum of digits = 10



C program to print sum of the digits of the number

Solution : Using function Without Passing Arguments
Program/Source Code

#include <stdio.h>
void check()
{
    int n,s=0,d;
    printf("Enter any no ");
    scanf("%d",&n);
    while(n>0)
    {
        d=n%10;
        s=s+d;
        n=n/10;
    }
    printf("Sum of digits = %d",s);
}

int main()
{
    check();
    return 0;
}

Output:

Enter any no 1452
Sum of digits = 12



C program to print sum of the digits of the number

Solution : Using function Passing Arguments
Program/Source Code

#include <stdio.h>
void check(int n)
{
    int s=0,d;
    while(n>0)
    {
        d=n%10;
        s=s+d;
        n=n/10;
    }
    printf("Sum of digits = %d",s);
}

int main()
{
    int n;
    printf("Enter any no ");
    scanf("%d",&n);
    check(n);
    return 0;
}

Output:

Enter any no 854
Sum of digits = 17

Previous:

Next:

C Language Programming Tutorial

C Language Tutorial Home    Introduction to C Language     Tokens     If Condition     goto statement and Labelname     Switch Statements     For loop     While Loop    Do while loop     break and continue    Functions    Recursion    Inbuild Functions    Storage Classes    Preprocessor    Arrays    Pointers     Structures and Unions    File Handling     Projects

Tutorials

Technical Questions

Interview Questions

C Programming
C++ Programming
Class 11 (Python)
Class 12 (Python)
C Language
C++ Programming
Python

C Interview Questions
C++ Interview Questions
C Programs
C++ Programs