w3resource

C Exercises: Find the integer that appears the least often

C Basic-II: Exercise-1 with Solution

Write a C program that takes n number of positive integers. Find the integer that appears the least number of times among the said integers. If there are multiple such integers, select the smallest one.

Sample Date:

(1,2,3) -> 1
(10, 20, 4, 5, 11) -> 4

C Code:

#include <stdio.h> // Include standard input/output library

int ctr[101]; // Declare an array 'ctr' of size 101 to count occurrences
int num; // Declare a variable 'num' to hold the number of integers

int main()
{
int i, x, min_num, result; // Declare variables for iteration, input, minimum value, and result

  // Prompt the user to enter the number of integers
printf("What is the number of integers you wish to input? ");

  // Read the number of integers from the user
scanf("%d", &num);

  // Prompt the user to input the numbers
printf("Input the number(s):\n");

  // Loop to read and count occurrences of each integer
for (i = 0; i<num; i++)
  {
    // Read an integer from the user
scanf("%d", &x);

    // Increment the count of occurrences for the input integer
ctr[x]++;
  }

min_num = 100; // Initialize 'min_num' to a large value for comparison

  // Loop to find the smallest integer with non-zero occurrences
for (i = 1; i<= 100; i++)
  {
    // Check if the count of occurrences is non-zero and smaller than 'min_num'
if (ctr[i] > 0 &&ctr[i] <min_num)
    {
result = i; // Update 'result' with the current integer
min_num = ctr[i]; // Update 'min_num' with the current count
    }
  }

  // Print the smallest integer among the input integers
printf("Smallest among the said integers: %d\n", result);

  // Return 0 to indicate successful program execution
return 0;
}

Sample Output:

What is the number of integers you wish to input? 3
Input the number(s):
1
2
3
Smallest among the said integers: 1

Flowchart:

C Programming Flowchart: Find the integer that appears the least often

C Programming Code Editor:

Previous C Programming Exercise: C Basic Part-II Exercises Home
Next C Programming Exercise: Reverse a string partially.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.