#include <iostream>
#include <conio>
#define SIZE 4
int main()
{
float score[SIZE];
int i;
cout<<"Enter "<<SIZE <<" floats: \n";
for(i=1; i<=SIZE;i=i+1)
cin>>score[i];
cout<<"The scores in reverse order are: \n";
for(i=SIZE; i>=1; i=i-1)
{cout<<score[i];
cout<<endl;}
getch();
return 0;
}
Hi, can I know why I must put ">" inside line 13 above? Why can't I do like the one below? I mean the "end" point is just at i=1, so why do we need to use i>=1 instead? Thanks...
I think you meant i==1, as i=1 is assignment, not comparison.
The second part of the for loop is not the end loop. It's the loop condition; the loop will only run so long as that condition is true, just like a while loop.
Your code invalid because indexing of array elements starts from zero. So your array score has no element with the index equal to 4.
Also if you have a modern compiler it shall issue an error because you did not specify that you are using names from the standard name space. The correct code will look
What ZHuge said. The second part is the running condition, not the stopping condition. It might be easier to understand by turning it into a while loop:
for (int i = SIZE; i >= 1; i--) { ... }
is equivalent to:
The above while loop should work. and Vlad is right. An array of size 4 is actually 5 indexes, 0 1 2 3 and 4. index 4 is used for the "null terminator" or /0. This tells the computer where your array ends. 0 1 2 and 3 store all four of your values.
The above while loop should work. and Vlad is right. An array of size 4 is actually 5 indexes, 0 1 2 3 and 4. index 4 is used for the "null terminator" or /0. This tells the computer where your array ends. 0 1 2 and 3 store all four of your values.
An array of size 4 has 4 valid indexes. 0, 1, 2 and 3. There is no "null terminator" that tells the computer where your array ends.
This is correct, if somewhat odd. i < SIZE or i != SIZE would be more usual.
1 2
for(i=1; i<=SIZE;i=i+1)
cin>>score[i];
This is not correct. It uses the indexes 1-4, and as we've already established, valid indexes are 0-3.
And I just noticed: you have the indexes wrong in the first block for the while loop and right in the second code block. Strangely, in the opposite way you got the for loops right/wrong.
Thanksn cire for ur explanation of "null terminator", actually before that I confuse why we need it, now I know that no "null terminator" actually....
NerdTastic actually confused that with a string. if you have something like this: constchar *x = "1234"; then he's right. There's a '\0' terminator and 5 elements and you can use 'x' as an array.