Debugging a recursive function - c

#include<stdio.h>
void binary(int n)
{
int bin=0;
if(n!=0)
{
bin=n%2;
binary(n/2);
}
printf("%d",bin);
}
void main()
{
int a;
printf("Decimal value: ");
scanf("%d",&a);
binary(a);
}
When I tried to run above code, it outputs the binary value of the decimal number a preceding with one 0. As I have used recursive function here, it also puts the initial value of bin (i.e. 0) on stack and prints that 0 as well. But I want to display only binary values not that preceding 0.
I would be glad if anyone suggest me how to make this function not to store that initial value of bin on stack.

Try this.
#include<stdio.h>
void binary(int n)
{
bin=n%2;
if(n/2!=0)
binary(n/2);
printf("%d",bin);
}
void main()
{
int a;
printf("Decimal value: ");
scanf("%d",&a);
binary(a);
}
Since it checks whether n/2 == 0 before calling binary() it never prints the intial 0.

Related

C programming , recursion

#include <stdio.h>
void main(){
static int n=7;
if(n){
n--;
main();
printf("%d",n);
}
}
Sol: I was trying to trace the recursion. In my logic answer should be 1234567, but the answer is 000000. My question is how to trace this recursion?
That is because you are calling main before printing.
if you do:
#include <stdio.h>
void main(){
static int n=7;
if(n){
n--;
// main();
printf("%d",n);
main();
}
return;
}
You will get the output: 6543210
But in your case, it will print only when the value of n is 0. And since 7 print is pending therefore 0000000
There exists only one variable since it's static. A slight modification (including the fix of void return type) demonstrates it:
#include <stdio.h>
int main(void)
{
static int n=7;
if(n) {
n--;
printf("%d",n);
main();
printf("%d",n);
}
}
Output:
65432100000000
The best way to trace it probably is using gdb to follow it along.
If you declare n as static, it's value would be preserved across function calls. Note that you are calling printf after the recursive step (calling main). This causes printf to see the value of n after all the calls to main.
Think of this sequence, executing with n = 2
if (n) // first time, n == 2.
n--; // n == 1
main();
if (n) // second time, n == 1
n--;
main();
if (n) // third time, n == 0, fails
printf("%d",n); // n == 0.
printf("%d",n); // n == 0.

Function won't print anything back [duplicate]

This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 2 years ago.
#include<stdio.h>
#include<math.h>
float ar(int a);
int main()
{
int a;
scanf("%d",&a);
printf("%.2f",ar(a));
return 0;
}
float ar(int a)
{
int i,br=0,uk=0;
float ar;
for(i=0;i<=a;i++)
{
if(a%i==0)
{
br++;
uk=uk+i;
}
}
ar=uk/br;
return ar;
}
I'm trying to return the arithmetic value of all of the divisors of the number I enter.
Why isn't anything getting printed back?
#include<stdio.h>
#include<math.h>
int razlika(int a);
int main(){
printf("%d",razlika(26931));
return 0;
}
int razlika(int a)
{
int i,min=10000000,max=0,br=0,p,z;
do{
a=a/10;
br++;
}
while (a!=0);
for(i=0;i<br;i++)
{
p=a%10;
a=a/10;
if(p<min) min=p;
if(p>max) max=p;
}
z=max-min;
return z;
}
In this one im supposed to find the difference between the largest and the smallest digit of the number but it always prints out 0. I think it is because of the do while loop where i think i turn my number into 0? But I dont know how to count the number of the digits without making that mistake.
In your first program, your loop starts from 0, and you cant divide by zero.
As to your second program, you are correct, you changed the number to zero so you cant use it in the second loop, simply create a temporary variable and set it = a, use it in the do- while loop instead of a itself.
also in the do-while loop, let the condition be while (a>0). Help this helps!

The control does not flow beyond 45th line

The question is as follows.
Q) Develop a function f1 to accept an integer argument, reverse the digits and return the reversed value. Also, develop another function f2 to accept two integer arguments x and n and to return the value of x raised to the power n. The return value of f2 should be passed on to f1 and the return value of f1 must be checked whether it is prime or not by another function f3. The result must be printed in the program.
The control does not flow beyond the 45th line in this code. I do not really know what it the issue here because when i run the code in code blocks, the output screen displays the output of f2 and then it remains idle. for example, if i give the input as 8 and 2, then the output returns a value of 81 and then it does not do anything beyond that.
#include <stdio.h>
#include <math.h>
int f1(int npow)
{
int ret=0;
while (npow>0)
{
ret=(ret*10)+(npow%10);
}
return ret;
}
int f2(int x,int n)
{
int res;
res=pow(x,n);
return res;
}
int f3(int resrev)
{
int i,check;
for (i=2;i<resrev;i++)
{
if (resrev%i==0)
{
check =1;
break;
}
else
{
check=0;
break;
}
}
return check;
}
void main()
{
int resrev,x,n,npow,prime;
printf("Enter two numbers x and n\n");
scanf("%d %d",&x,&n);
npow=f2(x,n);
printf("x to the power n is %d\n",npow);
resrev=f1(npow);
printf("Reversed value of x to the power n is %d \n",resrev);
prime=f3(resrev);
if (prime==1)
printf("It is not a prime number \n");
else
printf("It is a prime number\n");
}
Problem is in function f1. It is an infinite loop.
Loop condition is until npow>0 but you are not updating value of npow in the loop.
Following is corrected code:
int f1(int npow)
{
int ret=0;
while (npow>0)
{
ret=(ret*10)+(npow%10);
npow = npow/10;
}
return ret;
}
Loop inside f1 is infinite as condition to exit while loop is unaltered.
snippet has to be updated as follows,
int f1(int npow)
{
int ret=0;
while (npow>0)
{
ret=(ret*10)+(npow%10);
npow /= 10; // divide to remove lsb digit
}
return ret;
}

Fibonacci sequence while loop

I have to write code that displays the Fibonacci sequence to the user desired number of terms and must also use a while loop. I'm not sure why this code isn't working.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int max;
printf("Enter the max term of the Fibonacci Sequence:\n");
scanf("%i", &max);
int a=0;
int b=0;
a=2;
while(a<max) {
if((a==0||a==1))
{
printf("%i\n", &a);
++a;
}
else if(a>1)
{
a=(a-1)+(a-2);
printf("%i\n", &a);
++a;
}
}
return 0;
}
You can try this.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int max;
printf("Enter the max term of the Fibonacci Sequence:\n");
scanf("%i", &max);
int n=0;
int a=0;
int b=1;
int next;
while(n<max) {
if ( n <= 1 )
{
next = n;
n++;
}
else
{
next = a + b;
a = b;
b = next;
n++;
}
printf("%d\n", next);
}
return 0;
}
issues with your code:
following declaration & initialisation, you set a=2 => it won't take the true branch of the if statement -- '0' will not be printed in your result.
a=(a-1)+(a-2); i.e a = 1
then you are doing ++a; => a == 2. thus it again else statement with same a==2.
hence it will print the same value and loop executes infinitely.
In the very beginning of your program (before the while loop) a is 2 (see the line a=2).
And in the while loop you do following:
a=(a-1)+(a-2); // a = 2-1+2-2 i.e. a = 1
and right after it
++a; // a == 2
So, after it a==2 again. This loop never ends.
But it is technical problem. More important is that you are trying to calculate not Fibonacci Sequence. In the Fibonacci Sequence each subsequent number is the sum of the previous two. But in your code there is adding of not two previous numbers of Fibonacci Sequence, but previous two Natural numbers.
You have variable b, because someone told you to add it. And it was right! Just remember previous found element of the Fibonacci Sequence in b. When you know previous one element and current one, it is possible to calculate next one.

Decimal To Binary conversion using Array and Stack

This is the C Program I have written to convert a Decimal number to it's equivalent Binary number. I have used Stack (implemented using array) and the following algorithm:
Number is divided and remainders are pushed in stack.
Remainders are popped one at a time and converted into Binary
The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.
// Decimal to Binary conversion using Stack
#include<stdio.h>
#include<math.h>
#define max 20
int top=-1, stk[max];
void push(int);
int pop(void);
int main()
{
int i,num,x,flag=0,s, bin=0, factor;
printf("Enter any decimal number: ");
scanf("%d",&num);
while(num>0)
{
if(num==1)
push(num);
else
{
x = num%2;
push(x);
}
num/=2;
flag++;
}
for(i=0;i<flag;i++)
{
s = pop();
bin = bin + s*pow(10,(flag-1-i));
}
printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}
void push(int n)
{
if(top == max-1)
{
printf("Error! Overflow");
return;
}
stk[++top] = n;
}
int pop(void)
{
int y;
if(top == -1)
{
printf("Error! Underflow");
return;
}
y = stk[top];
top = top-1;
return y;
}
Will anybody help me by finding the logical flaw?
Thank You
My answer is your program is unnecessarily complicated.
#include<stdio.h>
int main()
{
unsigned num, i, zeros = 0;
printf("Enter a decimal number: ");
scanf("%u", &num);
printf ("Decimal %u in binary is ", num);
for (i=sizeof(unsigned)*8; i>0; i--)
{
if ((int)num < 0) // get MSB
zeros = printf ("1"); // cancel 0-suppresion
else if (zeros)
printf ("0");
num <<= 1;
}
printf ("\n");
return 0;
}
The function pow return a double that can have a 9999999... after the decimal point, which is rounded to the floor when it is casted to int, you can fix your problem using ceil() function, that returns the smallest integer value greater than or equal the argument, like this.
bin = bin + ceil(s*pow(10,(flag-1-i)));
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
/*------ Function Prototype------------*/
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
/*-------------------------------------*/
void main()
{
int num, total = 0,item;
printf( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
printf("%d",item);
}
}
Here is a simpler version of your above program
int main(){
int n,remainder;
printf("Enter a decimal number:");
scanf("%d",&n);
while(n!=0){
remainder = n%2;
n = n/2;
push(remainder); // inserting in stack
}
display(); // displaying the stack elements
}
reference of above code
C program to Convert Decimal number into Binary using Stack
So I've done the math on several numbers, and this appears to be correct. I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.
So the output of this program appears correct, from a logical standpoint. Lets look into other potential issues:
You're indexing an array with an int that you initialize to -1
This is bad practice, and unnecessary. Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. Always use a unsigned value for array indexes
What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say. But it's probably attempting to convert your negative number into an unsigned int before you do your addition. Fix this by changing your declaration of top to:
unsigned int top = 0;
and changing where you access top from:
stk[++top] = n;
to
stk[top++] = n;
You will also have to change
y = stk[top];
top = top-1;
to
top = top-1;
y = stk[top];
I'd say start there. I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.
PRINTF("%d%d%d",stk[2],stk[1],stk[0]);

Resources