The for loop can be used to count how many positive and negative numbers are entered by the user. In this program, the user enters 10 numbers. Each entered number is checked using the if-else statement. If the number is positive or zero, the positive counter is increased by 1. Otherwise, the negative counter is increased by 1.
How It Works?
k, no, p, and n. Initialize p and n with 0.k with 1 in the for loop.k <= 10.no >= 0.p by 1; otherwise, increase n by 1.#include <stdio.h> #include <conio.h> main() { int k, no, p = 0, n = 0; clrscr(); for(k = 1; k <= 10; k = k + 1) { printf("\n Enter any number: "); scanf("%d", &no); if(no >= 0) { p = p + 1; } else { n = n + 1; } } printf("\n %d positive numbers are there", p); printf("\n %d negative numbers are there", n); getch(); }
for loop to read 15 numbers from the user and count how many positive numbers and negative numbers are entered.for loop with the if-else statement to count positive and negative numbers separately.p and n with 0. Use the loop condition k <= 15. If no >= 0, increase p by 1; otherwise, increase n by 1.#include <stdio.h> #include <conio.h> main() { int k, no, p = 0, n = 0; clrscr(); for(k = 1; k <= 15; k = k + 1) { printf("\n Enter any number: "); scanf("%d", &no); if(no >= 0) { p = p + 1; } else { n = n + 1; } } printf("\n %d positive numbers are there", p); printf("\n %d negative numbers are there", n); getch(); }
for loop. Each entered number is checked to determine whether it is positive (or zero) or negative. The corresponding counter is increased by one. After all inputs are completed, the program displays the total count of positive and negative numbers separately.