Recursive function that counts number of times a perticular number appears in the given array


write a function "count1(number, array, length) that counts the number of times 'number' appears in 'array'. The array has 'length' size. Use recursive function only.

Program:

#include<stdio.h>
int count1(int number,int array[],int length);
int count=0;
int main()
{
                  int i,length,number,count;
                  printf("enter the length of the array: ");
                  scanf("%d",&length);
                  int array[length];
                  printf(" enter array elements: ");
                  for(i=0;i<length;i++)
                  scanf("%d",&array[i]);
                  printf("enter the number to be counted: ");
                  scanf("%d",&number);
                  count=count1(number,array,length);
                  printf("%d",count);
                  return 0;
}
int count1(int number,int array[],int length)
{
                  if(length>0)
                 {
                           if(array[length-1]==number)
                           count++;
                           length--;
                           count1(number,array,length);
                           return count;
                 }
                 else return count;
}
 

Sample input and output:

enter the length of the array: 15
 enter array elements: 2 4 5 6 1 3  4  7 8  9  4  6 4 6 8
enter the number to be counted: 4

4

No comments: