cc510 beginning of c programming park, kyungmi [email protected]

60
CC510 Beginning of C Programming Park, KyungMi [email protected]

Upload: lauren-cobb

Post on 12-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

CC510Beginning of C Programming

Park, [email protected]

Page 2: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Contents

• Using Visual C++• Basic C Programming

2

Page 3: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

USING VISUAL C++

3

Page 4: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

VISUAL C++

4

Microsoft Visual C++ is a commercial integrated development environment (IDE) for the C.

An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development.

Wikipedia

Page 5: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Start Page

5

Page 6: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Create Project (1/3)

6

Page 7: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Create Project (2/3)

7

Page 8: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Create Project (3/3)

8

Page 9: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Create Files

9

Page 10: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Programming

10

Page 11: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Compile, Build, Execute

11

Page 12: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Results

12

Page 13: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

BASIC C PROGRAMMING

13

Page 14: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Definitions

• Computer programming (often shortened to programming or coding) is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs.

• Computer programs (also software programs, or just programs) are instructions for a computer.

• C is a general-purpose computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.

14

Wikipedia

Page 15: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Program Design

• Five phases in developing a program• Specify the problem• Analyze the problem• Design a method of solution (algorithm)• Coding (using programming lang.)• Test the program

15

Page 16: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

C History

• 1970 : K Tompson wrote B for the first UNIX system on the PDP-7

• 1972 : C was designed as an extension of B• 1973 : UNIX OS was written in C over 90%• 1976 - 1977 : UNIX was ported to VAX• BCPL -> B -> C• S/W used in UNIX is almost written in C

16

Page 17: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Genealogy of High-Level Language

1957

1960

1965

1970

1975

1980

1885

1990Ada 95

Ada

Pascal Prolog

ALGOL-W

LISP

ALGOL 58

ALGOL 60

FORTRAN IFORTRAN II

FORTRAN IV

FLOW-MATIC COMTRAN

BASIC

PL/I

ALGOL 68

CPLCOBOL

Smalltalk 80

C++

ANSI C FORTRAN 90

FORTRAN 77

C

BBCPL

17

Page 18: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

From Source Code to Executable File

Source Code Source File

Object File Executable FileLibraryLinker

Text Editor

Compiler

18

Page 19: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Sample Program

#include <stdio.h>

#define SCOPE 10

void main(){ int x, y; /* Variables */ int sum; x = 10; y = 200; sum = SCOPE * x + y;

printf(“Sum = %d\n”, sum); /* print function */}

Sum = 300

19

Page 20: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Name, Variables, Declarations

• "identifier" : variable name • letters, digits, _,

• First character : letter or _.• Long name with _ : help readability of program.

(up to 31 characters)• Upper and lower case letters are distinct.• Variable name : lower case • Symbolic constant : upper case• Key words are reserved. (lower case only)

20

Page 21: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Data Types and Sizes

• Char : a single byte, one character• int : integer ( 32 bit long in general )• float : single-precision floating point

precision: 6 digits, range: 10^(-38~+38)

• Double: double-precision floating pointprecision: 12 digits, range: 10^(-

308~+308)

• short, long: specifying the size of integershort int sint; short sint; long int lint; long counter;

int cntr;

21

Page 22: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Unsigned vs. Signed

• unsigned int vs. signed int : range of value• unsigned char vs. signed char

• Signed integer : 1 bit for the sign of the number• the rest for the magnitude of the number

• Unsigned integer use all the bits for the magnitude, non-negative.

unsigned short int x; /* 0 ~ 2^16-1 */ signed int y; /* -2^31 ~ 2^31-1 */signed char zz; /* -128 ~ +127 */

22

Page 23: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Data Types and Values

• Numeric data types : int, float, double ......• Single ASCII character : char (also integer)

Ex) 'A' '7' '+' 'a' '‘

• int • short int e.g. 1234 938 -392• long int : 1234567890123L 29438l /* L or l */• unsigned int: 2132U 332u /* u or U */

• octal representation of integer: begin with 0Ex) 0177 034 02222222222L 09932U

• hexadecimal representation of ingeter: 0X or 0xEx) 0X3ff 0x23 0X2B 0XFUL

23

Page 24: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Data Types and Values II

• float : either an int, a decimal fraction, an exponent part or their combination (but not integer) Ex) -5.3e-3 1.0 1. .023 3.14159 314.159e-2

314158e-5 0.00314158e+3 0.00314158e3

0.00314158e003 0.0 0e0 .0e0

• Special notation for characters : Ex) '\013' /* ascii vertical tab */

'\007' /* ascii bell character */

'\xb' /* ascii vertical tab */

'\0' /* null character */

24

Page 25: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Escape Sequence

Name of character written in C Integer value in decimal

null '\0' 0

backspace '\b' 8

tab '\t' 9

newline '\n' 10

formfeed '\f' 12

carriage return '\r' 13

double quote '\"' 34

single quote '\'' 39

backslash '\\’ 92

25

Page 26: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

String Constant (1/2)

• String constant or string literal• A sequence of zero or more characters surrounded by “”

Ex) "This is string" "Thisisstring"

"This is\talso string" "This is string\n"

"" /* empty string */

26

Page 27: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

String Constant (2/2)

• String constants can be concatenated at compile timeEx) "hello," " world" --- "hello, world"

• String constant is an array of character terminated with• Null character.

27

Page 28: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Class declaration

• Variables must be declared before use

• class (storage class)• automatic (default within functions)• extern (global)• Static• register

• variable type• short, long, int, float, unsigned char, etc.

• identifier_list• a list of variable names, separated by commas whose values are to be of the

designed type and class.

class type identifier_list;

28

Page 29: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Declaration: examples

• Initialization of variables at the DECLARATION TIME (must be a constant expression)

• qualifier const

float x, sum, av;int n;static unsigned long int real_long, rl;

#define MAXLINE 1000char esc = '\\';int i = 0;int limit = MAXLINE+1 /* constant expression*/float eps = 1.0e-5

const double e = 2.71828182845905;const char msg[] = "warning: ";int strlen(const char[]);

29

Page 30: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Size of Data Types: program

#include <stdio.h>

/* compute the size of the fundamental types */main(){ printf("\n char: %d bytes", sizeof( char)); printf("\n short: %d bytes", sizeof( short)); printf("\n int: %d bytes", sizeof( int)); printf("\n long: %d bytes", sizeof( long)); printf("\nunsigned: %d bytes", sizeof(unsigned)); printf("\n float: %d bytes", sizeof( float)); printf("\n double: %d bytes", sizeof( double)); printf("\n\n");}

30

Page 31: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Arithmetic Operators

• binary arithmetic operators:• + - * / % (modulus operator)

• relational and logical operators: • > >= < <= == !=

int year;if ((year % 4 == 0 && year % 100 != 0) ||

year % 400 == 0) printf(%d is a leap year\n", year);

else printf(%d is not a leap year\n", year);

for (i=0; i<lim-1 && (c!='\n' && c!=EOF; i++) s[i] = c;

31

Page 32: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Arithmetic Conversion Rules

double

long

unsigned

int

float

char, short

32

Page 33: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Conversion Rule: example

char c; double d; float f; int i; long l; short s; unsigned u;

Expression Type

c - s / i Int

u * 3 - i unsigned

u * 3.0 - i Double

f * 3 - i float

c + 1 int

c + 1.0 double

3 * s * l long

33

Page 34: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Increment and Decrement

• ++ (increment: add 1)• -- (decrement: substract 1)

• ++n -> increment n before using its value• n++ -> increment n after its value has been used

• only applied to variables (not to expresson or const)

34

Page 35: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Assignment Operators

• compress form

i = i + 2; i += 2; /* assignment operator */

• expr1 op= expr2 expr1 = (expr1) op (expr2)• op : + - * / % << >> & ^ |

// x *= y + 1 means x = x * (y+1) rather than x = x*y + 1

/* bitcount: count 1 bits in x */ int bitcount(unsigned x) { int b; for (b = 0; x != 0; x >>=1) if (x &01) b++; return b;}

35

Page 36: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Statement and Block

if (x == 0) x = 0; /* expression & statement */ x = 0; i++; printf("%d %d\n", i,j); /*statement */

{ x = 0; i++; printf("%d %d\n", i,j); } /* block */

• Expression: combination of var, const and operators

• statement : expression + semicolon• Block: { series of statement}

36

Page 37: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Ambiguity of If-Then-Else

• Part of if statement is optional : problem with nested if statements

if (n > 0) { if (a > b) z = a; } else z = b;

if (n >= 0) for ( i = 0; i < n; i++) if (s[i] > 0) { printf("..."); return i; } else /* WRONG */ printf("error --n is negative-n");

37

Page 38: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Else-If : multiple choice

/* count blanks, digits, letters, newlines, and others */#include <stdio.h>

main(){ int c, blank_cnt, digit_cnt, letter_cnt, nl_cnt, other_cnt;

blank_cnt=digit_cnt=letter_cnt=nl_cnt=other_cnt = 0;

while ((c = getchar()) != EOF) /* brace not necessary */ if (c == ' ') ++blank_cnt; else if ('0' <= c && c <= '9') ++digit_cnt; else if ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') ++letter_cnt; else if ( c == '\n') ++nl_cnt; else ++other_cnt;}

38

Page 39: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Binary Search : example

/* binsearch: find x in v[0]<=v[1]<=....<=v[n-1] */int binsearch(int x, int v[], int n){ int low, high, mid;

low = 0; high = n - 1; while (low <= high) { mid = (low+high) / 2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else /* found match */ return mid; } return -1; /* no match */}

39

Page 40: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

While

• While ( expression ) : While expression is evaluated true(non zero), repeat statement.

while (i++ < n) factorial = factorial * i;

while ((c = getchar()) != EOF) { if ('a' <= c && c <= 'z') ++lower_case_letter_cnt; ++total_cnt;}

while (++i < LIMIT) { j = 2 * i + 3; printf("\n%d", j);}

40

Page 41: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

While : continued

1. repeat statement zero or more times.

2. Control is passed to the next statement of while when expression is false (zero).

3. If expression is zero at first, skip while loop.

int n;

printf("\ninput an integer: ");scanf("%d", &n);while (--n) { ........ /* do something */} /* for positive integer OK, but for negative ....*/

while (--n > 0) { /* do something */ }

41

Page 42: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

FOR

for ( init_expr; test_expr; update_expr)statementnext_statement...

int i, sum;

sum = 0;for (i = 1; i <= 10; ++i) /* say evaluation seq */ sum += i;

42

Page 43: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

FOR : examples

for (i = 1; i <= n; ++i) factorial *= i;

for (j = 2; k % j == 0; ++j) { printf("\n%d is a divisor of %d", j, k); sum += j;}

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

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

for ( ; ; ) ; /* loop forever */

43

Page 44: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

COMMA operator

•expression1, expression2 • evaluate expression1, and then expression2, left to right,

value of operation is value of expression2

• comma operator : extends the flexibility of for loop• allowing you to include initialize, test or update expression in

a for loop

sum = 0, i = 1

for ( sum = 0, i = 1; i <= n; ++i) sum += i;

for ( sum = 0, i = 1; i <= n; sum += i, ++i) ; /* empty statement */

44

Page 45: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

COMMA and FOR

#include <stdio.h>main(){int even_sum, odd_sum;int cnt, j, k, n;

scanf("%d", &n); /* get the number */

even_sum = odd_sum = 0;for (cnt = 0, j = 2, k = 1; cnt < n; ++cnt, j +=2, k += 2) { even_sum += j; odd_sum += k;}printf("%7d%7d\n", even_sum, odd_sum);}

45

Page 46: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Do while statement : exit condition loop

•do statement while (expression);• evaluate statement first and then evaluate

expression • If expression is true (nonzero) , repeat

statement.• If expression is false (zero), control passes to

next statement.do { printf("\n\ninput a positive integer: "); scanf("%d", &n);} while (n <= 0);

46

Page 47: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Fibonacci Number: example

#include <stdio.h>/* print fibonacci number and quotients */#define LIMIT 46main(){ int f0 = 1, f1 = 1, n, temp; printf("\n%7d%19d", 0, 1); /* fi(0) = 1 */ printf("\n%7d%19d", 1, 1); /* fi(1) = 1 */

temp = f0; for (n = 2; n <= LIMIT; ++n) {

f1 += temp; temp = f0;f0 = f1;

printf("\n%7d%19d%19.16f",n, f1, (double) f1 / (double) f0); } printf("\n\n");}

47

Page 48: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Prime Number: example

#include <stdio.h>/* print all primes less than LIMIT */#define LIMIT 1000main(){ int cnt = 0, j, k;

for (k = 2; k < LIMIT; ++k) { j = 2; while (k % j != 0) ++j; if (j == k) { ++cnt; /* a prime has been found */ if (cnt % 6 == 1) printf("\n"); printf("%12d", k); } } printf("\n\nthere are %d prime numbers less than %d\n", cnt, LIMIT);}

48

Page 49: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

SWITCH statement : multiple choice

switch ( expression ) {case const_expr : statement1case const_expr : statement2default: statement3

}

• switch onst_expr(label): must have integer valued constants (type char is included), expressions formed solely from constants• Evaluate the expression.• Execute the case with label constant matching the value. If no match,

execute the default, or if no default, terminate.• Terminate the switch when a break stmt is encountered, or by "falling

off the end".

49

Page 50: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Switch: example

switch (c) { case 'a': ++a_cnt; break; case 'b': ++b_cnt; break; case 'c': ++c_cnt; /* what happen if no break?*/ case 'd': case 'D': ++dD_cnt; break; default: ++other_cnt; /* break is not necessary */}

50

Page 51: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

BREAK and CONTINUE

• break: causes an exit from the innermost loop or switch.• terminate : for, while, do while, and switch

• continue: causes the current iteration of a loop to stop and the next iteration to begin immediately.• effective only in : for, while and do while

51

Page 52: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Break: example

.....while (1) { scanf("%f", &x); if (x < 0.0) break; /* exit loop if the value is negative */ printf("\n%f", sqrt(x));....} /* break jumps to here */

52

Page 53: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Continue: example

for (i = 0; i < TOTAL; ++i) { c = getchar(); if ( '0'<=c && c <='9') continue; ....... /* process other character */

/* continue transfers control to here to begin next iteration */}

53

Page 54: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Goto : unconditional branch

goto label;

………

label : statement

........ /* some program text */{ ........ if (flag != 0 ) goto error; ....... /* process when no error */}......error: printf("\nan error has occurred");.........

54

In general, GOTO should be AVOIDED!!!

Page 55: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

printf()

• printf("format", var1, var2,....)• a library function to output various type of values.

• # of % :number of variable_or_constant• what happens if not matched?

printf(" This is a simple text\n");printf("This is an integer %d output\n", i);printf("These are integers: %d %d\n", i, 36);printf("This is a float number %f\n", f_number);printf("How about a char %c?", 'A');

55

Page 56: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

I/O conversion specification

%d integer output decimal

%o integer output octal

%x integer output Hexadecimal

%u unsigned integer Decimal

%c character ascii

%s string output print till null char

%f floating float (decimal point)

%e floating float with exponent

56

Page 57: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Conversion Specification Modifier

• %10d : width of output ==10

• %-10d : output is printed beginning at the left of its field width. Normally, item is ending at the right of it’s field

• %9.3f : width = 9, number after decimal pt = 3

• %ld : the corresponding data item is long rather than int

57

Page 58: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

FORMAT : example

main(){ printf("/%f/\n", 1234.56); printf("/%e/\n", 1234.56); printf("/%4.2f/\n", 1234.56); printf("/%3.1f/\n", 1234.56); printf("/%10.3f/\n", 1234.56); printf("/%-10.3f/\n", 1234.56); printf("/%10.5f/\n", 1234.5678901); printf("/%10.5e/\n", 1234.5678901);}

58

Page 59: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

Scanf()

• scanf("format", &var1, &var2, ...);• input the value for variables as specified in format

• don’t use ‘&’ for string variables

scanf("%d %d", &i, &j);scanf("%c", &char);scanf("%f", &f_number);

scanf(“%s”, string);

59

Page 60: CC510 Beginning of C Programming Park, KyungMi kmpark@bulsai.kaist.ac.kr

LAB #4

• Write a credit calculation program. • Input:

• You should input the alphabet score of 3 courses

• Output:• The program calculates average credit by float (limit to 2.2f)

• Note:• don’t use + or – in input(just use A~F)

Ex ) Score: A B A

Ex ) credit:3.66

60