-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrays.cpp
More file actions
51 lines (38 loc) · 2.29 KB
/
Arrays.cpp
File metadata and controls
51 lines (38 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
int main()
{
//array = a data structure that can hold multiple values of the same type
// values are accessed by an index number
// "kind of like a variable that holds multiple values"
std::string cars[] = {"Corvette", "Mustang", "Camry"}; // arrays can only contain valyes of the same type
//could also declare an array without assigning values, size is required though: cars[3];
//You then could individually assing values to the indexes: cars[0] = "Corvette"; cars[1] = "Mustang"; cars[2] = "Camry";
cars[0] = "Camaro";
std::cout << "Example 1:\n";
std::cout << cars << '\n'; //prints the memory address of the first element in the array
std::cout << cars[0] << '\n'; // prints the variable stored at the first memeory address
std::cout << cars[1] << '\n';
std::cout << cars[2] << '\n';
std::cout << sizeof(cars) << " bytes in size\n"; // prints the size of the array in bytes
std::cout << sizeof(cars)/sizeof(std::string) << " elements in array\n"; // prints the size of the array in bytes
double prices[] = {5.00, 7.50, 9.99, 15.00}; // array of doubles
std::cout << "Example 2:\n";
std::cout << prices[0] << '\n'; // prints the variable stored at the first memeory address
std::cout << prices[1] << '\n';
std::cout << prices[2] << '\n';
std::cout << prices[3] << '\n';
std::cout << sizeof(prices) << " bytes in size\n"; // prints the size of the array in bytes
std::cout << sizeof(prices)/sizeof(double) << " elements in array\n"; // prints the size of the array in bytes
std::cout << "Example 3: Iterating through an array\n";
std::string students[] = {"spongebob", "patrick", "squidward", "Sandy"};
for(int i = 0; i < sizeof(students)/sizeof(std::string); i++) //calulates number of elements in array and sets that as the limit for the loop
{
std::cout << students[i] << '\n'; // prints the variable stored at the first memeory address
}
char grades[] = {'A', 'B', 'C', 'D', 'F'}; // array of chars
for(int i = 0; i < sizeof(grades)/sizeof(char); i++) //calulates number of elements in array and sets that as the limit for the loop
{
std::cout << grades[i] << '\n'; // prints the variable stored at the first memeory address
}
return 0;
}