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;
Related
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!)
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.
I have some problem with that. I am trying to learn C programming. Please help me
#include<stdio.h>
int main()
{
int a, factorial;
printf("Please enter a value :" );
scanf("%d", &a);
for (int i = 1; i<=a; i++)
{
a = (a - 1)*a;
}
printf("%d", factorial);
return 0;
}
Well in your code line a = (a - 1)*a; you actually changed your input for getting the factorial. It also will blow your loop. See your for loop will continue as long as your i is less than a, lets say you choose a=3 after first iteration the a itself will become 6, so the for loop will continue until it reach the integer limit and you will get overflow error.
What you should do?
First of all you should use a second variable to store the factorial result, you introduced it as factorial, the way that #danielku97 said is a good way to write a factorial since if you present 0 as input it will also give the correct result of 1. so a good code is:
factorial = 1;
for (int i = 1; i<=a; i++)
{
factorial *= i;
}
But lets say you insist of subtraction, the way you just tried to use, then you need to change the code like:
scanf("%d", &a);
if (a==1 || a==0){
printf("1");
return 0;
}
factorial = a;
for (int i = 1; i<a; i++)
{
factorial *= (a - i)*factorial;
}
You can see that the code just got unnecessarily longer. An if included to correct the results for 1 and 0. Also you need to make sure that i never become like i =a since in that case a-i will be equal to zero and will make the factorial result equal to zero.
I hope the explanations can help you on learning C and Algorithm faster.
Your for loop is using your variable 'a' instead of the factorial variable and i, try something like this
factorial = 1;
for (int i = 1; i<=a; i++)
{
factorial *= i;
}
You must initialize your factorial to 1, and then the for loop will keep multiplying it by 'i' until 'i' is greater than 'a'.
You are modifying the input a rather than factorial and also wrong (undefined behaviour) because you are using factorial uninitialized. You simply need to use the factorial variable you declared.
int factorial = 1;
...
for (int i = 1; i<=a; i++) {
factorial = i*factorial;
}
EDIT:
Also, be aware that C's int can only hold limited values. So, beyond a certain number (roughly after 13! if sizeof(int) is 4 bytes), you'll cause integer overflow.
You may want to look at GNU bugnum library for handling large factorial values.
I would like to find all the primes within 100. Here is my codes.
// Find all the prime number within 100.
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
int main() {
int i,n;
int j = 0;
for ( n = 2; n <= 100; ++n) {
bool isPrime = true;
for (i = 2; i <= sqrt(float(n)); ++i) {
if(n % i == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
++j;
printf("%d is a prime number\n",n);
}
}
printf("The total number of prime number within 100 is %d\n",j);
return 0;
}
When compile it, there is one error.
prime.c:14:8: error: expected expression before ‘float’
m = float(n);
^
Could anyone help solve this problem? Thanks.
You're using the wrong syntax when casting (you're using one of C++'s many styles of casting, but for C there is only one way). Change:
sqrt(float(n))
to
sqrt((float)n)
Note however that sqrt takes a double, so strictly speaking this should be:
sqrt((double)n)
Note also that the cast is not necessary, and you can just write:
sqrt(n)
Change this
sqrt(float(n))
to this
sqrt((float)n)
You want to cast n to float.
You should use this function:
float sqrtf (float x);
which in C99 receives a float as an argument. Otherwise, it would be better to cast into double (if you use sqrt()).
sqrt-ref
What you have written:
float(n)
is like saying that float is a name of a function and you pass to it the parameter n.
Notice, that in your case, you don't need casting, since it's going to be performed automatically (to float if you use sqrtf() or to double if you use sqrt()).
Other notes, irrelevant with your syntax error.
Why not start the loop from 3 and increase the counter by two? If you think about it, this will faster and will produce the same results. If you want to test yourself, check my example here.
Also, what I had found pretty exciting when I was searching for primes, is the sieve of Eratosthene's (Κόσκινο του Ερατοσθένη) . Here is an example of it.
If you want to cast n to a float, use (float)n.
Just do:
sqrt(n);
You'll be having the exam same result as the casting for your case.
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;
}