Veske
Veske

Reputation: 557

C - Problems with indexes

So I am making this simple sorting algorithm that puts the numbers in an array to be in ascending order.

This is how my code looks like right now:

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

int main(void){
    int x,smallest,z,n,count;
    int * numbers = NULL;
    printf("Sisestage arvude hulk: ");
    scanf("%d",&n); 
    numbers = malloc(sizeof(int)*n);
    if(numbers==NULL){
        return -1;
        }
    for(count=0;count<n;count++){
        printf("Arv %d: ",count+1);
        scanf("%d",&numbers[count]);
        }
    smallest = numbers[0];
    for(count=0;count<n;count++){
        printf("Number %d  Index %d\n",numbers[count],count);
        if(numbers[count]<smallest)
            smallest = numbers[count];
            z = count;
        }
    /*numbers[0] = smallest;
    numbers[z] = x;*/
    printf("Smallest: %d, It's index: %d Array size: %d\n",smallest,z,n);
    }

The problem here is that when the program is finished, z = the last index in the array for some reason. The z = count is in a if statement that should help this kind of thing not happen, yet it still does. Why is that?

Upvotes: 2

Views: 97

Answers (3)

Pandrei
Pandrei

Reputation: 4961

 if(numbers[count]<smallest)
            smallest = numbers[count];
            z = count;

is the same as:

if(numbers[count]<smallest)
{
     smallest = numbers[count];
}
z = count;

So it's a parentheses problem

Upvotes: 1

Martin R
Martin R

Reputation: 539975

You forgot to enclose the if-block in braces:

if(numbers[count]<smallest) {
        smallest = numbers[count];
        z = count;
}

Therefore, in your case, z = count is always executed.

Also, z is uninitialized if the first element numbers[0] happens to be the smallest, therefore you should initialize it with

 smallest = numbers[0];
 z = 0;

Upvotes: 6

mclc
mclc

Reputation: 65

You need to use brackets {}with your if when you can have more than ONE statement.

That should fix it.

Solution:

if(numbers[count]<smallest) {
        smallest = numbers[count];
        z = count; }

Upvotes: 1

Related Questions