The while loop can be used to read multiple numbers from the user and calculate the total of positive and negative numbers separately. In this program, the user enters 10 numbers. Each number is checked using an if-else statement. If the number is less than 0, it is added to the negative total. Otherwise, it is added to the positive total.
How It Works?
k with 1, n with 0 for negative total, and p with 0 for positive total.while loop checks whether k <= 10.k by 1.#include <stdio.h> #include <conio.h> main() { int k = 1, n = 0, p = 0, no; clrscr(); while(k <= 10) { printf("\n Enter any number: "); scanf("%d", &no); if(no < 0) { n = n + no; } else { p = p + no; } k = k + 1; } printf("\n Negative number total: %d", n); printf("\n Positive number total: %d", p); getch(); }
while loop to read 15 numbers from the user and find the total of positive numbers and negative numbers separately.while loop with the if-else statement to identify positive and negative numbers and calculate their totals separately.k with 1, n with 0 for negative total, and p with 0 for positive total. Use the while loop condition k <= 15. Check whether the entered number is less than 0. If true, add it to n; otherwise, add it to p. Increase k by 1 after each iteration.#include <stdio.h> #include <conio.h> main() { int k = 1, n = 0, p = 0, no; clrscr(); while(k <= 15) { printf("\n Enter any number: "); scanf("%d", &no); if(no < 0) { n = n + no; } else { p = p + no; } k = k + 1; } printf("\n Negative number total: %d", n); printf("\n Positive number total: %d", p); getch(); }
while loop. Each entered number is checked using an if-else statement. If the number is less than 0, it is added to the negative total; otherwise, it is added to the positive total. After all 15 numbers are entered, the program displays the total of negative numbers and the total of positive numbers separately.