#include <iostream>
int main()
{
int i, num;
std::cout << "수를 입력하시오 : ";
std::cin >> num; // 축이 될 수를 사용자에게 입력받음
for(i=1 ; i< 10 ; i++) // 1 ~ 9까지 곱연산
{
// 'x' 피연산자, 결과 출력
std::cout << num << " x " << i << "= " << num*i << std::endl;
}
return 0;
}
C에서 구구단 계산 함수 만드는 방법과 출력방식에서만 차이가 있을 뿐이다.
C에서 처럼 while(1) 무한루프에 "if ~ break"를 삽입한다.(조건부에 바로 조건을 입력해도 무방)
if the value of sale equals to -1(when input value -1 to sale), print out "프로그램을 종료합니다."
#include <iostream>
int main()
{
int sale;
while(1)
{
std::cout << "판매 금액을 만원단위로 입력(-1 to end): ";
std::cin >> sale;
if(sale == -1)
{
std::cout << "프로그램을 종료합니다.";
// -1 입력 시 수령액 출력하지 않고, 반복문 종료
break;
}
// 급여 + 보너스 = 실수령액 출력
std::cout << "이번달 급여 : " << 50+sale*0.12 << "만원\n";
}
return 0;
}
역시 출력에 사용되는 표준함수만 다를 뿐 C에서 while문을 사용하던 방식과 동일하다.
#include <iostream>
#include <cstring>
/*
1) 매개변수의 타입이 다르다
2) 매개변수의 개수가 다르다
둘 중 하나만 만족하면 동일한 이름의 함수를 여러개 겹쳐 생성한다는 의미의 "오버로드"가 가능
*/
// swap1
void swap(int * num1, int * num2) // integers
{
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
// swap2
void swap(char * ch1, char * ch2) // charaters
{
char chh;
chh = *ch1;
*ch1=*ch2;
*ch2=chh;
}
// swap3
void swap(char * str1, char * str2, int len) // strings
{
char temp[len];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
int main()
{
int num1=1, num2=2;
char ch1='a', ch2='b';
char str1[30] = "Today is friday";
char str2[30] = "Tomorrow is saturday";
// call defined functions
swap(&num1, &num2);
swap(&ch1, &ch2);
swap(str1,str2, strlen(str1));
// 결과 확인
std::cout << "num1, num2 : "<< num1 << ", " << num2 << std::endl;
std::cout << "ch1, ch2 : "<< ch1 << ", " << ch2 << std::endl;
std::cout << "str1, str2 : "<< str1 << ", " << str2 << std::endl;
return 0;
}
C와 달리 매개변수의 형, 개수가 다르다면 동일이름의 함수를 여러개 생성할 수 있다(함수의 오버로드