Game Programming




 
game programming
Game Programming :: Programming :: General Programming :: Code Examples :: [C++] The Array - View Topic
Topic Rating: *****
Printable View
Andy
Administrator
*****

Posts: 40
Status: Offline
Gender: Male
Joined:  
pm

Reputation: 0%

[C++] The Array (11th Jan 08 at 2:08am UTC)
Level: Beginner

An array is a data structure which can store multiple pieces of data of the same type. This is very important because in most cases, a program wants to collect a set of values related to each other. For example, let's say you needed a program to collect the heights of 50 people. Without an array, you would have to make 50 separate variables. One for each person. However, with the array in C++, you can actually store all 50 pieces of data in one array. Below is the syntax for this array

Code:
 
  1. double heightCollector [50];
  2.  
 


Then to store all the data into the array. You would implement a for loop. Below is a code example that gets the height data on 50 people:

Code:
 
  1. #include <iostream>
  2. #define cls system ("cls")
  3. #define pause system ("pause")
  4.  
  5. using namespace std;
  6.  
  7. int main () {
  8. const int MAX = 50; // sets array to hold 50 heights
  9. int num = 0; // for second for loop
  10. double heightCollector [MAX]; // holds 50 pieces of data
  11.  
  12. // This for loop fills the array from user input
  13. for (int i=0; i < MAX; i++)
  14. {
  15. cout << "Enter a height value: ";
  16.  
  17. cin >> heightCollector [i];
  18.  
  19. cls; // Will clear above statement off the console window
  20. }
  21.  
  22.  
  23. // This will print out the arrays data values
  24. cout << "Print Out Array:\n\n";
  25.  
  26. for (int i = 0; i < (MAX / 10); i++)
  27. {
  28. for (int j = 0; j < 10; j++)
  29. {
  30. cout << heightCollector [num] << " ";
  31. ++num;
  32. }
  33.  
  34. cout << "\n\n";
  35. }
  36.  
  37. pause; // Will force the program to stop so window will not close
  38.  
  39. return(0);
  40. }// end of main
  41.  
  42.  
 
 Printable View

All times are GMT+0 :: The current time is 7:57am
Page generated in 0.1637 seconds
Purchase Ad-Free Credits
This Forum is Powered By vForums (v2.4)
Create a Forum for Free | Find Forums