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;
}
Related
I wrote a code in C to find the odd numbers from a given interval of min and max number. The function works well when it is inside the int main() but not well when outside the program as a function.
What's more is that it also prints the incremented number outside the max number given.
This is the code...
#include <stdio.h>
// My Function
int odd_numbers(int x, int y) {
for (int i = x; i <= y; ++i) {
if (i % 2 == 1) {
printf("%d\n",i);
}
}
}
// Main Program
int main(void) {
int min_num, max_num;
printf("Input your minimum number: ");
scanf("%d", &min_num);
printf("Input your maximum number: ");
scanf("%d", &max_num);
printf("%d",odd_numbers(min_num,max_num));
}
and this is the output...
As you can see, it adds an 11 besides the 9...
How can I solve this? I've tried return 0; and it returns the value 0 but i only want to return no number except the odd numbers.
Here is the working code.
Notes
Change the return type of odd_numbers from int to void because you are not returning anything when the function is called.
Only call the function odd_numbers, no need to printf anything because odd_numbers already does the job.
#include <stdio.h>
// My Function
void odd_numbers(int x, int y) {
for (int i = x; i <= y; i++) {
if (i % 2 != 0) {
printf("\n%d",i);
}
}
}
// Main Program
int main(void) {
int min_num, max_num;
printf("Input your minimum number: ");
scanf("%d", &min_num);
printf("Input your maximum number: ");
scanf("%d", &max_num);
odd_numbers(min_num,max_num);
}
Here is the modified code.
you have declare function return type int but return nothing. odd_numbers made to void type. no need to return anything
code:
#include <stdio.h>
// My Function
void odd_numbers(int x, int y)
{
int i = 0;
for (int i = x; i <= y; i++)
{
if (i % 2 != 0)
{
printf("%d\n", i);
}
}
}
// Main Program
int main(void) {
int min_num, max_num;
printf("Input your minimum number: ");
scanf("%d", &min_num);
printf("Input your maximum number: ");
scanf("%d", &max_num);
odd_numbers(min_num, max_num);
return 0;
}
I want to create a program to find the factorial of a number also I want to make it using pointers.
I have tried to make a program but it is not giving the factorial of the number . Can anybody explains me why ?
#include<stdio.h>
#include<stdlib.h>
int fact(int* num, int* n)
{
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
*n = (*n)*(*num);
}
}
int main()
{
int num, n;
printf("Write the number to take factorial \n");
scanf("%d", &num);
fact(&num, &n);
printf("Factorial = %d", n);
return 0;
}
As you are using int function it must contain some return value. If you make following changes it runs perfectly.
#include <stdio.h>
#include <stdlib.h>
int fact(int *num, int *n)
{
long long unsigned int fact = 1;
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
fact = fact * (*n);
}
return fact;
}
int main()
{
int num, n;
long long unsigned int b;
printf("Write the number to take factorial \n");
scanf("%d", &num);
b = fact( &num, &n);
printf("Factorial = %llu", b);
return 0;
}
*n=(*n)*(*num); is changing the value of the counting variable used in the for loop!
Whilst this is perfectly legal in C, it's leading to the incorrect answer.
You also don't return a value explicitly from fact despite it having a non-void return type. That's undefined behaviour.
Note also that the range for an int can be as small as -32767 to +32767, which only allows for 7! or lower. Consider using a long long type instead.
Correct me if I am wrong, but I think the logic itself is incorrect in your attempt :
for ((*n) = 1; (*n) <= (*num); (*n)++)
{
*n = (*n)*(*num);
}
You are using the counting variable ('*n' in this case) for purpose of storing the result. If you check the flow the loop will end after first iteration then increment it giving you the value of (*num + 1).
A good modification for your fact function could be :
void fact(int* num, int* n)
{
int counter;
*n=1;
for (counter = 2 ; counter <= (*num) ; counter++)
{
*n = (*n)*(counter);
}
}
Can't see a reason to keep the return type of the function as int if you are using call by reference for the result as well.
As in response to answer given by '#nikhil biijjala' , I can't understand your reason to pass the pointer (*n) in the first place.All that pointer does is works as a local counter for the loop.
As in case of large integers you can add limits to input or use long long.
C++ Version:
#include <iostream>
int abc(int *a);
int main()
{
int a,fact;
int *ptr;
std::cout << "Enter a:"<< std::endl;
std::cin >> a;
ptr= &a;
fact=*ptr;
while(*ptr!=1)
{
fact = fact * abc(ptr);
}
std::cout << "Factorial is : <<" << fact << std::endl;
return 0;
}
int abc(int *a)
{
*a=*a-1;
return *a;
}
#include<stdio.h>
int facto(int *);
int main()
{
int factorial, v;
printf("Enter the value : ");
scanf("%d", &v);
factorial = facto(&v);
printf("The factorial of %d is %d.\n", v, factorial);
}
int facto(int *p)
{
int c;
c = *p - 1;
if (*p == 1)
return 1;
else
return (*p) * (facto(&c));
}
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
}
Please explain how this program is working. I applied a for loop after if statement in factorial function but how this is working.
int factorial(int n){
if(n==1)
return 1;
return n*(factorial(n-1));
}
This is correct :) I think that your code shouldn't compile because the function factorial(int n) has no defined return statement!
I have to find all the prime numbers between two numbers m and n. (1 <= m <= n <= 1000000000 and n-m <= 100000). I am using sieve of eratosthenes but getting wrong answer. Can anyone help me what is wrong with my code.
#include<stdio.h>
#include<math.h>
int S[100002];
void sieve(long long int m, long long int n)
{
long long int x=sqrt(n);
long long int i,j;
long long int a;
for(i=0;i<=n-m+2;i++)
S[i]=0;
if(m%2==0)
i=m;
else {
i=m+1;
}
for (;i<=n;i+=2){
S[i-m]=1;
}
for (i=3;i<=x;i+=2){
if(i>=m && S[i-m]) continue;
if(i*i>=m)j=i*i;
else {
a = (m-i*i)%(2*i);
if(a==0)j=m;
else
j=m+ (2*i -a);
}
for (;j<=n;j+=2*i){
S[j-m]=1;
}
}
if (m==1)i=1; else i=0;
for (;i<=n-m;i++)
if (!S[i]){
printf("%lld\n",i+m);
}
}
int main(){
int t;
long long int m,n;
scanf("%d\n",&t);
while(t--){
scanf("%lld %lld",&m,&n);
sieve(m,n);
printf("\n");
}
return(0);
}
if(m%2==0)
i=m;
else {
i=m+1;
}
for (;i<=n;i+=2){
S[i-m]=1;
}
Now, what happens if m <= 2? Will 2 be considered prime or not?
You should use loop in main and call prime function.
For performance, I recommend you to avoid using sqrt function because it requires a lot of CPU clocks.
bool isPrime(int number){
if(number < 2) return false;
if(number == 2) return true;
if(number % 2 == 0) return false;
for(int i=3; (i*i)<=number; i+=2){
if(number % i == 0 ) return false;
}
return true;
}
***Change datatype for the range of number (long, long long, etc).
It is the most efficient(Sieve method) way of finding prime number between a range.
Here 1 is not consider as a prime number as a conventionally way.
#include<stdio.h>
#include<string.h>
#define max 10000000
using namespace std;
int main()
{
unsigned long long int i, j, k, m, n;
unsigned long long int* a = new unsigned long long int[max];
scanf("%ul %ul",&m,&n);
for(i = 1;i<=n;i++)
a[i]=i;
a[1] = 0;
for(i=2;(i*i)<=n;i++)
if(a[i]!=0)
for(k=2*i;k<=n;k=k+i)
if(a[k]!=0)
a[k]=0;
for(i =m;i<=n;i++)
if(a[i]!=0)
printf("%ul ",a[i]);
memset(a, 0, sizeof(a));
return 0;
}
#include<stdio.h>
#include<stdlib.h>
void prime(int );
int main(){
int x, end;
printf("Enter end of the range:\n");
scanf("%d", &end);
for(x = 2;x <= end;x++){
prime(x);
}
return 0;
}
void prime(int x){
int j, count = 1;
for(j=2;j <= x;j++){
if(x % j == 0){
count += 1;
//printf("count = %d,x = %d", count, x);
}
}
if(count == 2){
printf("\n%d\n", x);
}
}
I'm new to C, and I'm getting a segmentation fault that I can't understand. I have the following program, which attempts to calculates the number of factors of a strictly positive number:
#include <stdio.h>
#include <math.h>
int numberOfFactors (int number, int factor) {
if (number % factor == 0) {
number = number/factor;
return numberOfFactors(number, factor) + 1;
} else {
return 0;
}
}
int check (int x) {
if (x>0) {
return 1;
} else {
return 0;
}
}
int main(void) {
int number;
printf("Please enter a positive integer n such that n >= 1: ");
scanf("%d", &number);
if (check(number)){
int i;
for (i=1; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
}
return 0;
}
The segmentation fault occurs immediately after entering an integer and ENTER after these lines in main():
printf("Please enter a positive integer n such that n >= 1: ");
scanf("%d", &number);
What in these lines is causing the segmentation fault, and what can I do to avoid it?
Your recursion doesn't stop if you try to divide out factor one.
Just let factor never be 1:
for (i=2; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
I should say WHY it segfaults: It's because every function call pushes the current program counter (the position in your program where you currently stand) and function arguments on the stack (aka call stack), where the stack is a relatively small memory block used for, well, function calling and local variables.
So if you are pushing your stack too hard, it will fall over. End of game, aka segfault ;)
You probably have a problem with this recursion:
int numberOfFactors (int number, int factor) {
if (number % factor == 0) {
number = number/factor;
return numberOfFactors(number, factor) + 1;
} else {
return 0;
}
}
Change your numberOfFactors to something like:
int numberOfFactors (int number)
{
int i=1;
int ret=0;
for(;i<=number;i++) {
if (number%i == 0) {
ret++;
}
}
return ret;
}
And then, change this portion:
if (check(number)){
int i;
for (i=1; i<=number; i++) {
int factors;
factors = numberOfFactors(number, i);
printf("%d^%d ", i, factors);
}
}
To something simpler like:
if (check(number)){
factors = numberOfFactors(number);
printf("%d^%d ", number, factors);
}