Computer

C++공부 시작 2일

TOYOBA 2012. 7. 9. 08:28

루프문 부터 시작 ( '-' )/


<5장>

루프문 예제

입력받은 수만큼 더하는 예제

int n = 0;


cout<<"How many Integers do you want to sum: " ;

cin >> n;


int sum = 0;

int i = 1;

cout<<"Values are : " << endl;

while(i<=n){

cout<<setw(5) << i;

if(i%10==0)

cout << endl;

sum +=i++;

}

cout<<endl <<  "Sum is " << sum << endl;


온도의 평균 내기 do-while

char ch=0;

int count = 0;


double temperature = 0.0;

double average = 0.0;


cout<<endl;

do{

cout<<"Enter a temperature reading:";

cin >> temperature;


average += temperature;

count ++;

cout<<"Do you wnat to enter another ?(y/n)";

cin>>ch;

cout << endl;

}while(ch=='y');


average /=count;

cout<< " The average temperature is" <<average<<endl;


for loop 

정수의 합을 구하는 프로그램

int sum = 0;

int count = 0;


cout<<"How many integers do you want to sum";

cin >> count ;

for(int i=1;i<=count; i++)

sum +=i;


cout<<endl<<"The sum of the integers from 1 to" << count<<"is" <<sum<<endl;

실수값 제어식 예제

const double pi = 3.14159265;

cout<<endl;


for(double radius =.2; radius <=3.0; radius+=.2)

cout<<"radius =" << setw(12) <<radius<<"area="<<setw(12)<<pi*radius*radius<<endl;

2.8이 마지막. 이유는 2.8에 0.2를 더했을때 3.0보다 4x10^-16만큼 크기떄문에 3.0을 초과하므로 3.0은 출력되지 않는다.


실수값 변화

const double pi = 3.14159265;

cout << endl;


for (double radius = .2; radius <=3.0 ; radius +=.2){

cout<<"radius="<<setprecision(numeric_limits<double>::digits10+1)<<scientific<<radius<<"area="<<setw(10)<<setprecision(6)<<fixed<<pi*radius*radius<<endl;

}

플랫폼에 따라서 가수의 자릿수 계산이 달라질수 있음을 유념.


다중 초기화도 가능

int count = 0;

cout<<endl<<"What upper limit would you like";

cin>>count;


cout<<endl<<"integer"<< " sum" <<" factorial" <<endl;

for(long n=1,sum=0,factorial=1;n<count;n++){ <- 다중 초기화

sum+=n;

factorial *=n;

cout<<setw(4)<<n<<" "<<setw(7)<<sum<<" "<<setw(16)<<factorial<<endl;

}

콤마 연산자

int count=0;

cout<<endl<<"What upper limit would you like?";

cin>>count;


cout<<endl<<"integer"<<" sum"<<" factorial"<<endl;


for(long n=1,sum=0,factorial=1;sum+=n,factorial *=n,n<=count; n++)

cout<<setw(4)<<n <<" "<<setw(7)<<sum<<" "<<setw(15)<<factorial<<endl;

- 좋은 타입의 코딩 형태는 아니므로 참고.


구구단 테이블 출력(중첩 루프)

int table =0; // size of table

int table_min = 2; //  max size of table;

int table_max = 12; // min size of talbe;

char ch=0; // answer of prompt;


do{

cout<<endl<<"What size table would you like(" << table_min<<"to"<< table_max<<")?";

cin>>table;

cout<<endl;


//check table size

if(table<table_min||table>table_max){

cout<<"Invalid table size entered. Program terminated."<<endl;

exit(1);

}

//first line of table

cout<<" |";

for(int i=1;i<=table;i++)

cout<< " "<<setw(3) <<i<<" |";

cout<<endl;


//구분선 생성

for(int i = 0; i<=table ; i++)

cout<<"------";

cout<<endl;


for(int i =1; i<=table ;i++){ // 한 행씩 반복

cout<< " " <<setw(3)<<i<<" |";

//행에 값을 출력

for(int j=1;j<=table;j++)

cout << " " <<setw(3)<<i*j <<" |";

cout<<endl;

}


//다른 테이블이 필요한지 검사

cout<<endl<<"Do you wnat another table(y or n)";

cin >>ch;

cout<<endl;

}while(tolower(ch)=='y');


cout<<endl<<setw(13)<<"Character " <<setw(13) << "Hexadecimal " << setw(13) << "Decimal " <<endl;


cout<<uppercase;


unsigned char ch=0;


//문자와 그 해당 코드를 출력

do{

if(!isprint(ch)) // 입력 가능한 문자를 체크 

continue; // 입력 가능하면 continue

cout<<setw(7)<<ch<<hex<<setw(13)<<static_cast<int>(ch)<<dec<<setw(13)<<static_cast<int>(ch)<<endl;

// hex : 16 , decimal : 10

}while(ch++<numeric_limits<unsigned char>::max()); // unsigned char가 가질 수 있는 최대값


테이블 사이즈 입력할수있는 3번의 기회를 줌

int table=0;

const int table_min = 2;

const int table_max = 12;

const int table_tries = 3;

char ch=0;


do{

for(int count=1;;count++){ //무한루프

cout <<  endl << "What size table would you like(" << table_min << "to" <<table_max<<")?";

cin >> table;


//table 범위 확인

if(table>=table_min && table<=table_max)

break;

else if(count < table_tries)

cout<<"Invalid input -. Try agin.";

else{

cout<<"invalid table size entered-.for the third time."<<"\nSorry,only three goes- program terminated."<<endl;

exit(1);

}

}

// 테이블 첫줄 생성

cout<<" |";

for(int i=0;i<=table; i++)

cout<< " " <<setw(3) << i << " |";

cout<<endl;


//구분선 생성

for(int i=0;i<=table;i++)

cout<<"------";

cout<<endl;


for(int i = 1; i<=table ; i++){

cout<< " " << setw(3) << i << "|"; //행 시작

for(int j=1;j<=table;j++)

cout<< " " << setw(3) << i*j << " |";

cout<<endl;

}

//다른 테이블 필요 검사


cout<<endl<<"Do you want another table(y or n)";

cin>>ch;

cout<<endl;

}while(tolower(ch)=='y');

온도의 평균

char ch = 0;

int count =0;

double temperature = 0.0;

double average = 0.0;


for(; ;){

cout<<"Enter a value:";

cin>> temperature;

average += temperature;

count ++;


cout<<"Do you want to enter another?(y/n):";

cin>>ch ;


if(tolower(ch)=='n')

break;

}

cout<<endl<<"The average temperature is " <<average/count<<endl;

연습문제 1. 1부터 사용자가 입력한 정수사이에 존재하는 홀수제곱 출력.

int number =0; //사용자가 입력한 정수

int sum = 0; //제곱의 합계

int seconde = 0; //제곱 표시


cout<<"Enter the Integer :";

cin>>number;


//홀수 찾기

for(int i = 1; i<=number;i++){

if(i%2==1)

//sum = sum + i*i;

//seconde=i*i;

cout<<i*i<<endl;

}

//cout << "sum : " <<sum <<endl;

int number = 0; //사용자가 입력한 정수값

double average = 0.0; // 평균 실수값

//float average = 0.0; // 평균 실수값

double sum = 0.0; //합계

int count = 0; // 갯수

cout<<"Enter the integer :" ;

cin>>number;


count=number;


while(count!=0){


sum +=count;

count--;

}

average = sum/number;

cout << "sum: " << sum << "average :" << average <<endl;


char ch = 0; //입력받을 문자열

int count = 0; //문자열 셈


do{

cout<<"Enter the character;";

cin>>ch;


count++;



}while(ch!='#');//#가 아니면 loop탈출

cout<<"count:"<<count<<endl;

8글자의 알파벳 혹은 숫자 발생 프로그램

const int pwlength = 8; //8글자의 패스워드

char alpha = 0; // 알파벳

int number = 0; //숫자

char checkalphanum = 0; //알파벳인지 숫자인지 선택



cout<<"Enter the mode (alphabet :a, number:n)";

cin>> checkalphanum;


srand(time(NULL)); // 랜덤 ('ㅅ')/


for(int i =1;i<=pwlength;i++){


if(checkalphanum=='a'){

alpha = rand() %26 + 65;


cout<<alpha;

}

else{

number = rand()%10;

cout<<number;

}


}

int lotto = 0; //로또숫자('ㅅ')

const int lottonum = 6; //6자

int count = 0; //카운팅


srand(time(NULL));

for(int i =1;i<=lottonum;i++){

lotto = rand()%50;

count++;

cout<<lotto<<" ";

}


//cout<<"count"<<count;