I'm working on a factorial sum which goes like: 1/1!+1/2!+1/3!... until the desired count. Here is my code so far:
#include <stdio.h>
int factorial(int n)
{
if (n==0)
return 1;
else
return 1/(n * factorial(n-1));
}
int main ()
{
int i, n;
float sum=0;
printf("Enter desired factorial fraction: ");
scanf("%d", &n);
for (i=1; i<=n; i++) sum = sum + factorial(i);
printf("The value is %f\n", sum);
return 0;
}
I have a small idea of what I'm doing, I am really new at this. My thought process was to set up the number crunching function (My jargon is probably off) and then initiate the main function. I thought I had the right set up, but after a couple hours with this I feel just lost. Any help and guidance will be much appreciated.
Update
Here is the updated code:
#include <stdio.h>
float factorial(int n)
{
if (n==1)
return 1;
else
return ((1.0/n) * factorial(n-1.0));
}
int main ()
{
float i, n;
float sum=0;
printf("Enter desired factorial fraction: ");
scanf("%f", &n);
for (i=1; i<=n; i++) sum = sum + factorial(i);
printf("The value is %f\n", sum);
return 0;
}
So thank you guys, now the only thing left is for me to figure out why my input of "0" does not produce the result "1" since 0!=1. Should I move that if statement inside the "int main()"?
You should use float as the return value of factorial() (you can only get 0 or 1 if you use int) and its logic is not correct.
You need to change it to
float factorial(int n)
{
if (n==0) // or n==1
return 1;
else
return (1.0/n) * factorial(n-1);
}
Full code example can be seen here: http://ideone.com/o2XGhE
your factorial() must be like this
int factorial(double n)
{
if (n==0)
return 1;
else
return ((1/n) * factorial(n-1));
}
The definition of factorial() should be
int factorial(int n)
{
if
(n==0) return 1;
else
return n * factorial(n-1);
}
And in your main() function, you should do something like:
for (i=1; i<=n; i++) sum = sum + 1.0 / factorial(i);
Have a separate function the calculate factorial(n)
than add the rest of the code, so the only recursive thing will be calculation of n!
you can use this one :
int factorial(float n)
{
if (n==1)
return 1;
else
return (1/n) * factorial(n-1));
}
An elegant solution is to use conditional ternary operator:
float factorial(float n) {
return n ? ((1/n) * factorial(n-1)) : 1;
}
Related
I wanted to write a simple program to calculate the factorial of a given number using C. Yet my code seems to have some logical error that I can't detect. Would be glad for help.
int fact(int n);
int main(void)
{
int num = get_int("Type number: ");
printf("%i\n", fact(num));
}
//define function
int fact(int n)
{
for (int i = 1; i < n; i++)
{
n *= i;
}
return n;
}
You can't use n to calculate.
You have to save total with another variable
int fact(int n)
{
int product = 1;
for (int i = 1; i <= n; i++)
{
product = product * i;
}
return product;
}
In mathematics, the factorial of a positive integer N, denoted by N!, is the product of all positive integers less than or equal to N:
N!=N*(N-1)*(N-2)*(N-3)*.......*1
+-------------------------+
notice that this is: (N-1)! <==> So, N! = N*(N-1)!
we can use these mathematical facts to implement the factorial function in 2 different forms, recursive and iterative approaches:
recursive approach
size_t rec_factorial(size_t n)
{
/*Base case or stopping condition*/
if(n==0)
{
/* 0! = 1 */
return 1;
}
/*n! = n * (n-1)!*/
return n * rec_factorial(n-1);
}
iterative approach
size_t factorial(size_t n)
{
size_t j = 1;
size_t result = 1;
while(j <= n){
result *= j; /* n!=n*(n-1)*(n-2)*(n-3)*....1 */
++j;
}
return result;
}
I have to calculate the arithmetic and geometrical mean of numbers entered by the user in C language. The algorithm works fine, but I don't know how to do the enter numbers until 0 is pressed part. I have tried many things but nothing works. Here is what I have tried to do until now. Thanks for the help.
int main() {
int n, i, m, j, arr[50], sum = 0, prod = 1;
printf("Enter numbers until you press number 0:");
scanf("%d",&n);
while (n != 0) {
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum = sum + arr[i];
prod = prod * arr[i];
}
}
int armean = sum / n;
float geomean = pow(prod, (float)1 / n);
printf("Arithmetic Mean = %d\n", armean);
printf("Geometric Mean = %f\n", geomean);
getch();
}
Your code is asking for the number of values in advance and subsequently reading that many values. That's not what you were asked to do.
You need to ask for numbers in a loop and exit the loop when the number that you read is 0. You don't even need an array:
int n = 0, i, m, j, sum=0, prod=1;
while (1) {
int value;
scanf("%d",&value);
if (value == 0) {
break;
}
sum=sum+value;
prod=prod*value;
n++;
}
int armean=sum/n;
float geomean=pow(prod,(float) 1/n);
You have to break the for loop when value 0 entered; so you should check for arr[i].
While loop is not required.
Please go through below code; this could be help full:
#include <stdio.h>
int main()
{
int n, i, m, j, arr[50], sum=0, prod=1;
printf("Enter numbers until you press number 0:");
for(i=0; i<50; i++)
{
scanf("%d",&arr[i]);
if (arr[i] == 0)
{
break;
}
sum=sum+arr[i];
prod=prod*arr[i];
}
printf ("%d %d\n",sum, prod);
n = i+1;
int armean=sum/n;
float geomean=pow(prod,(float) 1/n);
printf("Arithmetic Mean = %d\n",armean);
printf("Geometric Mean = %f\n",geomean);
getch();
return 0;
}
what dbush said is right, you don't need array and are not asking the number in advance but what he did not tell is how can you find the number of values
int main()
{
int n, sum=0, prod=1, num;
printf("Enter numbers until you press number 0:\n");
for(n=0; ; n++)
{
scanf("%d",&num);
if(num==0)
break;
sum=sum+num;
prod=prod*num;
}
printf("sum is %d \n",sum);
printf("prod is %d \n",prod);
printf("n is %d \n",n);
float armean=sum/n; //why int?
float geomean=pow(prod,(float) 1/n);
printf("Arithmetic Mean = %d\n",armean);
printf("Geometric Mean = %f\n",geomean);
//getch(); why getch(), you are not using turboc are you?
}
There is no need for an array, but you should test if the number entered in 0 after reading it from the user. It would be better also to use floating point arithmetic to avoid arithmetic overflow, which would occur quickly on the product of values.
In any case, you must include <math.h> for pow to be correctly defined, you should test the return value of scanf() and avoid dividing by 0 if no numbers were entered before 0.
#include <stdio.h>
#include <math.h>
int main() {
int n = 0;
double value, sum = 0, product = 1;
printf("Enter numbers, end with 0: ");
while (scanf("%lf", &value) == 1 && value != 0) {
sum += value;
product *= value;
n++;
}
if (n > 0) {
printf("Arithmetic mean = %g\n", sum / n);
printf("Geometric mean = %g\n", pow(product, 1.0 / n));
getch();
}
return 0;
}
I wish to write a program which calculates the series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) by taking x and n as user inputs.
This is what i've tried, and well there's no output when I enter the values for x,n:
#include<stdio.h>
#include<math.h>
//#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
double x,n,res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%lf%lf",&x,&n);
/*if(n%2!=0)
{
printf("Please enter a positive value!\n");
exit(0);
}*/
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n %lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r,fact,exec;
for(i=1;i<=t;i+2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1.0;
while(p>0)
{
f*=p;
p--;
}
return f;
}
When I enter values for x and n, it simply shows nothing.
While I've written in C, C++ solutions are also appreciated.
Output window in code::blocks
The loop
for(i=1;i<=t;i+2)
in the function series() is an infinite loop when t >= 1 because i isn't updated in the loop. Try changing + to += and use
for(i=1;i<=t;i+=2)
instead. Also it seems you should use type int for x and n in the function main() because the arguments of series() is int. Don't forget to change the format specifier when changing their types.
Thanks to all those who helped. Here's the final working code:
#include<stdio.h>
#include<math.h>
#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
int x,n; double res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%d%d",&x,&n);
if(n%2==0)
{
n=n-1;
}
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n%lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r=0.0,fact,exec;
for(i=1;i<=t;i+=2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1;
while(p>0)
{
f*=p;
p--;
}
return f;
}
in loop we step by two for getting odd numbers.by multiplying the current temp variable by the previous temp variable in the loop with neccesary terms like x square and dividing by i*(i-1) i.e for factorial and multiply with -1 i.e to achive negavtive number alternatively. by using this temp variable and adding it to sum variable in every iteration will give us answer.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, x;
cout << "enter x and no.of terms: ";
cin >> x >> n;
float sum = 0, temp = x;
for (int i = 3; i < 2 * n + 2; i = i + 2)
{
temp = ((-1 * temp) *(x*x)) / i*(i-1);
sum = sum + temp;
}
cout << x + sum;
return 0;
}
// series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)
#include<stdio.h>
#include<math.h>
double factorial (int);
double calc (float, float);
int
main ()
{
int x, deg;
double fin;
printf ("x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf ("Enter value of x\n");
scanf ("%d", &x);
printf ("highest degree in denom i.e., 1 or 3 or 5 whatever, it should be odd .\n");
scanf ("%d", °);
fin = calc (x, deg);
printf ("the summation of series =%1f\n", fin);
return 0;
}
double calc (float num, float res)
{
int count, sign = 1;
double rres = 0;
for (count = 1; count <= res; count += 2)
{
rres += sign * (pow (num, count) / factorial (count));
sign *= -1;
}
return (rres);
}
double factorial (int num)
{
int count;
double sum = 1;
for (count = 1; count <= num; count++)
{
sum *= count;
}
return (sum);
}
I thought of making this An=8(An-1)*(An-1)/An-2 while a1=1,a0=1
With the following code for n=2 a2=0.0000 which is altogether wrong
On the other hand (Sum of An) S(n)=1+1+0.0000(false number) theoretically correct
#include <stdio.h>
float rec(int n);
float sum(int n);
main()
{
int n;
printf("\nInput N of term an: ");
scanf("%d",&n);
printf("\n\na%d=%f",n,rec(n));
printf("\n\nS(%d)=%f",n,sum(n));
}
float rec(int n)
{
int i;
float a[1000]={1,1};//a0=1,a1=1
if(n<0)
printf("\nNegative values of N are invalid");
else if(n==0)
return a[0];
else if(n==1)
return a[1];
else if(n>1)
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
}
float sum(int n)
{
int i;
float sum=0;
for(i=0;i<=n;i++)
sum+=rec(i);
return sum;
}
float a[1000]={1,1};
initializes a[0] = 1 and a[1] = 1 and rest of the elements to 0.
Now, you are returning a[i] from your function. For n=2 it will return a[3], which is 0 of course, but not the a[2] as you are expecting.
Now just change the return value to a[i-1] and it will work.
float rec(int n)
{
int i;
...
...
return a[i-1];
}
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
problem here, you will always get zero!!! why?
say i input 3,, now say i = 3,alls well a[3] gets calcualted, now you program goes back to the for loop, now i =4, it now does not fit the check i<=n, and so now i is 4,
you are returning a[i] which is actually a[myanswer+1]...
fix it by returning a[i-1]
At this point in rec:
return a[i];
i is 3, not 2, because it was incremented before the last test of the loop. As such you're returning the element of the array after the last one set. Be careful if you fix this by returning a[i-1] because if i is never initialized or is 0, this will cause a problem. You should clean up the rec method a bit to handle these corner cases, but the immediate problem is that i is 3, not 2.
Replace
return a[i];
with
return a[n];
(As an aside, you do not need the extra branches for 0 and 1.)
A beautiful example of Schlemiel the Painter's algorithm :)
About half the computations are done unnecessarily multiple times
The array is unnecessary and defeats the whole point of using a recursive approach
Beside, it is defined to hold 1000 values, but the function grows so fast that it will exceed a float capacity after 10 terms or so.
A more streamlined version here :
#include <stdio.h>
float A (int n, float * sum)
{
if (n <= 0) { *sum = 0; return 0; }
if (n == 1) { *sum = 1; return 1; }
if (n == 2) { *sum = 2; return 1; }
float anm2 = A(n-2, sum); // store A(n-2). sum will be overwritten by A(n-1)
float anm1 = A(n-1, sum); // store A(n-1) once to avoid calling A twice, and get preceding sum
float an = ((8 * anm1*anm1) - 1)/anm2;
*sum += an;
printf ("index %d : term %g sum %g\n", n, an, *sum);
return an;
}
int main (void)
{
int n;
float sum;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
printf("\na%d=%f",n,A(n, &sum));
printf("\n\nS(%d)=%f",n,sum);
}
Beside, recursion is unnecessary and leads to inefficient and confusing code.
See a more straightforward solution here:
#include <stdio.h>
typedef struct {
float term;
float sum;
} A; // current term and sum of series A
void compute_A (int n, A * res)
{
int i;
float anm1, // a[n-1]
anm2; // a[n-2]
// special case for n<=1
if (n == 1)
{
res->sum = res->term = 1;
return;
}
if (n <= 0)
{
res->sum = res->term = 0;
return;
}
// initial terms
anm2 = anm1 = 1;
// initial sum
float sum = anm1+anm2;
// compute the remaining n-2 terms and cumulate the sum
for (i = 2 ; i <= n ; i++)
{
// curent term
float an = ((8 * anm1*anm1) - 1)/anm2;
// cumulate sum
sum += an;
// shift computation window
anm2 = anm1;
anm1 = an;
printf ("index %d : term %g sum %g\n", i, an, sum);
}
// report result
res->sum = sum;
res->term = anm1;
}
int main (void)
{
int n;
A res;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
compute_A (n, &res);
printf("\na%d=%f",n,res.term);
printf("\n\nS(%d)=%f",n,res.sum);
}
float rec(int n){
static max_i = 1;
static float a[1000]={1,1};//a0=1,a1=1
int i;
if(n<0){
printf("\nNegative values of N are invalid");
return NAN;//<math.h>
}
if(n >= 1000){
printf("\nMore than 1000 are invalid");
return NAN;
}
if(n<2)
return a[n];
if(n>max_i){
for(i=max_i+1;i<=n;++i)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
max_i = n;
return a[n];
}
return a[n];
}
Factorial program using recursion in c with while loop.In this program once the execution reaches the function return statement it will not go back to the function call. Instead,it executes the function repeatedly. can anybody please tell me what's wrong in this program.
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x=n*fact(n-1);
}
return(x);
}
void main()
{
int n,fact1;
scanf("%d",&n);
fact1=fact(n);
printf("%d",fact1);
}
The reason that your program gets into an infinite loop is that the loop
while (n > 1)
x = n * fact(n-1);
never decrements n. Since n never decreases, the program will never leave the loop. Peter is correct in the comments: change the while to an if, and you will have a factorial function that handles all positive parameters correctly. However, even after changing while to if, your fact won't have the property that fact(0) == 1, as is required for a correct factorial function.
This
while(n>1)
is causing the looping. You don't change n inside the loop, so the loop is infinite.
Change while to if.
This is the method of factorial:
public int fact(int n)
{
if (n < 1)
{
return 1;
}
else
{
return n * fact(n - 1);
}
}
#include <stdio.h>
#include <stdlib.h>
/** main returns int, use it! */
int main(int argc, char **argv)
{
if (argc <= 2) {
if (argv) argc = atoi(argv[1] );
else return argc;
}
argc *= main (argc-1, NULL);
if (argv) {
printf("=%d\n", argc);
return 0;
}
return argc;
}
/*
Write a C++ Program to input a positive number,
Calculate and display factorial of this number
by recursion.
*/
#include<iostream.h>
#include<conio.h>
long factorial(int n);
void main()
{
clrscr();
int number, counter;
label1:
cout<<"\n Enter the Number = ";
cin>>number;
if ( number < 0)
{
cout<<"\n Enter a non negative number, please!";
goto label1;
}
cout<<"\n\n ----------- Results ------------";
cout<<"\n\n The Factorial of the number "<<number<<"\n is "<<factorial(number);
getch();
}
long factorial(int n)
{
if ( n == 0 )
return 1;
else
return n * factorial(n-1);
}
You can use the simple approach using recursion
#include <stdio.h>
int fact(int n)
{
if(n==1)
return 1;
else
return n * fact(n-1);
}
int main()
{
int f;
f = fact(5);
printf("Factorial = %d",f);
return 0;
}
Read it more C program to find factorial using recursion
/*several versions of a factorial program.*/
#include<stdio.h>
int main()
{
int n;
long factorial;
printf("Compute the factorial of what number? ");
scanf("%d", &n);
factorial = 1L;
while(n > 0)
factorial *= n--;
printf("The factorial is %ld\n", factorial);
return 0;
}
#include<stdio.h>
/*the same, but counting up to n instead of down to 0*/
int main()
{
register int count;
int n;
long factorial;
printf("Compute the factorial of what number? ");
scanf("%d", &n);
factorial = 1L;
count = 1;
while(count <= n)
factorial *= count++;
printf("%d! = %ld\n", n, factorial);
return 0;
}
#include<stdio.h>
/*an equivalent loop using 'for' instead of 'while'*/
int main()
{
register int count;
int n;
long factorial;
printf("Compute the factorial of what number? ");
scanf("%d", &n);
for(factorial = 1L, count = 1; count <= n; count++)
factorial *= count;
printf("%d! = %ld\n", n, factorial);
return 0;
}
/*WAP to find factorial using recursion*/
#include<stdio.h>
#include<stdlib.h>
int fact1=1;
int fact(int no)
{
fact1=fact1*no;
no--;
if(no!=1)
{
fact(no);
}
return fact1;
}
int main()
{
int no,ans;``
system("clear");
printf("Enter a no. : ");
scanf("%d",&no);
ans=fact(no);
printf("Fact : %d",ans);
return 0;
}
Factorial program using recursion in C with while loop.
int fact(int n)
{
int x=1;
while(n>=1)
{
return(n*fact(n-1));
}
return(1);
}
You can use this approach.
int factorial(int a)
{
while(a>1)
{
return a*factorial(a-1);
}
return 1;
}