Print a number converted in base 2 recursively - c

So I've been trying to do this but I just can't think of a solution for this. I've got this bit of code but it outputs it backwards(if the answer is 11110 I get 01111):
#include <stdio.h>
int base(int n)
{
if(n==0)
return 0;
else
{
printf("%d",n%2);
}
return base(n/2);
}
int main() {
int n;
scanf("%d",&n);
base(n);
return 0;
}
Is there any trick for this problem or do I need to analyze this deeper?

As #rici stated, a very simple fix is to print after the recursive call:
#include <stdio.h>
void base(int n){
if(n==0)
return;
base(n/2);
printf("%d",n%2);
}
int main() {
int n;
scanf("%d",&n);
base(n);
return 0;
}

I would use a mask:
#include <stdio.h>
int base(int n, int mask){
if(!mask) {
printf("\n"); // we reach the end, print a line return
return 0;
}
printf("%d", !!(n & mask)); // if mask and n match, print '1', else print '0'. !! convert any value into 1, and 0 remains 0.
return base(n, mask >> 1); // divide mask by 2, check the next bit on the right
}
int main() {
int n;
scanf("%d",&n);
base(n, 1 << (31 - __builtin_clz(n))); // call the function with a mask initialized at the same level than the most important bit of n.
return 0;
}

Related

How to store individual units of an int in an int array; C Language

I am a beginner starting in C and am doing some exercises on codewars. The exercise requires me to take a decimal int, convert it into binary and output the number of 1s in the binary number. Below my incomplete code. I store the binary in int b and I want to output it into an array so that I can run a loop to search for the 1s and output the sum.
Thanks in advance!
#include <stddef.h>
#include <stdio.h>
//size_t countBits(unsigned value);
int countBits(int d);
int main() {
int numD = 1234;
int numB = countBits(numD);
printf("The number %d converted to binary is %d \n", numD, numB);
}
int countBits(int d) {
if (d < 2) {
return d;
} else {
int b = countBits(d / 2) * 10 + d % 2; //convert decimal into binary
int c;
int bArray[c];
}
Your function is almost correct:
you should define the argument type as unsigned to avoid problems with negative numbers
you should just return b in the else branch. Trying to use base 10 as an intermediary representation is useless and would fail for numbers larger than 1023.
Here is a corrected version:
int countBits(unsigned d) {
if (d < 2) {
return d;
} else {
return countBits(d / 2) + d % 2;
}
}
There are many more efficient ways to compute the number of bits in a word.
Check Sean Eron Anderson's Bit Twiddling Hacks for classic and advanced solutions.
You can make an array char as one of the replies said, for example:
#include <stdio.h>
#include <string.h>
int main(){
int count=0;
int n,bit;
char binary[50];
printf("Enter a binary: \n");
scanf("%s",binary);
n=strlen(binary);
for(int i=0;i<n;i++){
bit=binary[i]-'0';
if (bit==1){
count=count+1;
}
}
printf("Number of 1's: %d\n",count);
return 0;
}
This should count the number of 1's of a given binary.
Try something like this!
edit: I know that binary[i]-'0' might be confusing, if you don't understand that..take a look at this:
There are definitely 'smarter'/more compact ways to do this, but here is one way that will allow you to count bits of a bit larger numbers
#include <stdio.h>
int count_bits(int x)
{
char c_bin[33];
int count=0;
int mask=1;
for( int i =0; i < 32; i++){
if (x & mask ){
count=i+1;
c_bin[31-i]='1';
}
else{
c_bin[31-i]='0';
}
mask=mask*2;
}
c_bin[32]='\0';
printf("%d has %d bits\n",x,count);
printf("Binary x:%s\n",c_bin);
return count;
}
int main()
{
int c=count_bits(4);
return 0;
}

SUM Recursive function in C

I'm trying to recursive function in C that calculates the sum of the numbers from x to max (inclusive). For example, sum (4, 7) would compute 4 + 5 + 6 + 7 and return the value 22. The function code a must be recursive so you are not allowed to use any conventional loop constructs.
I have this and i think it should work but i'm not entirely sure why its not
#include <stdio.h>
int main()
{
int sum (x, max);
int total, y, x, max;
if (x<max){
y=x+1;
total = x+sum(y,max);
return total;
return x;
}
return 0;
}
Thanks for any help with this in advance!
Here is one possible solution:
#include <stdio.h>
int sum_in_range(int a, int b){
if(a != b){
return sum_in_range(a+1,b)+a;
}
else{
return b;
}
}
int main(void) {
// your code goes here
printf("%d",sum_in_range(2,4));
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int sum(int s,int max)
{
if(s==max)
{
return s;
}
else
{
return(s+sum(s+1,max));
}
}
int main()
{
int r,s,max;
printf("\n enter s and max");
scanf("%d%d",&s,&max);
r=sum(s,max);
printf("%d",r);
}
I spotted some errors on your code. I'm not a pro yet but here's what I think
I just edit your code. removed, added and rearranged some stuff*/
/*First, let's look at your code*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int sum(x, max);//I think what you want to do here is declare a function but instead declaring, you define it here because you added semicolon (;)
int total, x, y, max;
if(x < max)
{
y = x + 1;
total = x + sum(y, max); //you don't have a function declaration for "sum"
return total;
return x; //this will never return since you already "return the total before this"
}
return 0;
}
//////////////////////////////////////////////////////////////
/*And I think this is what you want to do*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6; //We declare this here for the "sum" function. This way "sum" function can recognize these variables
int total = x; //be sure to set the total to x.
//you can make a void function for this instead of "int". but either way, it can do the job.
void sum(int y) //no need to pass a "max" because "max" is already recognized by the "sum" function since we declare the variables at the top of "main" function
{
if(x < max)//don't make it x <= max. Because of the argument "total = total + (x + 1)" on this function. If you do, the total will exceed.
{
//You can see here why we set the value of "total" to x.
total = total + (x + 1);//And also, you can see why we didn't make the argument in if() statement like this: if(x <= max).
x++;//increment "x" every loop
//call the function again and pass the total until x == max.
sum(total);
}
}
//pass the x
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}
//////////////////////////////////////////////////////////////
/*It looks messy with comments*/
/*Here's the code looks like without a comment.It's pretty short code if you look remove the comments.. LOL..*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x = 4, max = 6;
int total = x;
void sum(int y)
{
if(x < max)
{
total = total + (x + 1);
x++;
sum(total);
}
}
sum(x);
//check the answer
printf("The total is %d\n\n", total);
return 0;
}

Extracting bytes in C

I'm making a program in C. I am to extract bytes. un8 extractbyte (int r, int pos) should return byte number pos from number r. As example, I use as input: 0x7788AABB. Output then should be:
Part number 0 is BB
Part number 1 is AA
Part number 2 is 88
Part number 3 is 77
I am stuck at the last part of the program, where I have put the question marks in the comments. Those lines aren't right and I am confused in how I should make it work... The output I get now is bb at every part. I am pretty new at C by the way.
#include <stdio.h>
#include <stdlib.h>
typedef unsigned int un32;
typedef unsigned char un8;
un8 extractbyte (un32 r, un8 pos);
int main ()
{
un32 number;
un8 k;
printf("Enter a number:\n");
scanf("%x",&number);
for (k=0; k<=3;k++)
printf ("Part number %d is: %x \n", k , extractbyte(number, k) );
return 0;
}
un8 extractbyte (un32 r , un8 pos)
{
un32 mask;
un32 size = pos*8;
un32; // ??
un8; // ??
return (un8) r; // ??
}
un8 extractbyte(un32 r, un8 pos)
{
return (r >> (8 * pos)) & 0xFF;
}
I would make your extractbyte function something like this.
int extractbyte(int n, int pos)
{
return (n >> (pos * 8)) & 0xff;
}
#include <stdio.h>
char extractbyte(int number, int v) {
char *x=(char *)&number;
return x[3-v];
}
int main() {
int n=0x7788aabb;
int i;
for (i=0; i<4; i++) {
printf("%d) %x\n",i,(unsigned char)extractbyte(n,i));
}
return 0;
}

3n+1 weird stuff happening

While simulating the Colatz Conjecture problem i have made recursion when i want to print the count number in the recursion i get the result i need but when the function return the result it gives me weird numbers, why is that?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1){divide(n=3*n+1, ++count);}
else{divide(n/=2, ++count);}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}
You don't have any default return. So the return value is undefined.
You need to return the results of the recursive calls:
if (n % 2) { return divide(3 * n + 1, count + 1); }
// %%%%%%
else { return divide(n / 2, count + 1); }
Note that there's no point in assigning to the local variables, so I've changed that to simple computations.
A. you need to return the returned value from the recursion calls.
B. why do you assign a value to n in the calls to divide?
#include <stdio.h>
#include <stdlib.h>
int divide(int n,int count){
if(n<=1){printf("%d ",count);return count;}
if(n%2==1)
{
return divide(3*n+1, ++count);
}
else
{
return divide(n/2, ++count);
}
}
int main(void) {
printf("%d ",divide(10,1));
return 0;
}

Program to print the binary equivalent of a number without using format specifiers

Jus check out this program.Logically it seems fine but its giving 000000000000000000000 for everything
#include<stdio.h>
void main()
{
int n=25,k=32;
printf("binary equivalent\n");
while(k!=0)
{
if((n>>1&0x01)!=0)
printf("1");
else
printf("0");
k--;
}
}
You don't ever change n.
Don't try and cram everything into one line, be a little more verbose so that things are clearer.
while(k!=0)
{
if((n & 0x01) != 0)
printf("1");
else
printf("0");
k--;
n >>= 1;
}
That is because you don't change n.
For n=25 we have (n>>1)=12 hence it prints zero. And since you don't change n it prints zero for all k.
You can change it in the following way:
#include
void main()
{
int n=25,k=32;
printf("binary equivalent\n");
while(k!=0)
{
if((n & 0x01)!=0)
printf("1");
else
printf("0");
k--;
n = n >> 1;
}
}
However it will print binary presentation in reversed form.
Your n is never getting changed:
if((n>>1&0x01)!=0)
should be
if(n & 0x01)
and add
n>>=1; after k--;
Also this will produce the binary representation in reverse order.
You are not modifying n - every time you compare 0x01 with second bit on n.
You don't change the value of n within the loop. And probably you want to test the least significant bit before shifting.
/*
* Author: Andrey Vlassov
* Date: Thu Apr 19 03:10:49 UTC 2012
*
* Description:
* An expample program demonstrating how
* to convert decimal integer number to
* binary representation
*
* NOTE:
* For simplicity additional check left out
*
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char help[] = ">>> Please provide an integer number as argument!!!";
char id[] = "d2b (c) Andrey Vlassov Apr 18, 2012 8:15PM PST";
if( argc < 2 ) {
printf("%s\n", help);
exit(0);
}
printf("\n%s\n\n", id);
int n = atoi(argv[1]);
int i, bites, bits, mask;
printf("Number is %d\n", n);
printf("size: %d bites\n", bites=sizeof(n));
printf("dec: %d\n", n);
printf("hex: %#x\n", n);
printf("oct: %#o\n", n);
printf("bin: b");
bits = bites*8-1;
mask = 0x01 << (bits-1);
for( i=0; i<bits; i++) {
printf("%d", ( n & mask ? 1 : 0 ) );
mask >>= 1;
}
printf("\n\n");
exit(0);
}
i think it will help the result is the same as other poster posted
#include<stdio.h>
int main()
{
int n=25;
int k=32;
printf("binary equivalent\n");
for (int i=0;i<32;i++){
if((n&1)!=0)
printf("1");
else
printf("0");
n>>=1;
}
}
as #falagar said result will be printed in reverse order
// how to print binary number representation of an integer
// using bitwise operators
//
// oon
// 18.04.2013
// Refs
// http://www.cs.northwestern.edu/~wms128/bits.c
// http://www.cs.cmu.edu/~guna/15-123S11/
#include <stdio.h>
#define no_of_bits_in_a_byte 8
#define get_bit(w,i) ((w>>i)&1)
void print_binary(signed int x);
int main()
{
print_binary(2); // 00000000000000000000000000000010
print_binary(-2); // 11111111111111111111111111111110
return 0;
}
void print_binary(signed int x)
{
int i;
int no_of_bytes = sizeof(x);
for (i=no_of_bytes*no_of_bits_in_a_byte-1; i>=0; i--) {
printf("%d",get_bit(x,i));
}
printf("\n");
}
/*
* print_binary2.c
*
* oon
*
* 19.04.2013
*/
// http://www.cs.northwestern.edu/~wms128/bits.c
// http://www.cs.cmu.edu/~guna/15-123S11/
#include <stdio.h>
#define no_of_bits_in_a_byte 8
#define get_bit(w,i) ((w>>i)&1)
void print_binary2(signed int x, unsigned int n);
int check_bits_fit_in_2s_complement(signed int x, unsigned int n);
void main()
{
print_binary2(2,2); // output: The signed integer 2 cannot be represented by 2 bit(s) in two complements form.
print_binary2(2,3); // output: 010
print_binary2(-2,2); // output: 10
print_binary2(-2,3); // output: 110
}
int check_bits_fit_in_2s_complement(signed int x, unsigned int n) {
int mask = x >> 31;
return !(((~x & mask) + (x & ~mask))>> (n + ~0));
}
void print_binary2(signed int x, unsigned int n)
{
// check if x can be represented by n bits in two's complement form.
if (check_bits_fit_in_2s_complement(x,n)) {
int i;
for (i=n-1; i>=0; i--) {
printf("%d",get_bit(x,i));
}
printf("\n");
} else {
printf("The signed integer %d cannot be represented by %u bit(s) in two complements form.\n",x,n);
}
}
The above code shows how to print binary number in two's complement form where n denotes the number of bits.
int binary(int n)
{
if(n/2)
binary(n/2);
printf("%d",n%2);
}
void main()
{
int n;
printf("enter any number");
scanf("%d",&n);
binary(n):
getch();
}
Try this!
#include<iostream>
#include<stack>
using namespace std;
int main(){
stack<int> st;
int n=25, k=32;
while(k!=0){
if((n&0x01)!=0)
st.push(1);
else
st.push(0);
k--;
n=n>>1;
}
while(!st.empty()){
cout<<st.top();
st.pop();
}
}

Resources