본문 바로가기

Programming/C language

Chapter 06, 07. 조건문, 반복문 (연습문제 풀이)


연습문제) 


6-1 if문을 사용하여 사용자로부터 정수 다섯 개를 입력받아 그중 가장 큰 수를 출력하는 프로그램을 작성하세요. 단, 사용자는 0~100 사이 값만 입력하도록 강제합니다. 만일 범위를 벗어난 숫자를 입력할 경우 0 미만은 0으로, 100 초과는 100으로 조정합니다.



6-2 다음 코드에서 잘못된 부분은 무엇인지 찾고 이유도 쓰시오.



#include <stdio.h>

int main(void)

{

       int nAge = 0;

       scanf("%d", &nAge);

       if(nAge = 20)

             puts("당신은 성인입니다.");

       puts("End");

       return 0;

}


if(nAge = 20) 때문에 nAge의 값이 어떻든간에 20을 넣고, 당신은 성인입니다. 를 출력한다. 

if(nAge == 20)으로 고쳐야한다. 



6-3 다음 코드를 작성하고 사용자가 15를 입력했다면 어떤 결과가 출력되는지 쓰세요.




#include <stdio.h>

int main(void)

{

       int nInput = 0;

       scanf("%d", &nInput);

       if(nInput > 10)

       {

             int nInput = 20;

             printf("%d\n", nInput);

             if(nInput < 20)

             {

                    int nInput = 30;

                    printf("%d\n", nInput);

             }

       }

       printf("%d\n", nInput);

       return 0;

}


출력 결과

20

20



7-1 1~100까지의 숫자 중에서 4의 배수가 몇 개이며, 이들의 총합이 얼마인지 계산해 출력하는 프로그램을 작성하세요.




7-2 다음과 같이 '*'을 출력하는 프로그램을 작성하세요.


*

*                    *

*                     *                    *

*                    *                      *                    *

*                    *                       *                    *                    *





7-3 다음 코드의 실행결과를 쓰세요.


#include <stdio.h>

int main(void)

{

       int i = 0;

       for(i = 0; i < 10; ++i)

       {

             if(i > 4)

                    continue;

             printf("%dth\n", i);

       }

       printf("END: i == %d\n", i);

       return 0;

}


출력결과

1th

2th

3th

END: i == 10




7-4 다음 코드에서 goto문을 제거하고 반복문을 이용해서 같은 결과를 얻을 수 있도록 프로그램을 변경하세요.


#include <stdio.h>

int main(void)

{

int nInput;


INPUT:

printf("Input number : ");

scanf("%d", &nInput);


if(nInput < 0 || nInput > 10)

goto INPUT;


puts("End");

return 0;

}


단순히 반복문을 사용해 nInput이 0보다 작거나 10보다 큰 경우 새로 입력받으면 되는 문제이다. 


#include <stdio.h>


int main(void)

{

int nInput;


while( (nInput < 0) || (nInput > 10) )

{

printf("Input number : ");

scanf("%d", &nInput);

}


puts("End");

return 0;

}


로 고쳐주면 된다. 



- 출처 : 독하게 시작하는 C 프로그래밍 (최호성, 루비 페이퍼)