0

This is the C program that I've written to find the least element in the given array.

But the output is "0" every time. I've checked other websites too but I found no problem in my program. Can anyone please rectify the problem in this program. (Thanks in advance)

#include <stdio.h>
main()
{
    int i,least,x[10];
    printf("Enter the elements into the array\n");

    for (i=0;i<10;i++)
    {
        scanf("%d",&x[10]);
    }
    least=x[0];
    for (i=1;i<10;i++)
    {
        if(least > x[i])
        {
            least=x[i];
        }
    }
    printf("The least element in the array is %d", least);
 }
5
  • You may want to check your understanding of: 1) the number of elements x has space for. 2) What &x[10] means. Commented Jan 6, 2021 at 13:56
  • 3
    Should be voted to be closed as a typo. Commented Jan 6, 2021 at 13:56
  • 1
    You want &x[i] in your scanf(). Right now you always wrote to the 11th element of the array, leading to a buffer overflow btw. Commented Jan 6, 2021 at 13:57
  • When you fill an array you should write scanf("%d",&x[i]); (each case has one value) but in your code you write scanf("%d",&x[10]); so you fill the 10th case for 10 times Commented Jan 6, 2021 at 13:59
  • @Jarvis it's true that when the typo is corrected, there is no more question! ;) Commented Jan 6, 2021 at 13:59

1 Answer 1

8

In your code

 scanf("%d",&x[10]);

should be

 scanf("%d",&x[i]);
              ^^^

as you'd need to loop over the array element by element and the counter is i.

Also, by using index 10 on a 10-element array, you're off-by-one, accessing out of bound memory and invoking undefined behavior.

That said,

  • Use a proper signature for main(), for a hosted one, the minimalistic one would be int main(void).
  • Always check for success of scanf() for user inputs. Avoid using scanf() at all costs, use fgets() for better.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. How much time did you take to spot that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.