Home / Programs / Find the sum of the digits of a number by command line Arguments
Programming Example

Find the sum of the digits of a number by command line Arguments

👁 496 Views
💻 Practical Program
📘 Step by Step Learning
Find the sum of the digits of a number by command line Arguments

Program Code

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
    long num, temp, digit, sum = 0;
    if(argc == 1 ||  argc > 2)
    {
         printf("Enter the number\n");
         exit(1);
    }
    num = atoi (argv[1]) ;
    temp = num;
    while (num > 0)
    {
        digit = num % 10;
        sum  = sum + digit;
        num /= 10;
    }
    printf("Sum of the digits of %ld = %ld\n", temp, sum);
}

Output

123

Sum of the digits of 123 = 6


Explanation

Nope

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.