C Program to Find Sum of Numbers in Command Line Arguments Recursively

This is a C Program to find sum of numbers given in command line arguments recursively.

Problem Description

This C Program find sum of numbers given in command line arguments recursively.

Problem Solution

This C Program Prints the sum of numbers given in command line arguments.

Program/Source Code

Here is source code of the C Program to find sum of numbers given in command line arguments recursively. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C Program to Find Sum of Numbers given in Command Line Arguments 
 * Recursively
 */
#include <stdio.h>
 
int count, s = 0;
void sum(int *, int *);
 
void main(int argc, char *argv[])
{
    int i, ar[argc];
    count = argc;
    for (i = 1; i < argc; i++)
    {
        ar[i - 1] = atoi(argv[i]);
    }
    sum(ar, ar + 1);
    printf("%d", s);
}
 
/* computes sum of two numbers recursively */
void sum(int  *a, int  * b)
{
    if (count == 1)
        return;
    s = s + *a + *b;
    count -= 2;
    sum(a + 2, b + 2);
}
Program Explanation

In this C Program, the sum() function is used to compute the sum of two numbers recursively. If condition statement is used to check the value of ‘count’ variable is equal to 1.

advertisement
advertisement

If the condition is true, then we can’t compute the summation of two numbers hence return the value. Otherwise, if the condition is false, then compute the summation of the value of ‘s’ variable with the pointer variables ‘a’ and ‘b’, and decrement the value of ‘count’ variable by 2.

Runtime Test Cases
 
$ cc arg4.c
$ a.out 1 2 3 4
sum is 10

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.