Recursive print of binary number - c

I'm struggling to write a recursive way to print a binary number. Here is what I have so far:
int bin(unsigned char n)
{
if (n==0) {
return 0;
} else {
printf("%d", bin(n<<1));
}
}
bin(7)
What seems to be wrong with the logic above?

A few errors such as using << (shift up) instead of >> (shift down). Also not always returning something. I'm surprised the compiler didn't pull you up on that. You don't gain anything from a return value, So you may as well get rid of it.
A simple implementation could look like this. We need to have the wrapped function (bin_recur) to allow us to differentiate between 0 the input value and 0 which signifies its time to stop recursion.
#include <stdio.h>
void bin_recur(unsigned char n)
{
if (n > 0)
{
printf("%d", n & 1);
bin_recur(n >> 1);
}
}
void bin(unsigned char n)
{
if (n == 0)
{
printf("0\n");
} else
{
bin_recur(n);
printf("\n");
}
}
int main()
{
for(unsigned i = 0; i < 10; i++)
{
bin(i);
}
}
The fact that your bin function calls printf is not completely ideal. This is what's known as tight coupling and the function could be more reusable if it was not bound to how it is presented. Perhaps copying to a string is a good way or even using fprintf to print to a file.

Stopping when n is 0 is wrong.
This fails for the trivial case where n is 0 to start with.
What you really need to do is pass down a shift amount as a second argument and stop after 8 bits.
Using the return with value just gets in the way.
Here's some refactored code with a full diagnostic test:
#include <stdio.h>
void
bin2(unsigned char n,int shf)
{
if (shf <= 7) {
bin2(n,shf + 1);
printf("%d", (n >> shf) & 1);
}
}
void
bin(unsigned char n)
{
bin2(n,0);
}
int
main(void)
{
for (unsigned int chr = 0; chr <= 0xFF; ++chr) {
printf("%2.2X: ", chr);
bin((unsigned char) chr);
printf("\n");
}
return 0;
}

please add this lines to your code.
void binary(int n) {
if(n==0)
return;
binary(n/2);
printf("%d",n%2);
}

You need the print call to execute after the recursive function for this to work. Here's an example:
void bin(unsigned char n)
{
if (n > 1) bin(n>>1);
putchar(n&1 ? '1' : '0');
}
int main(void)
{
for (unsigned char i = 255; i; i--) {
printf("%d --> ", i), bin(i);
getchar(); // inspect element if you want
}
}
Link to running code here.

Related

Understanding returning values functions C

I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}

How can I call with a int function in main function?

I have a requirement to insert something in the function main > my_isneg to call my_isneg function. How can I do it?
#include <unistd.h>
void my_putchar (char c)
{
write (1, &c, 1);
}
int my_isneg (int n)
{
if (n < 0) {
my_putchar (78); }
else {
my_putchar (80);
}
}
int main (void)
{
my_isneg();
}
It's somewhat unclear what you're asking, but maybe you want this:
...
// print 'N' 1 if the number n is strictly negative, print 'P' otherwise
int my_isneg(int n)
{
if (n < 0) {
my_putchar('N'); // use 'N' instead of 80 (it's more readable)
}
else {
my_putchar('P'); // use 'P' instead of 80
}
}
int main(void)
{
my_isneg(-1);
my_isneg(1);
my_isneg(2);
}
Output
NPP
Or maybe this, which matches the name my_isneg more closely:
...
// return 1 if the number n is strictly negative
int my_isneg(int n)
{
return n < 0;
}
int main(void)
{
if (my_isneg(-1))
my_putchar('N');
else
my_putchar('P');
if (my_isneg(1))
my_putchar('N');
else
my_putchar('P');
}
Output
NP

Print all binary numbers of length N

I've done this question on leetcode before but wanted to do it in C. Was wondering if anyone could let me know if there is a better way to do it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printBinaryLenthHelper(int currentLength, int maxLength, char accum[]) {
if (currentLength == maxLength) {
printf("%s\n", accum);
return;
}
accum[currentLength++] = '0';
printBinaryLenthHelper(currentLength, maxLength, accum);
accum[--currentLength] = '1';
printBinaryLenthHelper(++currentLength, maxLength, accum);
}
void printBinaryLength(int length) {
char accum[length + 1];
printBinaryLenthHelper(0, length, accum);
}
int main() {
printBinaryLength(20);
}
You can avoid recursion by simply iterating from 0 to 2^n -1. This range represents all the numbers with binary length n (assuming smaller numbers are padded with leading zeroes).
Code
#include <stdio.h>
void printBinary(int len) {
//This loop iterates from 0 to 2^len - 1
for(int i = 0; i < 1 << len; ++i) {
//This loop is to print the integer in its binary representation.
for(int j = len - 1; j >= 0; --j) {
// ((1<<j)&i) > 0 evaluates to 1 if the jth bit is set, 0 otherwise
printf("%d", ((1<<j)&i) > 0);
}
printf("\n");
}
}
int main(void) {
// your code goes here
printBinary(10);
return 0;
}
Output
0000000000
0000000001
0000000010
0000000011
0000000100
0000000101
0000000110
0000000111
0000001000
0000001001
0000001010
...
Tested here.
PS: If you do not understand what 1<<j and (1<<j)&j means, read about bitwise operators in C.
There is a problem in your function printBinaryLenthHelper: you do not null terminate the string before passing it to printf. It is also confusing to increment and decrement currentLength as a side effect, just pass the next value in the recursive call.
Here is a corrected version:
void printBinaryLenthHelper(int currentLength, int maxLength, char accum[]) {
if (currentLength == maxLength) {
accum[currentLength] = '\0';
printf("%s\n", accum);
return;
}
accum[currentLength] = '0';
printBinaryLenthHelper(currentLength + 1, maxLength, accum);
accum[currentLength] = '1';
printBinaryLenthHelper(currentLength + 1, maxLength, accum);
}
Note also that the name should be printBinaryLengthHelper.

Parameter not being passed correctly.

I have a Piece of code here. The code Runs fine and there is no error shown by the system. Although I have a recursive function the recursion does not occurs.
Here is my code....
What exactly is the problem???
int no_of_moves(int n,int s[], int m)
{ int move=0,i;
if(n==1)
return 0;
for(i=m-1;(i>=0&&s[i]!=n&&n%s[i]==0); i--)
{
//printf("(%d %d)",n,s[i]);
move = max(move, 1+no_of_moves(s[i],s,m));
}
return move;
}
There is nothing easier than add debug output like this
int no_of_moves(int n,int s[], int m)
{ int move=0,i;
printf("Recursion test\n");
if(n==1)
return 0;
for(i=m-1;( i>=0 && s[i] != n && n%s[i] == 0); i--)
{
printf("(%d %d)",n,s[i]);
move = max(move, 1+no_of_moves(s[i],s,m));
}
return move;
}
Note
printf("Recursion test\n");
Output
Recursion test
(12 4)Recursion test
(12 3)Recursion test
(12 2)Recursion test
It means that your function is called recursively 3 times.
The problem why does the function give you wrong output is in passing parameters. But Q was
Program not entering into Recursion
but it does.

My binary is outputting in reverse order

I'm writing a program that takes a users input of characters, singles each character, converts each to binary, and also counts the amount of '1's in each binary. So far, I have a working code. However, the output of each binary is in reverse order. Like this:
The character A = 10000010 1's = 2
When what I want/need is:
The character A = 01000001 1's = 2
I am required to use the amount of functions I already have and have been told that fixing this will be as simple as doing recursion on my binaryPrinter function. I'm confused about where I would do that within my function and what arguments I would send through. Any help would be fantastic, thanks.
p.s. I'm required to use recursion in the binaryPrinter function to loop the program which apparently is going to solve my backwards binary problems if I place it in the right part of the binaryPrinter function.
#include <stdio.h>
#include <stdlib.h>
void binaryPrinter(int digitsLeft, int value, int * numberOfOnes);
void print(char c);
int charToInt(char C)
{
int c;
c=C;
return (int) c;
}
int main ()
{
char value;
int result = 1;
while (result != EOF)
{
result = scanf("%c", &value);
if (result != EOF)
{
print(value);
}
}
}
void print(char c)
{
int digits=8, value=c;
int ones=0;
printf("The character %c = ", c);
binaryPrinter(digits, value, &ones );
printf(" 1's = %d\n", ones);
}
void binaryPrinter(int digitsLeft, int value, int * numberOfOnes)
{
for (digitsLeft=8; digitsLeft>0; digitsLeft--)
{
if( value & 1 )
{
printf("1");
*numberOfOnes=*numberOfOnes+1;
}
else
{
printf("0");
}
value = value >> 1;
}
}
Here's the recursive version. Notice that it recurses before printing anything, so it prints as it's returning from processing each digit, which prints them in the proper order.
void binaryPrinter(int digitsLeft, int value, int * numberOfOnes)
{
if (digitsLeft > 1) {
binaryPrinter(digitsLeft - 1, value >> 1, numberOfOnes);
}
if (value & 1) {
printf("1");
(*numberOfOnes)++;
} else {
printf("0");
}
}
Change the loop to
for (digitsLeft=1; digitsLeft<=8; digitsLeft++)
Well, you are looking at the digits in reverse order:
if (value & 1) --> take the right-most digit
value = value >> 1; --> shift to the right
so if you have
12345678
(yes, that's not bits, this is just to illustrate the positioning) for inputs, you're doing:
8,7,6,5,4,3,2,1
for output. You need to reverse the logic by working from the left (highest) bits in your original string and work yourway down to the least significant bits.

Resources