C++/문제풀이

[C++] 2차원 배열 원소들의 합 구하기(난수 이용)

year.number 2022. 6. 13. 20:15

 

Power C++ p.229

2차원 배열 원소들의 합 구하기(난수 이용)


//
//  main.cpp
//
//  Created by yeonsu on 2022/06/13.
//

// 함수를 이용하여 2차원 배열의 원소들의 합 구하기

#include <iostream>
#include <ctime>        //rand 함수
#include <iomanip>
using namespace std;

//함수 원형 선언
int sum(int sum_array[][3]);


int main(){
    int array[3][3] = {0};       //2차원 배열 초기화
    srand((unsigned)time(NULL)); //매번 새로운 난수 출력
    
    //2차원 배열에 난수 집어넣기(이중 for문 활용)
    for(int i = 0; i<3; i++)
        for(int j = 0; j<3; j++)
            array[i][j] = (rand()%10);
    cout << endl;

    cout << "========" << endl;
    
    //2차원 배열 출력하기(이중 for문 활용)
    for(int i = 0; i<3; i++){
        for(int j = 0; j<3; j++)
            cout << array[i][j] << "\t";
    cout << endl;
    }
    cout << "========" << endl;
    
    //sum 함수 호출
    int result;
    result = sum(array);
    
    cout << "\n3x3 난수 배열의 합은 " << result << "입니다\n";
    
    return 0;
}

int sum(int sum_array[][3]){
    int sum = 0;
    
    for(int i = 0; i<3; i++)
        for(int j = 0; j<3; j++)
            sum += sum_array[i][j];
    
    return sum;
}

[실행결과]

 


[Key Point]

배열과 반복문은 짝꿍이다. (원소를 초기화할 때, 출력할 때 등 자주 사용)