<<

ECE15: Introduction to Computer Using the C Language

2: Variables and Data Types

A. Orlitsky and A. Vardy, based in part on slides by S. Arzi, G. Ruckenstein, E. Avior, S. Asmir, and M. Elad A. Orlitsky and A. Vardy, based in part on slides by & much printf() 3+4 scanf()

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 2 Outline ❖ Writing

❖ Reading

❖ Variables and data types ‣ Text ‣ Integers ‣ Reals ‣ Characters ‣ ❖ Rudimentary input/output

Lecture 5 ECE15: Introduction to Computer Programming Using the C Language 3 Writing (Printing)

❖ C printing function printf() “print formatted” ❖ Name shared by several programming languages ❖ Prints ‣ Text (“Hello world”) ‣ Integers ‣ Reals ‣ Characters ‣ Strings

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 4 Printing Text

printf(“Hello world!”); Hello world!>

printf(“Hello world!\n”); Hello world! >

printf(“Hello\n world!\n”); Hello world! >

printf(“Hello\nworld!\n”); Hello world! >

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 5 Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 6 Integer Constants

❖ Used to print, in program,

‣ 7

‣ -13

‣ 1234 (not 1,234)

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 7 Printing Integers ❖ Format using %d (decimal) or %i (integer) printf("%d", -13); Same as printf("-13"); -13

Format statement printf("my %i cents", 2); my 2 cents Regular text gets printed normally. %d, %i, etc. don’t printf("%d", 2*3+4); 10 get printed. They More math later determine how arguments after printf("%d+%d=%d", 1, 2, 1+2); 1+2=3 “...” get printed.

printf("%d+%d=%d", 1, 2, 1+3); 1+2=4

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 8 Minimum Print Size

❖ %3d - use least 3 locations

printf("#%d#%3d#%3d#",1, 2, 3456); #1# 2#3456# left adjust

printf("#%d#%3d#%-3d#",1, 2, 3); #1# 2#3 #

printf("#%5.3d#%-5.3d#", 1, 2); # 001#002 # Precede . 0’s ❖ Useful for printing table

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 9 Formatting errors

❖ %d and %i indicate how subsequent arguments get printed ❖ # of %d %i should match # of subsequent arguments ❖ What if these numbers don’t match?

printf("%d", 1, 2); Compilation warning 1

printf("%d %d", 1); Compilation warning 1 73858 mismatch.c

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 10 Variables

❖ So far, everything fixed and rigid, nothing changes ‣program always prints same thing (“Hello, world”, -13)

❖ Need something more flexible, dynamic ‣ Print different values, read user input

❖ Variables ‣ Hold information ‣ Take user input ‣ Can change with

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 11 Data Types

❖ All constants and variables have a type ‣ Integer, real number, character, string ❖ Type determines ‣ # memory bytes allocated ‣ Interpretation / meaning of the bits stored in these bytes ‣ Operations allowed ❖ Variables must be declared ‣ type, name, optional initial value int num,; double weight = 0.0; char digit = '4'; ‣ Instructs compiler to Shortly Now ๏ Allocate right # memory cells ๏ Interpret content of these cells according to type ๏ Associate variable name with these cells

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 12 int ❖ Basic integer type (more types later) ❖ Declaration int year; int temperature, humidity;

❖ Uninitialized (contains previously stored value) ❖ Initialization Hint ‣ At declaration = does not mean equal. int a=0; int a=0, b=1; a = 5 means store 5 in the variable called a. ‣ Assignment int a; int a, b; int a, b; Hint a=0; a=0; a=b=0; Initialize or assign b=1; value to a variable ❖ Printing: same as constants before using its contents. printf("%d", year); Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 13 Quiz

❖ What’s printed? #include quiz.c int main() { int a=0, b, c, d, e, f; b=1; c=d=2; printf("a=%d\n", a); a=0

printf("b=%d\n", b); b=1

printf("c=%d\n", c); c=2

printf("d=%d\n", d); d=2

printf("e=%d\n", e); e=589 Or whatever stored before

printf("f=%d\n", f); f=-2381039 Likewise return 0; }

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 14 Reading Integers

❖ scanf() with %d (or %i)

#include scanf1.c int main() { int myvar; printf("Type an integer: "); scanf("%d", &myvar); printf("It is: %d\n", myvar); return 0; }

Always (for now..) use scanf with & - stores value in that location Think of &myvar as the address of myvar More later

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 15 Non-Integer Input

%d skips initial white space (space, tab, ) Then reads till first non-integer character #include scanf1.c int main() { int value; Preceding printf("Type an integer: "); white space scanf("%d", &value); printf(“You typed %d\n", value); ignored } return 0;

15 You typed 15 15 You typed 15

1b 1.5 1+234 You typed 1 rest left for future scanf’s

b < .5 You typed -183793 whatever stored before

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language Reading More Values

#include scanf2.c int main() { int value1, value2; printf("Now gimme two: "); scanf("%d%d", &value1, &value2); printf("Their sum: %d\n", value1+value2); return 0; }

❖ Spaces preceding %d don’t matter (as skips initial spaces) same scanf(" %d %d", &value1, &value2);

❖ Spaces following last %d may matter (later)

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 17 Maximum Field Size

Integer between % and d specifies maximum # digits read

scanf("%2d", &a); 1 a=1

123 a=12

scanf("%1d%d", &a, &b); 123 a=1 b=23

same

scanf("%1d", &a); 123 a=1 b=23 scanf("%d", &b);

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language Field Separators

❖ Non % text is expected and must appear scanf("%d,%d", &a, &b); 1,2 a=1 b=2 Remember mainly this scanf("%dxy%d", &a, &b); 1xy2 a=1 b=2 part! ❖ ALLOWED modifications Keep rest in ‣ %d skips initial space, so space after separator ok mind, but scanf("%d,%d", &a, &b); 1, 2 a=1 b=2 likely to scanf("%dxy%d", &a, &b); 1xy 2 a=1 b=2 be in exams. ‣ Format space means >=0 spaces, so remove/add space ok scanf("%d x y %d", &a, &b); 1 x y 2 a=1 b=2

❖ DISALLOWED 1 xy2 a=1 b=2 separator.c ‣ Add space before separator scanf("%d,%d", &a, &b); 1 ,2 a=1 b=#&<) scanf("%dxy%d", &a, &b); 1 xy2 a=1 b= time.c int main() { int hour, minute; printf("Enter current time (hh:mm): "); scanf("%d:%d", &hour, &minute); printf("%d hours and %d minutes left\n", 23-hour, 59-minute); return 0; }

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 20 How Many Values scanf Read?

❖ Returns # of successfully read variables #include scanf_num.c int main() { int numRead, firstVal, secondVal; printf("Two integers please: "); numRead = scanf("%d%d", &firstVal, &secondVal); printf("Read %d ints, first was %d, second %d\n ", numRead, firstVal, secondVal); return 0; } Try entering 5a

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 21 Using # Values scanf Read

❖ Calculate average of up to 4 integers #include average.c int main() { int a1=0, a2=0, a3=0, a4=0; int number;

printf("Enter up to 4 integers followed by *: "); number = scanf("%d%d%d%d", &a1,&a2,&a3,&a4); printf("Sum=%d, Number=%d\n",a1+a2+a3+a4,number); printf("APPROXIMATE average is %d\n", (a1+a2+a3+a4)/number); return 0; } Approximate because integer!!

❖ Later - better ways of doing that

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 22 Can we Print Everything?

Means How to print? Like so

” end format ” \”

\n newline \ \\

%d decimal % %%

printf(“\””); ” printf(“\\\\”); \\

printf(“\\n”); \n

printf(“%%d”); %d

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 23 ❖ Rest of the material about integers is important, and you should know it

❖ Yet a bit harder to memorize, hence less likely to appear in in-class midterm and exam

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 24 Representation of Integers ❖ Computers represent everything in binary: 0,1 ❖ Nonnegative integers: standard binary representation ‣ Reserve leftmost bit for sign ‣ For 3 bits: 0 → 000, 1 → 001, 2 → 010, 3 → 011 ‣ Always start with 0 Though not on exam, ‣ With n bits, represent 0 to 2n-1-1 you should know this!

❖ Negative integers: 2’s complement, -x represented as 2n-x ‣ For 3 bits: -1 → 111, -2 → 110, -3 → 101, -4 → 100 ‣ Start with 1 ‣ With n bits, represent -1 to -2n-1 Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 25 Size of int

❖ Standards don’t determine size of int ❖ compilers allocate 4 bytes (32 bits) byte = 8 bits ❖ Range: -231,…,-1,0,1,…,231-1 31 ❖ 2 = 2,147,483,648 ~ 2 Billion 10 1,024 2 ~thousand #include int main() { 220 1,048,567 ~million int x=2147483647; 230 1,073,741,824 ~billion printf("x=%d\n", x); printf("x+1=%d\n", x+1); return 0; > a.out } largest_int.c x=2147483647 x+1=-2147483648 ❖ Often not enough > ❖ How do we know # bytes? Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 26 sizeof ❖ sizeof(object) returns # bytes used to store object ❖ object: ‣ Type name: int ‣ Variable name: x ‣ Expression: 3*x+5 printf("Number of bytes:\n"); sizeof1.c printf("int: %lu\n", sizeof(int)); int dummy=57; printf("dummy: %lu\n", sizeof(dummy)); printf("3*dummy: %lu\n", sizeof(3*dummy));

Number of bytes: ❖ Shortly use for other types int: 4 dummy: 4 3*dummy: 4

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 27 Other Integer Types ❖ short, long (often = int), long long (large integers) ‣ Sizes guaranteed to satisfy sizeof(short)≤sizeof(int)≤ sizeof(long)≤ sizeof(long long)

printf("short: %lu, int: %lu, \ Line continues long int: %lu, long long int: %lu\n", sizeof(short), sizeof(int), sizeof(long int), sizeof(long long int)); long long int dummy=57; printf("dummy: %lu, 3*dummy: %lu\n", sizeof(dummy), sizeof(3*dummy));sizeOfTypes1.c

short: 2, int: 4, long int: 8, long long int: 8 dummy: 8, 3*dummy: 8

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 28 Reading & Writing Integer Types

❖ Constants Needed only for really long integers ‣ long - 35L, long long - 21537LL ❖ printf and scanf ‣ short - %hd, long - %ld, long long - %lld sizeOfTypes2.c #include Largest int: int main() { 2147483647 long int a ü= 5, b ü= 5L; int c ✘= 2147483648, d ✘= 2147483648L; long int e ü= 2147483648L; long long int f=ü2147483648LL; printf("a=%ld b=%ld e=%lld f=%lld\n", a,b,h,h); return 0; } Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 29 Unsigned

❖ unsigned represents only positive integers, hence doubles the range. For example, if int occupies 4 bytes int: -231,…,-2,-1,0,1,2,…,231-1 unsigned int: 0,1,2,…,232-1 ❖ Similarly: unsigned char, unsigned short, unsigned long

#include needed only when large unsigned.c int main() { unsigned int us1 = 5u, us2 = 5U, us3 = 5; printf("us1=%d us2=%u us3=%U\n, us1,us2,us3); return 0; }

❖ Same for scanf

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 30 Octal and Hexadecimal Constants ❖ Constants ‣ Octal - precede with 0 (zero) printf("%d", 012); 10 ‣ Hexadecimal - precede with 0x printf("%d", 0x12); 18 ❖ Printing ‣ Octal (%o) printf("%o", 13); 15 ‣ Hexadecimal (%x,%X) printf("%x", 13); d

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 31 Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 32 Constants

❖ Floating point 1.23 0.7 .7 +13.0 -13.

❖ Scientific notation 1.23e1 .123E+2 =.123*102 = 12.3

❖ Integers (converted) 13 Caution when printing integer as float

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 33 Printing

❖ Print: %g, %lf, %f, or %e

printf("%g", 24.00); 24 scientific notation .174e2=.174*102

printf("%g", .174e2); 17.4 gcc - alerts to problem printf("%g", 7);û -3.23732e-232 by default 6 printf("%f", 2.4); 2.400000 digits after point 2 digits after point printf("%.2f", 2.4); 2.40 print total of at least 6 digits including point printf("#%-6.2f#", 2.4); #2.40 # - left justify printf("%e", -24.); -2.400000e+01

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 34 float and double ❖ Basic types, double provides more precision, more common ❖ Constants are double ❖ Declaration double fraction; float width, height; ❖ Uninitialized (contains previously stored value) ❖ Initialization ‣ At declaration float a=0.5; double a=5, b=3e-2; ‣ Assignment double a; double a, b; a=.13; a=b=-17.23; ❖ Printing: same as constants (for both double and float) printf("%f", width); Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 35 Reading ❖ scanf() with %f (float), %lf (double)

#include int main() { Again! double x; printf("Real #: "); scanf("%lf", &x); printf("Typed: %g\n", x); return 0; } ❖ Reading & writing mixed types int i; double x; float y; mix.c printf("Enter int, double, and float: "); scanf("%d%lf%f", &i, &x, &y);

printf("Int: %d dbl: %f flt: %f\n", i, x, y);

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 36 Representation Represented by binary floating-point expansion

sign exponent mantissa

3.1415926 11.001001000011111

0|10|11001001000011111 You should know, but not in exams.

Integers (42.0) and byadic fractions (42/1024) represented exactly

Other reals are approximated

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 37 Other Real-Valued Data Types

❖ In addition to double and float can use long double ❖ Standard guarantees sizeof(float) ≤ sizeof(double) ≤ sizeof(long double) ❖ Most compilers allocate ‣ double:8 bytes, ±5.0×10-324 to ±1.7×10308, 15 precision digits ‣ float: 4 bytes, ±1.5×10-45 to ±3.4×1038, 7 precision digits

sizeofFloatingPoint.c

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 38 Characters

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 39 char

❖ Constants Forward ‣ Enclosed in ‘ ‘: 'a', 'Z', '3', '+', '#', '$' ‣ Some letters cannot be written directly, use escape: \ '\n'-- newline '\t'-- tab '\b'-- backspace '\a' -- bell (alert) moves back, ❖ Declaration doesn’t erase char letter_name; char letter_name, initial; ❖ Uninitialized (contains previously stored value) ❖ Initialization char a; char a, b; char a=’d’; a=’#’; a=b=’\b’;

‣ Wrong: char a=d;çThinks it’s a variable

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 40 Printing and Reading

❖ Printing printf("%c", ’d’); same as printf("d"); char vowel=’H’; printf("%ca%c", vowel, ’!’); Ha!

printf("%c%c%c", ’a’,’\b’,’b’); b printf("%c%c%c%c", ’a’,’\b’,’b’,’\b’); b printf("%c%c%c%c",’\a’,’\a’,’\a’,’\a’); ❖ Reading Assume: char a1, a2;

scanf("%c", &a1); again char.c scanf("%c%c", &a1, &a2); nt ten Lectureprintf( 2 "%ce%c\n" ECE15: Introduction to ,Computer a2, Programming a1); Using the C Language 41 Representation ❖ Character stored in one byte (8 bits)

❖ Represented as integer from 0 to 127 using ASCII (American Standard Code for Information Interchange)

Character Represented as Decimal A 01000001 64+1=65 B 01000010 64+2=66 a 01100001 64+32+1=97 0 00110000 32+16=48

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 42 ASCII Table FreeFree ASCII ASCII ChartFree ChartFree ASCII ASCII Chart Chart

CharChar Desc DescCharChar Desc Desc Dec Dec Hex Hex Ke Dec Ke Decyy Hex HexChar KeChar Key y Dec DecChar HexChar Hex DecHTM HTM DecL HexL Hex HTMChar HTMCharL L Dec DecChar Hex HexChar Dec Dec Char Char Hex Hex Dec Dec CharHex Hex Char Dec Dec Char CharHex Hex HTML HTML Char Char Code Code HTML HTML Code Code !"#!"# NULLNULL!"#!"#NULLNULL 00 0000 ^@^@0 0 0000$$^@%%&'(^@&'( 3232$%$20&'(%20&'(3232 2020 )) 6464 40)40) 6464*40*409696 60*60* 9696$$%%&'(60&'(60 &nbs$&nbs$%%&'(p&'(p; ; &nbs p; ; $+,$+,StartStart$+, of $+,of Headin HeadinStartStartg ofg ofHeadin Heading g 11 0101 ^A^A1 1 0101 ^A-^A- 3333 21-21- 3333 2121 .. 6565 41.41. 6565&41&419797 6161&& 9797 /61/61 &am&am/p/p; ; &am&p; ; $01$01 StartStart$01 of $01of Text TextStartStart of ofText Text 22 0202 ^B^B2 2 0202 ^B2^B2 3434 222222 &&34qquot;34uot;2222&q&uot;q3uot;3 6666 423423 66664424429898 624624 9898 562562 <<55 << 601601 EndEnd 601of of601 Text TextEndEnd of ofText Text 33 0303 ^C^C3 3 0303 ^C7^C7 3535 723237 3535 2323 88 6767 438438 6767'43'439999 6363'' 9999 963963 &&g9gt;9t; &&ggt;t; 6+06+0 EndEnd 6+0of of6+0 Transmission TransmissionEndEnd of ofTransmission Transmission 44 0404 ^D^D4 4 0404^D:^D: 3636 :2424: 3636 2424 ;; 6868 44;44; 6868<44<44100100 64<64< 100100=64=64 &co&co=py=py; ; &co©py; ; 6!6!>>EnEnqquir6!uir6!y>y >EnEnquirquiry y 55 0505 ^E^E5 5 0505 ^E??^E 3737 ?25?25 3737 2525 66 6969 456456 6969(45(45101101 6565(( 101101@65@65 &re&re@g@g; ; &re®g; ; .8A.8A AcknoledAcknoled.8A.8AggeAcknoledeAcknoledgege 66 0606 ^F^F6 6 0606 ^F/^F/ 3838 /2626/ &am&am3838pp;26;26&am&amBBp;p;7070 46B46B 7070C46C46102102 6666C C 102102D66D66 &&supDp1;D1; &su&supp1;1; 36#36# BellBell36#36#BellBell 77 0707 ^G^G7 7 0707^GE^GE 3939 27E27E 3939 2727 FF 7171 47F47F 7171G47G47103103 67G67G 103103H67H67 &su&supHp2;H2; &su&supp2;2; 3$3$ BacksBacks3$p3$paceaceBacksBackspacepace 88 0808 ^H^H8 8 0808^HI^HI 4040 28I28I 4040 2828 ,, 7272 48,48, 7272J48J48104104 68J68J 104104K68K68 &su&supKp3;K3; &su&supp3;3; 0.30.3 HorizontalHorizontal0.30.3 HorizontalTab TabHorizontal Tab Tab 99 0909 ^I^I9 9 0909 ^IL^IL 4141 29L29L 4141 2929 MM 7373 49M49M 7373M49M49105105 6969M M 105105 E69E69 &a&appos;E os;E &a&appos;os; #B#B LineLine #BFeed Feed#B LineLine Feed Feed 1010 0A0A ^J10^J10 0A0A ^JN^JN 4242 2AN2AN 4242 2A2A OO 7474 4A4AO O 7474P4AP4A106106 6A6AP P 10610626A26A &&qquot;2uot;2 &&qquot;uot; Q0Q0 HomeHomeQ0Q0 HomeHome 1111 0B0B ^11^K11K 0B0B^RK^RK 4343 R2B2BR 4343 2B2B AA 7575 4BA4BA 7575S4BS4B107107 6B6BSS 107107T6BT6B ¼¼TT; ; ¼¼ ; BBBB FormFormBB Feed BBFeedFormForm Feed Feed 1212 0C0C ^12^L12L 0C0C ^UL^U L 4444 2CU2CU 4444 2C2C ## 7676 4C#4C# 7676V4CV4C108108 6C6CV V 108108W6CW6C ½½WW; ; ½½ ; 8X8X CarriaCarria8Xg8Xgee Return CarriaReturnCarriageg Returne Return 1313 0D0D ^M13^M13 0D0D^MY^MY 4545 2DY2DY 4545 2D2D ZZ 7777 4DZ4DZ 7777[[4D4D109109 6D[6D[ 109109\6D\6D ¾¾\\; ; ¾¾ ; $+$+ ShiftShift$+ Out $+OutShiftShift Out Out 1414 0E0E ^N14^N14 0E0E^N]^N] 4646 2E]2E] 4646 2E2E !! 7878 4E!4E! 7878^4E^4E110110 6E^6E^ 110110!6E!6E &&p!pi;!i; &&ppi;i; $M$M ShiftShift$M In $MIn ShiftShift In In 1515 0F0F ^O15^O15 0F0F^O_^O_ 4747 _2F2F_ 4747 2F2F ++ 7979 4F+4F+ 7979`4F`4F111111 6F`6F` 111111a6Fa6F ™™aa ™™ ;#6;#6 DataData;#6 ;#6Link EscaData EscaDatap Linkpe eLink Esca Escapepe 1616 1010 ^P16^P16 1010 ^Pb^Pb 4848 b3030b 4848 3030 cc 8080 50c50c 8080%50%50112112 70%70% 112112"70"70 ∞∞"" ∞∞ ;8d;8d DeviceDevice;8d;8d Control ControlDeviceDevice 1 1 Control Control 1 1 1717 1111 ^Q17^Q17 1111^Qd^Qd 4949 d3131d 4949 3131 >> 8181 51>51> 8181e51e51113113 71e71e 113113#71#71 ≠≠## ≠≠ ;8f;8f DeviceDevice;8f;8f Control ControlDeviceDevice 2 2 Control Control 2 2 1818 1212 ^18^R18R 1212 ^fR^fR 5050 f3232f 5050 3232 XX 8282 52X52X 8282g52g52114114 7272g g 114114$72$72 ≤≤$$ ≤≤ ;8h;8h DeviceDevice;8h;8h Control ControlDeviceDevice 3 3 Control Control 3 3 1919 1313 ^S19^S19 1313 ^Sh^Sh 5151 h3333h 5151 3333 $$ 8383 53$53$ 8383i53i53115115 7373ii 115115%73%73 &&g%ge;%e; &&gge;e; ;8j;8j DeviceDevice;8j;8j Control ControlDeviceDevice 4 4 Control Control 4 4 2020 1414 ^T20^T20 1414 ^Tj^Tj 5252 j3434j 5252 3434 00 8484 540540 8484k54k54116116 7474k k 116116&74&74 &as&asy&ym&mpp; ; &as&asymympp; ; !.A!.ANeNeggative!.Aative!.A Acknowled NeAcknowledNegativegative Acknowledg geAcknowlede geg21e21 1515 ^U21^U21 1515^Ul^Ul 5353 l3535l 5353 3535 "" 8585 55"55" 8585m55m55117117 75m75m 117117!75!75 &e&eqquiv;!uiv;! &e&eqquiv;uiv; $n!$n! SSyyncronousncronous$n!$n!Sy SIdlencronous Idleyncronous Idle Idle 2222 1616 ^V22^V22 1616 ^Vo^Vo 5454 o3636o 5454 3636 QQ 8686 56Q56Q 8686p56p56118118 7676pp 118118'76'76 ∑∑'' ∑∑ 603603 EndEnd 603of of603 trans. trans.EndEnd Block ofBlock oftrans. trans. Block Block 2323 1717 ^W^W2323 1717^Wq^Wq 5555 q3737q 5555 3737 rr 8787 57r57r 8787ss5757119119 77s77s 119119t77t77 ••tt •• 8.!8.!CancelCancel8.!8.!CancelCancel 2424 1818 ^X24^X24 1818 ^Xu^Xu 5656 u3838u 5656 3838 11 8888 581581 8888v58v58120120 78v78v 120120w78w78 &helli&helliwwpp; ; &helli&hellipp; ; 6Z6Z EndEnd 6Zof of6Z Medium MediumEndEnd of ofMedium Medium 2525 1919 ^Y25^Y25 1919 ^Yx^Yx 5757 x3939x 5757 3939 nn 8989 59n59n 8989y59y59121121 7979yy 121121(79(79 ΔΔ(( ΔΔ $"3$"3 SubstituteSubstitute$"3$"3SubstituteSubstitute 2626 1A1A ^Z26^Z26 1A1A^Zz^Zz 5858 3Az3Az 5858 3A3A {{ 9090 5A{5A{ 9090|5A|5A122122 7A7A|| 122122"7A"7A ←←"" ←← 6$86$8 EscaEsca6$8ppe6$8e EscaEscapepe 2727 1B1B ^[27^[27 1B1B ^[}^[} 5959 3B}3B} 5959 3B3B ~~ 9191 5B5B~ ~ 91915B5B123123 7B7B 123123#7B#7B ↑↑# # ↑↑ B$B$ CursorCursorB$B$ Ri RigCursorghthtCursor ( File(File RiSe SegRiphtgperatorht erator(File (File )Se) Seperatorp28erator28 )1C1C) ^\28^\28 1C1C ^\55^\ 6060 53C3C5 60<<60 3C3C <<ÄÄ 9292 5CÄ5CÄ 9292Å5CÅ5C124124 7C7CÅ Å 124124$7C$7C →→$$ →→ F$F$ CursorCursorF$F$ Left LeftCursor ( CursorGrou(Grou pLeftp SeLeft Se p(Grouperator (eratorGroup )Sep) Seperator29p29erator1D1D) ) ^]29^]29 1D1D ^]ÇÇ^] 6161 Ç3D3DÇ 6161 3D3D ÉÉ 9393 5D5DÉ É 9393Ñ5DÑ5D125125 7D7DÑÑ 125125%7D%7D ↓↓% % ↓↓ X$X$ CursorCursorX$X$ U Upp Cursor( Record(CursorRecord U pSeU Se(ppRecord perator(Recorderator )Se) Seperator30p30erator1E)1E) ^^30^^30 1E1E^^9^^9 6262 93E3E9 &62&g62gt;t;3E3E &g&Öt;Ögt; 9494 5EÖ5EÖ 9494Ü5EÜ5E126126 7EÜ7EÜ 126126&7E&7E ↔↔&& ↔↔ "$"$ CursorCursor"$"$ Down DownCursorCursor ( Unit(Unit Down SeDown Sepperator (eratorUnit (Unit )Se) Seperator31p31erator1F)1F) ^31^_31_ 1F1F ^á_^á_ 6363 á3F3Fá 6363 3F3F àà 9595 5Fà5Fà 9595;6#;6#5F5F127127;6#7F;6#7F 127127â7Fâ7F ƒƒââ ƒƒ

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 43 HTMLHTML Codes CodesHTML HTMLuse use Codes the theCodes #& #& use withuse with the thethe the#& #&decimal decimalwith with the thevalue valuedecimal decimal followed followed value value b ybfollowedy afollowed a semi semi colon.b colon. yb ya asemi semi Exam Exam colon. colon.pple:le: Exam@ @Examp le:pfor le:for @the the@ @ @ s forys ymbol.formbol. the the @ @ s ysmbol.ymbol. HTMLHTML Post PostHTML O OHTMLpperationeration Post Post Ouse usepOerationp theeration the % % usesi siuseggn then and theand % the% thesi gsi hexn ghex nand andvalue. value. the the hex Examhex Exam value. value.pple:le: Exam S SpExampaceacep le:wouldp wouldle: S acebep beace %20 would%20 would be be %20 %20 ToTo obtain obtain codesTo codesTo obtain obtain 0-31, 0-31, codes codesconsole console 0-31, 0-31, Control Control console console Ke Ke Controly yControlis is p pressedressed Ke Key yiswhile while isp ressedpressed simultaneousl simultaneousl while while simultaneousl simultaneouslyy p pressinressingg ythe theyp ressinp Letter ressinLetterg gKethe Kethey y.Letter. Letter Ke Key.y.

www.kellermansoftware.comwww.kellermansoftware.comwww.kellermansoftware.comwww.kellermansoftware.com Free Free quick quick referenceFree reference Free quick quick sheets sheetsreference reference and and sheets.net .net sheets components components and and .net .net components components Implications

0 ... 7 ... 48 49 ... 65 66 ... 97 98 ... 127 \0 ... \a ... 0 1 ... A B ... a b ... DEL ❖ Can (not recommended) use numbers instead of characters char let = ’b’; same as char let = 98;

scanf("%c", &let); b same as scanf("%d", &let); 98

printf("%d", let); 98 printf("%c", let); b

❖ Can add and subtract

printf("%c", ’b’+2); d printf("%d", ’b’+2); 100

printf("%d", ’I’-’B’); 7 printf("%c", ’I’-’B’);

bell.c

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 44 Quiz

❖ What does the following program do? #include int main() { -32 char c; printf("Lower case letter: "); + 66 - 97 scanf("%c", &c); printf("I druther type: %c\n", c + ’A’ - ’a’); return 0; lower case to } UPPER what.c

0 ... 48 49 ... 65 66 ... 97 98 ... 127 \0 ... 0 1 ... A B ... a b ... DEL

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 45 Skipping White Space

❖ %d reads integers, skips white space ❖ %c reads characters, doesn’t skip anything ❖ What if scanf %d followed by %c printf("Number: "); skipWhite.c > a.out scanf("%d", &num); Number: 57 printf("Letter: "); Letter: 57 scanf("%c", &let); printf("%d %c\n", num, let); > ‣ Newline after int is not be read by %d, read as char ❖ To skip white spaces before char, use " %c" scanf(" %c", &let); > a.out or Number: 57 Letter: c scanf("%d %c", &num, &let); 57 c > Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 46 Skipping Specific Input

❖ To skip specific input use * ❖ %*d skips an integer scanf("%*d"); ❖ To skip specific values (at least one): scanf("%*[ \t\n]");

Read three integers, Read integer, skip white spaces print first and last and b’s, and read character

#include #include int main() { int main() { int i, j; int i; char c; printf("Three ints: "); printf("Intchar: "); scanf("%d%*d%d", &i, &j); scanf("%d%*[b \t\n]%c",&i,&c); printf("i=%d j=%d\n",i,j); printf("i=%d c=%c\n",i,c); return 0; return 0; } skip_int.c } skip_b_white.c

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 47 getchar() and putchar()

❖ Simple way of reading and writing single characters #include int main() { char a, b; a=getchar(); b=getchar(); putchar(b); putchar(a); return 0; } getputchar.c ❖ Useful for pausing programs Especially demos...

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 48 Strings

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 49 Strings

❖ Sequence of characters enclosed in quotes

"Hi" "hello world.\n" " ?!# @" "a" " " ""

❖ 'a' and "a" stored differently (more when study arrays) ❖ Printing printf("hello"); same as printf("%s", "hello"); hello

int a=1, b=2; printf("%d+%d%s%d\n", a, b, " equals ", a+b); 1+2 equals 3

printf("\a"); printf("\b "); space, so overwrites ❖ Reading: when study arrays (need to allocate space)

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 50 File Input and Output

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 51 Basic File Input / Output

❖ Read input from a file or write output to a file? ❖ Useful: long in/out, saving, consistency ❖ Simplest method (others later): > m InFile ‣ a.out < file1 input read from file1 > 7 11 a.out < InFile ‣ a.out > file2 output printed to file2 1st: 7 2nd: 11 All input from all output to > m OutFile ❖ file1 file2 OutFile: No such file.. (none from keyboard / to screen) a.out > OutFile 20 #include inOut.c 11 > m OutFile int main() { 1st: 20 int x, y; 2nd: 11 > a.out OutFile scanf("%d %d", &x, &y); > m OutFile printf("1st: %d\n2nd: %d\n", x,y); 1st: 7 2nd: 11 return 0; } >

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 52 Outline ❖ Writing

❖ Reading

❖ Variables and data types ‣ Text ‣ Integers ‣ Reals ‣ Characters ‣ Strings ❖ Rudimentary file input/output

Lecture 5 ECE15: Introduction to Computer Programming Using the C Language 53 gets?

❖ Most

❖ Some

❖ None

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 54 Where are we?

❖ Two weeks old ❖ Already can read & write! ❖ What’s next?

Lecture 2 ECE15: Introduction to Computer Programming Using the C Language 55