Using C Programming Write a program that implements a recursive function which c
ID: 3606757 • Letter: U
Question
Using C Programming
Write a program that implements a recursive function which can take a positive integer, N, and computes the sum of all the non-negative integers smaller or equal to N. For example, if you call the function with N=5, it will output 1+2+3+4+5=15. Note that the main part of your program will just have a function call. No other components need to be there in the main part.
Q.2 Write a program that will take a number from the user, use a recursive function to find out the sum of the digits of that numbers and display the sum on the screen.
Q.3 Write a program which implements a recursive function to check if a number is a prime or not. Again the main part of the program will just take the input from the user and call the recursive function with user input passed as a parameter.
Explanation / Answer
Question 2
Answer:
#include <stdio.h>
int sum(int n) {
if(n == 0){
return 0;
} else {
return n + sum(n-1);
}
}
int main()
{
int n;
printf("Enter the number: ");
scanf("%d",&n);
printf("Sum = %d ",sum(n));
return 0;
}
Output:
Question 3
Answer:
#include <stdio.h>
int isPrime(int num, int i)
{
if (i == 1)
{
return 1;
}
else
{
if (num % i == 0)
{
return 0;
}
else
{
return isPrime(num, i - 1);
}
}
}
int main()
{
int n;
printf("Enter the number: ");
scanf("%d",&n);
if(isPrime(n, n/2)) {
printf("%d is a prime ", n);
} else {
printf("%d is not a prime ", n);
}
return 0;
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.