Showing posts with label occurrence in array. Show all posts
Showing posts with label occurrence in array. Show all posts

Tuesday 27 December 2016

C Program to count the number of times an element occurs in an array

This program searches and counts the number of times the given element is present in an array. If the number is not found then an appropriate message "Number not present in the array" is displayed.

Algortihm

1. Read the array elements

2. Input the element whose occurrence is to be counted

3. Compare the array elements one by one with the search element

4. If there is a match, the counter is incremented

5. At the end of the array,
                   if counter=0  print "number not present in the array"
                    else
                        print Counter

Program

//Program to count the number of occurrences of an element in an array
#include<stdio.h>
#include<conio.h>
#define SIZE 20
main()
{
  int arr[SIZE],i,n,found=0,key;

  clrscr();
  printf("Enter the number of elements in the array\n");
  scanf("%d",&n);
  printf("\nEnter the array elements one by one\n");
  for(i=0;i<n;i++)
   scanf("%d",&arr[i]);
  printf("\nEnter the element to be searched\n");
  scanf("%d",&key);

  for(i=0;i<n;i++)
    if (arr[i]==key)
       found++;

  if (found==0)
     printf("\nThe element %d does not occur in the array\n",key);
  else
     printf("\nThe element %d occurs %d times in the array",key,found);

  getch();
}

/*
OUTPUT
--------
Enter the number of elements in the array
10                                                                            
                                                                               
Enter the array elements one by one                                            
1                                                                              
2                                                                              
3                                                                              
1                                                                              
4                                                                              
5                                                                              
1                                                                              
67                                                                            
1                                                                              
8                                                                              
                                                                               
Enter the element to be searched                                              
1                                                                              
                                                                               
The element 1 occurs 4 times in the array
*/