본문 바로가기

Programming/C++ 1

[C++] Chapater 7. Single-Dimensional Arrays and C-Strings

반응형
  • 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;
}

 

반응형