Decrementing a number in c as an argument

Note: I am a beginner to the world of C language.
I was trying to write a program that calculates the sum of N natural number.
Here it is:


int sum_of_N_with_recursion(int N);

int main()
    int n,result;
        printf("enter a natural number : ");
            printf("%d is not a natural numbern",n);
    result = sum_of_N_with_recursion(n);
    printf("sum of the first %d natural numbers is %dn",n,result);    

    return 0;

int sum_of_N_with_recursion(int N)
        return 0;
    return  N + sum_of_N_with_recursion(N--);

What is my problem?

When I tried to decrement N in the sum_of_N_number() like this sum_of_N_number(N--) but it doesn’t work. Why?

Example: sum_of_N_number(3) should equal to 6 but I got 3!!

Stack Overflow Asked on February 22, 2021

1 Answers

One Answer

On this line:

return  N + sum_of_N_with_recursion(N--);

You're both reading the value of N and writing the value of N in the same expression without a sequence point in between. Attempting to do so is undefined behavior.

You don't actually need to change the value of N here. You just want to pass in the value N-1, so do that instead:

return  N + sum_of_N_with_recursion(N-1);

Correct answer by dbush on February 22, 2021

Add your own answers!

Related Questions

Can i show all variable results in a div in jQuery?

0  Asked on December 5, 2021 by nippledisaster


Comparing two generics in compareTo()

2  Asked on December 5, 2021 by chalupabatmac


arranging the json file base on key value

1  Asked on December 5, 2021 by prateek-singh


Vue watch method not filtering object

3  Asked on December 5, 2021


Passing a variable between HTML pages using JavaScript

2  Asked on December 5, 2021 by robert-little


How to avoid code redundancy with JAVA generics

1  Asked on December 5, 2021 by cosimoth


Why is my project no longer updating when I write new code?

1  Asked on December 5, 2021 by stephen-horton


node https ssl your connection is not private error

2  Asked on December 5, 2021 by andrea-dattero


Nested for loop using dict

9  Asked on December 5, 2021 by purwu


React Hooks – Input loses focus when 1 character is typed in

4  Asked on December 5, 2021 by dragos-strugar


How do I build a C Python Extension for Windows using Cygwin64?

2  Asked on December 5, 2021 by zenith2198


Wificonfiguration is deprecated Android 10

1  Asked on December 5, 2021 by ahmad-idrees


Wrong tootip in chartjs

1  Asked on December 5, 2021 by thiago-scher


Ask a Question

Get help from others!

© 2022 All rights reserved.