Factorial using Goto Statement in C++


This program calculates the factorial of a given number using a loop and a goto statement. The long int data type is used to accommodate large values of factorial.

Here's how the program works:

  • It prompts the user to enter a number.
  • It reads the number into the variable a.
  • It initializes a variable n to 1, which will be used to store the factorial value.
  • It uses a goto statement to create a loop that multiplies n by a and decrements a until a becomes 0.
  • The loop exits when a is not greater than 0.
  • The program outputs the final value of n, which represents the factorial of the input number.

While this program works correctly, using a goto statement is generally not considered good programming practice because it can make the code difficult to read and maintain. A better alternative would be to use a for or while loop to calculate the factorial.

Source Code

#include<iostream>
using namespace std;
int main()
{
    long int a,n=1;
    cout<<"\nEnter the number :";
    cin>>a;
    start:
    n=n*a;
    a--;
    if(a>0)
    {
            goto start;
    }
    cout<<"\nThe Total value is :"<<n;
    return 0;
}
To download raw file Click Here

Output

Enter the number :5
The Total value is :120

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples