What is printed by the following code?
Code:int s[4] = {9,1,2,5}; printf("%d\n", s[4]);
When I run this program I get 0, however I'm not sure why it is that it prints 0. Could anyone explain this to me?
What is printed by the following code?
Code:int s[4] = {9,1,2,5}; printf("%d\n", s[4]);
When I run this program I get 0, however I'm not sure why it is that it prints 0. Could anyone explain this to me?
You declare s to be an array with 4 items. In C, arrays start at 0, so valid indexes are s[0]...s[3]. s[4] does not print the whole array (you need to do that one element at a time). Instead, it tries to print the 5th element of an array with only 4 elements. This is an out of bounds error, and results in undefined behavior, meaning anything can happen though likely it will vary from "random" behavior (like printing a 0) to program crashes due to invalid memory accesses.
I suggest you re-read carefully the section on arrays in your textbook or whatever online tutorials you're using.
Thanks, I read through the section again and got a little bit better of handle on it.
However now I am working on this.
I want this program to print the position of the smallest value rather than the smallest value itself. Therefore instead of printing 1 it should be printing 2 because that is the position of the smallest value.Code:#include <stdio.h> int main(){ int x[7] ={4,2,1,6,3,8,9}; int min = x[0]; int i; for (i = 0; i < 7; ++i) { if (x[i] < min) { min = x[i]; } } printf("%d\n", min); }
Any help?
If 'x[i]' represents a value, then 'i' represents the position of that value in the array. You're using the variable "min" to keep track of the smallest value - so why not make another variable to keep track of which position the minimum value is found?
"...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson
Right, just like others said...add additional variable such as int minpos and within your "if" statement just add under min = x[i]; minpos = i ; and print minpos, that will give you the location within the array for the lowest number.
Two notes. First, regarding your question, it might be a bit easier if you gave better variable names (they're not bad as is, but could be better) to what you wanted to keep track of:
Second, even for a trivial program like this, you should use a constant for your array size, and used it in the declaration, any loops, etc:Code:int min_value = x[0]; int min_index = ???
That would make changing your array size (e.g. from 4 to 7) much easier, you only have to change the #define, and in this case the initial values. This will become absolutely critical for writing, testing and maintaining your programs as they become more complex.Code:#define ARRAY_SIZE 7 ... int x[ARRAY_SIZE] = {...}; for (i = 0; i < ARRAY_SIZE; i++)