데일리 codeup/이차원 배열

배열의 합_220713

hayo_su 2022. 7. 13. 13:22

2차원 배열 입력


배열의 합

4개의 줄에 각 줄마다 4개의 정수가 주어집니다. 줄의 합을 구하는 프로그램을 배열을 사용하여 작성해보세요.

#include <iostream>
using namespace std;
int main(){
    int arr[4][4];
    int cnt;
    for(int x=0;x<4;x++)    for(int y=0;y<4;y++)    cin>>arr[x][y];
    for(int i=0;i<4;i++){
        cnt = 0;
        for(int j=0;j<4;j++){
            cnt += arr[i][j];
        }
        cout<<cnt<<endl;
    }
    return 0;
}

대문자로 바꾸기

소문자 알파벳으로 이루어진 5행 3열의 배열이 주어지면 대문자로 바꾸어서 출력하는 프로그램을 작성해보세요.

대소문자 변환
대문자 -> 소문자

  • 32를 더해줌
  • tolower

소문자 -> 대문자

  • 32를 빼줌
  • toupper
#include <iostream>
using namespace std;
int main(){
    char arr[5][3];
    for(int x=0;x<5;x++)    for(int y=0;y<3;y++)    cin>>arr[x][y];
    for(int x=0;x<5;x++){
        for(int y=0;y<3;y++)    cout<<(char)toupper(arr[x][y])<<' ';
        cout<<endl;
    }
    return 0;
}

배열의 평균

숫자로 이루어진 2행 4열의 배열이 주어지면 가로 평균, 세로 평균, 전체 평균을 소수 첫째 자리까지만 출력하는 프로그램을 작성해보세요.

#include <iostream>
using namespace std;
int main(){
    int arr[2][4];
    int sum;
    cout<<fixed;
    cout.precision(1);
    for(int i=0;i<2;i++)    for(int j=0;j<4;j++)    cin>>arr[i][j];
    //가로평균
    for(int x=0;x<2;x++){
        sum = 0;
        for(int y=0;y<4;y++)    sum += arr[x][y];
        cout<<(double)sum/4<<' ';
    }
    cout<<endl;
    //세로평균
    for(int y=0;y<4;y++){
        sum = 0;
        for(int x=0;x<2;x++)    sum += arr[x][y];
        cout<<(double)sum/2<<' ';
    }
    cout<<endl;
    // 전체평균
    sum = 0;
    for(int x=0;x<2;x++)    for(int y=0;y<4;y++)    sum += arr[x][y];
    cout<<(double)sum/8;
    return 0;
}

특정 원소들의 합

4 x 4 크기의 격자에 정수가 하나씩 주어져있습니다. 이 정수들 중 다음 그림에서 색칠된 칸들에 해당하는 정수의 합을 2차원 배열을 통해 구하는 프로그램을 작성해보세요.

#include <iostream>
using namespace std;
int main(){
    int arr[4][4];
    int sum = 0;
    for(int x=0;x<4;x++)    for(int y=0;y<4;y++)    cin>>arr[x][y];
    for(int i=0;i<4;i++){
        for(int j=0;j<4;j++){
            if(i>=j)    sum+= arr[i][j];
        }
    }
    cout<<sum;
    return 0;
}