To print sum of values using Goto statement
This is a C program that prompts the user to enter an integer 'a' and then uses the goto statement to calculate the sum of the integers from 'a' to 0.
- 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 integers a and n are declared, where n is initialized to 0. 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 sum of the integers is calculated by adding the current value of 'a' to the previous sum 'n' 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("\nTotal value :%d",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.
Source Code
#include <stdio.h>
int main()
{
int a,n=0;
printf("\nEnter the value :");
scanf("%d",&a);
start:
n=n+a;
a--;
if(a>=0)
{
goto start;
}
printf("\nTotal value :%d",n);
return 0;
}
To download raw file
Click Here
Output
Enter the value : 9
Total value : 45