p16

Write a C program that will take any number of integers from the command line as argument and print the sum of all those integers.

  1. /* 
  2.  * C Program to Find Sum of Numbers given in Command Line Arguments 
  3.  * Recursively
  4.  */
  5. #include <stdio.h>
  6.  
  7. int count, s = 0;
  8. void sum(int *, int *);
  9.  
  10. void main(int argc, char *argv[])
  11. {
  12.     int i, ar[argc];
  13.     count = argc;
  14.     for (i = 1; i < argc; i++)
  15.     {
  16.         ar[i - 1] = atoi(argv[i]);
  17.     }
  18.     sum(ar, ar + 1);
  19.     printf("%d", s);
  20. }
  21.  
  22. /* computes sum of two numbers recursively */
  23. void sum(int  *a, int  * b)
  24. {
  25.     if (count == 1)
  26.         return;
  27.     s = s + *a + *b;
  28.     count -= 2;
  29.     sum(a + 2, b + 2);
  30. }
$ cc arg4.c
$ a.out 1 2 3 4
sum is 10

No comments:

Post a Comment