Factorial program using recursive function in c with while loop - c

Factorial program using recursion in C with while loop. Hi all thanks for your valuable replies.
You all said use (if condition Instead of while). Its correct I accept your suggestion. Then why don't I use while for finding the factorial using recursive function.
Somebody said while(n>1) is an infinite loop. But in this program n value is decremented in the fact(n-1) function itself. Now in this program I put a printf() and getch() after the while loop to know the value of n. The printf() and getch() function executes only when the while condition becomes false.
When I run this program the printf() function and getch() function executes repeatedly and the printf() function return n value = 1. So I determine that the value of n is decremented. Then why does this program execute the while loop again and again?
In all function the return statement is the last function termination statement. When the execution reaches the return statement the execution terminate from the function and go back to the next line of the called function.But in this program after the execution reaches the return statement it will repeat the same function to execute. Why is that?
Note: I am using Turbo C 3.0 to run this program,
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x=n*fact(n-1);
}
printf("N value after the while loop:%d",n);
getch();
return(x);
}
void main()
{
int n,fact1;
scanf("%d",&n);
fact1=fact(n);
printf("%d",fact1);
}

You do have an infinite loop. The line fact(n-1) doesn't decrease the value of n. It invoked another call of the function with a smaller n.
So, if you call fact(2), you have a call with n==2. In this function, you have an infinite loop that call fact(1). In this second call, n==1, so the loop condition is false, and this call prints your line and return - into the infinite loop of the first call (which its n is still 2).

First of all may I suggest you put a prompt like that before scanf? It is strange to be prompted for a number by the console when there is no text asking you to do so. Looks like the program has hung.
printf("Give the value of n:");
So in order to fix your program I would suggest you do something like the example below.
You have to understand how recursion works. You can't just be calculating a number inside the while(). You have to be returning something , else it's an infinite loop.
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x = n*fact(n-1);
return x;
}
return x;
}
void main()
{
int n,fact1;
printf("Please provide the value of \'n\':");
scanf("%d",&n);
fact1=fact(n);
printf("Result is %d",fact1);
return 0;
}

Here i would have a pretty easy code to understand for you. It is very short and effective. Of course i coded it using recursion:
The only header you need to include is stdio.h.
Main:
int main() {
unsigned long n;
scanf("%lu", &n);
printf("%lu\n", factorial(n));
}
Function calculation factorial:
unsigned long factorial(unsigned long n) {
if (n==1) {
return 1;
} else {
return n * factorial(n-1);
}
}
As you see it's a pretty short and effective program. I used unsigned longs, so that the program can output and can calculate with very long numbers without getting overflows or stuff like that. You don't need any kind of loop, just the recursive function.

Related

while calculating factorial in c why doesn't operation keep continuing further to negative values?

i was writing a recursion program for finding factorials , once x reaches zero why does the operation stop in the called function instead of continuing further to negative values like going -1,-2,-3 and so on as int takes negative values too and keep continuing the operation as it is my own user defined function.
#include<stdio.h>
int factorial( int x);
int main() {
int n;
scanf("%d",&n);
n=factorial(n);
printf("%d",n);
return 0;
}
int factorial(int x){
int f;
if(x==0||x==1){
return 1;
}
else{
f= x*factorial(x-1);
return f;}
}
When factorial is called with an argument value of 2, it evaluates x==0||x==1 in the if statement. This condition is false, so the “then” clause in the if is not executed, and program control flows to the else.
The else executes f = x*factorial(x-1), in which x is 2 and factorial(x-1) is factorial(1).
Thus we have a recursive call to factorial with an argument value of 1. It evaluates x==0||x==1 in the if statement. This condition is true, so the “then” clause is executed.
The “then” clause is return 1;, so the function returns 1, and program control returns to the caller.
In the caller, we are still evaluating x*factorial(x-1). factorial(x-1) has returned 1, so we have 2*1. So f is set to 2.
The next statement is return f;. So 2 is returned to the caller, and program control returns to the caller, which is main. The program continues executing main.
The program does not continue further to negative values because nothing called factorial with negative values.

recursion c, program does not display

im facing an problem in this program, may anyone tell me, what im doing wrong, the program won't display anything after i give it input.
(Code is about sum of digits enter #example 12345 = 15)
#include<stdio.h>
int sum(int num);
int sum(int num){
int total=0;
if(sum==0){
return total;
}
else{
total+=num%10;
num/=10;
return sum(num);
}
}
int main()
{
int num,k;
printf("Enter 5 positive number: ");
scanf("%d",&num);
printf("Sum is: %d",sum(num));
}
Here is a rule of thumb, whenever you have a non-stopping recursion program try to verify your base cases.
Here you are verifying sum the function instead of num the parameter. The C compiler let's you do that because functions in C are pointers, and pointers hold the addresses as numeric value.
You just need to change the condition from sum==0 to num==0. It will now print something. However, the logic of your program is still wrong. You can change your sum function to this.
int sum(int num){
if(num==0) {
return 0;
}
return num % 10 + sum(num/10);
}
And you can try learning more about recursion through stack since recursion is basically just stack.
In your code the total gets initialized to zero every time the function is called. and a variable named sum is not initialized. Just change sum==0 to num==0.I have also given the logic to sum the digits of a number.

Reverse by Recursion

My code for finding reverse by recursion says Segmentation Fault
Why?And how to find reverse by recursion?
What is wrong with my code?
#include<stdio.h>
int rev(int);
main()
{
int a,b;
scanf("%d",&a);
b=rev(a);
printf("%d",b);
}
int rev(int x)
{
int q,r;
static int p=0;
p=p*10+(x%10);
r=x/10;
q=rev(r);
return(p);
}
You are using q=rev(r); without any conditions, i.e. you jump deeper and deeper into the recursive calls, and this never ends.
In the end, you get a stack overflow.
A recursive function needs a way to know when the recursion ends. This is referred to as the base case. Without a base case, the recursion will keep happening until you run out of stack space, which typically causes your program to crash.
For your code, you want to get out when the argument is 0. So you need to to this:
int rev(int x)
{
int q,r;
static int p=0;
if (x == 0) return; // base case
p=p*10+(x%10);
r=x/10;
q=rev(r);
return(p);
}
Add any breaking condition in your code in you rev() function
if x == 0:
return 0

Can anyone explain the dry run, output behind this function below for j=2?

#include<stdio.h>
int p(int);
void main()
{
int j;
scanf("%d",&j);
p(j);
printf("Return value: %d",j);
}
int p(int j)
{
int i;
for( i=j; i>0; p(i-1) )
{
printf("%d",i);
}
return(j);
}
Please explain the dry run and output as well. I have trouble finding the logic behind this function.
The function p() will never return on positive input. In the loop, i is not modified, therefore the condition i > 0 always holds true for a positive input. With a negative or zero input, a single line will be printed: "Return value: x" where x is your input value.
Without knowing what output you are expecting, we really can't help you improve your code.
may be this will give an error because the function p() return int value so you need to store return value in any int variable.

unexpected error of "control may reach end of a non void function"

I write a program to sum the elements in an array. However, when I am compiling the program, it tells me that "control may reach end of a non void function". I don't know why.
//a program to sum the elements of an array
#include <stdio.h>
int sum(int array[],int n)
{
int sum =0, *ptr;
int *arrayend=array +n;
for(ptr=array; ptr<arrayend;++array)
{
sum +=*ptr;
return sum;
}
}
int main(void)
{
int sum(int array[],int n);
int value[10]={1,2,3,4,5,6,7,8,9,10};
printf("The sum is %i\n",sum(value,10));
return 0;
}
Your function sum() is poorly formed and let's say the for loop condition fails at first attempt and you never enter the loop then you have a situation where you are not returning anything and your function return type is int
So this case needs to be addressed so that even if you fail to enter the loop there should be return after the loop.
return within a loop makes no sense unless there is a condition based on which you return.
You try to return sum each time the loop body is executed, but functions only return once. So on the first iteration of the loop the function will return. That's the same as having no loop.
You need to put return sum after the loop, so that your loop makes sense. I.e. first add *ptr to sum n times, then return the resulting sum.
Also, in the loop you do ++array. That should probably be ++ptr.

Resources