Home > Software engineering >  Unexpected output - Choosing the lowest number from an array
Unexpected output - Choosing the lowest number from an array

Time:06-06

I want to find the smallest number from the numbers in an array entered by the user. The output I am getting for the program is a vague number -858993460. This is generally because of a type mismatch but they seem alright here. Not able to think of a solution. Thanks for the help!

    
```

    //
    #include<stdio.h>
    int main()
    {
        int a;
        int i;
        int num[25];
        printf("Enter the 25 numbers:");
        for (i = 0; i <= 24; i  )
        {
            scanf("%d", &num[i]);
        }
    
        for (i = 0; i <= 24; i  )
        {
            a = num[i];
            if (a < num[i 1])
            {
                a = a;
            }
            else
                a = num[i 1];
        }
        printf("Lowest number is %d\n", a);
        return 0;
    
    }

CodePudding user response:

Hope this will work for you. Just remove the else statement and bring a=num[i] inside if statement and consider the first element is the minimum element by doing this a = num[0]

#include<stdio.h>
int main()
{
    int a;
    int i;
    int num[25];

    printf("Enter the 25 numbers:");

    for (i = 0; i <= 24; i  )
    {
        scanf("%d", &num[i]);
    }

    a = num[0];
    
    for (i = 0; i <= 24; i  )
    {     
        if (num[i] < a)
        {
             a = num[i]; 
        }
    }
    printf("Lowest number is %d\n", a);
    return 0;
}

CodePudding user response:

Your problem is the i 1 statement. When on i = 24, the next index is out of bounds. Instead of throwing an error, C lets you access that part of memory, giving you whatever garbage data was stored there. That's why you're getting such a random result.

  • Related