Is there an easy way to find a minimum value in an array? Thanks.
Printable View
Is there an easy way to find a minimum value in an array? Thanks.
Certainly,
1. Declare a variable (foo) to store the minimum.
2. foo = arr[0]
3. for every element in arr, if less than foo, assign foo to new value.
Code:int min=0;
for (int i=0;i<iSizeOfArray;i++)
{
if (i==0)
min=Array[i];
else
if (Array[i]<min) min=Array[i];
}
Thanks, sorry for not providing an example in C in the first place, I unrealistically expected them to try to learn things for themselves.
Thanks a lot. But I have another question. Is there a way to make it so that all the numbers will print out from smallest to largest? All that gives me is the smallest number every time.
Sort the array, then print it.
Search the board for lots of examples.
I checked, but still do not understand how to sort the array. Most examples have the array with numbers already entered, but in my program, the user enters up to 10 numbers, or presses 0 to quit. Any help? Here is my code:
Code:#include <stdio.h>
#include <math.h>
#define Max_numbers 10
int main(void)
{
double x[Max_numbers],
sum = 0,
average;
int y;
int i;
int step = 1;
char str[256];
printf("Created by Matt Torsiello\n\n");
printf( "Please enter your name:\t " );
gets(str);
printf("Hello, %s!\n", str);
printf("Please Enter %d numbers separated by returns\n",
Max_numbers);
for (i = 0; i < Max_numbers; ++i) {
scanf("%lf", &x[i]);
if (x[i] == 0) {
y = i;
i +=10;
step = 2; }
}
if (step == 2) {
printf ("You entered %d numbers.\n", y);
for (i = 0; i < y; ++i) {
printf("\n%.2f", x[i]);
sum += x[i]; }
}
printf("\n\nThe total is %.2f.", sum);
average = sum / y;
printf("\nThe average is %.2f.", average);
system("Pause");
return (0);
}
Read in your numbers like this:
then use a bubble sort like the one hereCode:for (count = 0; count < MAX; count++)
{
printf ("Enter an integer - 0 to quit: ");
scanf ("%d", &temp);
if (temp != 0)
numbers [count] = temp;
else break;
}
just change the looping condition to outer < count instead of 9.
That should then sort the array, for as many entries as you have
entered.
EDIT: Use fgets for reading in your string!!!!!!!!!!!!!
\:D/Quote:
Originally Posted by cwr