This blog is under construction

Wednesday, 24 July 2013

C program to print the number of even, odd and prime numbers in an array

Write a C program to separate the even, odd and prime numbers in an array.


  #include <stdio.h>
  #define MAXLIMIT 256

  /* checks whether the given number is prime or not */
  int isPrime(int data) {
        int i, flag = 1;

        if (data == 1)
                return 0;

        for (i = 2; i < data; i++) {
                if (data % i == 0) {
                        flag = 0;
                        break;
                }
        }
        return flag;
  }

  int main() {
        int data[MAXLIMIT], i, n, j = 0, k = 0, l = 0;
        int even[MAXLIMIT], odd[MAXLIMIT], prime[MAXLIMIT];
        int noEven = 0, noOdd = 0, noPrime = 0;

        /* get the number of elements from the user */
        printf("Enter the number of elements:");
        scanf("%d", &n);

        /* get the elements from the user */
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", &data[i]);
        }
        /* finding the even, odd and prime nos in the given array */
        for (i = 0; i < n; i++) {
                if (data[i] % 2 == 0) {
                        even[j++] = data[i];
                        noEven++;
                } else if (isPrime(data[i])) {
                        prime[k++] = data[i];
                        noPrime++;
                } else {
                        odd[l++] = data[i];
                        noOdd++;
                }
        }

        /* printing the even numbers alone */
        printf("No of even numbers is %d\nEven Numbers:", noEven);
        for (i = 0; i < j; i++) {
                printf(" %d ", even[i]);
        }

        /* printing the odd numbers */
        printf("\nNo of odd Numbers is %d\nOdd Numbers:", noOdd);
        for (i = 0; i < l; i++) {
                printf(" %d ", odd[i]);
        }

        /* printing the prime numbers */
        printf("\nNo of prime Numbers is %d\nPrime Numbers:", noPrime);
        for (i = 0; i < k; i++) {
                printf(" %d ", prime[i]);
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of elements:5
  Data[0]: 1
  Data[1]: 2
  Data[2]: 3
  Data[3]: 4
  Data[4]: 5
  No of even numbers is 2
  Even Numbers: 2  4 
  No of odd Numbers is 1
  Odd Numbers: 1 
  No of prime Numbers is 2
  Prime Numbers: 3  5 


No comments:

Post a Comment