C++

반복문과 If문 그리고 함수

switch_user 2023. 3. 28. 21:04

선언한 메소드(함수)

- while문을 사용하여 구구단을 출력하는 메소드

- for문을 사용하여 구구단을 출력하는 메소드

- 두 정수를 입력받고 더 큰 정수를 return 해주는 메소드

#include <iostream>
using namespace std; 

//while문으로 구구단 출력 
void printTimesTableByWhile(){
	int i = 1; 
	int j = 1;
	
	while(i<=9){
		while(j<=9){
			cout << j << "X" << i << "=" << i * j << "  ";
			j++;
		}
		cout << endl;
		j=1;
		i++;
	}
	
	cout << endl;
}

//for문으로 구구단 출력 
void printTimesTableByFor(){
	for(int i=1; i<=9; i++){
		for(int j=1; j<=9; j++){
			cout << j << "X" << i << "=" << i * j << "  ";
		}
		cout << endl;
	}
	
	cout << endl;
}

//두 정수를 입력받고 더 큰 정수를 return한다.
int getMaxValueAfterTwoInput(){
	int first, second;
	int return_value;
	
	cout << "두 정수를 입력하세요 : "; 
	cin >> first;
	cin >> second;
	
	if(first>second){
		return_value = first;
	}
	else if(first<second){
		return_value = second;
	}
	else{
		return_value = first;
	}
	
	return return_value;
}
	
int main(int argc, char** argv) {
	printTimesTableByWhile();
	printTimesTableByFor();
	
	int maxValue;
	maxValue = getMaxValueAfterTwoInput();
	cout << "두 정수중에 큰 수는 " << maxValue << "입니다." << endl;
	return 0;
}

출력해보면 잘 돌아가지만 구구단의 줄이 맞지 않는다. 이럴 땐 '\t'으로 포매팅 해주거나 <iomanip> 헤더파일의 setw()함수를 사용하면 정리 할 수 있다. (사용 예 : cout << x << "X" << y << "=" << right << setw(2) << x*y << " "; )