Introduction to C programming
History of C programming Invented and Developed by Dennis Ritchie and Brian Kernighan at Bell Laboratories in 1972 Predecessor – BPCL and B language Originally implemented on UNIX system on DEC PDP-11 Feature of C language –Is both a high-level and low-level language UNIX is written in ‘C’
Features of C language - 1 Provides a variety of data types –integer –character –floating-point Other derived data types –pointers –arrays –structure –union Expressions –formed from operators and operands –e.g. assignment, function call –Collectively known as ‘statement’
Features of C language - 2 Provides fundamental control- flow constructions 3 types of control-flow –Sequence structure, e.g., Any assignment expression –Selection structure, e.g. if statement (if-else) statement (switch) statement (while) statement (do-while) statement for statement
Features of C language - 3 Functions ( 函數 ) –May return values of basic types Int, char, float –May be called recursively –Local variables are automatic C program –May exist in separate source files compiled separately –Variables may be Internal to a function External but known only within a single file Visible to entire program
Features of C language - 4 Keywords for ‘C’ - reserved Autobreakcasechar Constcontinue defaultdo double elseenumextern Floatforgotoif intlongregister return Shortsigned sizeof static Structswitchtypedefunion unsigned void volatilewhile
C environment C programs go through 6 steps: 1. edit 2. preprocess 3. compile 4. link 5. load 6. execute
Examples - 1 #include main() { printf(“Welcome “); printf(“to SCE, HKBU\n“); } Preprocessor Main program statement \nReturn \tTab \\Blackslash \”Double quote
Examples - 2 #include main() { int integer1, integer2, sum; /* declaration */ printf(“Enter the first integer\n “); scanf(“”%d”, &integer1”); printf(“to SCE, HKBU“); scanf(“”%d”, &integer2”); sum = integer1 + integer2; /* assignment */ printf(“Sum is %d\n”, sum); }
Examples - 3 If-else control statement #include main() { int n1, n2, sum; printf(“Enter the first integer, and I will tell you\n “); printf(“the relationship they satisfy:”); scanf(“”%d %d”, &n1, &n2”); if (n1 == n2) printf(“%d is equal to %d\n”, n1,n2); if (n1 != n2) printf(“%d is not equal %d\n”,n1,n2); if (n1 < n2) printf(“%d is less than %d\n”,n1,n2); if (n1 > n2) printf(“%d is greater than %d\n”,n1,n2); return 0; }
Examples - 4 While repeat statement #include main() { int num1 = 1; printf(“We count from 1 to 10\n “); while (num1 <= 10) { printf(“We are counting %d. \n”, num1); num1 = num1 + 1; } return 0; }