Late submissions not accepted. Submit your solution in a single, plain text sour
ID: 3852687 • Letter: L
Question
Late submissions not accepted. Submit your solution in a single, plain text source file named sod.c Write a program for the following man page: NAME sod- finds the sum of digits of a specified number and displays it to the screen. SYNOPSIS sod DIGIT DESCRIPTION Accepts an integer as it's only argument. The program then finds the sum of all digits from 1 through DIGIT and displays it on the screen. So, if DIGIT was 5, then the program calculates 1 + 2 + 3 + 4 + 5 = 15. 15 is then displayed on the screen. EXAMPLES sod displays synopsis message sod 5 displays 15 NOTES Displays the synopsis message if an incorrect number of command line arguments are supplied. Does not use any C++ specific code. Does not prompt the user in any way. Does not perform input validation. Does not use scanf, uses command-line arguments to get input. To compile the code: gcc sod.c -o sod Use c-string C functions from the C library. Requires you to look up the functions in the library. Use the links above. If there isn't an explicit requirement, you don't have to do it. 10-POINT SAMPLE RUN (using Cloud9) hstalica: ~/workspace exist gcc sod.c -osod hstalica: ~/workspace exist /sod 6 21 hstalica: ~/workspace exist /sod usage: sod DIGIT hstalica: ~/workspace existExplanation / Answer
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
/* variable declaration */
int num;
int sum, i;
/* validating if DIGIT is passed as part of command line argument */
if(argc != 2){
printf(" usage: sod DIGIT ");
exit(1);
}
/* converting number in character array to integer */
num = atoi(argv[1]);
/* summing the digits upto the number */
for(i = 1; i <= num; i++){
sum += i;
}
printf(" %d ", sum);
}
Execution and output:
Unix Terminal> cc sod.c -o sod
Unix Terminal> ./sod 15
120
Unix Terminal> ./sod 20
210
Unix Terminal> ./sod 6
21
Unix Terminal> ./sod
usage: sod DIGIT
Unix Terminal>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.