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));
}
Related
my question is when I run the code the loop goes on infinitely. the expected output is to print hi 5 times then go to a new line and print 4 times the 3 and so on I cant understand what is causing the loop to go infinite.
#include <stdio.h>
int star(int);
int main()
{
printf("enter number\n");
int a;
scanf("%d", &a);
star(a);
return 0;
}
int star(int m)
{
int n;
for (n = 0; n < m; n++)
{
printf("hi");
}
printf("\n");
star(m - 1);
return 0;
}
you forgot to check if m > 0 somewhere in your function. In this case, the loop goes infinetely, because it doesn´t have a way to get out of recursion.
Simple fix:
#include <stdio.h>
int star(int);
int main()
{
printf("enter number\n");
int a;
scanf("%d", &a);
star(a);
return 0;
}
int star(int m)
{
int n;
for (n = 0; n < m; n++)
{
printf("hi");
}
printf("\n");
if (m > 0){
star(m - 1);
}
return 0;
}
For starters the return type of the function star is useless and does not make a sense. Also there is no great sense to declare the parameter as having the signed integer type int. It would be more logically correct to declare the parameter as having at least the unsigned integer type unsigned int.
So the function should be declared like
void star( unsigned int n );
The function calls infinitely itself recursively because such a call is unconditional and does not depend on the value of the parameter m.
int star(int m)
{
//...
star(m - 1);
return 0;
}
The function can be defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
void star( unsigned int );
int main( void )
{
printf( "Enter number: " );
unsigned int n;
if ( scanf( "%u", &n) == 1 ) star( n );
return 0;
}
void star( unsigned int n )
{
if ( n )
{
for ( unsigned int i = 0; i < n; i++)
{
printf( "hi" );
}
putchar( '\n' );
if ( --n ) star( n );
}
}
Pay attention to that if the function was called initially with the argument equal to 0 then the function should output nothing.
I have tried different inputs and when it exceeds a 7 or 8 digit value it just shows some wrong answers as outputs but it worked fine with most of my cases.
#include <stdio.h>
#include <stdlib.h>
int bin(unsigned long long int n){//gave function for binary convertion
if(n==0)
return 0;
else
return (n%2+10*bin(n/2));
}
int main()
{
unsigned long long int n,x;/*I even gave high digit data type*/
int i, v, count=0, max=0;
scanf("%llu",&n); /*if input is >8-digit output is wrong*/
x = bin(n);
v = floor(log10(x))+1; /*Its length*/
int a[v];
for(i = v-1; i >= 0; i--){ /*string it in array*/
a[i] = x%10;
x = x/10;
}
for(i = 0; i < v; i++){
if(a[i] == 0){
count = 0;}
else{
count++;}
if(max < count){
max = count;}
}
printf("%d",max);/*I gave 99999999 output is 8 but its shows 9*/
}
Your program has a number of problems. Here is one example:
int bin(unsigned long long int n){
^^^
The function returns an int so the calculation will overflow for even small numbers:
printf("%d\n", bin(1023)); // will print 1111111111 (fine)
printf("%d\n", bin(1024)); // will/may print 1410065408 (ups - very bad)
Even if you change to
unsigned long long int bin(unsigned long long int n){
overflow will happen soon.
In I'll recommend that you look directly into the binary pattern of the number using the & operator.
I'll not solve the complete task for you but here is some code that may help you.
#include <stdio.h>
#include <stdlib.h>
int main()
{
size_t t = 1;
size_t limit;
size_t n;
if (scanf("%zu", &n) != 1)
{
printf("Illegal input\n");
exit(1);
}
limit = 8 * sizeof n; // Assume 8 bit chars
for (size_t i = 0; i < limit; ++i)
{
if (n & t)
{
printf("Bit %zu is 1\n", i);
}
else
{
printf("Bit %zu is 0\n", i);
}
t = t << 1;
}
return 0;
}
I was given an assignment to write a code which takes in numbers as input from the user and provides the sum of it, specifically by the use of pointer arithmetic i.e. no array subscripting a[i] is allowed.
Below is the code that I wrote, which got compiled and even ran. But almost always it gives the sum of the input numbers as 0. I tried to fix it, but to no avail. Thus, I am asking for help, any help is greatly appreciated.
#include<stdio.h>
#define N 5
int sum_array( const int *p, int n)
{
int sum, a[N];
sum = 0;
for(p=&a[0]; p<&a[N]; p++)
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(i,N);
printf("the sum is %d\n", x);
return 0;
}
Beware, you are declaring array int a[N] in both main and sum_array. They are in different scopes, so they are different arrays (and the one from sum_array is never initialized so reading it invokes Undefined Behaviour).
The correct way is to pass the array along with its used length:
Here is a fixed version:
#include<stdio.h>
#define N 5
int sum_array( const int *a, int n) // a points to a array of at least n elements
{
int sum = 0; // initialize at definition time
for(const int *p=a; p<&a[n]; p++) // have the pointer p take all values from a
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
Finally it is mainly a matter of taste, but I was too often burnt for trying to add an instruction in a for loop without braces, so I strongly recommend using always braces for loops:
for(i=a; i<a+N; i++) {
scanf("%d", i);
}
int sum_array( const int *p, int n)
{
int sum = 0, i = 0;
for(i = 0; i < n ; i++)
sum += *(p+i);
return sum;
}
int main(void)
{
int a[N], i = 0, x = 0;
printf("Enter %d Numbers: ", N);
for(i=0; i<N; i++)
scanf("%d", a+i);
// all the input values get scanned as i or the array a
x= sum_array(a,N);
printf("the sum is %d\n", x);
return 0;
}
In x= sum_array(i,N); i is the iterator of your loop so after the loop has finished it points to the first position after the array.
You should pass the original array instead x= sum_array(a,N);
In the sum function you just throw away the passed pointer and replace it with your local a[].
int sum_array( const int *p, int n)
{
int sum = 0;
int *end = &p[n]; // first element after the array.
for(; p<end; p++) // just use p because you don't need the reference to the start of the array
{
sum += *p;
}
return sum;
}
but as you said that array notation is not allowed you can change it as follows
#include "stdio.h"
#define N 5
int sum_array( const int *p, int n)
{
int sum = 0;
const int *end = p+n; // first element after the array.
for(; p<end; p++)
{
sum += *p;
}
return sum;
}
int main()
{
int *a, *i, x;
a = malloc(N * sizeof(*a));
if (a == NULL)
exit(-1);
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
{
scanf("%d", i);
}
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
in general, when programming, the code should be kept as simple as possible while still being complete.
The program criteria shows no need to keep a number after it is applied to the sum of the numbers, So in the proposed code, the input number is only kept long enough to be applied to the sum, then it is discarded.
The following proposed code:
cleanly compiles
performs the desired functionality
is kept very simple
properly checks for; and handles any errors
And now the proposed code:
#include <stdio.h> // scanf(), printf(), fprintf(), stderr
#include <stdlib.h> // exit(), EXIT_FAILURE
#define N 5
int main( void )
{
int num = 0;
int sum = 0;
printf("Enter %d Numbers: ", N);
for(size_t i=0; i<N; i++)
{
if( scanf("%d", &num) != 1 )
{
fprintf( stderr, "failed to read number\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
sum += num;
}
printf( "the sum is %d\n", sum );
return 0;
}
I have used the below code for a simple operation
(to reverse a string). But the program is not executing. It gets a run time error (SIGSEGV) . I used a GCC compiler. Please help me in debugging the program.
#include <stdio.h>
#include <stdlib.h>
int *create(int n) {
int *a;
a = (int *)malloc(n * sizeof(int));
return a;
}
void get(int *a, int n) {
int i;
for (i = 0; i < n; i++) {
scanf("%d", *(a + i));
}
}
void reverse(int *a, int n) {
int i;
for (i = n - 1; i >= 0; i--) {
printf("\n %d", *(a + i));
}
}
int main() {
int n, *a;
scanf("%d", &n);
a = create(n);
get(a, n);
reverse(a, n);
return 0;
}
scanf("%d",*(a+i)); invokes undefined behavior because you passed int where int* is expected.
You must pass pointer to tell scanf() where to store the data read, so stop dereferencing and try using scanf("%d",(a+i)); instead.
More notes are:
You should check if readings are successful.
They say you shouldn't cast the result of malloc() in C.
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;
}