프로그래밍 문제/c# 문제
61. c# 2차원 배열 주변 요소의 합 구하기
지나팩
2025. 1. 27. 15:31
아래의 2차원 배열에서 행과 열의 인덱스를 입력받아 해당 인덱스 주변 요소의 합을 구하여 출력하는 코드를 작성하세요.
입력 예) 행: 1 열: 1, 주변요소
출력 예) 1+2+3+6+8+11+12+13 = 56
코드는 아래에~~~~~~~~~~~~~~~~~~~~~
00000000000000000000000000000
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
|
using System;
class Program
{
static void Main()
{
// 5x5 배열 생성 및 초기화
int[,] array = {
{ 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 }
};
// 특정 위치 입력받기
Console.Write("행 인덱스 (0~4): ");
int row = int.Parse(Console.ReadLine());
Console.Write("열 인덱스 (0~4): ");
int col = int.Parse(Console.ReadLine());
// 주변 요소의 합 계산
int sum = GetSurroundingSum(array, row, col);
Console.WriteLine($"({row}, {col}) 주변 요소의 합: {sum}");
}
static int GetSurroundingSum(int[,] array, int row, int col)
{
int sum = 0;
int rows = array.GetLength(0);
int cols = array.GetLength(1);
// 주변 8칸 및 자기 자신 탐색
for (int i = row - 1; i <= row + 1; i++)
{
for (int j = col - 1; j <= col + 1; j++)
{
if (i >= 0 && i < rows && j >= 0 && j < cols && !(i == row && j == col))
{
sum += array[i, j];
}
}
}
return sum;
}
}
|
cs |