Given a number, the task is to find the Sum of Digits of this number using Command Line Arguments.
Examples:
Input: num = 687
Output: 21
Input: num = 12
Output: 3
Approach:
- Since the number is entered as Command line Argument, there is no need for a dedicated input line
- Extract the input number from the command line argument
- This extracted number will be in string type.
- Convert this number into integer type and store it in a variable, say num
- Declare a variable to store the sum and set it to 0
- Repeat the next two steps till the number is not 0
- Get the rightmost digit of the number with help of remainder ‘%’ operator by dividing it with 10 and add it to sum.
- Divide the number by 10 with help of ‘/’ operator
- Print or return the sum
Program:
C
#include <stdio.h>
#include <stdlib.h> /* atoi */
int findSumOfDigits( int num)
{
int sum = 0;
while (num > 0) {
sum = sum + (num % 10);
num = num / 10;
}
return sum;
}
int main( int argc, char * argv[])
{
int num;
if (argc == 1)
printf ( "No command line arguments found.\n" );
else {
num = atoi (argv[1]);
printf ( "%d\n" , findSumOfDigits(num));
}
return 0;
}
|
Java
class GFG {
public static int findSumOfDigits( int num)
{
int sum = 0 ;
while (num > 0 ) {
sum = sum + (num % 10 );
num = num / 10 ;
}
return sum;
}
public static void main(String[] args)
{
if (args.length > 0 ) {
int n = Integer.parseInt(args[ 0 ]);
System.out.println(findSumOfDigits(n));
}
else
System.out.println( "No command line "
+ "arguments found." );
}
}
|
Python
def findSumOfDigits(num):
sum = 0
while (num > 0 ):
sum = sum + (num % 10 )
num = num / / 10
return sum
num = ( input ())
n = int (num)
if len (num)> 0 :
print (findSumOfDigits(n))
else :
print ( "No command line" )
|
C++
#include <iostream>
#include <cstdlib> // for atoi function
using namespace std;
int findSumOfDigits( int num)
{
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
int main( int argc, char * argv[])
{
int num;
if (argc == 1) {
cout << "No command line arguments found." << endl;
return 0;
}
num = atoi (argv[1]);
cout << findSumOfDigits(num) << endl;
return 0;
}
|
Output:
- In C:

- In Java:

- In Python
Time complexity: O(logn)
Auxiliary Space: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Mar, 2023
Like Article
Save Article