Hello,
Like I've said C++ is very new to me and I have some questions...
- 1. #include <iostream>
-
2. using namespace std;
-
3. const int MAXSIZE = 10;
-
4. main(){
-
5. int tbl[ MAXSIZE ], n;
-
6. n = 0;
-
7. while( ( n < MAXSIZE ) && ( cin >> tbl[ n ] ) ) { n++; }
-
8. cout << “FIRST ELEMENT ” << tbl[ 0 ] << endl;
-
9. cout << “MIDDLE ELEMENT ” << tbl[ n / 2 ] << endl;
-
10. cout << “LAST ELEMENT ” << tbl[ n – 1 ] << endl;
-
11. return 0;
-
12. }//MAIN
please correct my terminology if it's wrong.
I'm having a hard time understanding this program...I dont even know where to begin. I'm not sure why in line seven I understand the first part of the loop. But if tbl is declared with the varible MAXSIZE on line seven and eight I'm not sure what purpose the "tbl[n] play and tbe[0] in 9 and 10 I'm completely lost too...can someone help me out with this?
Mike
First, I'm going to move this thread to the C/C++ forum, where you're much more likely to get an accurate answer.
Next, I'll try and summarize what this code does as well as I can.
Lines 1 and 2 are standard and should require no explanation.
Line 3 defines MAXSIZE to be a constant variable (type int, value 10). This is used to limit the size of your array to 10 elements.
Line 5 declares an int n and Line 6 sets it to 0. n is the index for your array - it is first used to initialize each value in you array, and later, to access certain elements.
Line 5 also declares your array tbl with 10 elements, although the const MAXSIZE is used. Thus, if you changed the value in MAXSIZE, there would more more/less elements.
Now is where you might start to have trouble. Line 7 is a complicated line, so I'll try to break it down.
You're entering a while loop, which will get values from the user to put into the array. The first condition is that n < MAXSIZE. This ensures that you do not try to put values into an area that is not controlled by the array. The second condition isn't exactly a condition - it will prompt the user for input into the nth value of tbl. As long as the user enters a proper int value, this will return true - thus, as long as n is less than MAXSIZE and the user enters an int value, the loop will execute. If the user hits a bad value - a character, for example - then cin will return false, and your loop will stop executing.
The body of your loop will increment n, so as long as the input was fine and you haven't filled the array, you continue initializing values to tbl.
After your loop executes, n will be the index of the last number entered into tbl. Note that this is not necessarily the same as MAXSIZE, because if the user hits a bad value for the 6th element, there will only be 5 elements in the array, and so n would be 4.
The final few lines print various values of tbl and then and your program.
Please feel free to ask any more questions you may have.