Priniting Sum of Numbers using Goto Statement in C++


This program calculates the sum of all the natural numbers from a given value down to 1 using a goto statement. Here's how the program works:

  • It prompts the user to enter a value.
  • It reads the value into the variable a.
  • It initializes the variable n to 0.
  • It uses a goto statement to create a loop that adds the value of a to n and decrements a by 1.
  • It checks if a is greater than or equal to 0. If it is, the loop goes back to the start label and repeats. If it is not, the loop exits.
  • It prints the total value of n.
  • The program ends.

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 while or for loop to calculate the sum.

Source Code

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

Output

Enter the value :5
Total value :15

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