Calculating Factorial of a Number using Goto Condition in C


This is a C program that prompts the user to enter a long integer 'a' and then uses the goto statement to calculate the factorial of the given number 'a'. The factorial of a number is the product of all the positive integers less than or equal to that number.

  • The #include<stdio.h> is a preprocessor directive that includes the contents of the standard input-output library in the program. The int main() function is the starting point of the program execution. Inside the main function, two variables a and n are declared, where n is initialized to 1.
  • printf() is used to display the prompt for the user to enter a value, and scanf() is used to get the input and store it in the variable 'a'.A label start is defined and a goto statement is used to jump to this label. The code between the label and the goto statement will execute repeatedly until the condition a>0 is false.
  • The first time the code is executed, the factorial of 'a' is calculated by multiplying the current value of 'n' and 'a' and storing the result back in 'n' using n=n*a. Then the value of 'a' is decremented by 1. Then the condition a>0 is checked, if it's true the control jumps back to the label 'start' and the same process is repeated until the condition is false.
  • Finally, the program prints the result using printf("\nThe Total value is :%ld",n) and returns 0 to indicate the successful execution of the program.

It is worth noting that the use of the goto statement is generally discouraged in modern programming because it can lead to unstructured and hard-to-maintain code. Alternative control structures such as for loops, while loops or do-while loops can be used for the same purpose and are considered more readable, maintainable and less prone to errors.

Also note that the variable a should be declared as a long int as factorial of large numbers can be very large and can't be stored in a regular integer variable.

Source Code

#include <stdio.h>
int main()
{
long int a,n=1;
printf("\nEnter the number :");
scanf("%ld",&a);
start:
n=n*a;
a--;
if(a>0)
{
  goto start;
}
printf("\nThe Total value is :%ld",n);
return 0;
}
To download raw file Click Here

Output

Enter the number:5
The Total value is:120

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C