CHAPTER 2
GETTING COMFORTABLE WITH C

[IMAGE: An Quarter-Size Version of The Joy of C Front Cover]

This chapter continues our tutorial introduction to C. We focus on two new example C programs: one that computes interest accumulating in a bank account over time, the other that assigns pass/fail grades based on student scores. We describe how each of these programs works and provide several different extensions. These programs introduce C's while and for loops, if statement, and predefined {\headkw scanf} input function. By the chapter's end you'll have been exposed to a wide variety of C's features, and you should feel comfortable writing small but useful C programs.


Jump to: [Previous Chapter | Next Chapter]


  1. A PROGRAM TO COMPUTE SIMPLE INTEREST
  2. DEALING WITH COMPILE ERRORS
  3. A MORE COMPACT INTEREST COMPUTING PROGRAM
  4. EXTENDING OUR INTEREST PROGRAM TO READ VALUES
  5. A PROGRAM TO PROCESS SCORES
  6. HANDLING INPUT ERRORS
  7. THE ASSIGNMENT OPERATOR


Objectives

/*
 *     add2.c
*/
#include <stdio.h>    // standard I/O header file
 
void main()
{
    int n1, n2, total;  // Á¤¼öÇü º¯¼ö Á¤ÀÇ
 
    printf("This program adds two numbers.\n");

    printf("1st number? ");
    scanf("%d", &n1);

    printf("2nd number? ");
    scanf("%d", &n2);

    total = n1 + n2;
    printf("The total is %d.\n", total);
}


#include ³ª #define ¹®ÀÇ '#' ±âÈ£´Â ù¹ø° Çà¿¡ ÀÖ¾î¾ß ÇÑ´Ù.

#include <stdio.h> ¹®Àº standard I/O library function Á¤ÀǵéÀ» ÇÁ·Î±×·¥¿¡ Æ÷ÇÔ½ÃÄÑ ÀÚ·á ÀÔÃâ·ÂÀ» °¡´ÉÇÏ°Ô ÇÑ´Ù. C´Â stdio ¿Ü¿¡ string, time, math °°Àº ¸¹Àº standard libraryµéÀ» Á¦°øÇÑ´Ù.

main() Àº main functionÀ» Á¤ÀÇÇÑ´Ù. ¸ðµç C programÀº ÇϳªÀÇ main functionÀ» ÇÁ·Î±×·¥¿¡ Æ÷ÇÔÇÏ¿©¾ß ÇÑ´Ù. (À§Ä¡´Â »ó°ü¾øÀ½)

printf ¹®Àº ƯÁ¤ Çü½ÄÀÇ Ãâ·Â ½Ã »ç¿ëÇϸç Ãâ·Â Çü½ÄÀº format string À̶ó ºÒ¸®´Â " ¿Í " »çÀÌÀÇ ³»¿ë¿¡ µû¶ó °áÁ¤µÈ´Ù.

¸ðµç º¯¼ö´Â »ç¿ëÇϱâ Àü¿¡ ÀÚ·áÇüÀÌ ¸ÕÀú Á¤ÀǵǾî¾ß ÇÑ´Ù.
±âº» ÀÚ·áÇü

Integer (Á¤¼öÇü)

int, unsigned, long, unsigned long, short

Real (½Ç¼öÇü)

float, double, long double

Character (¹®ÀÚÇü)

char, unsigned character

ÀÚ·áÇü Á¤ÀÇ ¿¹)

      int  a, b, c, d;
      float  e, f, g, h;
      char  i, j;
      a = 1, b = 2, c = 3, d = 4;
      a = 32768; 
ÀÚ·áÇü¿¡ µû¸¥ °ª Çã¿ë ¹üÀ§

ÀÚ·áÇü

Bytes

Çã¿ë °ª ¹üÀ§

short (int)

2 ÀÌ»ó

-32768 ~ 32767

int

2 or 4

-32768 ~ 32767 or -2147483648 ~ 2147483647

unsigned (int)

2 or 4

0 ~ 65535 or 0 ~ 4294967295

long (int)

4 ÀÌ»ó

-2147483648 ~ 2147483647

float

4

10-38 ~ 1038

double

8

10-308 ~ 10308

char

1

ASCII Value (-128 ~ 127)

unsigned char

1

0 ~ 255

* Byte ¼ö´Â ÄÄÇ»ÅÍ È¯°æ¿¡ µû¶ó ´Ù¸§. sizeof·Î °Ë»ç °¡´É

            sizeof(int), sizeof(double) µî

¿¬»êÀÚ (Operators)

ÀÌÇ× ¿¬»êÀÚ (Binary operators) : +, -, *, /, %

     a + b
     3.14 * 2
     5 / 2
     5 % 2

»ê¼ú ´ÜÇ× ¿¬»êÀÚ (Unary operator): - (minus: ºÎÈ£¸¦ ¹Ù²Ù´Â ¿ªÇÒÀ» ÇÔ)

¿¬»ê ¿ì¼± ¼øÀ§ (Operator precedence): - (unary) > (*, /, %) > (+, -)