Recursive Function equation - c

Forewarning, this is a homework assignment.
I am supposed to create a recursive function but I am doing this wrong. When I enter a 4 I am supposed to get a result of 16 from f(x) but I get -2. I don't really understand where I went wrong. Also I don't know if I am supposed to print my results inside of main or in f.
Write a program that queries the user for an integer value and uses a recursive
function that returns the value of the following recursive definition:
f(x) =x+3 if x <=0
f(x)=f(x-3)+(x+5) otherwise
My attempt:
#include <stdio.h>
int f(int x); //Prototype to call to f
int main(void) {
int n; //number the user will input
//Ask user to input data an reads it
printf("Enter a whole number: ");
scanf("%d", &n);
//Pointer for f
f(n);
//Prints results
printf("\nn is %d\n", n);
printf("f(x) is %d\n", f(n));
return 0;
}
int f(int x) {
//Checks if equal to zero
if (x <= 0) {
x + 3;
}
//If not equal to zero then do this
else {
f(x - 3) + (x + 5);
}
}
Thank you all for the help, learned a lot from your comments and suggestions.
I was able to get it work I believe https://pastebin.com/v9cZHvy0

as far as I can see first one is scanf
scanf("%d", &n);
second one is your function f is not returning anything, so this
int f(int x) {
//Checks if equal to zero
if (x <= 0)
{
return (x + 3);
}
return ( f(x-3) + (x+5) );
}
minor - the below statement is actually useless
//Pointer for f
f(n);

As a student of life, I am always willing to help a fellow academic:
Your code has a few errors that should be of note:
int f(int x) has no return statement, even though it is expecting an integer. I assume you wish to return the result of the program (See Issue #3).
You execute f(n) twice. First on line 12, then again on line 16. printf("f(x) is %d\n", f(n)); actually executes F(n) in order to receive its return value to associate with the %d format specifier.
You have not assigned x+3 OR f(x-3) + (x+5) to any integer. These statements do not save the return values of f(x) that you need to return.
This link may be of help to you:
https://www.geeksforgeeks.org/c-function-argument-return-values/
Notice specifically how the output of functions are captured.
Hope this helps (And I wish you academic success!)

Related

Writing a recursive function in C

I am studying how to program and have recently been working on a problem that calculates the total of 2 entered numbers from min to max. For example, if someone entered the numbers 4, 7. The calculation would be 4+5+6+7=22.
I've attempted what i think would be the definition of recSum but obviously it is wrong as I get a segmentation fault. What is wrong with my definition?
/* Define the recursive function */
int recSum (int x, int max)
{
int incrementalSum = 0;
if (x == max)
{
return x; /* Exit if summated lower to upper numbers */
}
else
{
return (x + recSum(x++, max)); /* My recursive call */
}
} /* End of function call */
*new code is shown above, sorry, i used the wrong code.
Your code has 3 important problems
The expression
incrementalSum = x + x++;
is undefined, read this for more information
Your function is not recursive, a recursive function calls it self until a condition happens where it should end.
Also, noting that I am not an irrational "don't ever use goto person", this is precisely why some people advice against using goto.
The reason your code doesn't work is this line:
return x + recSum(x++, max);
x++ increments x but returns the previous value, so in the recursive calls it never increments and you never reach the base case. Like an infinite loop. You have to replace x++ with ++x in order to give any result, even though it won't be correct. ++x is modifying x so it will alter the final sum of x + recSum. You'd better use:
return x + recSum(x + 1, max);
See What is the difference between ++i and i++?
It seems you mean the following
int recSum(int x, int max)
{
return max < x ? 0 : x + recSum( x + 1, max );
}
Or it would be even better to declare the return type of the function like long long int.
long long int recSum(int x, int max)
{
return max < x ? 0 : x + recSum( x + 1, max );
}
The function can be called like
printf( "%lld\n", recSum( 4, 7 ) );
As for your function then it exits in the first call
int recSum(int x, int max)
{
int incrementalSum = 0;
recCall: if (x < max)
return incrementalSum;
^^^^^^^^^^^^^^^^^^^^^
because usually it is called when x is less than max. So the function does not make sense. Moreover the function is not recursive because it does not call itself.

Error when using array elements in conditional statements in C

I have done my fair share of studying the C language and came across this inconsistency for which I cannot account. I have searched everywhere and reviewed all data type definition and relational syntax, but it is beyond me.
From the book C How to Program, there is a question to make a binary to decimal converter where the input must be 5-digits. I developed the follow code to take in a number and, through division and remainder operations, split it into individual digits and assign each to an element in of an array. The trouble arises when I try to verify that the number entered was indeed binary by checking each array element to see whether it is a 1 or 0.
Here is the code:
#include <stdio.h>
int power (int x, int y); //prototype
int main(void)
{
int temp, bin[5], test;
int n=4, num=0;
//get input
printf("%s","Enter a 5-digit binary number: ");
scanf("%d", &temp);
//initialize array
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
//verify binary input
for (test=4; test>=0; test--){
if ((bin[n]!=0)&&(bin[n]!=1)){
printf("Error. Number entered is not binary.\n");
return 0; }
//convert to decimal
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
printf("\n%s%d\n","The decimal equivalent of the number you entered is ",num);
return 0;
}
//function definition
int power(int x, int y)
{
int n, temp=x;
if(y==0) return 1;
for(n=1; n<y; n++){
temp*=x; }
return temp;
}
Could someone explain to me why regardless of input (whether: 00000, or 12345), I always get the error message? Everything else seems to work fine.
Thank you for your help.
Update: If the if statement is moved to the while loop before. This should still work right?
Update2: Never mind, I noticed my mistake. Moving the if statement to the while repetition before does work given the solution supplied by sps and Kunal Tyagi.
After this
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
n is set as -1 so when you try to convert to decimal the statement bin[n] is actually bin[-1] so it returns you error.
One issue is that, while checking if the number is binary or not, you are returning at wrong place. You need to return only if the number is not binary. But you are returning outside the if condition. So your program returns no matter what the input is.
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1))
printf("Error, numbered entered was not binary.\n");
// Issue here, you are returning outside if
return 0; } //exit program
You can change that to:
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1)) {
printf("Error, numbered entered was not binary.\n");
// Return inside the if
return 0; // exit program
}
}
There is one more issue. Before you convert your number to decimal, you need to set n = 0;
//convert to decimal
n = 0; /* need to set n to zero, because by now
n will be -1.
And initially when n is -1, accessing
bin[-1] will result in undefined behavior
*/
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
This looks like a homework, but your issue is in the brackets. More specifically line 23. That line is not part of the logical if statement despite the indentation (since that doesn't matter in C).
No matter what, the program will exit on test=4 after checking the condition.
Solution:
if ((bin[test]!=0)&&(bin[test]!=1)) { // << this brace
printf("Error, number entered was not binary.\n");
return 0; } } //exit program // notice 2 braces here

Getting output from recursion manually in C

So, I have two questions.
Question 1) I find recursion difficult in C. And I have this one question, that I dont know how should I go about attempting it. I want to know its output, Please help me.
#include <stdio.h>
void fun (int);
int main (void)
{
int a;
a = 3;
fun(a);
printf("\n");
return 0;
}
void fun ( int n )
{
if ( n > 0 )
{
fun(--n);
printf("%d",n);
fun(--n);
}
}
How can I solve this recursion manually?
I know during recursion, the information is stored on stack. Therefore, I tried doing it by that way. Firstly, a will be decremented all the way upto 0. But then, it will exit out of the loop. So, when will it print the values?
Question 2) Also, I Wanted to know since the topic I am studying right now is functions. If I make a function and lets suppose it returns some value, then IS IT MANDATORY that I collect its value upon calling or I can call it without collecting its return value?
For eg: Let's say I made the function as,
int foo ( int a )
{
........
return b;
}
Now, if I call this function from inside main, then is it mandatory that I store the returned value in some variable?
You had 2 questions: the first one is what happens in your code:
To your question #1: Function fun(n) could be rewritten so that it is functionally equivalent but easier to understand, as:
void fun(n) {
if (n > 0) {
fun(n - 1);
printf("%d", n - 1);
fun(n - 2);
}
}
That is:
for fun(n)
if n > 0,
first call fun(n - 1)
then print the number n - 1
lastly call fun(n - 2)
Thus the following happens when unwinding the recursion:
fun(3) ->
fun(2) ->
fun(1) ->
fun(0) ->
n <= 0 -> exits
prints 0
fun(-1) ->
n <= 0 - exits
prints 1
fun(0) ->
n <= 0 - exits
prints 2
fun(1) ->
fun(0) ->
exits as n <= 0
prints 0
fun(-1) ->
exits as n <= 0
Execution goes from up to down sequentially - thus the output 0120 from the prints lines.
Question #2:
No, return value does not need to be stored in a variable. In fact, the printf you used returns an int, that tells the number of characters written, but you did not store that return value anywhere.
For no 1 - Get a note pad and a pencil.
Start off an write fun(3) - It is in Main.
You can now cross that out an instead write
if ( 3 > 0 )
{
fun(2);
printf("%d",2);
fun(1);
}
(applying the logic of --n)
Repeat with both of those fun. You can do the leg work on this one
Number 2 - You do not have to collect the return value from a function
I would like to answer your second question About storing the value returned by the called function.
The answer returned by the called function can be displayed in two ways..
No.1-You need not store it in any variable in the calling function and print it directly as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, b=9, add(int,int);
printf("Sum of %d and %d is : %d",a,b,add(a,b));
getch();
}
int add(int m,int n)
{
return(m+n);
}
Here,the function call has been written in the printf() function and hence the need of an extra variable has been eliminated
No.2-The other way and the code for the same-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a=10,b=9,c,add(int,int);
c=add(a,b);
printf("Sum of %d and %d is : %d",a,b,c);
getch();
}
int add(int m,int n)
{
return(m+n);
}
So,you do need a variable for the second method.Because there has to be something to catch the value thrown by the called function

Incorrect output from recursive function to compute sum of digits of a number

I was trying to write a function that would compute the sum of the digits of a number using recursion, but the output is incorrect. Here's the code:
/*Write a function to calculate sum of digits of a number using recursion*/
/*Author:Udit Gupta Date:10/08/2011*/
#include<stdio.h>
int sum (int);
int main () {
int n,s;
printf ("Enter the number:");
scanf ("%d",&n);
s = sum (n);
printf ("The sum of the digits of the number is %d",s);
}
int sum (int a) {
int f;
if (a == 0) {
return f;
}
f = (a% 10) + sum (a/10);
}
Here are some of the output values:
udit#udit-Dabba ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:123
The sum of the digits of the number is 7
udit#udit-Dabba ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:1234
The sum of the digits of the number is 2919930
udit#udit-Dabba ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:123456
The sum of the digits of the number is 4620297
udit#udit-Dabba ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:12345
The sum of the digits of the number is 15 /*Only this one seems correct*/
Can someone help me figure out why this isn't working correctly?
Let's look at this recursive function in more detail:
int sum (int a) {
int f;
if (a == 0)
return f;
f = (a% 10) + sum (a/10);
}
While you're on the right track and you have the right idea in general, your actual implementation is a bit buggy. For starters, let's look at these lines:
if (a == 0)
return f;
You have the right idea to terminate the recursion when a reaches zero, but the way you're doing it is a bit off. In particular, you're returning the value of the integer f, but you've never initialized it. This means that the return value is completely arbitrary. Instead of writing this, I think that you probably meant to write something closer to
if (a == 0)
return 0;
which correctly says "if the number is zero, the sum of its digits is zero."
Similarly, take a look at the last line of your function:
f = (a% 10) + sum (a/10);
Again, your intuition is spot-on: the sum of the digits of a number are given by the sum of its first digit and the sum of the rest of its digits. However, notice that while you're correctly computing the sum of the digits, you aren't correctly returning the sum of the digits. In fact, you don't return anything at all if you execute this code, so the return value from the function is unspecified, hence the garbage output. To fix this, consider rewriting the code like this:
return (a % 10) + sum (a / 10);
This actually says to hand back the value that you just generated right here, instead of storing it in a local variable that will be immediately cleaned up as soon as the function returns.
I believe that the reason you coded this function this way is that you're under the impression that the value of int f; is carried across the function calls. Unfortunately, it is not. When writing a recursive function, each instance of the function is completely independent of each other instance and local variables accessible in one recursive call are not accessible in other recursive calls. Consequently, even though each recursive call has its own variable int f, those variables are all completely independent of one another. The value isn't carried through them. If you want to communicate values across recursive functions, the best way to do it is by using the return value of the recursive calls, or (if you must) by passing a pointer to some value down through the recursion.
Hope this helps!
When a is 0, you are returning an uninitialized value (f was not initialized).
Change it to:
if (a == 0)
return 0;
You also forgot the return in the end of the function:
return (a% 10) + sum (a/10);
It is highly recommended that you always compile with the flag -Wall, which would warn you about those mistakes.
Your recursive function will calculate nothing it either returns an uninitialized int or nothing. You need to be returning the work you are doing in the function.
int sum (int a) {
if (a == 0) {
return 0;
}
return (a% 10) + sum(a/10);
}
return a == 0 ? 0 : ((a% 10) + sum (a/10));
You only return f is it is 0, but not if it isn't, which makes your return value undefined. I assume you want to do:
int sum (int a) {
int f;
if (a == 0)
return 0;
f = (a % 10) + sum (a / 10);
return f;
}

C Programming: Recursion

so I wrote this simple recursion program and am getting an error when I compile it with GCC
error: lvalue required as left
operand of assignment
Hopefully this isnt anything to serious, any insight is appreciated
THanks!
#include <stdio.h>
int factorial (int);
int main (void)
{
int i = 0;
int a = 0;
printf("Please enter an integer: ");
scanf("%d", &i);
a = factorial (i);
printf("\n\n%d factorial equals: %d \n", i, a);
return 0;
}
int factorial ( int n )
{
if ( n <= 0 )
return 0 ;
else
f(n) = f( n-1) + 2;
}
The following statement is not valid C:
f(n) = f( n-1) + 2;
(I assume this is the line on which you got the error; you didn't say.)
You might want to try the following:
return factorial(n-1) + 2;
but then the name factorial is misleading because that is not the correct formula for the factorial function.
Why are you writing this
f(n) = f( n-1) + 2;
I can't see any function named f().
This is not the correct formula for calculation factorial of any number. Look at Greg's provided link.
Change it to
int factorial (int n)
{
if (n==1||n==0)
return 1;
else
return n*factorial(n-1);
}
The error is with f(n) = f(n+1) in your factorial function. Anything with parenthesis is a function in c and a function cannot be assigned a value. You probably want n = factorial(n+1);
The assignment operator = needs a variable on the left hand side, to which the value on the right hand side is assigned to. You can't assign something to a function, which is what f(n) is according to C syntax. This is assigning a value to lines of code, which makes no sense. The only thing that makes sense on the left hand side of a function is something that can store a value.
Functions can go on the right hand side of the assignment though, as long as they return something (they are not type void).
To get the factorial right you need to think through it a little more... first of all remember that you want the last value to be 1, not zero. And all of the numbers in the factorial are multiplied.
replace f(n) = f( n-1) + 2; with
return n*factorial(n-1)
and yes, 0! is one so add
if(n==0) return 1;

Resources