Zanderg
Zanderg

Reputation: 157

Finding the smallest integer

So I feel like im really close to the answer. just i cant figure out exactly what i'm missing. The program fills an array with random numbers and then runs it to find which number is the smallest. once it finds the smallest number it prints it out along with its location. Im having trouble with my for loop to find the smallest integer.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void main(int argc, char* argv[])
{
    const int len = 8;
    int a[len];
    int smallest;
    int location =1;
    int i;

    srand(time(0));

    //Fill the array
    for(i = 0; i < len; ++i)
    {
        a[i] = rand() % 100;
    }

    //Print the array
    for (i = 0; i < len; ++i)
    {
        printf("%d ", a[i]);
    }
    printf("\n");

    //Find the smallest integer
    smallest = a[0];
    for (i = 1; i < len; i++)
    {
        if (a[i] < smallest)
        {
            smallest = a[i];
            location = i++;
        }
        printf("The smallest integer is %d at position %d\n", smallest, location);
        getchar();
    }
}

Upvotes: 1

Views: 489

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753705

You have two problems. One is correctly identified by Pete Pei Guo in his answer. For my money, the correct fix is location = i; but it depends on what you want to report.

The other problem is that your printf() call is in the loop. You should have:

smallest = a[0];
for (i = 1; i < len; i++)
{
    if (a[i] < smallest)
    {
        smallest = a[i];
        location = i;
    }
}
printf("The smallest integer is %d at position %d\n", smallest, location);
getchar();

I wouldn't bother with the getchar(), but I know people using GUI/IDE development tend to need it to prevent the window vanishing just because the program exited.

Upvotes: 0

Peter Pei Guo
Peter Pei Guo

Reputation: 7870

The trouble is this:

location = i++;

This line actually changes the value of i, which is the index you used to loop, so some of the elements are skipped - basically about half are skipped.

You probably wanted something like the following, which does a simple assignment without change the value of i:

location = i + 1; 
//or location = i, 
//depending on whether you want to print the location as 0-based or 1-based

Upvotes: 2

Related Questions