This program keeps accepting integers and adds them to a running total. A sentinel value tells the loop when to stop.
#include <stdio.h>
int main(void) {
int sum = 0;
int value;
while (1) {
printf("Enter a number (0 to stop): ");
if (scanf("%d", &value) != 1) {
printf("Invalid input.\n");
return 1;
}
if (value == 0) {
break;
}
sum += value;
}
printf("Sum of the entered numbers: %d\n", sum);
return 0;
}
Sample output
Enter a number (0 to stop): 4
Enter a number (0 to stop): 5
Enter a number (0 to stop): 7
Enter a number (0 to stop): 0
Sum of the entered numbers: 16
When zero is a valid value, choose a different sentinel. Here, any negative number stops the loop and is not included in the sum.
#include <stdio.h>
int main(void) {
int sum = 0;
int value;
while (1) {
printf("Enter a non-negative number (negative to stop): ");
if (scanf("%d", &value) != 1) {
printf("Invalid input.\n");
return 1;
}
if (value < 0) {
break;
}
sum += value;
}
printf("Sum of the entered numbers: %d\n", sum);
return 0;
}
#include <stdio.h>
int main(void) {
int sum = 0;
int value;
int highest = 0;
int has_value = 0;
while (1) {
printf("Enter a non-negative number (negative to stop): ");
if (scanf("%d", &value) != 1) {
printf("Invalid input.\n");
return 1;
}
if (value < 0) {
break;
}
sum += value;
if (!has_value || value > highest) {
highest = value;
has_value = 1;
}
}
printf("Sum: %d\n", sum);
if (has_value) {
printf("Highest number: %d\n", highest);
} else {
printf("No numbers were entered.\n");
}
return 0;
}
#include <stdio.h>
int main(void) {
int count;
int sum = 0;
printf("How many numbers do you want to add? ");
if (scanf("%d", &count) != 1 || count < 0) {
printf("Enter a valid non-negative count.\n");
return 1;
}
for (int i = 1; i <= count; i++) {
int value;
printf("Enter number %d: ", i);
if (scanf("%d", &value) != 1) {
printf("Invalid input.\n");
return 1;
}
sum += value;
}
printf("The sum is: %d\n", sum);
return 0;
}
#include <stdio.h>
int main(void) {
int values[] = {10, 20, 30, 40, 50};
size_t count = sizeof values / sizeof values[0];
int sum = 0;
for (size_t i = 0; i < count; i++) {
sum += values[i];
}
printf("The sum of the array elements is: %d\n", sum);
return 0;
}
Output
The sum of the array elements is: 150
See also while loops, arrays, and sum of digits.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
30-04-2022 | |
| #include <stdio.h> #include <conio.h> int main() { int grade=74; if (grade>74) { printf(“Passed”); } else if (grade<75 && grade>69) { printf(“Conditional Pass”); } else (grade<70) { printf(“Failed!”); } getch(); return 0; } | |