Index array variables in C on the Parallax Propeller
We've gone over array variables, and my many foibles with them, so of course we have another example to learn from :)
http://learn.parallax.com/propeller-c-start-simple/index-array-variables
As you remember, arrays are pretty much the awesome. And with the use of a for loop, you get even greater things like being show what's in the array without having to say print or printf all the time. (http://tymkrs.tumblr.com/post/56883271024/array-variables-in-c-on-the-propeller <-- example).
Here we have our array of numbers in array p. And set a variable i to go through the number of elements in the array. Variable i would be what was plugged into the p[%d] portion, and then whatever was in that would be put out into the serial terminal - much like what you see above!
Now. Sometimes you may not know how many elements you have in an array. Luckily, you can use sizeof. It returns the number of bytes consumed by an object in memory, such as an array, or even an element within the array.
In the example program above, we knew our array had 5 elements, so we used i < 6 as the for loop's condition to access all of the elements in the p array. But what if we didn't know how many elements were in the p array? Here's a for loop that would work:
for(int i = 0; i < sizeof(p)/sizeof(int); i++)
So here, we use that trick. First you notice we don't set the conditional statement to a set number. We instead use the sizeof function. We use the number of bytes taken up by the whole array and divide it by the number of bytes taken up by a single element in the array to get the number of elements in the array. And voila! It works!
The assignment for today is to
Write a program that multiplies each array element by 100 and then stores the result back to the array element. Then, have a second loop display all the values. If you did it right, that second loop should display 100, 200, 300, 500, 700, 1100, etc.
Wahoo!
@atdiy/@tymkrs












