C++ or C program to find sum of n numbers using Recursion/Recursive function

File name:- sumnrec.cpp
#include <iostream.h>
#include<conio.h>
int main(){
int sum(int n);
int num, result;
clrscr();
cout<<"Enter a positive integer"<<endl;
cin>>num;
result = sum(num);
cout<<"sum= "<<result<<endl;
getch();
}
int sum (int n){
if(n!=0) return n + sum(n-1);
else return n;
}


File name:- sumnrec.c
#include <stdio.h>
#include<conio.h>
int main(){
int sum(int n);
int num, result;
clrscr();
printf("Enter a positive integer\n");
scanf("%d", &num);
result = sum(num);
printf("sum=%d", result);
getch();
}
int sum (int n){
if(n!=0) return n + sum(n-1);
else return n;
}

No comments:

Post a Comment

Priority Queue

Priority queue:-  It is a special type of queue which stores group of elements. Each element has a priority number associated with it. Prior...