C program to print positive numbers in an array

Before get started with this problem,

kindly refer the positive or negative problem (without array) using the below link positive or negative in c.




Example

Input

array size = 5

Elements = { 10, 2, -1, -6, 30}

Output

10

2

30

Input

array size = 4

Elements = {12, -1, 0, 8}

Output

12

8


Let's approach the problem in two steps.

1.Get the array elements and print it.

2.Next step we will print only positive elements.




Get the array elements and print it

Example

#include<stdio.h>

int main()
{
    //let's assume the maximum array size as 100.
    int arr[100],size,i;

    //Get size input from user
    printf("Enter array size\n");
    scanf("%d",&size);

    //Get all elements using for loop and store it in array
    printf("Enter array elements\n");
    for(i = 0; i < size; i++)
          scanf("%d",&arr[i]);

    //print all elements using for loop
    printf("Elements are\n");
    for(i = 0; i < size; i++)
          printf("%d\n",arr[i]);

    return 0;
}





Print only the positive elements

Before printing each element in the array, we need to check whether it is positive or not.

This can be achieved using if statement .

If it's positive print it.

Otherwise, ignore it.


Example

#include<stdio.h>

int main()
{
    //let's assume the maximum array size as 100.
    int arr[100],size,i;

    //Get size input from user
    printf("Enter array size\n");
    scanf("%d",&size);

    //Get all elements using for loop and store it in array
    printf("Enter array elements\n");
    for(i = 0; i < size; i++)
          scanf("%d",&arr[i]);

    //print only the positive elements in the array
    printf("Elements are\n");
    for(i = 0; i < size; i++)
    {
          //positive numbers are greater than 0.
          /*if you want to print the negative numbers,
            just change the if condition as arr[i] < 0 */
          if(arr[i] > 0)
              printf("%d\n",arr[i]);
    }

    return 0;
}


Topics You Might Like