11번 A+B - 5
문제
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력
입력은 여러 개의 테스트 케이스로 이루어져 있다.
각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)
입력의 마지막에는 0 두 개가 들어온다.
출력
각 테스트 케이스마다 A+B를 출력한다.
이번에는 얼마나 반복할지 횟수를 정해주지 않고 마지막 케이스를 통해 루프를 종료하는 조건으로 사용하면 된다.
C++
#include <iostream>
using namespace std;
int main(){
cin.tie(NULL);
ios_base::sync_with_stdio(false);
while(true){
int a, b;
cin >> a >> b;
if (a + b == 0) break;
else
cout << a + b << "\n";
}
}
두 값이 모두 0인 경우 반복문을 종료한다.
C#
using System;
class Program{
static void Main(string[] args){
using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
while(true){
int a, b;
string input = Console.ReadLine();
string[] arr = input.Split(' ');
a = int.Parse(arr[0]);
b = int.Parse(arr[1]);
if (a + b == 0) break;
else
Console.WriteLine(a + b);
}
}
}
}
Python
while True:
input_str = input()
arr = input_str.split(' ')
a = int(arr[0])
b = int(arr[1])
if a + b == 0:
break
print(a + b)
파이썬의 while문 사용법을 숙지한다.
Node.js
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
for (const line of input){
const [a, b] = line.split(' ').map(Number);
if (a + b === 0) break;
console.log(a + b);
}
js는 입력을 한 번에 받은 다음 줄 별로 처리해야 하기 때문에 while이 아닌 for를 사용해서 처리한다.
12번 A+B - 4
문제
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력
입력은 여러 개의 테스트 케이스로 이루어져 있다.
각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)
출력
각 테스트 케이스마다 A+B를 출력한다.
반복문 챕터의 마지막 문제이다. 종료 조건을 어떠한 것도 주지 않은 상태로 입력이 끝날 때까지 반복하여 처리해야 한다.
C++
#include <iostream>
using namespace std;
int main(){
int a, b;
cin.tie(NULL);
ios_base::sync_with_stdio(false);
while(cin >> a >> b){
if (a + b == 0)
break;
cout << a + b << "\n";
}
return 0;
}
cin >> a >> b를 조건으로 체크하여 입력이 더 이상 없는 경우를 판단한다.
조건으로 사용하게 되면 EOF(End of File)에 도달하여 더 이상 입력이 없거나 잘못된 값이 입력된 경우 반복문이 종료된다.
using System;
class Program{
static void Main(string[] args){
using (StreamWriter writer = new StreamWriter(Console.OpenStandardOutput())){
while (true){
string input = Console.ReadLine();
if (input == null) break;
string[] arr = input.Split(' ');
int a = int.Parse(arr[0]);
int b = int.Parse(arr[1]);
Console.WriteLine(a+b);
}
}
}
}
C#에서 string의 초기화값은 null이기 때문에 input이 없는지 확인하기 위해서 null과 비교하여 검사한다.
Python
import sys
input = sys.stdin.read
arr = input().splitlines()
for line in arr:
a, b = map(int, line.split())
print(a+b)
기존 input 함수를 표준 입력으로 변경하여 전체 입력된 정보를 저장한 다음 배열을 읽어서 처리하여 입력된 값들만 처리한다.
또 다른 방법으로는 입력이 더 이상 없을 때 발생하는 에러를 체크해서 루프를 종료시킬 수 있다.
while True:
try:
input_str = input()
except EOFError:
break
arr = input_str.split()
a = int(arr[0]);
b = int(arr[1]);
print(a+b)
에러가 발생하는 지점을 예외처리하기 위해서 try ~ except를 사용한다. 입력이 더 이상 없을 때는 EOFError를 리턴한다.
Node.js
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
for (const line of input){
const[a, b] = line.split(' ').map(Number);
console.log(a+b);
}
모든 입력을 줄 바꿈으로 끊어서 배열로 저장한다. 그리고 이 배열을 순회하면서 각각의 케이스를 처리한다.
'Coding Test' 카테고리의 다른 글
백준 코딩테스트 #19. 1차원 배열 3 (0) | 2024.08.03 |
---|---|
백준 코딩테스트 #18. 1차원 배열 (1, 2) (0) | 2024.08.03 |
백준 코딩테스트 #16. 반복문 (7~10) (0) | 2024.08.01 |
백준 코딩테스트 #15. 반복문 6 (0) | 2024.08.01 |
백준 코딩테스트 #14. 반복문 (4, 5) (0) | 2024.07.31 |