Question
C program to calculate the sum of Numbers Until a Negative Value is Entered using break statement.
Solution
β Verified
In this program, the goal is to continuously input numbers from the user and calculate their sum. The loop will keep adding the numbers until the user enters a negative number. As soon as a negative number is entered, the program will stop collecting input and print the total sum of all the entered positive numbers.
How it works:
- The program asks the user to enter numbers in a loop.
- It keeps adding the entered numbers to a variable sum.
- If the user enters a negative number, the loop ends using the break statement.
- The program then prints the total sum of all the non-negative numbers entered.
#include <stdio.h>
int main() {
int num, sum = 0;
// Infinite loop to keep asking for numbers
while (1) {
printf("Enter a number: ");
scanf("%d", &num);
// If the number is negative, break the loop
if (num < 0) {
break;
}
// Add the number to the sum
sum += num;
}
// Print the total sum of the entered numbers
printf("Sum of numbers: %d\n", sum);
return 0;
}
Output -
Enter a number: 34
Enter a number: 67
Enter a number: 89
Enter a number: -90
Sum of numbers: 190Β
Click here to download practice questions on
Break Statement in CMore Questions on Break Statement in C
Question 1
C Program to Print Numbers Until a Multiple of 7 is Found Using the break Statement
View solution