ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [C Language] 17. while 문 - C 언어
    CSE/C Language 2015. 6. 13. 10:16

    1. 사용방법 

     while() 의 형식은 다음과 같다.


     형  식

    예  제 

     while (조건식) 수행문;

    i = 1;

    while (i <= 10) printf("%d\n", i++); 

     while (조건식)

     {

        수행문;

        수행문;

        ...

     }

     i = 1;

     while (i <= 10) 

     {

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

        i++;

     } 



     while()문의 조건식이 참일 때만 수행문을 처리하고 그렇지 않으면 수행문을 처리하지 않는다.



    2. while() 예제

     1 부터 100까지 더하는 예제를 살펴보자.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    /*
     * sumhund.c
     *
     *  Created on: 2015. 5. 12.
     *      Author: root
     */
     
    #include <stdio.h>
     
    int main(void) {
     
        int count, total;
     
        count = total = 0;
     
        while (count <= 100) {
            total += count;
            count++;
        }
     
        printf("Sum of 1 to 100 : %d\n", total);
     
        return 0;
    }
    cs













     다음으로 입력한 문자열에 따른 간단한 암호화 예제를 살펴보자.

     간단한 암호화 기법으로 기존 문자열에 한 칸씩 옮겨진 암호화다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /*
     * encrypt.c
     *
     *  Created on: 2015. 5. 12.
     *      Author: root
     */
     
    #include <stdio.h>
     
    int main(void) {
     
        int i = 0;
        char buf[20 + 1];
     
        puts("Input string to encrypt( < 20).");
        fgets(buf, sizeof(buf), stdin);
     
        while (buf[i]) {
            if (buf[i] != ' ')
                putchar(buf[i] + 1);
            else
                putchar(' ');
            i++;
        }
        return 0;
    }
    cs








     여기서 쓰인 fgets()는 키보드(stdin)로부터 문자열을 받아서 그 값을 buf에 저장하는 함수이다.

     문자열을 받아들이는 것은 fgets()를 사용하는 것을 습관화하자!



     다음 예제는 문자열을 단어 단위로 자르는 예제이다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /*
     * wordcut.c
     *
     *  Created on: 2015. 5. 12.
     *      Author: root
     */
     
    #include <stdio.h>
     
    int main(void) {
     
        int ch;
     
        puts("Input strings.");
     
        while ((ch = getchar()) != EOF)
            if (ch == ' ') putchar(' \n');
            else putchar(ch);
     
        return 0;
    }
    cs

     



     



     

     

     

     

    * Programming in C 서적을 참고하여 작성하였습니다 


    댓글

Designed by Tistory.