In C Programming language please! Write a program that: Prompts you to enter a p
ID: 3800023 • Letter: I
Question
In C Programming language please!
Write a program that: Prompts you to enter a positive integer value or q to quit. Verify that the integer read is > 0. Use "tail recursion" where a function calls itself as explained on page 356 to calculate the sum of all integers from 1 to the value entered. Print out the value entered and the sum of the integers calculated using the tail recursion function calls. Repeat items 1 through 4 until scanf() fails to return an integer. Example output would be: Enter an integer greater than zero, (g to quit): 4 Sum (4) = 10 Enter an integer greater than zero, (q to quit): 6 Sum (6) = 21 Enter an integer greater than zero, (q to quit): qExplanation / Answer
#include <stdio.h>
int sum(int n){
if(n == 0){
return 0;
}
else{
return n + sum(n-1);
}
}
int main()
{
int n;
while(1){
printf("Enter an integer greater than zero, (q to quit): ");
if (scanf("%d", &n) != 1) {
break;
}
printf("Sum(%d) = %d ", n, sum(n));
}
return 0;
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
Enter an integer greater than zero, (q to quit): 4
Sum(4) = 10
Enter an integer greater than zero, (q to quit): 6
Sum(6) = 21
Enter an integer greater than zero, (q to quit): q