codescracker
c

C Program to Count Positive, Zero and Negative Numbers



« Previous Program Next Program »

In this tutorial, you will learn and get code about counting the occurrence of positive numbers, negative numbers, and zero from the given list of numbers by user (at run-time).

Count Occurrence of Positive Negative & Zero in C

To count the number of positive number, negative number, and zero from the given set of numbers entered by user in C Programming, apply for loop to check all the number in a way that, whether the current number is 0, less than zero or greater than 0. And increment the corresponding variable's value as shown in the program given below.

#include<stdio.h>
#include<conio.h>
int main()
{
    int countPositive=0, countNegative=0, countZero=0, arr[10], i;
    printf("Enter 10 Numbers: ");
    for(i=0; i<10; i++)
        scanf("%d", &arr[i]);
    for(i=0; i<n; i++)
    {
        if(arr[i]<0)
            countNegative++;
        else if(arr[i]>0)
            countPositive++;
        else
            countZero++;
    }
    printf("\nOccurrence of");
    printf("\nPositive Numbers = %d times", countPositive);
    printf("\nNegative Numbers = %d times", countNegative);
    printf("\nZero = %d times", countZero);
    getch();
    return 0;
}

This program was build and run using Code::Blocks IDE. Here is the sample run:

c program count positive negative zero

Supply any 10 numbers say 5, -9, 10, 17, -23, -65, 0, 45, 0, 38 as input, and press ENTER key to see the output as given in the following snapshot:

count occurrence positive negative number c

You saw the above output, because -9, -23, -65 are 3 negative numbers, 5, 10, 17, 45, 38 are 5 positive numbers, and 0, 0 are two zeros from all the given 10 numbers.

Allow User to Define Size

Here is another program that allows user to define the size of array (that how many numbers he want to enter). Let's have a look at the program:

#include<stdio.h>
#include<conio.h>
int main()
{
    int countPositive=0, countNegative=0, countZero=0, arr[10], n, i;
    printf("How many numbers you want to enter ? ");
    scanf("%d", &n);
    printf("Enter %d Numbers: ", n);
    for(i=0; i<n; i++)
        scanf("%d", &arr[i]);
    for(i=0; i<n; i++)
    {
        if(arr[i]<0)
            countNegative++;
        else if(arr[i]>0)
            countPositive++;
        else
            countZero++;
    }
    printf("\nOccurrence of");
    printf("\nPositive Numbers = %d times", countPositive);
    printf("\nNegative Numbers = %d times", countNegative);
    printf("\nZero = %d times", countZero);
    getch();
    return 0;
}

The snapshot given below shows the sample run of above program:

c count positive negative numbers

Same Program in Other Languages

C Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker