Maker Pro
Maker Pro

Positive and negative number

Hello
I wrote program in c that can be find positive and negative number. after that I am trying to find out how many positive and negative number's are there in array
Code:
#include <stdio.h>

 int main(void)
{
    int i;
    int PositiveNegative[10] = {5,2,-1,4,8,-6,8,-7,9,1};
 
    for (i = 0; i <10; i++)
    {
        if (PositiveNegative[i]>0)
        {
           printf("Positive number %d \n",PositiveNegative[i]);
        }
        else
        {
           printf("Negative number %d \n",PositiveNegative[i]);
        }
           
    }
     
    return 0;
}

Code:
Positive number 5
Positive number 2
Negative number -1
Positive number 4
Positive number 8
Negative number -6
Positive number 8
Negative number -7
Positive number 9
Positive number 1

How to find out how many positive and negative number's are there in array
 

Harald Kapp

Moderator
Moderator
I say you could have answered this question with a bit of thinking yourself.
Have two variables initialized to 0, e.g.
Code:
int pos=0, neg=0;
Within the loop increment the respective variable when you find a positive or negative number.

By the way: What will your program output for a value of 0? Do you think that is correct?
 
By the way: What will your program output for a value of 0? Do you think that is correct?
look at this
Code:
#include <stdio.h>

 int main(void)
{
    int i;
    int positive= 0, negaive=0;
    int PositiveNegative[10] = {5,2,-1,4,8,-6,8,-7,9,1};
 
    for (i = 0; i <10; i++)
    {
        if ((PositiveNegative[i]==0))
            
            {
                printf(" Entered 0 number \n");
            }
        else if (PositiveNegative[i]>0)
        {
        
           printf("Positive number %d \n",PositiveNegative[i]);
           positive++;
        }
        else if (PositiveNegative[i]<0)
        {
           printf("Negative number %d \n",PositiveNegative[i]);
           negaive++;
        }
    }
         printf("Number of positive  numbers %d \n",positive);
         printf("Number of negative  numbers %d \n",negaive);         
    
    
    return 0;
}

Output
Code:
Positive number 5
Positive number 2
Negative number -1
Positive number 4
Positive number 8
Negative number -6
Positive number 8
Negative number -7
Positive number 9
Positive number 1

Number of positive  numbers 7
Number of negative  numbers 3
 
Looks good. But you should test it with 0 values in your array, too.
PositiveNegative[10] = {5,2,-1,4,0,-6,0,-7,9,1};

The program does not count 0 as a positive or negative number.

Code:
Positive number 5
Positive number 2
Negative number -1
Positive number 4
 Entered 0 number
Negative number -6
 Entered 0 number
Negative number -7
Positive number 9
Positive number 1

Number of positive  numbers 5
Number of negative  numbers 3
 
Top