Sum of Digits of a number using command line

Write a program to find the sum of digits of a number using command line argument

//definition of main in command-line arguments

int main(int argc, char *argv[])

{

  //some coding

  1. argc – It is known as argument count, it stores the count of the number of arguments.
  2. argv[] – Pointer, contains location of all the values(arguments).
  3. *argv[] – Array of values of all the arguments

Approach

C

#include <stdio.h>
#include <stdlib.h>
int main(int argcchar *argv[])
{
    if (argc != 2)
    {
        printf("Enter a number ");
        return -1;
    }
    else
    {
        int num = atoi(argv[1]);
        int sum = 0;
        while (num > 0)
        {
            int temp = num % 10;
            sum += temp;
            num = num / 10;
        }
        printf("Sum of digits of number is %d"sum);
    }
    return 0;
}
To Run a Program
  1. Go to the location/directory where your program is present.
  2. g++ proramName.c -o out
  3. ./out  45321

Example:

Input: num = 45321
Output: Sum of digits of number is 15


No comments:

Post a Comment