c++/2주차
[c++][4강] 제어문과 함수/배열
아너
2022. 1. 15. 17:37
1. 2차원 배열
1)2차원 배열의 초기화
int s[][5]={
{0,1,2,3,4},
{10,20,30,40,50}
}
최고차원의 사이즈 정보만 생략가능
case1)
int s[][5]={
{0,1,2},
{10,20,30}
}
5개 다 넣어주지 않아도 됨
case2)
int s[][5]={
0,1,2,3,4,
10,20,30,40,50
}
일렬로 넣어도 자동으로 하나씩 끊어서 입력됨.
2)2차원 배열 예시
#include <iostream>
using namespace std;
int main()
{
const int ROW = 4;
const int COL = 3;
int arr[ROW][COL] = { 0, };
//배열의 이름 정보
cout << arr << endl;
cout << &arr << endl;
cout << sizeof(arr) << endl;
//배열의 층 정보
cout << arr[0] << endl;
cout << &arr[0] << endl;
cout << sizeof(arr[0]) << endl;
//배열의 방 정보
cout << arr[0][0] << endl;
cout << &arr[0][0] << endl;
cout << sizeof(arr[0][0]) << endl;
return 0;
}
<lab실습>
lab1) 2차원 배열
3개의 방에 겹치지 않도록 문자 3개를 랜덤하게 배치
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int ROW = 10;
const int COL = 10;
int arr[ROW][COL] = { 0, };
string item[4] = {"※","○","☆","□"};
srand(time(NULL));
for (int i = 1; i < 4; i++)
{
int x = rand() % 10;
int y = rand() % 10;
if (arr[x][y] == 0)
arr[x][y] = i;
else
i--;
}
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
switch (arr[i][j])
{
case 0:
cout << item[0]; break;
case 1:
cout << item[1]; break;
case 2:
cout << item[2]; break;
case 3:
cout << item[3]; break;
}
}
cout << endl;
}
return 0;
}
lab2)좌석 예약하기
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
const int ROW = 6;
const int COL = 4;
int arr[ROW][COL] = { 0, };
string item[2] = {"○","●"};
string reserve;
while (true)
{
system("cls"); //계속하려면 아무키나 누르십시오..
//좌석 출력
for (int i = 0; i < ROW; i++)
{
cout << char(i + 'A') << " : ";
for (int j = 0; j < COL; j++)
{
switch (arr[i][j])
{
case 0:
cout << item[0]; break;
case 1:
cout << item[1]; break;
}
}
cout << endl;
}
//좌석 입력받기
cout << "좌석을 입력해주세요(예: A1). 종료를 원할경우 행,열 문자를 동일하게 입력(예: AA) ";
char x, y;
cin >> x >> y;
if (x == y)
{
cout << "종료합니다" << endl;
return 0;
}
else
{
if (arr[x - 'A'][y - '1'] == 0)
{
arr[x - 'A'][y - '1'] = 1;
cout << "예약이 완료되었습니다" << endl;
}
else if (arr[x - 'A'][y - '1'] == 1)
{
cout << "이미 예약된 좌석입니다." << endl;
}
system("pause"); //화면 잠시 멈추기
}
}
}