The Program in C to Calculate Factorial using Pointer is given below:
#include <stdio.h>
int factorial(int *n) {
int result = 1;
int temp = *n;
while (*n > 0) {
result *= *n;
(*n)--;
}
*n = temp;
return result;
}
int main() {
int num;
int *p = #
printf("Enter a positive integer: ");
scanf("%d", &num);
int factorial_result = factorial(p);
printf("Factorial of %d = %d\n", num, factorial_result);
return 0;
}
Output:
Enter a positive integer: 10
Factorial of 10 = 3628800
Pro-Tips💡
A pointer 'p'
is declared in the main function, and it is assigned the address of the variable ‘num'
.
The pointer ‘p'
is then passed as an argument to the 'factorial'
function, where it is used to access and modify the value stored in 'num'
.
The 'factorial'
function uses the dereference operator '*'
to access the value pointed to by 'p'
,
and it modifies the value stored at the address by decrementing it in each iteration.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.