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:
- Input the first number and assume it to be the smallest number.
- 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
Javac: File Not Found: First.Java Usage: Javac <Options> <Source Files>
Spring - Read Property Value from Properties File in Static Field of Class
Eclipse No Tests Found Using Junit 5 Caused by Noclassdeffounderror for Launcherfactory
How to Specify the Required Java Version in a Gradle Build
Split Comma Separated Values in Java, Int and String
Launching Spring Application Address Already in Use
How to Handle Errors in Spring-Webflux
Using an Empty Keystore Password Used to Be Possible
How to Find Max Duplicate Number Count in Given Array Using for Loop
Javax.Net.Ssl.Sslexception: Certificate Doesn't Match Any of the Subject Alternative Names
Org.Hibernate.Annotationexception: @Onetoone or @Manytoone on <Entity> References an Unknown Entity
Automatically Size Jpanel Inside Jframe
How to Check Heap Usage of a Running Jvm from the Command Line
Error While Running Allure Command Line Generate Command
Spring Security Configuration Filter Any Requests Except a Specific Endpoint