The for 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 entered number is checked using the if-else statement. If the number is negative, it is added to the negative total. Otherwise, it is added to the positive total.
How It Works?
k, no, n, and p. Initialize n and p with 0.k with 1 in the for loop.k <= 10.no < 0.n; otherwise, add it to p.#include <stdio.h> #include <conio.h> main() { int k, no, n = 0, p = 0; clrscr(); for(k = 1; k <= 10; k = k + 1) { printf("\n Enter any number: "); scanf("%d", &no); if(no < 0) { n = n + no; } else { p = p + no; } } printf("\n Negative total: %d", n); printf("\n Positive total: %d", p); getch(); }
for loop to read 15 numbers from the user and calculate the total of positive numbers and negative numbers separately.for loop with the if-else statement to calculate the sum of positive and negative numbers separately.n and p with 0. Use the loop condition k <= 15. If no < 0, add the number to n; otherwise, add it to p.#include <stdio.h> #include <conio.h> main() { int k, no, n = 0, p = 0; clrscr(); for(k = 1; k <= 15; k = k + 1) { printf("\n Enter any number: "); scanf("%d", &no); if(no < 0) { n = n + no; } else { p = p + no; } } printf("\n Negative total: %d", n); printf("\n Positive total: %d", p); getch(); }
for loop. Each entered number is checked to determine whether it is negative or positive (including zero). Negative numbers are added to the variable n, while positive numbers are added to the variable p. After all numbers are entered, the program displays the totals of negative and positive numbers separately.