Lets write a C program to enter number till the user wants. At the end it should display the count of positive number, negative number and zeros entered, without using arrays.
Related Read:
while loop in C programming
Number is Positive or Negative or Zero: C Program
Note:
Any number greater than 0 is positive.
Any number less than 0 is negative.
Expected Output for the Input
User Input:
Enter the limit
5
Enter 5 numbers
0
5
3
2
-1
Output:
Positive Numbers: 3
Negative Numbers: 1
Number of zero: 1
Video Tutorial: C Program to Count Positive, Negative and Zero without using Array
[youtube https://www.youtube.com/watch?v=SuvrPe4Bg2c]
Source Code: C Program to Count Positive, Negative and Zero without using Array
#include < stdio.h > int main() { int limit, num, positive = 0, negative = 0, zero = 0; printf("Enter the limit\n"); scanf("%d", &limit); printf("Enter %d numbers\n", limit); while(limit) { scanf("%d", &num); if(num > 0) { positive++; } else if(num < 0) { negative++; } else { zero++; } limit--; } printf("\nPositive Numbers: %d\n", positive); printf("Negative Numbers: %d\n", negative); printf("Number of zero: %d\n", zero); return 0; }
Output 1:
Enter the limit
8
Enter 8 numbers
1
-5
0
6
-2
0
5
4
Positive Numbers: 4
Negative Numbers: 2
Number of zero: 2
Output 2:
Enter the limit
10
Enter 10 numbers
2
6
9
3
-5
-7
0
9
-10
-50
Positive Numbers: 5
Negative Numbers: 4
Number of zero: 1
Logic To Count Positive, Negative and Zero without using Array
We ask the user to enter the maximum numbers he or she wants to enter, and store it inside variable limit. Now we iterate the while loop limit number of times. Inside the while loop, for each iteration, until limit is equal to zero, we keep asking the user to enter a number. Once the user enters the number we check if its greater than 0, if its true we’ll increment the value of variable positive by one. If the user entered number is less than 0, then we increment the value of variable negative by one. If the user entered number is neither greater than 0 nor less than 0, then its a zero – so we increment the value of variable zero by one.
For each iteration of the while loop, we decrement the value of variable limit by one. Once the value of variable limit is 0, control exits the while loop and the result will be printed. That is, the number of positives, negatives and the zeros entered by the user.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert