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.
1 2 3 4 5 6 7 8 9 |
int sum(int n) { if(n==0||n==1) return n; else return n+sum(n-1); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <stdio.h> #include <stdlib.h> int sum(int n) { if(n==0||n==1) return n; else return n+sum(n-1); } int main() { int n; printf("Enter a number:"); scanf("%d",&n); printf("Sum of numbers up to %d:%d",n,sum(n)); return 0; } |
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.