So, first of all I'm a total beginner in C, we're studying it at University on the course 'Structured Programming'.
Now, the last few lectures about 'Recursive functions' have been a pain for me as a beginner. Could anyone of you be kind enough to explain me this:
So I have this little script, a recursive function that takes a decimal number and converts it to a binary one:
#include <stdio.h>
void binary(int num)
{
if (num == 0) return;
binary(num / 2);
printf("%d", num % 2);
}
int main()
{
int n;
scanf("%d", &n);
binary(n);
return 0;
}
Now I was wondering, how does this function work? I know the logic behind it and whats its supposed to do, but I don't know how it does IT. The printf in the bottom is especially throwing me off, for example if the printf function is before the recursive call, for the input decimal 10 it prints out (0101) but if its under it it prints out the correct binary number (1010)?
Any kind of help is greatly appreciated, kind regards.
The reversal is done using the call stack of the functions. By that I mean that the way the functions are called, this guarantess that the MSB will be printed first then the next one and so on.
void binary(int num)
{
if (num == 0) return;
binary(num / 2); // Wait, I will print but you first print the MSB's.
printf("%d", num % 2); // Now I print the last digit.
}
Downward motion moves the calls.
{binary(12)
{binary(6)
{binary(3)
{binary(1)
binary(0) -- returns
Now we print 1
}
print 1
}
prints 0
}
prints 0
}
If one wants to print recursively the bits of a char with leading zeros,
he may use following code:
#include <stdio.h>
void print_bit_iter(char x, int n)
{
int bit = (x & (1 << n - 1)) != 0;
printf("%d", bit);
if(n != 0)
print_bit_iter(x, n - 1);
}
int main()
{
print_bit_iter('U', 8);
}
This will have
01010101
as the output.
Related
I am very new to Coding. Here is a program that I wrote to convert decimal to binary
but there is one problem I am getting the result but it's in reverse
Example: Binary of 122 is 1111010 and I'm getting output 0101111.
Can anyone please tell me is it possible to reverse the output in my code?
Or what changes can I make in the following to get the correct output?
#include<stdio.h>
int main()
{
int n, q, r;
printf("Enter the decimal Number : ");
scanf("%d", &n);
int num=n;
while(n!=0)
{
r=n%2;
q=n/2;
printf("%d", r);
n=q;
}
return 0;
}
Seems like you are new to coding. It doesn't matter here is the problem.
Converting decimal to binary is like this,
eg:
division by 2
quotient
reminder
bit
10/2
5
0
0
5/2
2
1
1
2/2
1
0
2
1/2
0
1
3
=(1010)
So the output should have digits from bottom to top of the reminder column. Your output is printed from top to bottom.
See the code below where you need an array in order to store reminders and print the array in reverse order so you get the output you need
#include<stdio.h>
#include<stdlib.h>
int main(void){
int a[10],n,i;
printf("Enter the decimal Number : ");
scanf("%d",&n);
for(i=0;n>0;i++)
{
a[i]=n%2;
n=n/2;
}
printf("\nBinary of Given Number is=");
for(i=i-1;i>=0;i--)
{
printf("%d",a[i]);
}
return 0;
}
void display(unsigned n)
{
if(n == 0) return;
display(n /2);
printf("%d", n % 2);
}
and example usage:
https://godbolt.org/z/ahGPc74nf
As a homework: how to correctly handle 0?
Or not recursive version. This one can print or not leading zeroes:
void display(unsigned n, int printzeroes)
{
unsigned mask = 1 << (CHAR_BIT * sizeof(mask) - 1);
int print = printzeroes;
while(mask)
{
if(n & mask)
{
print = 1;
}
if(print) printf("%d", !!(n & mask));
mask >>= 1;
}
}
And usage: https://godbolt.org/z/7Eq71TMWb
First of all, please note that all numbers in a C program are to be regarded as binary. It's a common misconception among beginners that different number formats somehow co-exist in the executable program. But everything there is raw binary.
Sure the programmer may write numbers in different formats 7, 07 or 0x7 in the source code, but they get translated to binary by the compiler. Therefore, converting between binary and "x" doesn't make sense, because everything is already binary. You may however, convert from binary to a decimal string or similar, for the purpose of displaying a number to the user etc.
With that misconception out of the way - yes, you can create a binary string with the method you picked, dividing by ten and checking the remainder. The problem with that approach is that you'll get the most significant digit first. This is why you get the number backwards. So in order to do that, you'd have to store down the string in a character array first, before displaying it.
A more convenient way would be to use the "bitwise" operators like & and shift to mask out bit by bit in the data. Basically this:
if(n & (1u << bit)) // 1u to avoid shifting signed type
printf("1");
else
printf("0");
Where bit is the bit position 7,6,5... down to 0. If we prefer an up-counting loop instead, we can tweak the code into:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << 8-i-1;
...
}
And finally we can make the output a bit more compact, which is just a stylistic concern:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << 8-i-1;
printf("%c", n & mask ? '1' : '0');
}
If you aren't dead certain about C operator precedence, then use parenthesis, which is perfectly fine too:
for(size_t i=0; i<8; i++)
{
size_t mask = 1u << (8-i-1);
printf("%c", (n & mask) ? '1' : '0');
}
Here's the homework demanded by 0___________:
void printbin(int n)
{
static int depth;
if (n) ++depth, printbin(n / 2), --depth;
else if (depth) return; // print leading 0 only for n = 0
printf("%d", n % 2);
}
A leading 0 is not printed unless on the topmost recursion level.
You could maybe create an array of size 32 and keep adding the digits to the array. Or create a int variable and add the digits to the variable.
int result = 0;
while(n!=0)
{
r=n%2;
n=n/2;
result = result*10+r;
}
I am new to coding. so I wanted to write a c program using recursion to calculate the factorial of a number.
#include <stdio.h>
int fact(int a) {
int n = 1;
if (a != 0)
return;
else
n = n * a;
a--;
fact(a);
return n;
}
int main() {
printf("%d", fact(5));
return 0;
}
This is the program I have written. I know this is probably wrong but I think I would understand programming better if I was able to understand why the above program is exactly wrong.
Because whenever you pass any value other than 0 to fact your code exits without even returning a value:
if(a!=0)
return;
You should get at least a warning from your compiler that this is invalid code, since fact is expected to always return an int value.
But even more so, this is a logical error.
Did you mean to write:
if (a == 0) return 1; //0! = 1
Lev M. pointed out your mistakes in his answer. This is a working recursive implementation of the factorial algorithm.
unsigned int fac(unsigned char n)
{
if (n == 0)
return 1;
return n * fac(n - 1);
}
This is a recursive function to find the amount of 2 appearing in a number.
Example Input:
221122
Example Output:
countTwo(): 4
#include <stdio.h>
void countTwo2(int num, int *result);
int main()
{
int number, result;
printf("Enter the number: \n");
scanf("%d", &number);
countTwo2(number, &result);
printf("countTwo2(): %d\n", result);
return 0;
}
void countTwo2(int num, int *result)
{
if(num > 0) {
if((num % 10)/2 == 1) {
*result += 1;
}
countTwo2(num/10, result);
}
}
I can't increment result since it has not been initialised but I also can't initialise result in the recursive function as this will reset the result.
Edit: This is a question given, with all the template written as above except for the code within countTwo. We are supposed to write the code in countTwo such that main() will be able to run.
Edit2: Thanks for the help! This problem has been solved by using static int. I understand that this is not very efficient. I will also ask my teacher pertaining to this question. Once again, Thanks!
The way to keep all the oddities of this code:
it has to be recursive
you cannot change main, so the initial result value will be undefined
is to, as you stated you cannot do, actually reset result inside countTwo2. However, you need to it in the right place, before you start incrementing.
The way to do that is to reorder your function and add the part that resets the value at the right place:
void countTwo2(int num, int* result)
{
if (num > 0)
{
countTwo2(num / 10, result);
if ((num % 10) / 2 == 1)
{
*result += 1;
}
}
else
*result = 0;
}
Notice that I moved the recursive call up above the if-then block that increments the result, and that when num is 0, we reset. This will call recursively down digits of the input until we're at the end, then reset the result, then return back up one digit at a time and optionally increment the value.
This requires no other changes to your code.
As many have stated, in comments and answers, this is obviously not a good implementation or design but if you have a confined context to work in, this is probably as good as it gets.
I can't see any good reason for declaring this as a void function with the result passed back via pointer parameter.
The following would be a lot cleaner, surely?
int countTwo(int num) {
return (num == 0) ? 0 : (num % 10 == 2) + countTwo(num / 10);
}
For reference, the proper way to write such a function is to not use recursion. It isn't obvious that the compiler will be able to unroll the recursion in this case, as the recursive call would be in the middle of the function, and also conditional.
Thus the only thing gained from recursion is slow execution and higher stack peak use. Why would we want slow execution when we can have fast execution? You should ask your teacher this question, so they can tell you why they are teaching it. I would be most curious to hear their rationale.
For a professional, non-academic programmer, the proper way to write the function would be to use a loop:
int count_n (int input, int n)
{
int result = 0;
for(; input>0; input/=10)
{
if(input%10 == n)
{
result++;
}
}
return result;
}
(This version doesn't work with negative numbers.)
As I mentioned before you may use static variables.
You do not need two arguments.
Here is a solution: #Lasse Vågsæther Karlsen
#include <stdio.h>
int countTwo2(long int num)
{
static int m=0; //static variable is initialized only once.
if (num==0)
return m;
else if (num % 10 ==2)
m=m+1;
num=num /10;
countTwo2(num);
}
int main()
{
int result; long int number;
printf("Enter the number: \n");
scanf("%ld", &number);
result=countTwo2(number);
printf("countTwo2(): %d\n", result);
return 0;
}
So, first of all I'm a total beginner in C, we're studying it at University on the course 'Structured Programming'.
Now, the last few lectures about 'Recursive functions' have been a pain for me as a beginner. Could anyone of you be kind enough to explain me this:
So I have this little script, a recursive function that takes a decimal number and converts it to a binary one:
#include <stdio.h>
void binary(int num)
{
if (num == 0) return;
binary(num / 2);
printf("%d", num % 2);
}
int main()
{
int n;
scanf("%d", &n);
binary(n);
return 0;
}
Now I was wondering, how does this function work? I know the logic behind it and whats its supposed to do, but I don't know how it does IT. The printf in the bottom is especially throwing me off, for example if the printf function is before the recursive call, for the input decimal 10 it prints out (0101) but if its under it it prints out the correct binary number (1010)?
Any kind of help is greatly appreciated, kind regards.
The reversal is done using the call stack of the functions. By that I mean that the way the functions are called, this guarantess that the MSB will be printed first then the next one and so on.
void binary(int num)
{
if (num == 0) return;
binary(num / 2); // Wait, I will print but you first print the MSB's.
printf("%d", num % 2); // Now I print the last digit.
}
Downward motion moves the calls.
{binary(12)
{binary(6)
{binary(3)
{binary(1)
binary(0) -- returns
Now we print 1
}
print 1
}
prints 0
}
prints 0
}
If one wants to print recursively the bits of a char with leading zeros,
he may use following code:
#include <stdio.h>
void print_bit_iter(char x, int n)
{
int bit = (x & (1 << n - 1)) != 0;
printf("%d", bit);
if(n != 0)
print_bit_iter(x, n - 1);
}
int main()
{
print_bit_iter('U', 8);
}
This will have
01010101
as the output.
I've been asked to write a void function in c(no loops), that gets an even number(lets say 80), and prints it like this
2*2*5*2*2
As you can see the result is 80 lol.
Between 2 numbers you need to print "*", and the odd number(for my example,5) you need to print it in the middle, or if there is an odd numbers of "2" in the number, lets say 96 you need to print it like that:2*2*2*3*2*2
If the given number is odd, return the number.
I whould like to get not only te answer, but the way you "think" before starting to code.
Here is what i got so far
if(n%4==0)
{
printf("2*");
PrintTwos(n/4);
return;
}
if(n%2==0)
{
printf("*2");
PrintTwos(n/2);
return;
}
printf("%d",n);
here is some pseudo code:
func(nbr)
isOdd(nbr) // recursive stop condition
print nbr
return
evenNbr = findFirstEven(nbr) //return the shortest even number from nbr
print evenNbr
func(nbr / evenNbr)
I didn't add logic for the * printing because i'm sure u can figure that about by yourself. And one case will break that pseudo code, but that's a good start to help you thinking about what your recursive function should do.
EDIT following comments: (NOT COMPLETE : odd number in the middle is missing in this)
int findFirstEven(nbr, i) {
if (nbr%i != 0)
return findFirstEven(nbr, i++);
return i;
}
int primefact(int n)
{
int i=2;
i = findFirstEven(n, i);
printf("%d*", i);
if(n==i)
printf("1");
return 0;
else
primefact(n/i);
}
(not tested)
You need to distribute 2's in halves, so you need to remove two twos from the number before the recursive step – otherwise the recursive step would have to know how deep it is to keep from printing too many twos on the left side.
Of course you must verify if there actualy are two twos!
So:
void PrintTwosInNumber(unsigned n)
{
if(n % 4 == 0)
{
printf("2*");
PrintTwosInNumber(n/4);
printf("*2");
}
else if(n % 2 == 0)
{
printf("2*");
PrintTwosInNumber(n/2);
}
else
printf("%u", n);
}
You can save the last recursive step with
void PrintTwosInNumber(unsigned n)
{
if(n % 4 == 0)
{
printf("2*");
PrintTwosInNumber(n/4);
printf("*2");
}
else if(n % 2 == 0)
printf("2*%u", n/2);
else
printf("%u", n);
}
Edit:
Please note the function will fall into an infinite recursion for n==0 – zero is infinitely divisible by 2. However, zero can not be represented as a product of any number of 2's and some odd numer, so it is out of scope of this problem.
Anyway if it was a real programming task, one should take that special case into account and add a protecting if(n==0) return; branch, just to be on the safe side if a caller passes a wrong parameter value.