본문 바로가기
개인 개발 공부/C ++

1-5 반복문과 다중반복문

by minjoothi 2024. 11. 9.

반복문에서 가장 중요한 것 : 언제까지 반복을 하는가, 무한루프

 

for 문

#include <iostream>

int main()
{
    using namespace std;

    int carrots = 7;

    if (carrots < 5)
    {
        cout << "Let's buy new carrots!" << endl;
        //buy new carrots
    }
    else if (carrots < 10)
    {
        cout << "Ummmm....." << endl;
    }
    else
    {
        cout << "No need to buy some carrots!" << endl;
        // no need to buy carrots.
    }

    return 0;
}

 

 

while문

// whileloop.cpp
#include <iostream>

int main()
{
    using namespace std;

    int counter = 0;

    cout << "Enter counter: " << endl;
    cin >> counter;

    int i = 0;
    while (i < counter)
    {
        cout << "Counting... " << i + 1 << endl;
        i++;
    }

    cout << "End" << endl;

    return 0;
}

 

다중반복문

1층부터 4층짜리 건물, 한층마다 8개의 호실이 있는 호텔의 방을 101호부터 카운트 하기

//다중반복문 = 반복문안에 또 반복문이 들어있는 것

#include <iostream>

int main () {

using namespace std;

// 4층짜리 건물, 8개호실 방번호 출력

int floor = 4; //층수는 4개
int room = 8; //방수는 8개

for(int i=1; i<= floor; i++) // 1층부터 floor 층까지
{
    for(int j = 1; j<=room; j++) // 1호부터 room 호까지 
    {
        cout << "Floor: " << i *100 + j << endl;

    }
}


return 0;

}

 

퀴즈1 : 구구단 출력

< 문제 >

/* 코딩테스트 준비 퀴즈 1

   1단부터 9단까지 구구단 출력하기

*/

#include <iostream>

int main()
{
    using namespace std;


    for(int i = 1; i<=9; i++) 
    {
        for(int j = 1; j<=9; j++) 
        {
            cout << i << " * " << j << " = " << i*j << endl;
        }

        cout << endl;
    }

    return 0;
}

맞았음

 

퀴즈 2  :  별찍기

#include <iostream>

int main() {

    using namespace std;


    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            cout << "*";
        }
        cout << endl;
    }
    return 0;
}

퀴즈 3 :  1부터 사용자가 입력한 숫자까지의 합을 구하기

//calsum.cpp
#include <iostream>

int main()
{
    using namespace std;
    int inputNum = 0;
    int sum = 0;

    cout << "숫자를 입력해주세요: " << endl;
    cin >> inputNum;

    for (int i = 1; i <= inputNum; i++)
    {
        sum += i;
    }

    cout << "총 합은: " << sum << endl;
    return 0;
}

 

퀴즈 4 : 약수 구하기

#include <iostream>

int main()

{
    using namespace std;

    int num = 0;
   
    cout << "숫자를 입력해주세요 : " << endl;
    cin >> num;
    cout << endl;

    cout << num << "의 약수는 아래와 같습니다. " << endl;
    for (int i = 1; i <= num; i++)
    {
        if (num % i == 0)
        {
            cout << i << endl;
        }
    }
    cout << endl;


    return 0;
}

'개인 개발 공부 > C ++' 카테고리의 다른 글

1-7. 포인터와 참조  (0) 2024.11.11
1-6 함수  (1) 2024.11.10
조건문  (0) 2024.11.09
연산자  (0) 2024.11.09
1-2. 변수와 자료형 그리고 입출력 함수  (0) 2024.11.09