Channi Studies

[C++] (Program) 함수 응용 프로그램 본문

C++/프로젝트 (Project)

[C++] (Program) 함수 응용 프로그램

Chan Lee 2023. 12. 18. 23:37

 

'반복문 응용 프로그램' 포스트에서 구현했던 프로그램을 함수를 적극적으로 이용하여 동일하게 구현해 보았습니다.

기존의 프로그램은 함수의 활용이 없었지만, 이번 프로그램은 함수로 변경하고 기능도 몇 개 추가하였습니다.

 

함수 없이 반복문들로만 구현된 기존의 프로그램은 다음 포스트에서 확인 가능합니다.

 

[C++] 반복문 응용 프로그램

코드 설명 switch문, for문, do-while문을 모두 활용한 간단한 프로그램입니다. 여러가지 기능을 수행하기 위해 사용자로부터 입력을 받고, 그 입력에 해당하는 기능을 수행합니다. 코드 #include using na

code-studies.tistory.com

 

간략하게 설명하자면,

사용자로부터 문자를 통해 옵션을 선택 받고 그에 따른 동작을 행하는 프로그램입니다.

모든 동작들은 벡터를 다루고 있으며, 프로그램 상으로는 리스트로 소개됩니다.

 


코드

#include <iostream>
#include <vector>

using namespace std;

// Prototype
void display_menu();
void print_nums(const vector<int> &vec);
void add_num(vector<int> &vec);
void del_num(vector<int> &vec);
void dp_mean(const vector<int> &vec);
void dp_min(const vector<int> &vec);
void dp_max(const vector<int> &vec);
void sort_vec(vector<int> &vec);
void clear_vec(vector<int> &vec);
void exit();

bool run{true};

int main() {
  vector<int> numbers{};
  char selection{};

  do {
    display_menu();
    cin >> selection;

    switch (selection) {
    case 'p':
    case 'P':
      print_nums(numbers);
      break;

    case 'a':
    case 'A':
      add_num(numbers);
      break;

    case 'd':
    case 'D':
      del_num(numbers);
      break;

    case 'm':
    case 'M':
      dp_mean(numbers);
      break;

    case 's':
    case 'S':
      dp_min(numbers);
      break;

    case 'l':
    case 'L':
      dp_max(numbers);
      break;

    case 'r':
    case 'R':
      sort_vec(numbers);
      break;

    case 'c':
    case 'C':
      clear_vec(numbers);
      break;

    case 'q':
    case 'Q':
      exit();
      break;

    default:
      cout << "❗️❗️❗️ INVALID INPUT. PLEASE RE-ENTER YOUR CHOICE ❗️❗️❗️ "
           << endl;
    }

    cout << endl;
  } while (run);
}

// Function Declare
void display_menu() {
  // Display menu
  cout << "\nP - Print numbers" << endl;
  cout << "A - Add a number" << endl;
  cout << "D - Delete a number" << endl;
  cout << "M - Display mean of the numbers" << endl;
  cout << "S - Display the smallest number" << endl;
  cout << "L - Display the largest number" << endl;
  cout << "R - Sort the list of numbers" << endl;
  cout << "C - Clear the list of numbers" << endl;
  cout << "Q - Quit" << endl;
  cout << "\nEnter your choice: ";
}

void print_nums(const vector<int> &vec) {
  if (vec.size() == 0) {
    cout << "Can't print numbers since there is no number in the list." << endl;
    return;
  }

  cout << "Printing numbers..." << endl;
  for (int num : vec) {
    cout << num << " ";
  }

  return;
}

void add_num(vector<int> &vec) {
  int adding_num;
  cout << "Enter a number you want to add: ";
  cin >> adding_num;

  cout << "Adding a number..." << endl;
  cout << "Succesfully added a number into the list." << endl;
  vec.push_back(adding_num);
}

void del_num(vector<int> &vec) {
  cout << "Displaying the numbers in the list with its index number:" << endl;
  for (size_t i{0}; i < vec.size(); i++) {
    cout << "[" << (i + 1) << "]"
         << " : " << vec.at(i) << endl;
  }

  int choice{};
  cout << "\nPlease enter the corresponding index of a number you want to "
          "delete from the list:";
  cin >> choice;

  vec.erase(vec.begin() + choice - 1);
  cout << "The number has been successfully deleted from the list." << endl;
}

void dp_mean(const vector<int> &vec) {
  if (vec.size() == 0) {
    cout << "Calculation failed since there is no number in the list." << endl;
    return;
  }

  cout << "Calculating mean of the numbers..." << endl;

  double total_num{};
  for (int num : vec) {
    total_num += num;
  }

  cout << "The mean of the numbers is " << (total_num / vec.size()) << "."
       << endl;
}

void dp_min(const vector<int> &vec) {
  if (vec.size() == 0) {
    cout << "Calculation failed since there is no number in the list." << endl;
    return;
  }

  int min_val = vec.at(0);

  for (int i{1}; i < vec.size(); i++) {
    if (vec.at(i) < min_val) {
      min_val = vec.at(i);
    }
  }
  cout << "The smallest number in the list is " << min_val << "." << endl;
}

void dp_max(const vector<int> &vec) {
  if (vec.size() == 0) {
    cout << "Calculation failed since there is no number in the list." << endl;
    return;
  }

  int max_val = vec.at(0);

  for (int i{1}; i < vec.size(); i++) {
    if (vec.at(i) > max_val) {
      max_val = vec.at(i);
    }
  }
  cout << "The largest number in the list is " << max_val << "." << endl;
}

void sort_vec(vector<int> &vec) {
  cout << "Sorting the list of numbers..." << endl;
  sort(vec.begin(), vec.end());
  cout << "The list has been successfully sorted." << endl;
}

void clear_vec(vector<int> &vec) {
  if (vec.size() == 0) {
    cout << "Can't clear the list because there is no element in the list."
         << endl;
    return;
  }

  cout << "🧹 Clearing the list of numbers... 🧹" << endl;
  vec.clear();
  cout << "The list has been successfully cleared out." << endl;
}

void exit() {
  cout << "👋 Turning off the program... 👋" << endl;
  run = false;
}

 

프로그램 출력 예시

 

pass by reference와 const 인자에 대한 개념이 있다면 쉽게 이해할 수 있는 코드입니다.