carraysfor-loop

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();
    }
}

Solution

  • 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