1.69k likes | 2.44k Views
K. N. King, C Programming A Modern Approach , W. W. Norton & Company, 1996. C Programming A Modern Approach. Note About Coverage. This class has only part of the semester dedicated to C You already know Java, which has similar syntax You should be able to read the book quickly.
E N D
K. N. King, C ProgrammingA Modern Approach, W. W. Norton & Company, 1996. C ProgrammingA Modern Approach
Note About Coverage • This class has only part of the semester dedicated to C • You already know Java, which has similar syntax • You should be able to read the book quickly
Similarities of C to Java • /* Comments */ • Variable declarations • If / else statements • For loops • While loops • Function definitions (like methods) • Main function starts program
Differences between C and Java • C does not have objects • There are “struct”ures • But data are not tied to methods • C is a functional programming language • C allows pointer manipulation • Input / Output with C • Output with printf function • Input with scanf function
Efficiency Limited amount of memory Fast Portability Compilers are small and easily written C: UNIX and ANSI/ISO standard Power Flexibility Standard library Input/output, string handling, storage allocation, etc. Integration with UNIX C Strengths
Can be error-prone Flexibility C compiler doesn’t detect many programming mistakes Pitfalls Can be difficult to understand Some features are easier to be misused Flexibility Can be difficult to modify No modules C Weakness
C is case-sensitive Compiler remembers only first 31 characters Type Should be declared int height, length, width; Declarations must precede the statements. The value should be assigned before using the variable in computations: height = 8; length = 12; width = 5; int volume = height * length * width; Variables and Assignments
Macro definition: #define SCALE_FACTOR (5.0/9.0) No semicolon at the end! Constants
printf(string, expr1, expr2,…) Format string contains both ordinary characters and conversion specifications Conversion specification is a placeholder representing a value to be filled in during printing. The information after % specifies how the value is converted form its internal form(binary) to printed form (characters) Formatted Output: printf
scanf(string, expr1, expr2,…) Reads input according to a particular format. Format string contains both ordinary characters and conversion specifications scanf(“%d%d%f%f”, &i, &j, &x, &y); Number of conversion specification should match number of variables. Each conversion should be appropriate for type of the variable. while (scanf (“%d”, &i)==1) { … } Formatted Input: scanf
For each conversion specification, tries to locate an item of appropriate type, skipping blank spaces if necessary. Reads it, stopping when it encounters the symbol that can’t belong o item. Ignores white-space characters. scanf(“%d%d%f%f”, &i, &j, &x, &y); How scanf Works
Simple assignment(right associative): = int i=5, j=3; int k = 5*3; i = 72.99; float f; f = 136; i = j = k = 7; f = i = 33.3; k = 1 + (j = i); Compound assignments(right associative): +=, -=, *=, /=, %= i += j += k; i += k; vs i =+ k; Assignment Operators
Prefix operators: ++i, --i Postfix operators: i++, i— Increment and Decrement Operators
a = 5; c = (b = a + 2) – (a = 1); i = 2; j = i * i ++; Any expression can be used as a statement i++; i*j -1; i + j ; /* i = j */ Sub expression Evaluation
Relational Operators • 0 (false) and 1 (true) • Their precedence is lower than the precedence of the arithmetic operators. • Left associative • i < j < k
0 (false) and 1 (true) Their precedence is lower than the precedence of the relational operators. i < j == j < k Left associative Equality Operators
Logical negation: ! !expr : 1 if expr has the value 0 Right associative The same precedence as unary plus and minus Logical and: && expr1 && expr2 : 1 if both expr1 and expr2 has non-zero values Logical or: || expr1 || expr2 : 1 if either expr1 or expr2 (or both) has non-zero values Short-circuit evaluation Left associative The precedence is lower that that of the relational and equality operators Logical Operators
if (expression) statement if (expression) statement else statement Statement can be compound: { statements} if (i==0) vs if (i=0) if (expression) statement else if (expression) statement … else statement if … else Statement
if (y != 0) if (x != 0) result = x / y; else printf (“Error: y is equal to ) \n”); Use compound statement {} Compiler always match the closest unmatched if statement “Dangling else” Problem
expr1 ? expr2: expr3 int i, j, k; i = 1; j = 2; k = i > j ? i : j ; k = (i > 0 ? i : 0) + j ; return (i > j ? i : j); printf (“%d\n”, i > j ? i : j); Conditional Expression
switch ( expression ){ case constant-expression: statements … case constant-expression: statements default: statements } Controlling expression should be an integer expression (characters) Constant expression can’t contain variables or function calls. Statements do not require {}. Usually, the last statement is break. switch Statement
while (expression) statement Statement can be compound: {} while (i>0) printf (“%d\n”, i--); while (i>0) { printf (“%d\n”, i); i--; } Infinite loops: while(1) Break, goto, return while Loop
Example scanf(“%d”, &n);
do statement while (expression); Statement can be compound: {} do printf (“%d\n”, i--); while (i>0) ; do { printf (“%d\n”, i); i--; } while (i>0); do Loop
for (expr1; expr2; expr3) statement Statement can be compound: {} expr1; while (expr2) { statement expr3; } for (i=10; i>0; i--) printf (“%d\n”, i); Infinite loop: for (;;) Comma operator: for (i=1, j=2; i+j<10; i++, j++) printf (“%d\n”, i+j); for Loop
for (d=2; d<n; d++) if (n%d==0) break; if (d<n) printf (“%d is divisible by %d\n”, n,d); else printf(“%d is prime \n”,n); for (;;){ printf (“Enter a number(0 to stop): ”); scanf(“%d”,&n); if (n==0) break; printf(“%d cubed is %d\n”,n,n*n*n); } break escapes only one level of nesting. Exiting From a Loop: break
n = 10; sum = 0; while (n-->0){ scanf(“%d”, &i); if (i%2==0) continue; sum+=i; } Skipping the Rest of Iteration: continue
; for (d=2; d<n; d++) if (n%d==0) break; for (d=2; d<n && n%d !=0 ; d++); Accidentally putting a semicolon after the parentheses in if, while or for statement ends the statement prematurely. if (i==0); printf (“Zero\n”); while (i>0); printf (“%d\n”, i--); Null statement
Signedness: signed (defaut), unsigned Size: short, long <limits.h> holds ranges for int types. Basic Types: Integers
Decimal (base 10) literals digits between 0-9, no leading zero 15, 255, 32767 Octal (base 8) literals digits between 0-7, must start with 0 017, 0377, 077777 Hexadecimal (base 16) literals digits between 0-9 and letters between A-F (a-f), must start with 0x (0X) 0xF, 0xFF, 0x7FFF Integer Constants
<float.h> Assume IEEE 754 standard Scientific notation: sign, an exponent, a fraction .57e2, 57, 5.7e+1, 570.0e-1 Basic Types: Floating Types
Character set: Latin (7 bit), ASCII (8 bit) Treats as integers unsigned (0-255) and signed (-128-127) version Some compilers use unsigned by default, the other compilers use signed by default. char ch=65; /* it’s ‘A’ now */ int i = ‘a’; /* it’s 97 */ ch++; /* it’s ‘B’ now */ if (‘a’< =ch && ch <=‘z’) ch = ch – ‘a’ + ‘A’; /* ch=toupper(ch);*/ for (ch=‘A’; ch<=‘Z’; ch++) … ch=‘a’ * ‘b’ / ‘c’ … Basic Types: char
ch = getchar(); putchar(ch); while ( ( ch = getchar() ) != ‘\n’ ) … while ((ch=getchar())==‘ ’); printf(“Enter an integer: ”); scanf(“%d”, &i); printf(“Enter a command: ”); command = getchar(); Read and Write char: Alternative
sizeof (type-name) Unsigned integer representing the number of bytes required to store a value of type-name sizeof(char) is always 1 Can be applied to constants, variables, expressions int i, j; int k= sizeof(i); /* k is assigned 2*/ k = sizeof (i + j ); sizeof Operator
Convert operands to the “narrowest” type that will safely accommodate both values. If the type of either operand is a floating point: float -> double - > long double Otherwise: if there are short and char operands, convert them to int, then int -> unsigned int -> long int -> unsigned long int int i= -10; unsigned int u=10; Implicit Type Conversion
char c = ‘A’; int ind; float f; double d; i = c; /* will get 65 */ f = i; /* will get 65.0 */ d = f; i = 824.97; /* 824 */ c= 100000000; f = 1.0e1000; Conversion During Assignment
(type-name) expression Unary operator float f = 3.45, frac; frac = f – (int) f; int num1=5, num2 =3; float quotient = (float) num1/ num2; int i=1000; long int i = (long int) j * j; long int i = (long int) (j * j) Explicit Type Conversion: cast
Celsius vs Fahrenheit table (in steps of 20F) • C = (5/9)*(F-32); #include <stdio.h> int main() { int fahr, celsius, lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr - 32) / 9; printf("%d\t%d\n",fahr, celsius); fahr += step; } return 1; } • 5/9 = 0 • Integer arithmetic: 0F = 17C instead of 17.8C • %d, %3d, %6d etc for formatting integers
New Version Using Float #include <stdio.h> int main() { float fahr, celsius; int lower, upper, step; lower = 0; upper = 300; step = 20; fahr = lower; while (fahr <= upper) { celsius = (5.0 / 9.0) * (fahr - 32.0); printf("%3.0f %6.2f \n", fahr, celsius); fahr += step; } return 1; } • %6.2f 6 wide; 2 after decimal • 5.0/9.0 = 0.555556 • Float has 32 bits • Double has 64 bits • Long Double has 80 to 128 bits • Depends on computer
Version 3 with “for” loop #include <stdio.h> int main() { int fahr; for (fahr=0; fahr <= 300; fahr += 20) printf("%3d %6.1f \n", fahr, (5.0 / 9.0) * (fahr – 32.0)); return 1; }