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
Related
I tried to write a code to calculate how many 1 are there in a number's binary form. This is my code:
#include <stdio.h>
#include <math.h>
static int num = 0;
void binary(int target){
int n = 0;
int a = 1;
if(target != 0){
while(target >= a ){
n++;
a = pow(2, n);
}
a = pow(2, n-1);
num++;
binary(target - a);
}
}
int main() {
int target = 0;
scanf("%d", &target);
binary(target);
printf("%d",num);
return 0;
}
However, this shows segmentation fault when I run it. I don't know where has the code tried to access memories that are not allowed. I figured it might have something to do with the recursion in the binary function. Can anyone tell me what have caused the segmentation fault here? Thank you so much. I really can't understand segfaults :(
As mentioned in the comments, pow is not a good candiate here due to its signature:
double pow(double x, double y);
so any place that you are using pow, you are implicitly using floating point numbers. I was able to cause a segfault with the input 1<<31 which is the value -2147483648. This will cause your loop to terminate with n=0, a=1. You then set a = pow(2, -1), but since a is an integer, this gets floored down to just 0. You then recurse with binary(target - 0) which might as well just be binary(target) again, hence you have an infinite call with no termination.
I'll also leave as a note that recursion for this type of problem is probably not the right tool, unless your goal is to learn about recursion. There is a much more concise and reliable method via a loop and the & operator. I would also suggest using unsigned values to avoid issues like this with negative terms.
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.
This is a problem where you have to enter a number having non zero digits and the program will convert it into a IP address having 4 parts and each part less than 255, and have to print all the IP addresses.
I have tried this recursive method and am running into an infinite loop.
#include<stdio.h>
#include<math.h>
int a[3];
void comuni(unsigned long n,int count){
int i=count;
do{
if(count<0){
return;
}
int t=pow(10,i);
a[count]=n/t;
int rem=n%t;
if(a[count]<=255 &&a[count]>0 && count>=0){
printf("%d.",a[count]);
comuni(rem,count-1);
}
i++;
}while(1);
}
int main()
{
// Insert your code here.
unsigned long n;
scanf("%ul",&n);
comuni(n,3);
return 0;
}
Your question is why there is an infinite loop.
Starting with a look at while(1) it does not surprise me.
But wait, there is a return inside, which is used if count is less than 0.
Nothing inside the loop changes count. So if count is greater or equal 0 to begin with you got your infinite loop.
I think the problem which causes that situation is that this
int i=count;
does NOT cause count to change when you change i.
You do change i inside the loop, but you know - it does not help.
In the following code I am trying to solve the towers of Hanoi problem. Why am I getting a segmentation fault (core dump)?
Segmentation fault should occur when I try to access unreachable memory but in this program I am not trying to access any unreachable memory.
#include <stdio.h>
#include <stdlib.h>
void steps(int n, int t, int p)
{
int i, k = 6 - (p + t);
if (n == 1) {
printf("%d-->%d\n", n, t);
}
for (i = 0; i < 2; ++i) {
if (i == 0) {
steps(n - 1, k, p);
printf("%d-->%d\n", n, t);
} else {
steps(n - 1, t, k);
}
}
}
int main()
{
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
steps(n, 3, 1);
return 0;
}
You are accessing memory you can't access. It just isn't obvious in the code (like a dangling pointer). Recursion is tricky; you can easily overflow the stack. The stack stores information when you enter a function (registers or addresses of parameters, saved values of registers used in the calling function and the called function, and a return pointer (where to jump to when you finish the function) basically.
The stack has a certain size. It might be quite large, but it is finite. In recursion, you keep calling the same function from within itself. If this happens too many times, you will "overflow the stack" -- that is, try to "push" more info onto the stack when it is already full, which means at an address past the end of the stack -- memory you may not have access to. (If you do have access to it, you maybe overwriting one of your variables or some such.)
When you have recursed far enough, you must return from your function without calling it again. Probably in your n==1 "if".
In the base case of your recursion, you do not have any return statement so your code goes on for infinite time(time limit exceeded), you should try like this:
if(n==1)
{
printf("%d-->%d\n", n, t);
return ;
}
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.