#include <stdio.h>
int FAC(int a)
{
if (a >= 1, a--)
{
return a + 1 * a;
FAC(a);
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
printf("%d\n", ret);
}
if I input 5 the outcome is 8
But in the first function should't it be
5>=1 5-1 return 5*4 4>=1...
First of all, you're returning a value before you're using recursion. The return keyword takes effect immediately, so all statements following this won't be executed.
Also, your factorial function does not actually calculate the factorial of a.
Examples for factorial functions:
Recursive
int factorial(int n) {
if(n > 0) {
return n * factorial(n - 1); // n! = n * (n-1) * (n-2) * ... * 1
} else {
return 1;
}
}
Iterative
// Does exactly the same, just an iterative function
int factorial(int n) {
int fac = 1;
for(; n > 0; n--) {
fac *= n;
}
return fac;
}
Your factorial function (FAC) should ideally be something like:
unsigned int FAC(unsigned int a)
{
// base condition - break out of recursion
if (a <= 1)
return 1;
return a * FAC(a - 1);
}
unsigned int restricts range of argument to be in [0, UINT_MAX].
Do note that FAC returns a unsigned int, so you may be able to provide argument value up to 12, else there will be an overflow and you can see weird output.
BTW, UINT_MAX is defined in limits.h
#include <stdio.h>
int FAC(int a)
{
if (a < 0) {
return -1;
} else {
if (a == 0) {
return 1;
} else {
return (a * FAC(a-1));
}
}
}
int main()
{
int a = 0;
int ret = 0;
scanf("%d", &a);
ret = FAC(a);
if (ret == -1) {
printf("%s\n", "Input was a negative integer.");
} else {
printf("%d\n", ret);
}
}
Related
I tried to write a code to check if a number is a perfect square, but I'm not able to call the function I defined. Where is my mistake?
#include <stdio.h>
#include <math.h>
int isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success");
break;
} else {
continue;
}
}
printf("Fail");
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", n);
isPerfectSquare(n);
return 0;
}
I don't get any answer ("Success" or "Fail").
You must pass the address of n instead of its value in scanf("%d", n);:
scanf("%d", &n);
Note however that your function will print both Success and Fail for perfect squares because you should return from the function instead of just breaking from the loop upon success.
Here is a modified version:
#include <stdio.h>
void isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success\n");
return;
}
}
printf("Fail\n");
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
isPerfectSquare(n);
}
return 0;
}
Note also that your method is quite slow and may have undefined behavior (and produce false positives) if i becomes so large that i * i exceeds the range of type int. You should instead use a faster method to figure an approximation of the square root of n and check if the result is exact.
It is also better for functions such as isPerfectSquare() to return a boolean value instead of printing some message, and let the caller print the message. Here is a modified version using the Babylonian method, also known as Heron's method.
#include <stdio.h>
int isPerfectSquare(int number) {
int s1 = 2;
if (number < 0)
return 0;
// use the Babylonian method with 10 iterations
for (int i = 0; i < 10; i++) {
s2 = (s1 + number / s1) / 2;
if (s1 == s2)
break;
s1 = s2;
}
return s1 * s1 == number;
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
if (isPerfectSquare(n)) {
printf("Success\n");
} else {
printf("Fail\n");
}
}
return 0;
}
'I need to calculate and print an upside down pascal triangle, so I wrote down 2 functions for factorial and for the nCr, and I have followed, the equation x! / (y! * (x - y)!)'
#include <stdio.h>
#include <stdlib.h>
int Factorial (int value)
{
if (value == 1 || value == 0)
{
return 1;
}
return value*Factorial(value - 1);
}
int nCr(int value, int r)
{
return Factorial(value)/(Factorial(r) * Factorial(value - r));
}
int main(int argc, char **argv)
{
int value, i, j, k;
char* p;
value = strtol(argv[1], &p, 10);
if (*p != '\0')
{
return 1;
}
if (argc != 2)
{
return 1;
}
if (value < 1 || value > 20)
{
printf("Error: Please enter a value between 1 and 20 inclusively\n");
return 1;
}
else
'The problem is supposed to be in the nested loops I guess'
{
for (i = value - 1; i >= 0; i--)
{
for (j = value - i; j > 0; j--)
{
printf(" ");
}
for (k = 0; k <= i; k++)
{
printf("%d ", nCr(i, k));
}
printf("\n");
}
}
return 0;
}
The problem was in the declaration of the Factorial functions, as int type would overflow if the input is more than 13!, so we should declare the Factorial function as long, so that it does not overflow.
int main()
{
int i,n;
printf("Enter the number");
scanf("%d",&n);
i=pali(n);
if(n==i)
printf("Number is pall");
else
printf("Not Pall");
}
int pali(int n)
{
int r;
static sum=0;
if(n!=0)
{
r=n%10;
sum=sum*10+r;
pali(n/10);
}
return sum;
}
I used a static variable to add up the sum. Is there any way where no static variable will be used?
Yes, the typical ("functional") approach is to carry the state in the form of a function argument. This often makes it necessary/nice to have a second function that does the actual recursion, which you can start by calling with the proper initial values for the state:
int do_pali(int sum, int n)
{
if(n != 0)
{
const int r = n % 10;
return do_pali(10 * sum + r, n / 10);
}
return sum;
}
the public function then just becomes:
int pali(int n)
{
return do_pali(0, n);
}
In languages with inner functions this can be more neatly expressed (GCC supports this as an extension).
Sure, you can do it this way :
#include <stdio.h>
int pali(int n)
{
int sum = 0;
int keeper = 0;
for (int i = n; i > 0; i /= 10) {
if (keeper != 0) {
sum *= 10;
sum += (keeper - i * 10);
}
keeper = i;
}
sum *= 10;
sum += keeper;
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Using recursion is even easier :
#include <stdio.h>
int pali(int n, int sum)
{
sum += n - ((n / 10) * 10);
n /= 10;
if (n > 0)
pali(n, sum * 10);
else
return sum;
}
int main(int argc, char** argv)
{
int i, n;
printf("Enter the number : ");
scanf("%d",&n);
i = pali(n, 0);
if(n == i)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
And a recursive version with only one parameter :
#include <stdio.h>
int pali(int n)
{
int fUnit, lUnit;
fUnit = n;
int mul = 1;
while (fUnit > 10) {
fUnit /= 10;
mul *= 10;
}
lUnit = n - ((n / 10) * 10);
n -= (fUnit * mul);
n /= 10;
if (mul == 1) return 1;
else if (fUnit == lUnit) return pali(n);
else return 0;
}
int main(int argc, char** argv)
{
int n;
printf("Enter the number : ");
scanf("%d",&n);
if(pali(n) == 1)
printf("Number is palindrome");
else
printf("Not Palindrome");
}
Since your function returns sum you could replace this line:
pali(n/10);
with
sum=pali(n/10);
You'd also have to move it up a line too.
Here is an optimized version that
Doesn't use local static.
Only includes stdio.h
Uses recursion.
#include <stdio.h>
static void perform_useless_recursion (int n)
{
if(n--)
{
perform_useless_recursion(n);
}
}
_Bool is_pali (int n)
{
perform_useless_recursion(1);
int sum = 0;
for(int i=n; i!=0; i/=10)
{
sum = sum*10 + i%10;
}
return n == sum;
}
int main (void)
{
int n=5005;
if(is_pali(n))
printf("Number is pall");
else
printf("Not Pall");
return 0;
}
The code could be improved even further by removing the perform_useless_recursion() function.
The advantage of this code is that the actual calculation is performed by a fast loop, instead of slow, dangerous recursion. In the real world outside artificial school assignments, there is no reason to write inefficient and dangerous code when you could write efficient and safe code. As a bonus, removing recursion also gives far more readable code.
If you benchmark this code you'll notice that it will be faster than all other versions posted and consumes less memory.
You can make a function that check only the first and the last digits of the number and pass the rest of the number onward.
To explain better, think about the following cases:
pali(1220) would check for the first (1) and last (0) digits. Since 1 != 0 pali would return false.
pali(17891) would check first (1) and last (1). Since they're equal then the function would recursively return pali(789) (which itself would return false since 7 != 9).
pali(878) would check that 8=8 and recursively return pali(7)
pali(3) would check that first (3) and last (3) numbers are equal and return 0.
The challenge here is to develop an algorithm that:
Check if first and last numbers are the same (even if it's only one digit!)
Strip the number from first and last digits and call itself on the remainder
Then all you need to do is apply recursion. Here's a sample implementation:
int pali(int number)
{
int smallDigit, bigDigit;
/* When recursion ends suceffuly*/
if (number == 0)
return 1;
/* Check for first and last digit of a number */
smallDigit = number % 10;
bigDigit = number;
while(bigDigit/10!=0)
{
bigDigit = bigDigit/10;
smallDigit = smallDigit*10;
}
/* Check to see if both digits are equal (Note: you can't use smallDigit here because it's been multiplied by 10 a few times) */
if (bigDigit != number%10)
return 0;
else
{
number = (number - smallDigit)/10; /* This is why smallDigit was multiplied by 10 a few times */
return pali(number); /* Recursion time */
}
}
I want to do a void factorial function in C that uses pointers. This is my code but it won't run.
#include <stdio.h>
void factorial(int, int*);
int main()
{
int n;
int r = 0;
printf("Enter n : ");
scanf("%d", &n);
if (n < 0)
{
printf("No factorial for negative");
}
else
{
factorial(n , &r);
printf("factorial of %d is %d", n, r);
}
}
void factorial(int n , int *r)
{
if (n == 0 || n == 1)
{
*r= 1;
}
else
{
*r= n* factorial((n-1), r);
}
}
The error I get is in the last line of the code saying : invalid operands of type "int" and "void" to binary operator * , what does that mean and how to fix it?
Well, if factorial() returns void (which is basically , returning nothing) , this line does not make any sense
*result = num * factorial ((num-1), result);
It's because factorial() returns void.
Try:
factorial((num-1), result);
*result= num *(*result);
Instead of that line.
You cannot use return value of a function if it is declared to return void.
If you want to declare function this way then your factorial function can be:
void factorial(int num , int *result)
{
if (num == 0 || num == 1)
{
//*result = 1;
return;
}
else
{
*result *= num;
factorial ((num-1), result);
}
But also in main function you should change int res = 0 into int res = 1.
void Factorial(int *a,int *result){
if (*a == 0 || *a == 1){
return;
}
else{
*result *= *a;
*a -= 1;
Factorial(a,result);
}}
I'm taking a course in C (it's my first week) and I need to write a program that prints out sequences of hailstone numbers.
I'm expected to build a function to do that.
The next number gets printed out but that's it. For example when I enter 58, I get 29. But I'd like to print out a whole sequence of 9 next numbers.
Please, if you could guide in the right direction, I'd be eternally grateful.
#include <stdio.h>
#include <stdlib.h>
int Hailstone (int n)
{
if (n % 2 == 0) {
return n /= 2;
}
else {
return n = 3 * n + 1;
}
return n;
}
int main (void)
{
int start, result;
printf("Input a number: ");
scanf("%d", &start);
result = Hailstone(start);
printf("%d\n", result);
return 0;
}
What you want is to iterate. You don't need the result variable; you just plug in the new value:
while (start > 1) {
start = Hailstone(start);
printf ("%d\n", start);
}
There's a bit more that could be improved, e.g. the return n; is unreachable and the assignments to n are useless:
int Hailstone (int n)
{
if (n % 2 == 0) {
return n / 2;
}
else {
return 3 * n + 1;
}
}
If you want to hand in a pro C version of Hailstone() you could even write it as
int Hailstone (int n)
{
return n % 2 ? 3 * n + 1 : n / 2;
}
see, in your program, you are trying to return only a single value to the main..Hence to print all the numbers just write a loop as below..
#include <stdio.h>
#include <string.h>
int Hailstone(int n)
{
if(n % 2 == 0) {
return n /=2;
}
else {
return n = (3 * n) + 1;
}
}
int main (void)
{
int start;
printf("Input a number: ");
scanf("%d", &start);
while(start!=1)
{
start = Hailstone(start);
printf("%d\n", start);
}
}