C++

C++ Program to Find Sum of N Numbers using Recursion Function1 min read

Calculates the sum of all the numbers that precede an integer in C++ language

Presentation

This tutorial aims to calculate the sum of the numbers that precede another, for example if we want to calculate the sum of the numbers that precede the number 5 it will be 0 + 1 + 2 + 3 + 4 + 5 which will give 15, in a program in C language under Code Blocks software.

Summary

– Functions




– Test of the program

– Conclusion

Functions

A recursive function called itself will need a single variable n which is the number we want to calculate all that precedes it, so we will need two tests:

1- If the number is 0 or 1 we return the number itself for example 0 there is nothing that precedes it so its will be 0 + 0 = 0 and the 1 will be 0 + 1 = 1.

2- Otherwise we return the number plus the function sum with the number – 1 in parameter.

For the main function we declare the integer n another time we will enter and then display by calling the function “sum” that we created above.

Conclusion

Simple tutorial that can help in mathematical exercises for example without the need to use a calculator to do a number of calculations to find the result.

Leave a Comment