반응형
- Introducing Arrays
- a collection fo the same types of data
int size = 4;
double myList[size]; //Wrong
const int size =4;
double myList[size]; //Correct
- No Bound Checking
- C++ does not check array's boundary
- e.g., myList[-1] and myList[11] does not cause syntax errors
dataType arrayName[arraySize]= {value0, value1, .... , valuek};
Wrong
double myList[4];
myList={1.9, 2.9, 3.4, 3.5};
Implicit Size
double myList[]={1.9, 2.9, 3.4, 3.5};
Printing arrays
for (int i=0; i<ARRAY_SIZE; i++)
{
cout<<myList[i]<<" ";
}
Copying Arrays
Wrong
list = myList;
Right
for(int i=0; i<ARRAY_SIZE; i++)
{
list[i]=myList[i];
}
Passing Arrays to Functions
#include <iostream>
using namespace std;
void printArray(int list[], int arraySize);
int main()
{
int numbers[5] = { 1,4,3,6,8 };
printArray(numbers, 5);
return 0;
}
void printArray(int list[], int arraySize)
{
for (int i = 0; i < arraySize; i++)
{
cout << list[i] << " ";
}
}
-> pass its size in another argument
- Initializing Character Arrays
char city[] = {'D', 'a', 'l', 'l', 'a', 's'}; //Wrong
char city[]="Dallas"; //Right
'D' | 'a' | 'l' | 'l' | 'a' | 's' | '\0' |
#include <iostream>
using namespace std;
int main()
{
char city[] = "Dallas";
cout << city;
cout << sizeof(city);
cout << strlen(city);
char city2[] = { 'D','a','l','l','s' };
cout << city2;
cout << sizeof(city2);
cout << strlen(city2);
return 0;
}
Converting Numbers to Strings
#include <iostream>
#include<string>
using namespace std;
int main()
{
int x = 15;
double y = 1.32;
long long int z = 10935;
string s = "Three numbers: " +to_string(x) + "," + to_string(y) + ",and " + to_string(z);
cout << s << endl;
return 0;
}
반응형
'Programming > C++ 1' 카테고리의 다른 글
[C++] Chapter 11. Pointers and Dynamic Memory Management (0) | 2021.04.04 |
---|---|
[C++] Swap Function (0) | 2021.04.04 |
[C++] Chapter 6. Functions (0) | 2021.04.04 |
[C++] Chapter 2. Elementary Programming (0) | 2021.04.04 |
[C++] Chapter1. Introduction to Computers, Programs, and C++ (0) | 2021.04.04 |