CS/C++

C++ 기초 정리

munsik22 2025. 3. 30. 00:03

📚 강의 영상

https://www.youtube.com/watch?v=-TkoO8Z07hI

C++이란?

  • C언어에 객체 지향 개념을 추가한 언어
  • C보다 확장된 언어로써 보다 복잡한 프로그래밍 구현 가능

1. 기본 출력

#include <iostream>

int main() {
    std::cout << "Hello world" << std::endl;
    std::cout << "I love pizza" << "\n";

    int x; // declaration
    x = 5; // assignment
    int y = 6;
    int sum = x + y;

    //std::cout << x << "\n";
    //std::cout << y << "\n";
    //std::cout << sum << "\n";

    // int
    int age = 21;
    int year = 2023;
    int days = 7.5;
    std::cout << days;

    // double (number including decimal)
    double price = 10.99;
    double gpa = 2.5;
    double temperature = 25.1;
    float height = 178.1;
    std::cout << height << std::endl;

    // single character
    char grade = 'A';
    char initial = 'B';
    char currency = '$';
    std::cout << initial;

    // boolean
    bool student = true;
    bool power = false;

    // string
    std::string name = "Bro";
    std::string day = "Friday";
    std::string address = "123 Fake St.";
    std::cout << "I live at " << address << "\n";

    return 0;
}

2. 상수 선언

#include <iostream>

int main() {
    const double PI = 3.14159;
    double radius = 10;
    double circumference = 2 * PI * radius;

    std::cout << circumference << "cm";
    return 0;
}

3. Namespace

#include <iostream>

namespace first{
    int x = 1;
    int y = 3;
}
namespace second{
    int x = 2;
}

int main() {
    /* Namespace provides a solution for preventing name conflicts
        in large projets. Each entity nedds a unique name.
        A namespace allows for identically anmed entities
        as long as the namespaces are different. */

    int x = 0;
    std::cout << first::x << std::endl; // 1
    std::cout << second::x << std::endl; // 2
    std::cout << x << std::endl; // 0

    using namespace first;
    std::cout << y << std::endl; // 3

    using namespace std;
    //using std::cout;
    //using std::string;
    string name = "Park";
    cout << "Hello " << name << "\n";

    return 0;
}

4. typedef

#include <iostream>
#include <vector>

//typedef std::vector<std::pair<std::string, int>> pairlist_t;
//typedef std::string text_t;
//typedef int number_t;
using text_t = std::string;
using number_t = int;

int main(){
    /* typedef = reserved keyword used to create an additional name
        (alias) for another data type.
        New identifer for an existing type
        Helps with readablility and reduces typos
        Use when there is a clear benefit
        Replaced with 'using' (work better with templates) */
    
    //pairlist_t pairlist;
    text_t firstName = "Park";
    number_t age = 21;

    std::cout << firstName << '\n';
    std::cout << age << '\n';

    return 0;
}

5. type 변환

#include <iostream>

int main() {
    /* type conversion = conversion a value of one data type oto another 
        Inplicit = automatic
        Explicit = Precede value with new data type (int) */

    double x = (int) 3.14;
    std::cout << (char) 100; // d

    int correct = 8;
    int questions = 10;
    double score = correct / (double) questions * 100;
    std::cout << score << "%";
	
    return 0;
}

6. 입출력

#include <iostream>

int main() {
    // cout << (insertion operator)
    // cin >> (extraction operator)

    std::string name;
    int age;

    std::cout << "What's your age? : ";
    std::cin >> age;

    std::cout << "What's your full name? : ";
    std::getline(std::cin >> std::ws, name); // ws -> strip
    //std::cin >> name;

    std::cout << "Hello " << name << std::endl;
    std::cout << "You are " << age << " years old" << std::endl;
    
    return 0;
}
  • std::getline(변수)는 공백을 포함한 문자열 입력에 사용된다.
  • 이전의 입력에서 받은 개행 문자의 영향을 없애기 위해 std::cin >> std::ws 를 추가해준다.

7. Cmath

#include <iostream>
#include <cmath>

int main() {
    double x = 3.99;
    double y = 4;
    double z;

    //z = std::max(x, y);
    //z = std::min(x, y);
    
    //z = pow(2, 4);
    //z = sqrt(9);
    //z = abs(-3)
    //z = round(x);
    //z = ceil(x);
    z = floor(x);
    std::cout << z;

    return 0;
}

8. 빗변(Hypotenous) 계산기 만들기

#include <iostream>
#include <cmath>

int main() {
    double a;
    double b;
    double c;

    std::cout << "Enter side A: ";
    std::cin >> a;
    std::cout << "Enter side B: ";
    std::cin >> b;

    a = pow(a, 2);
    b = pow(b, 2);
    c = sqrt(a + b);

    std::cout << "Side C: " << c;

    return 0;
}

9. 조건문

#include <iostream>

int main() {
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;

    if(age >= 18) {
        std::cout << "Welcome to the site!" << std::endl;
    } else if(age >= 100) {
        std::cout << "You are not too enough to enter!" << std::endl;
    } else {
        std::cout << "You are not old enough to enter!" << std::endl;
    }
    return 0;
}

10. Switch문

#include <iostream>

int main() {
    int month;
    std::cout << "Enter the month (1-12): ";
    std::cin >> month;

    switch(month) {
        case 1:
            std::cout << "It is January";
            break;
        case 2:
            std::cout << "It is Feburary";
            break;
        // ...
        defalult:
        	std::cout << "Not a valid input!";
    }
    return 0;
}

11. Ternary operator (삼항연산자)

#include <iostream>
int main() {
    int grade = 75;
    grade >= 60 ? std::cout << "You pass!" : std::cout << "You fail!";
    
    return 0;
}

12. 논리연산자

#include <iostream>
int main() {
    // && : and ; || : or ; ! : not
    
    int temp;
    std::cout << "Enter the temperature: ";
    std::cin >> temp;

    if(temp > 0 && temp < 30) {
        std::cout << "The temperature is good!";
    } else {
        std::cout << "The temperature is bad!";
    }
    // ...
    return 0;
}

13. 문자열 관련 메소드

#include <iostream>
int main() {
    std::string name;
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);

    if(name.empty()) {
        std::cout << "You didn't enter your name";
    } else if(name.length() > 12) {
        std::cout << "Your name can't be over 12 characters";
        name.clear();
    } else {
        name.append("@gmail.com");
        std::cout << "Welcome " << name << std::endl;
    }

    std::cout << name.at(1);
    std::cout << name[1] << std::endl;
    name.insert(0, "#"); // 0번째 인덱스에 삽입
    name.erase(1, 3); // 0~2 범위 삭제
    std::cout << name.find(' ');

    return 0;
}

14. while 반복문

#include <iostream>

int main() {
    std::string name;

    while(name.empty()) {
        std::cout << "Enter your name: ";
        std::getline(std::cin, name);
    }
    std::cout << "Hello " << name;
    
    /* while(1==1) {
        std::cout << "Help! ";
    } */

    return 0;
}

 

15. do~while

#include <iostream>

int main() {
    int num;

    // do while loop = do some block of code first,
    //                  THEN repeat again if condition if true

    /* while(num < 0) {
        std::cout << "Enter a positive #: ";
        std::cin >> num;
    } */

    do{
        std::cout << "Enter a positive #: ";
        std::cin >> num;
    }while(num < 0);

    std::cout << "The # is: " << num;
    
    return 0;
}

16. for 반복문

#include <iostream>

int main() {
    for(int i = 1; i <= 10; i++) {
        std::cout << i << "HAPPY NEW YEAR\n";
    }
    return 0;
}

17. 난수

#include <iostream>
#include <ctime>

int main(){
    // pseudo-random : NOT truly random
    srand(time(NULL));
    int num1 = (rand() % 6) + 1;
    int num2 = (rand() % 6) + 1;
    int num3 = (rand() % 6) + 1;
    std::cout << num1 << std::endl;
    std::cout << num2 << std::endl;
    std::cout << num3 << std::endl;
    return 0;
}

18. 함수 1

#include <iostream>
void happyBday(std::string name, int age);

int main() {
    // function = a block of reusable codes
    std::string name = "Park";
    happyBday(name, 21);
    return 0;
}

void happyBday(std::string name, int age) {
    for (int i=0; i < 3; i++){
        std::cout << "Happy birthday to " << name << std::endl;
    }
    std::cout << "Happy birthday dear my friend\n";
    std::cout << "Happy birthday to you!\n";
    std::cout << "Now you are " << age << " yeats old\n";
}

19. return

#include <iostream>

double square(double length);
std::string concatString(std::string s1, std::string s2);

int main() {
    double length = 5.0;
    std::cout << "Area : " << square(length) << std::endl;
    std::string firstName = "Munsik";
    std::string lastName = "Park";
    std::string fullName = concatString(firstName, lastName);
    std::cout << "Hello " << fullName << std::endl;
    return 0;
}

double square(double length){
    double result = length * length;
    return result;
}

std::string concatString(std::string s1, std::string s2){
    return s1 + " " + s2;
}

20. 함수 2

#include <iostream>

void pizza();
void pizza(std::string topping);
void pizza(std::string topping1, std::string topping2);

int main() {
    pizza();
    pizza("pineapple");
    pizza("pineapple", "bacon");
    return 0;
}

void pizza(){
    std::cout << "Here is your pizza!\n";
}
void pizza(std::string topping){
    std::cout << "Here is your " << topping << " pizza!\n";
}
void pizza(std::string topping1, std::string topping2){
    std::cout << "Here is your " << topping1 << " and " << topping2 << " pizza!\n";
}

21. 지역변수와 전역변수

#include <iostream>

int myNum = 3;
void printNum();

int main() {
    int myNum = 1;
    std::cout << myNum << std::endl;
    printNum();
    std::cout << ::myNum << std::endl;
    return 0;
}

void printNum() {
    int myNum = 2;
    std::cout << myNum << std::endl;
}

22. 은행 시뮬레이션 프로그램

#include <iostream>
#include <iomanip>

void showBalance(double balance);
double deposit();
double withdraw(double balance);

int main() {
    double balance = 0;
    int choice = 0;
    do{
        std::cout << "******************\n";
        std::cout << "Enter your choice:\n";
        std::cout << "******************\n";
        std::cout << "1. SHow Balance\n";
        std::cout << "2. Deposit Money\n";
        std::cout << "3. Withdraw Money\n";
        std::cout << "4. Exit\n";
        std::cin >> choice;
        
        std::cin.clear();
        fflush(stdin);

        switch(choice) {
            case 1: showBalance(balance);
                    break;
            case 2: balance += deposit();
                    showBalance(balance);
                    break;
            case 3: balance -= withdraw(balance);
                    showBalance(balance);
                    break;
            case 4: std::cout << "Thanks for visiting.\n";
                    break;
            default: std::cout << "Invalid choice\n";
        }
    }while(choice != 4);

    return 0;
}

void showBalance(double balance){
    std::cout << "Your balance is: $"<< std::setprecision(2) << std::fixed << balance << std::endl;
}
double deposit(){
    double amount = 0;
    std::cout << "Enter amount to be deposited: ";
    std::cin >> amount;
    if (amount > 0) {
        return amount;
    } else {
        std::cout << "That's not a valid amount.\n";
        return 0;
    }
    
}
double withdraw(double balance){
    double amount = 0;
    std::cout << "Enter amount to be withdrawn: ";
    std::cin >> amount;
    if (amount > balance) {
        std::cout << "Insufficient funds\n";
        return 0;
    } else if (amount < 0) {
        std::cout << "That's not a valid amount.\n";
        return 0;
    } else {
        return amount;
    }
}

23. 가위바위보 게임

#include <iostream>
#include <ctime>
using namespace std;

char getUserChoice();
char getComputerChoice();
void showChoice(char choice);
void chooseWinner(char player, char computer);

int main() {
    char player;
    char computer;

    player = getUserChoice();
    cout << "You choosed ";
    showChoice(player);

    computer = getComputerChoice();
    cout << "Computer choosed ";
    showChoice(computer);

    chooseWinner(player, computer);

    return 0;
}
char getUserChoice(){
    char player;
    cout << "Rock-Paper-Scissors Game!\n";
    cout << "*************************\n";
        cout << "'r' for rock\n";
        cout << "'p' for paper\n";
        cout << "'s' for scissors\n";
    do{
        cin >> player;
    }while(player != 'r' && player != 'p' && player != 's');

    return player;
}
char getComputerChoice(){
    srand(time(0));
    int num = rand() % 3 + 1;
    switch(num){
        case 1: return 'r';
        case 2: return 'p';
        case 3: return 's';
    }
}
void showChoice(char choice){
    switch(choice){
        case 'r': cout << "Rock\n";
                break;
        case 'p': cout << "Paper\n";
                break;
        case 's': cout << "Scissors\n";
                break;
    }
}
void chooseWinner(char player, char computer){
    cout << "You win!";
    // TODO
}

24. 배열

#include <iostream>
using namespace std;

int main() {
    string car[] = {"Corvette", "Mustang", "Camry"};
    car[0] = "Camero";
    cout << car[0] << car[1] << car[2] << endl;

    double prices[4];
    prices[0] = 5.00;
    prices[1] = 7.50;
    prices[2] = 9.99;
    prices[3] = 15.00;

    for (int i=0; i<4; i++){
        cout << prices[i] << endl;
    }
    return 0;
}

25. sizeof()

#include <iostream>
using namespace std;

int main() {
    double gpa = 2.5;
    cout << sizeof(gpa) << " bytes\n";
    string name = "Park";
    cout << sizeof(name) << " bytes\n";
    char grades[] = {'A', 'B', 'C', 'D', 'F'};
    cout << sizeof(grades) / sizeof(char) << " elements\n";

    return 0;
}

26. foreach loop

#include <iostream>
using namespace std;

int main() {
    string students[] = {"Kim", "Lee", "Park"};
    for(string student : students) {
        cout << student << endl;
    }
    return 0;
}
  • Python 코드 for student in students 와 동일한 기능을 한다.

27. 배열 원소들의 합

#include <iostream>
using namespace std;

double getTotal(double prices[], int size);

int main(){
    double prices[] = {49.99, 15.05, 75, 9.99};
    int size = sizeof(prices)/sizeof(double);
    double total = getTotal(prices, size);
    cout << "$" << total;
    return 0;
}

double getTotal(double prices[], int size){
    double total = 0;
    for (int i=0; i < size; i++) {
        total += prices[i];
    }
    return total;
}
  • getTotal 함수 내에서 prices[]의 크기를 구하면 1로 인식되기 때문에 제대로 동작되지 않는다. 함수 외부에서 배열 크기를 구해 매개 변수 size로 넘겨주는 것이 바로 이 때문이다.

28. 배열 원소 검색

#include <iostream>
using namespace std;

int searchArray(int array[], int size, int element);

int main() {
    int numbers[] = {1,2,3,4,5,6,7,8,9,10};
    int size = sizeof(numbers)/sizeof(int);
    int idx;
    int num;
    cout << "Enter element to search for: ";
    cin >> num;
    idx = searchArray(numbers, size, num);
    if(idx != -1){
        cout << num << " is at index " << idx << endl;
    } else {
        cout << num << " is not in the array.\n";
    }
    
    return 0;
}

int searchArray(int array[], int size, int element){
    for(int i=0; i < size; i++){
        if (array[i] == element) {
            return i;
        }
    }
    return -1;
}

29. fill()

#include <iostream>

using namespace std;

int main() {
    // Fills a range of elements with a specified value
    const int SIZE = 10;
    string foods[SIZE];
    fill(foods, foods + (SIZE/2), "pizza");
    fill(foods + (SIZE/2), foods + SIZE, "chicken");
    for(string food : foods) {
        cout << food << "\n";
    }
    return 0;
}

30. Memory Address

#include <iostream>

using namespace std;

int main() {
    // Memory address
    string name = "Park";
    int age = 21;
    bool student = true;

    cout << &name << '\n';
    cout << &age << '\n';
    cout << &student << '\n';

    return 0;
}

31. const parameter

#include <iostream>

using namespace std;

void printInfo(const string name, const int age);

int main() {
    string name = "Bro";
    int age = 21;
    printInfo(name, age);

    return 0;
}

void printInfo(const string name, const int age) {
    cout << name << age << endl;
    return;
}
  • const 매개 변수를 사용하는 함수 내부에서 변수의 값을 바꾸려고 하면 에러가 발생한다.

32. 포인터

#include <iostream>

using namespace std;

int main() {
    // pointers = variables that stores a memory address
    string name = "Park";
    string *pName = &name;
    int age = 21;
    int *pAge = &age;
    string freePizzas[5] = {"pizza1", "pizza2", "pizza3", "pizza4", "pizza5"};
    string *pFreePizzas = freePizzas;
    cout << pName << " " << *pName << endl;
    cout << pAge << " " << *pAge << endl;
    cout << pFreePizzas << " " << *pFreePizzas << endl;
    return 0;
}

'CS > C++' 카테고리의 다른 글

C++로 이진 탐색 트리 구현하기  (0) 2025.04.15
C++로 TIC TAC TOE 게임 구현하기  (0) 2025.04.15
C++로 스택/큐 구현하기  (0) 2025.04.12
C++로 연결 리스트 구현하기  (0) 2025.04.08