Method to Find the Smallest Number from an Integer

Finding the smallest number in an array of integers

If you simply want to print out the smallest element of an array, this is about the most basic way to do it:

#include <limits.h>
#include <stdio.h>

int smallest(int* values, int count)
{
int smallest_value = INT_MAX;
int ii = 0;
for (; ii < count; ++ii)
{
if (values[ii] < smallest_value)
{
smallest_value = values[ii];
}
}
return smallest_value;
}

int main()
{
int values[] = {13, -8, 237, 0, -3, -1, 15, 23, 42};
printf("Smallest value: %d\n", smallest(values, sizeof(values)/sizeof(int)));
return 0;
}

How to Find Smallest Number Based On User Input - Java

Algorithm:

  1. Input the first number and assume it to be the smallest number.
  2. Input the rest of the numbers and in this process replace the smallest number if you the input is smaller than it.

Demo:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
final int LIMIT = 5;
int counter = 1;
double number;

Scanner s = new Scanner(System.in);

// Input the first number
System.out.print("Enter the number: ");
number = s.nextDouble();
double smallest = number;

// Input the rest of the numbers
while (counter <= LIMIT - 1) {
System.out.print("Enter the number: ");
number = s.nextDouble();

if (smallest > number) {
smallest = number;
}

counter++;

}

System.out.println("The smallest number is " + smallest);
}
}

A sample run:

Enter the number: -4040404
Enter the number: 808080
Enter the number: -8080808
Enter the number: 8989898
Enter the number: -8989898
The smallest number is -8989898.0

Note: Do not close a Scanner(System.in) as it also closes System.in and there is no way to open it again.

Find smallest number in a list



Related Topics



Leave a reply



Submit