C language factorial function - c

The code below is running wrong. If I give the function 4 value, it returns the number -861720576. Can you help?
#include <stdio.h>
int fact(int x)
{
if (x<0)
{
return -1;
}
else if (x==0)
{
return 1;
}
else if (x==1)
{
return 1;
}
else
{
for (int i=2;i<x;i++)
{
x*=i;
}
return x;
}
}
int main()
{
printf("%d",fact(4));
return 0;
}
.................................

The loop termination condition is i<x but every time the loop runs, x is getting changed. Note that the termination expression gets evaluated before each iteration of the loop so it will use the latest values of both i and x.

at some point x will reach a number which isn't in the range of an integer. At that point x is gonna get messed up. Also your loop would be endless if x could reach any number.

You're changing the value of x every time. Rather try this.
int final_val = x;
for (int i=2;i<x;i++)
{
final_val *=i;
}
return final_val;

Related

Program that computes the nth element of a number series given by a formula

Write a method/function with name cpSeries that computes the nth element in a series of numbers, given by the formula: a(n) = (a(n-1))2+a(n-2) when: n>1 and assuming that: a(1)=1, a(0)=0 Note that indexing of the series starts from 0.
I have already written the above code but it runs for an infinite time and I don't know how to fix it in order to compute the nth element.
Any ideas? I have to use only functions to solve this problem.
# include <stdio.h>
int cpSeries(int n)
{
int Nthterm = 0;
int i;
if (n==0) {
cpSeries(0) == 0;
}
else if (n==1) {
cpSeries(1) == 1;
}
for (i=0; i<=n; i++){
Nthterm = cpSeries((n-1))*cpSeries((n-1)) + cpSeries((n-2));
return Nthterm;
}
}
int main()
{
int n=6;
printf("The Nth term of the series is: %d",cpSeries(n));
}
If the provided equation gives you the nth element, I don't see the need for a loop.
Also, in the if conditions, you are calling the function again, but what you should do is return the value you need.
int cpSeries(int n){
int Nthterm;
if (n==0){
Nthterm = 0;
}
else if (n==1){
Nthterm = 1;
}
else {
Nthterm = cpSeries((n-1))*cpSeries((n-1)) + cpSeries((n-2));
}
return Nthterm;
}
Your final conditions just call the function another time instead of returning 0 or 1.
instead of
if (n==0) {
cpSeries(0) == 0;
}
else if (n==1) {
cpSeries(1) == 1;
}
use
if (n==0) {
return 0;
}
else if (n==1) {
return 1;
}
C is not a declarative language where you can specify the return value y of a function f given an argument x by writing something like f(x) = y, but you have to use a return statement.
Change cpSeries(0) == 0; to
return 0;
to avoid the infinite recursion (and the same for n == 1).

Recursion code it not working properly what can be the issue here?

Tried a program which prints the first 50 natural number I wrote this code which returns the value using recursion but its not printing anything not returning any values what m I doing wrong here?
#include <stdio.h>
int naturalNumbers(int i)
{
if (i == 1)
{
return 1;
}
else
{
naturalNumbers(i--);
return i;
}
}
int main()
{
printf("%d", naturalNumbers(50));
return 0;
}
below recursion will print numbers in increasing order
void naturalNumbers(int i)
{
if(i<1) return; //base case
naturalNumbers(i-1);
printf("%d ", i);
}
naturalNumbers(50); // call from main function
To avoid creating an endless loop, you should modify your naturalNumbers function as follows:
int naturalNumbers(int i)
{
if (i == 1)
{
return 1;
}
else
{
naturalNumbers(--i);
return i;
}
}
This will decrement the value of i before calling naturalNumbers instead of afterwards as in your version. However, the return value of this original call will always be (i-1). Can you please explain a little bit more about the intent of this function?

Search of an element on a unsorted array recursively

This is an exercise that I took from an exam. It asks to write a function that receives an unsorted array v[] and a number X and the function will return 1 if X is present in v[] or 0 if X is not present in v[]. The function must be recursive and must work in this manner:
1. Compares X with the element in the middle of v[];
2. The function calls itself (recursion!!) on upper half and on the lower half of v[];
So I've written this function:
int occ(int *p,int dim,int X){
int pivot,a,b;
pivot=(dim)/2;
if(dim==0) //end of array
return 0;
if(*(p+pivot)==X) //verify if the element in the middle is X
return 1;
a=occ(p,pivot,X); //call on lower half
b=occ(p+pivot,dim-pivot,X); //call on upper half
if(a+b>=1) //if X is found return 1 else 0
return 1;
else{
return 0;
}
}
I tried to simulated it on a sheet of paper and it seems to be correct (Even though I'm not sure) then I've written it on ideone and it can't run the program!
Here is the link: https://ideone.com/ZwwpAW
Is my code actually wrong (probably!) or is it a problem related to ideone. Can someone help me? Thank you in advance!!!
The problem is with b=occ(p+pivot,dim-pivot,X); when pivot is 0. i.e. when dim is 1.
the next function call becomes occ(p,1,X); This again leads to the call occ(p,1,X); in a continuous loop.
It can be fixed by adding a condition to the call, as shown in the code below.
int occ(int *p,int dim,int X){
int pivot,a=0,b=0;
pivot=(dim)/2;
if(dim==0){
return 0;
}
if(*(p+pivot)==X)
return 1;
if (pivot != 0)
{
a=occ(p,pivot,X);
b=occ(p+pivot,dim-pivot,X);
}
if(a+b>=1)
return 1;
else{
return 0;
}
}
The implemetation is causing a stack overflow, as the recursion does not terminate if the input contains only one element. This can be fixed as follows.
int occ(int *p, int dim, int X)
{
int pivot, a, b;
pivot = (dim) / 2;
if (dim == 0)
{
return 0;
}
if (*(p + pivot) == X)
{
return 1;
}
if (dim == 1)
{
if (*(p + pivot) == X)
{
return 1;
}
else
{
return 0;
}
}
a = occ(p, pivot, X);
b = occ(p + pivot, dim - pivot, X);
if (a + b >= 1)
{
return 1;
}
else
{
return 0;
}
}
It's enought to change only this one line in the source code to avoid the endless loop with occ(p,1,X):
//if(dim==0) //end of array
if (pivot == 0)
return 0;

error: control may reach end of non-void function

This error appeared to me when i was trying to compile a c file which contains a declaration of a linear search function
bool search(int value, int values[], int n)
{
// TODO: implement a searching algorithm
for(int d = 0;d<n;d++){
if(n<0){
return false;
}
else if(values[d]==value){
return true;
}
else{
return false;
}
}
}
What is wrong with my code? Please help.
Some problems with the code:
The method have a path that don't return anything, as commented, when parameter n = negative number or 0
The for-loop don't do anything, will only execute one time and exit for one of the conditions. It would only work correctly when the first element is the element searched, in any other case only check the first element and return (without correct info of present or not). Test with array int values[] = { 1, 2, 3, 4, 5 }; and search 3, your code would not found this value.
If you're searching for a specific value the code is:
bool search(int value, int values[], int n) {
for (int d = 0; d < n; d++) {
if (values[d] == value) {
return true;
}
}
return false;
}
The problem is the argument n passed to the function is n <= 0. The loop never executes and the function finishes without returning any value.
To fix it put the if(n <= 0) statement before the for loop.
If the 'for' loop doesn't get to do any iterations you won't be able to return anything from the function. Maybe add an edge case like
if(n <=0 )
return false;
before the loop.
d is incremented in the for loop until it equals the value of n. At that point, the code beyond the for loop is executed.
Being that there are no instructions beyond the for loop, the function returns to the caller. The error occurs due to there being no (boolean) value returned from the function in this case.
The error can be avoided by following Rule #1 of the Mahonri List Of Rules For Writing Maintainable C Code. Example:
bool search(int value, int values[], int n)
{
bool rCode=false;
// TODO: implement a searching algorithm
for(int d = 0;d<n;d++)
{
if(n<0)
{
goto CLEANUP;
}
else if(values[d]==value)
{
rCode=true;
goto CLEANUP;
}
else
{
goto CLEANUP;
}
}
CLEANUP:
return(rCode);
}

Determine whether an integer is palindrome or not without using extra space

I wrote the following function for finding whether an integer is a palindrome or not without requiring any extra space:
int isPalindrome(int x)
{
int i=0,j,y,z;
if(x<0)
return 0;
for(i=0;;)
{
if((**y**=x/pow(10,i)) > 0) //Variable 'y' here
{
i++;
}
else
break;
}
printf("i=%d\n",i);
for(;i>0;)
{
if(x%10!=(**z**=x/pow(10,i-1))) //variable 'z' here
{
return 0;
}
else
{
x=x%(int)pow(10,i-1);
x=x/10;
i=i-2;
}
}
return 1;
}
Here returning 1 means it is palindrome and 0 means not.
But I found that when I remove the variable y and z from the statements in the code, the code does not give desired result. What may be the reason behind it?
when variables y or z removed than expression type changes from int to double.
type of expression 'x/pow(10,i)' is double
type of expression 'y = x/pow(10, i)' is int
'z = x/pow(10,i-1)' - int
'x/pow(10,i-1)' - double

Resources