Chapter 11 Introduction to Programming in C

Size: px
Start display at page:

Download "Chapter 11 Introduction to Programming in C"

Transcription

1 Programming Levels Chapter 11 Introduction to Programming in C Based on slides McGraw-Hill Additional material 2004/2005/2006 Lewis/Martin High-Level Languages Low-Level Languages Application Languages (Java, C#) Scripting Languages (Perl, Python, VB) System Programming Languages (C, C++) Assembly Language (x86, PowerPC, SPARC, MIPS) Machine Language (x86, PowerPC, SPARC, MIPS) Hardware (Application-Specific Integrated Circuits or ASICs) Interpreted Or Compiled Compilation Assembly 2 The Course Thus Far We did digital logic Bits are bits Ultimately, to understand a simple processor Why High-Level Languages? Easier than assembly. Why? Less primitive constructs Variables Type checking We did assembly language programming Programming the raw metal of the computer Ultimately, to understand C programming Portability Write program once, run it on the LC-3 or Intel s x86 Starting today: we re doing C programming C is still common for systems programming You ll need it for the operating systems class (CSE380) Ultimately, for a deeper understanding of any language (Java) Disadvantages Slower and larger programs (in most cases) Can t manipulate low-level hardware!all operating systems have some assembly in them Verdict: assembly coding is rare today 3 4

2 Our Challenge All of you already know Java We re going to try to cover the basics quickly We ll spend more time on poers & other C-specific nastiness Created two decades apart C: 1970s - AT&T Bell Labs C++: 1980s - AT&T Bell Labs Java: 1990s - Sun Microsystems Java and C/C++ Syntactically similar (Java uses C syntax) C lacks many of Java s features Subtly different semantics 5 C is Similar To Java Without: Objects No classes, objects, methods, or inheritance Exceptions Check all error codes explicitly Standard class library C has only a small standard library Garbage collection C requires explicit memory allocate and free Safety Java has strong type checking, checks array bounds In C, anything goes Portability Source: C code is less portable (but better than assembly) Binary: C compiles to specific machine code 6 More C vs Java differences C has a preprocessor A separate pre-pass over the code Performs replacements Include vs Import Java has import java.io.*; C has: #include <stdio.h> #include is part of the preprocessor Boolean type Java has an explicit boolean type C just uses an as zero or non-zero C s lack of boolean causes all sorts of trouble More differences as we go along 7 History of C and Unix Unix is the most influential operating system First developed in 1969 at AT&T Bell Labs By Ken Thompson and Dennis Ritchie Designed for smaller computers of the day Reject some of the complexity of MIT s Multics They found writing in assembly tedious Dennis Ritchie invented the C language in 1973 Based on BCPL and B, needed to be efficient (24KB of memory) Unix roduced to UC-Berkeley (Cal) in 1974 Bill Joy was an early Unix hacker as a PhD student at Cal Much of the early ernet consisted of Unix systems Mid-80s Good, solid TCP/IP for BSD in 1984 Linux - Free (re)implementation of Unix (libre and gratuit) Announced by Linus Torvalds in 1991 Much more in CSE380! 8

3 Aside: The Unix Command Line Text-based approach to give commands Commonly used before graphical displays Many advantages even today Examples mkdir cse240hw8 make a directory cd cse240hw8 change to the directory ls list contents of directory cp /mnt/eniac/home1/c/cse240/project/hw/hw8/*.! Copy files from one location to current dir (. ) emacs foo.c & run the command emacs with input foo.c gcc -o foo foo.c compile foo.c (create program called foo ) Unix eventually developed graphical UIs (GUIs) X-windows (long before Microsoft Windows) 9 What is C++? C++ is an extension of C Also done at AT&T Bell Labs (1983) Backward compatible (good and bad) That is, all C programs are legal C++ programs C++ adds many features to C Classes, objects, inheritance Templates for polymorphism A large, cumbersome class library (using templates) Exceptions (not actually implemented for a long time) More safety (though still unsafe) Operator and function overloading Kitchen sink Thus, many people uses it (to some extent) However, we re focusing on only C, not C++ 10 Quotes on C/C++ vs Java C is to assembly language as Java is to C Unknown "With all due respect, saying Java is just a C++ subset is rather like saying that `Pride and Prejudice' is just a subset of the Encyclopedia Britanica. While it is true that one is shorter than the other, and that both have the same syntax, there are rather overwhelming differences. Sam Weber, on the ACM SIGSCE mailing list Java is C++ done right. Unknown More quotes on C/C++ "The C programming language combines the power of assembly language with the ease-of-use of assembly language. Unknown "It is my impression that it's possible to write good programs in C++, but nobody does. John Levine, moderator of comp.compilers C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it, it blows your whole leg off. Bjarne Stroustrup, creator of C

4 Program Execution: Compilation vs Interpretation Different ways of executing high-level languages Interpretation Interpreter: program that executes program statements!directly erprets program (portable but slow)!limited optimization Easy to debug, make changes, view ermediate results Languages: BASIC, LISP, Perl, Python, Matlab Compilation Compiler: translates statements o machine language!creates executable program (non-portable, but fast)!performs optimization over multiple statements Harder to debug, change requires recompilation Languages: C, C++, Fortran, Pascal Hybrid Java, has features of both erpreted and compiled languages 13 Compilation vs. Interpretation Consider the following algorithm: Get W from the keyboard. X = W + W Y = X + X Z = Y + Y Pr Z to screen. If erpreting, how many arithmetic operations occur? If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation? 14 Compiling a C Program Entire mechanism is usually called the compiler Preprocessor Macro substitution Conditional compilation Source-level transformations!output is still C Compiler Generates object file!machine instructions Linker Combine object files (including libraries) o executable image Library Object Files Source Code Analysis Target Code Synthesis C Source and Header Files C Preprocessor Compiler Linker Executable Image Symbol Table 15 Compiler Source Code Analysis Front end Parses programs to identify its pieces!variables, expressions, statements, functions, etc. Depends on language (not on target machine) Code Generation Back end Generates machine code from analyzed source May optimize machine code to make it run more efficiently Very dependent on target machine Example Compiler: GCC The Free-Software Foundation s compiler Many front ends: C, C++, Fortran, Java Many back ends: Intel x86, PowerPC, SPARC, MIPS, Itanium 16

5 A Simple C Program #include <stdio.h> #define STOP 0 void main() /* variable declarations */ counter; /* an eger to hold count values */ startpo; /* starting po for countdown */ Preprocessor Directives #include <stdio.h> Before compiling, copy contents of header file (stdio.h) o source code. Header files typically contain descriptions of functions and variables needed by the program.!no restrictions -- could be any C source code /* prompt user for input */ prf("enter a positive number: "); scanf("%d", &startpo); /* read o startpo */ /* count down and pr count */ for (counter=startpo; counter >= STOP; counter--) prf("%d\n", counter); #define STOP 0 Before compiling, replace all instances of the string "STOP" with the string "0" Called a macro Used for values that won't change during execution, but might change if the program is reused. (Must recompile.) Comments main Function Begins with /* and ends with */ Every C program must have a function called main() Can span multiple lines Comments are not recognized within a string!example: "my/*don't pr this*/string" would be pred as: my/*don't pr this*/string Starting po for every program Similar to Java s main method!public static void main(string[] args) Begins with // and ends with end of line Single-line comment Much like ; in LC-3 assembly Introduced in C++, later back-ported to C The code for the function lives within brackets: void main() /* code goes here */ As before, use comments to help reader, not to confuse or to restate the obvious 19 20

6 Variable Declarations Input and Output Variables are used as names for data items Variety of I/O functions in C Standard Library Must include <stdio.h> to use them Each variable has a type, tells the compiler: How the data is to be erpreted How much space it needs, etc. counter; startpo; C has similar primitive types as Java, char, long, float, double More later prf("%d\n", counter); String contains characters to pr and formatting directions for variables This call says to pr the variable counter as a decimal eger, followed by a linefeed (\n) scanf("%d", &startpo); String contains formatting directions for looking at input This call says to read a decimal eger and assign it to the variable startpo (Don't worry about the & yet) More About Output Can pr arbitrary expressions, not just variables prf("%d\n", startpo - counter); Pr multiple expressions with a single statement prf("%d %d\n", counter, startpo - counter); Different formatting options: %d decimal eger %x hexadecimal eger %c ASCII character %f floating-po number Examples This code: prf("%d is a prime number.\n", 43); prf("43 plus 59 in decimal is %d.\n", 43+59); prf("43 plus 59 in hex is %x.\n", 43+59); prf("43 plus 59 as a character is %c.\n", 43+59); produces this output: 43 is a prime number. 43 plus 59 in decimal is plus 59 in hex is plus 59 as a character is f

7 Examples of Input Compiling and Linking Many of the same formatting characters are available for user input Various compilers available cc, gcc includes preprocessor, compiler, and linker scanf("%c", &nextchar); reads a single character and stores it in nextchar scanf("%f", &radius); reads a floating po number and stores it in radius scanf("%d %d", &length, &width); reads two decimal egers (separated by whitespace), stores the first one in length and the second in width Lots and lots of options! level of optimization, debugging preprocessor, linker options ermediate files -- object (.o), assembler (.s), preprocessor (.i), etc. Must use ampersand (&) for variables being modified (Explained in Chapter 16.) Remaining Chapters A more detailed look at many C features Variables and declarations Operators Control Structures Functions Poers and Data Structures I/O Emphasis on how C is converted to assembly language Chapter 12 Variables and Operators Also see C Reference in Appendix D Based on slides McGraw-Hill Additional material 2004/2005/2006 Lewis/Martin 27

8 Basic C Elements Variables Named, typed data items Operators Predefined actions performed on data items Combined with variables to form expressions, statements Statements and Functions Group together operations 29 Data Types C has several basic data types long float double char eger (at least 16 bits, commonly 32 bits) eger (at least 32 bits) floating po (at least 32 bits) floating po (commonly 64 bits) character (at least 8 bits) Exact size can vary, depending on processor is supposed to be "natural" eger size; for LC-3, that's 16 bits bits for most modern processors Signed vs unsigned: Default is 2 s complement signed egers Use unsigned keyword for unsigned numbers 30 Variable Names Any combination of letters, numbers, and underscore (_) Case sensitive "sum" is different than "Sum" Cannot begin with a number Usually, variables beginning with underscore are used only in special library routines Only first 31 characters are definitely used Implementations can consider more characters if they like Examples Legal i wordspersecond same identifier words_per_second _green areally_longname_morethan31chars areally_longname_morethan31characters Illegal 10sdigit ten'sdigit done? double reserved keyword 31 32

9 Literals Integer 123 /* decimal */ x123 /* hexadecimal */ Floating po e23 /* x */ 5E12 /* 5.0 x */ Character 'c' '\n' /* newline */ '\xa' /* ASCII 10 (0xA) */ 33 Scope: Global and Local Where is the variable accessible? Global: accessed anywhere in program Local: only accessible in a particular region Compiler infers scope from where variable is declared Programmer doesn't have to explicitly state Variable is local to the block in which it is declared Block defined by open and closed braces Can access variable declared in any "containing" block Global variable is declared outside all blocks 34 Example #include <stdio.h> itsglobal = 0; main() itslocal = 1; /* local to main */ prf("global %d Local %d\n", itsglobal, itslocal); itslocal = 2; /* local to this block */ itsglobal = 4; /* change global variable */ prf("global %d Local %d\n", itsglobal, itslocal); prf("global %d Local %d\n", itsglobal, itslocal); Output Global 0 Local 1 Global 4 Local 2 Global 4 Local 1 Expression Any combination of variables, constants, operators, and function calls Every expression has a type, derived from the types of its components (according to C typing rules) Examples: counter >= STOP x + sqrt(y) x & z w-- %

10 Statement Expresses a complete unit of work Executed in sequential order Simple statement ends with semicolon z = x * y; /* assign product to z */ y = y + 1; /* after multiplication */ ; /* null statement */ Compound statement formed with braces Syntactically equivalent to a simple statement z = x * y; y = y + 1; Operators Three things to know about each operator (1) Function What does it do? (2) Precedence In which order are operators combined? Example: "a * b + c * d" is the same as "(a * b) + (c * d)" because multiply (*) has a higher precedence than addition (+) (3) Associativity In which order are operators of the same precedence combined? Example: "a - b - c" is the same as "(a - b) - c" because add/sub associate left-to-right Assignment Operator Assignment Operator Changes the value of a variable All expressions evaluate to a value,even ones with the assignment operator x = x + 4; 1. Evaluate right-hand side. 2. Set value of left-hand side variable to result. For assignment, the result is the value assigned Usually (but not always) the value of the right-hand side!type conversion might make assigned value different than computed value Assignment associates right to left. y = x = 3; y gets the value 3, because (x = 3) evaluates to the value 3 y = (x = 3); 39 40

11 Arithmetic Operators Symbol Operation Usage Precedence Assoc * multiply x * y 6 l-to-r / divide x / y 6 l-to-r % modulo x % y 6 l-to-r + addition x + y 7 l-to-r - subtraction x - y 7 l-to-r All associate left to right * / % have higher precedence than + - Example * 4 (2 + 3) * 4 versus Arithmetic Expressions If mixed types, smaller type is "promoted" to larger x if x is, converted to double and result is double Integer division -- fraction is dropped x / 3 if x is and x=5, result is 1 (not ) Modulo -- result is remainder x % 3 if x is and x=5, result is Bitwise Operators Symbol Operation Usage Precedence Assoc ~ bitwise NOT ~x 4 r-to-l << left shift x << y 8 l-to-r >> right shift x >> y 8 l-to-r & bitwise AND x & y 11 l-to-r ^ bitwise XOR x ^ y 12 l-to-r bitwise OR x y 13 l-to-r Operate on variables bit-by-bit Like LC-3 AND and NOT instructions Shift operations are logical (not arithmetic) Operate on values -- neither operand is changed x = y << 1 same as x = y+y Logical Operators Symbol Operation Usage Precedence Assoc! logical NOT!x 4 r-to-l && logical AND x && y 14 l-to-r logical OR x y 15 l-to-r Treats entire variable (or value) as TRUE (non-zero), or FALSE (zero). Result is 1 (TRUE) or 0 (FALSE) x = 15; y = 0; prf( %d, x y); Bit-wise vs Logical 1 & 8 = 0 ( AND = ) 1 && 8 = 1 (True & True = True) 43 44

12 Relational Operators Symbol Operation Usage Precedence Assoc > greater than x > y 9 l-to-r >= greater than or equal x >= y 9 l-to-r < less than x < y 9 l-to-r <= less than or equal x <= y 9 l-to-r == equal x == y 10 l-to-r!= not equal x!= y 10 l-to-r Result is 1 (TRUE) or 0 (FALSE) Assignment vs Equality Don't confuse equality (==) with assignment (=) x = 9; y = 10; if (x == y) prf( not executed\n ); if (x = y) prf( %d %d, x, y); Result: is pred. Why? Compiler will not stop you! (What happens in Java?) Special Operators: ++ and -- Changes value of variable before (or after) its value is used in an expression Symbol Operation Usage Precedence Assoc ++ postincrement x++ 2 r-to-l -- postdecrement x-- 2 r-to-l ++ preincrement ++x 3 r-to-l -- predecrement --x 3 r-to-l Pre: Increment/decrement variable before using its value Post: Increment/decrement variable after using its value Using ++ and -- x = 4; y = x++; Results: x = 5, y = 4 (because x is incremented after assignment) x = 4; y = ++x; Results: x = 5, y = 5 (because x is incremented before assignment) Please, don t combine ++ and =. Really. Just don t! 47 48

13 Special Operators: +=, *=, etc. Arithmetic and bitwise operators can be combined with assignment operator Statement Equivalent assignment x += y; x = x + y; x -= y; x = x - y; x *= y; x = x * y; x /= y; x = x / y; x %= y; x = x % y; All have same x &= y; x = x & y; precedence and associativity as = x = y; x = x y; and associate x ^= y; x = x ^ y; right-to-left. x <<= y; x = x << y; x >>= y; x = x >> y; 49 Special Operator: Conditional Symbol Operation Usage Precedence Assoc?: conditional x?y:z 16 l-to-r x? y : z If x is non-zero, result is y If x is zero, result is z Seems useful, but I don t use it A normal if is almost always more clear You don t need to use every language feature Really, don t use it (you don t have to show how clever you are) 50 Practice with Precedence Assume a=1, b=2, c=3, d=4 x = a * b + c * d / 2; /* x = 8 */ same as: x = (a * b) + ((c * d) / 2); For long or confusing expressions, use parentheses, because reader might not have memorized precedence table Note: Assignment operator has lowest precedence, so all the arithmetic operations on the right-hand side are evaluated first 51 Practice with Operators In preparation for our dis-assembler (HW#8): opcode( ir) /* code to extract bits 15 through 12 of ir */ get_field( bits, hi_bit, lo_bit) /* code to extract hi_bit through lo_bit of bits */ For example, body of opcode function is now just get_field(ir, 15, 12); What about a signed-extended version? hi lo

14 Practice with Operators (Solution 1) Practice with Operators (Solution 2) opcode( ir) ir = ir >> 12; ir = ir & 0xf; return ir; OR opcode( ir) ir = ir & 0xf000; ir = ir >> 12; return ir; get_field( bits, hi_bit, lo_bit) inv_mask = ~0 << (hi_bit+1) mask = ~inv_mask; bits = bits & mask; // Mask off high-order bits bits = bits >> lo_bit; // Shift away low-order bits return bits; OR get_field( bits, hi_bit, lo_bit) bits = ~(~0 << (hi_bit+1)) & bits; // Mask high bits bits = bits >> lo_bit; // Shift away low-order bits return bits; Sign Extended Version get_sext_field( bits, hi_bit, lo_bit) most_significant_bit = bits & (1 << hi_bit); if (most_significant_bit!= 0) bits = (~0 << hi_bit) bits; // One extend else bits = ~(~0 << (hi_bit+1)) & bits; // Zero extend bits = bits >> lo_bit; // Shift away low-order bits return bits; Chapter 13 Control Structures Based on slides McGraw-Hill Additional material 2004/2005/2006 Lewis/Martin 55

15 Control Structures Conditional Making decision about which code to execute, based on evaluated expression if if-else switch If if (condition) action; condition T action F Iteration Executing code multiple times, ending based on evaluated expression while for do-while Condition is a C expression, which evaluates to TRUE (non-zero) or FALSE (zero). Action is a C statement, which may be simple or compound (a block) Example If Statements if (x <= 10) y = x * x + 5; if (x <= 10) y = x * x + 5; z = (2 * y) / 3; if (x <= 10) y = x * x + 5; z = (2 * y) / 3; Style: avoid singleton if statements (I really dislike them) compound statement; both executed if x <= 10 only first statement is conditional; second statement is always executed More If Examples if (0 <= age && age <= 11) kids = kids + 1; if (month == 4 month == 6 month == 9 month == 11) prf( The month has 30 days.\n ); if (x = 2) y = 5; Common C error, assignment (=) Versus equality (==) This is a common programming error (= instead of ==), not caught by compiler because it s syntactically correct

16 Generating Code for If Statement if (x == 2) y = 5; LDR R0, R6, #0 ; load x o R0 ADD R0, R0, #-2 ; subtract 2 BRnp NOT_TRUE ; if non-zero, x is not 2 AND R1, R1, #0 ; store 5 to y ADD R1, R1, #5 STR R1, R6, #1 NOT_TRUE... ; next statement If-else if (condition) action_if; else action_else; T action_if condition F action_else Else allows choice between two mutually exclusive actions without re-testing condition Generating Code for If-Else if (x) y++; z--; else y--; z++; LDR R0, R6, #0 BRz ELSE ; x is not zero LDR R1, R6, #1 ; incr y ADD R1, R1, #1 STR R1, R6, #1 LDR R1, R6, #2 ; decr z ADD R1, R1, #-1 STR R1, R6, #2 BR DONE ; skip else code Matching Else with If Else is always associated with closest unassociated if if (x!= 10) if (y > 3) z = z / 2; else z = z * 2; is NOT the same as... is the same as... if (x!= 10) if (y > 3) z = z / 2; else z = z * 2; ; x is zero ELSE LDR R1, R6, #1 ; decr y if (x!= 10) ADD R1, R1, #-1 if (y > 3) STR R1, R6, #1 z = z / 2; Solution: always use braces LDR R1, R6, #2 ; incr z ADD R1, R1, #1 (avoids the problem entirely) STR R1, R6, #2 else DONE... ; next statement 63 z = z * 2; 64

17 Chaining If s and Else s if (month == 4 month == 6 month == 9 month == 11) prf( Month has 30 days.\n ); else if (month == 1 month == 3 month == 5 month == 7 month == 8 month == 10 month == 12) prf( Month has 31 days.\n ); else if (month == 2) prf( Month has 28 or 29 days.\n ); else prf( Don t know that month.\n ); While while (test) loop_body; Executes loop body as long as test evaluates to TRUE (non-zero) test loop_body Note: Test is evaluated before executing loop body T F Generating Code for While x = 0; while (x < 10) prf( %d, x); x = x + 1; LOOP DONE AND R0, R0, #0 STR R0, R6, #0 ; x = 0 ; test LDR R0, R6, #0 ; load x ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R6, #0 ; load x... <prf>... ADD R0, R0, #1 ; incr x STR R0, R6, #0 BR LOOP ; test again ; next statement Infinite Loops The following loop will never terminate: x = 0; while (x < 10) prf( %d, x); Loop body does not change condition......so test is never false Common programming error that can be difficult to find 67 68

18 For for (init; end-test; re-init) statement Executes loop body as long as test evaluates to TRUE (non-zero). Initialization and re-initialization code included in loop statement. Note: Test is evaluated before executing loop body F init test T loop_body re-init 69 Generating Code for For for (i = 0; i < 10; i++) prf( %d, i); LOOP This is the same as the while example! DONE ; init AND R0, R0, #0 STR R0, R6, #0 ; i = 0 ; test LDR R0, R6, #0 ; load i ADD R0, R0, #-10 BRzp DONE ; loop body LDR R0, R6, #0 ; load i... <prf>... ; re-init ADD R0, R0, #1 ; incr i STR R0, R6, #0 BR LOOP ; test again ; next statement 70 Example For Loops /* -- what is the output of this loop? -- */ for (i = 0; i <= 10; i++) prf("%d ", i); /* -- what does this one output? -- */ letter = 'a'; for (c = 0; c < 26; c++) prf("%c ", letter+c); /* -- what does this loop do? -- */ numberofones = 0; for (bitnum = 0; bitnum < 16; bitnum++) if (inputvalue & (1 << bitnum)) numberofones++; Nested Loops Loop body can (of course) be another loop /* pr a multiplication table */ for (mp1 = 0; mp1 < 10; mp1++) for (mp2 = 0; mp2 < 10; mp2++) prf( %d\t, mp1*mp2); prf( \n ); 71 72

19 Another Nested Loop Here, test for the inner loop depends on counter variable of outer loop for (outer = 1; outer <= input; outer++) for (inner = 0; inner < outer; inner++) sum += inner; For vs. While In general: For loop is preferred for counter-based loops Explicit counter variable Easy to see how counter is modified each loop While loop is preferred for sentinel-based loops Test checks for sentinel value. Either kind of loop can be expressed as other, so really a matter of style and readability Do-While Break and Continue do loop_body; while (test); T loop_body test break; used only in switch statement or iteration statement passes control out of the nearest (loop or switch) statement containing it to the statement immediately following usually used to exit a loop before terminating condition occurs (or to exit switch statement when case is done) F continue; Executes loop body as long as test evaluates to TRUE (non-zero). Note: Test is evaluated after executing loop body used only in iteration statement terminates the execution of the loop body for this iteration loop expression is evaluated to see whether another iteration should be performed if for loop, also executes the re-initializer 75 76

20 Example What does the following loop do? for (i = 0; i <= 20; i++) if (i%2 == 0) continue; prf("%d ", i); What would be an easier way to write this? Switch switch (expression) case const1: action1; break; case const2: action2; break; default: action3; evaluate expression = const1? F = const2? F action3 T T action1 action2 What happens if break instead of continue? 77 Alternative to long if-else chain. If break is not used, then case "falls through" to the next. 78 Switch Example /* same as month example for if-else */ switch (month) case 4: case 6: case 9: case 11: prf( Month has 30 days.\n ); break; case 1: case 3: /* some cases omitted for brevity...*/ prf( Month has 31 days.\n ); break; case 2: prf( Month has 28 or 29 days.\n ); break; default: prf( Don t know that month.\n ); More About Switch Case expressions must be constant case i: /* illegal if i is a variable */ If no break, then next case is also executed switch (a) case 1: prf( A ); case 2: prf( B ); default: prf( C ); If a is 1, prs ABC. If a is 2, prs BC. Otherwise, prs C

21 Enumerations Keyword enum declares a new type enum colors RED, GREEN, BLUE, GREEN, YELLOW, MAUVE ; RED is now 0, GREEN is 1, etc. Gives meaning to constants, groups constants enum colors house_color; house_color = get_color(); switch (house_color) case RED: /* code here */ break; /* more here */ Enums are just s, but can provide more type checking Warning on assignment (example: house_color = 85;) Warning on partial switch statement C++ adds even more checking support 81 Example: Searching for Substring Have user type in a line of text (ending with linefeed) and pr the number of occurrences of "the" Reading characters one at a time Use the getchar() function -- returns a single character Don't need to store input string; look for substring as characters are being typed Similar to state machine: based on characters seen, move toward success state or move back to start state Switch statement is a good match to state machine 82 Substring: State machine to flow chart other 't' 't' no match 't' matched 't' 'h' matched 'th' 'e' other other increment count read char match = 0 F match = 1 F match = 2 F T T T if 't', match=1 if 'h', match=2 if 't', match=1 else match=0 if 'e', count++ and match = 0 if 't', match=1 else match=0 83 Substring: Code (Part 1) #include <stdio.h> enum state NO_MATCH, ONE_MATCH, TWO_MATCHES ; main() char key; /* input character from user */ match = NO_MATCH ; /* state of matching */ count = 0; /* number of substring matches */ /* Read character until newline is typed */ key = getchar(); while (key!= '\n') /* Action depends on number of matches so far */ switch (match) See next two slides for contents of switch statement key = getchar(); prf("number of matches = %d\n", count); 84

22 Substring: Code (Part 2) Substring: Code (Part 3) case NO_MATCH: /* starting - no matches yet */ if (key == 't') match = ONE_MATCH; else match = NO_MATCH; break; case ONE_MATCH: /* 't' has been matched */ if (key == 'h') match = TWO_MATCHES; else if (key == 't') match = ONE_MATCH; else match = NO_MATCH; break; case TWO_MATCHES: /* 'th' has been matched */ if (key == 'e') count++; /* increment count */ match = NO_MATCH; /* go to starting po */ else if (key == 't') match = ONE_MATCH; else match = NO_MATCH; break; C and the Right Shift Operator (>>) Does right shift sign extend or not? Answer: Yes and No Unsigned values: zero extend unsigned x = ~0; Then, (x >> 10) will have 10 leading zeros Signed values: Right shifting a signed quantity will fill with sign bits ( arithmetic shift ) on some machines and with 0-bits ( logical shift ) on others. - Kernighan and Ritchie In practice, it does sign extend! x = ~0; /* signed */!Then, (x >> 10) will still be all 1s Chapter 14 Functions Based on slides McGraw-Hill Additional material 2004/2005/2006 Lewis/Martin 87

23 Function Smaller, simpler, subcomponent of program Provides abstraction Hide low-level details Give high-level structure to program, easier to understand overall program flow Enables separable, independent development C functions Zero or multiple arguments (or parameters) passed in Single result returned (optional) Return value is always a particular type In other languages, called procedures, subroutines,... Example of High-Level Structure void main() setup_board(); /* place pieces on board */ determine_sides(); /* choose black/white */ /* Play game */ while (no_outcome_yet()) whites_turn(); blacks_turn(); Structure of program is evident, even without knowing implementation Functions in C Definition type of return value factorial( n) i; result = 1; for (i = 1; i <= n; i++) result = result * i; return result; Function call -- used in expression a = x + factorial(f + g); name of function types of all arguments 1. evaluate arguments 2. execute function 3. use return value in expression exits function with specified return value 91 Implementing Functions and Variables in LC-3 We ve talked about Variables!Local!Global Functions!Parameter passing!return values What does the assembly code look like for these idioms? Important notes Different compilers for different ISAs do things differently As long as a compiler is consistent We re straying from the book s version to simplify things!leaving out the R5 frame poer 92

24 Allocating Space for Variables Local Variable Storage Global data section All global variables stored here (actually all static variables) R4 pos to beginning Run-time stack Used for local variables R6 pos to top of stack New frame for each block (goes away when block exited) Offset = distance from beginning of storage area Global: LDR R1, R4, #4 0x0000 instructions global data run-time stack PC R4 R6 Local variables stored in activation record (stack frame) Symbol table offset gives the distance from the base of the frame A new frame is pushed on the run-time stack each time block is entered R6 is the stack poer holds address of current top of run-time stack Because stack grows downward, stack poer is the smallest address of the frame, and variable offsets are >= 0. R6 amount hours minute seconds Local: LDR R2, R6, #3 0xFFFF Symbol Table Compiler tracks each symbol (identifiers) and its location In assembler, all identifiers were labels In compiler, identifiers are variables Compiler keeps more information Name (identifier) Type Location in memory Scope Name Type Offset Scope amount hours minutes seconds double main main main main Symbol Table Example main() seconds; minutes; hours; double amount; R6 R6 Name Type Offset Scope amount hours minutes seconds amount hours minute seconds double main main main main 95 96

25 Example: Compiling to LC-3 Example: Code Generation #include <stdio.h> inglobal; main() inlocal; outlocala; outlocalb; Name inglobal inlocal outlocala Type Offset global main main Scope ; main ; inlocal = 5 AND R0, R0, #0 ADD R0, R0, #5 ; inlocal = 5 STR R0, R6, #2 ; (offset = 2) /* initialize */ inlocal = 5; inglobal = 3; outlocalb /* perform calculations */ outlocala = inlocal & ~inglobal; outlocalb = (inlocal + inglobal) + outlocalb; main /* pr results */ prf("the results are: outlocala = %d, outlocalb = %d\n", outlocala, outlocalb); 0 ; inglobal = 3 AND R0, R0, #0 ADD R0, R0, #3 ; inglobal = 3 STR R0, R4, #0 ; (offset = 0) Example (continued) ; first statement: ; outlocala = inlocal & ~inglobal; Example (continued) R0 ;outlocalb = (inlocal + inglobal) + outlocala; LDR R0, R6, #2 ; get inlocal(offset = 2) LDR R1, R4, #0 ; get inglobal NOT R1, R1 ; ~inglobal AND R2, R0, R1 ; inlocal & ~inglobal STR R2, R6, #1 ; store in outlocala ; (offset = 1) LDR R0, R6, #2 ; inlocal LDR R1, R4, #0 ; inglobal ADD R0, R0, R1 ; R0 is sum LDR R1, R6, #1 ; outlocala ADD R2, R0, R1 ; R2 is sum STR R2, R6, #0 ; outlocalb (offset = 0)

26 Implementing Functions Activation record Information about each function, including arguments and local variables Also stored on run-time stack Calling function copy args o stack or regs call function get result Called function allocate activation record save registers execute code put result in AR or reg pop activation record return Run-Time Stack for Functions Memory Memory Memory R6 func R6 main main main Before call During call After call R Activation Record func( a, b) w, x, y;... return y; Name Type Offset Scope R6 bookkeeping y x w save R0 return addr. (R7) return value a b locals args Activation Record Bookkeeping Return value Space for value returned by function Allocated even if function does not return a value Return address Save poer to next instruction in calling function Convenient location to store R7!in case another function (JSR) is called b a ret. value w x y func func func func func func Save registers Save all other registers used (but not R6, and often not R4)

27 Function Call Example main() x, y, val; x = 10; y = 11; val = max(x + 10, y); return val; max( a, b) result; result = a; if (b > a) result = b; return result; main s view R result save R0 save R1 save R7 max return value a b val y x main return value R6 max s view Main Function (1 of 2) MAIN ADD R6, R6, #-4 ; allocate frame AND R0, R0, #0 ; x = 10 ADD R0, R0, #10 STR R0, R6, #2 AND R0, R0, #0 ; y = 11 ADD R0, R0, #11 STR R0, R6, #1 LDR R0, R6, #1 STR R0, R6, #-1 ; load y o R0 ; 2nd argument LDR R1, R6, #2 ; load x o R1 ADD R1, R1, #10 ; R1 = x + 10 STR R1, R6, #-2 ; 1st argument JSR MAX ; more here ; call max function Max Function MAX ADD R6, R6, #-7 ; allocate frame STR R7, R6, #3 ; save R7 (link register) STR R1, R6, #2 ; save R1 STR R0, R6, #1 ; save R0 LDR R0, R6, #5 STR R0, R6, #0 ; load "a" ; store "a" o "result" LDR R1, R6, #6 ; load "b" NOT R1, R1 ; calculate -b ADD R1, R1, 1 LDR R0, R6, #5 ; load "a" ADD R0, R1, R0 ; compare BRp AFTER LDR R0, R6, #6 STR R0, R6, #0 ; load "b" ; store "b" o "result" AFTER LDR R0, R6, #0 ; load "result" STR R0, R6, #4 ; store "result" o return value LDR R0, R6, #1 LDR R1, R6, #2 LDR R7, R6, #3 ADD R6, R6, #7 RET ; restore R0 ; restore R1 ; restore R7 (link register) ; pop stack 107 Main Function (2 of 2) ; previous code here JSR MAX LDR R0, R6, #-3 STR R0, R6, #0 LDR R0, R6, #0 STR R0, R6, #3 ADD R6, R6, #4 RET ; call max function ; read return value of max ; put value o local "val" ; load "val" ; put "val" o main s ; return value ; pop stack 108

28 Summary of LC-3 Function Call Implementation 1. Caller places arguments on stack (last to first) 2. Caller invokes subroutine (JSR) 3. Callee allocates frame 4. Callee saves R7 and other registers 5. Callee executes function code 6. Callee stores result o return value slot 7. Callee restores registers 8. Callee deallocates frame (local vars, other registers) 9. Callee returns (RET or JMP R7) 10. Caller loads return value 11. Caller resumes computation 109 Callee versus Caller Saved Registers Callee saved registers In our examples, the callee saved and restored registers Saves/restores any registers it modifies What if a you wants R7 to be preserved across a call? Before call: caller saves it on the stack After call: caller restores it from the stack Caller saved registers R7 is an example of a caller saved register Value assumed destroyed across calls Only needs to save R7 when it s in use Which is better? Callee or Caller saved registers? Neither: many ISA calling conventions specify some of each 110 Compilers are Smart(er) In our examples, variables always stored in memory Read from stack, written to stack Compiler will perform code optimizations Keeps many variables in registers Avoids many save/restores of registers Why? Passing parameter values in registers First few parameters in registers Return value in register Like in your homework projects Again, why? 111

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T) Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Chapter 7 Assembly Language

Chapter 7 Assembly Language Chapter 7 Assembly Language Human-Readable Machine Language Computers like ones and zeros 0001110010000110 Humans like symbols ADD R6,R2,R6 increment index reg. Assembler is a program that turns symbols

More information

Instruction Set Architecture (ISA)

Instruction Set Architecture (ISA) Instruction Set Architecture (ISA) * Instruction set architecture of a machine fills the semantic gap between the user and the machine. * ISA serves as the starting point for the design of a new machine

More information

Programming Languages CIS 443

Programming Languages CIS 443 Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser) High-Level Programming Languages Nell Dale & John Lewis (adaptation by Michael Goldwasser) Low-Level Languages What are disadvantages of low-level languages? (e.g., machine code or assembly code) Programming

More information

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

An Introduction to Assembly Programming with the ARM 32-bit Processor Family An Introduction to Assembly Programming with the ARM 32-bit Processor Family G. Agosta Politecnico di Milano December 3, 2011 Contents 1 Introduction 1 1.1 Prerequisites............................. 2

More information

How To Write Portable Programs In C

How To Write Portable Programs In C Writing Portable Programs COS 217 1 Goals of Today s Class Writing portable programs in C Sources of heterogeneity Data types, evaluation order, byte order, char set, Reading period and final exam Important

More information

Chapter 7D The Java Virtual Machine

Chapter 7D The Java Virtual Machine This sub chapter discusses another architecture, that of the JVM (Java Virtual Machine). In general, a VM (Virtual Machine) is a hypothetical machine (implemented in either hardware or software) that directly

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

Figure 1: Graphical example of a mergesort 1.

Figure 1: Graphical example of a mergesort 1. CSE 30321 Computer Architecture I Fall 2011 Lab 02: Procedure Calls in MIPS Assembly Programming and Performance Total Points: 100 points due to its complexity, this lab will weight more heavily in your

More information

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1 The Java Series Java Essentials I What is Java? Basic Language Constructs Slide 1 What is Java? A general purpose Object Oriented programming language. Created by Sun Microsystems. It s a general purpose

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

I PUC - Computer Science. Practical s Syllabus. Contents

I PUC - Computer Science. Practical s Syllabus. Contents I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations

More information

C# and Other Languages

C# and Other Languages C# and Other Languages Rob Miles Department of Computer Science Why do we have lots of Programming Languages? Different developer audiences Different application areas/target platforms Graphics, AI, List

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6) Semantic Analysis Scoping (Readings 7.1,7.4,7.6) Static Dynamic Parameter passing methods (7.5) Building symbol tables (7.6) How to use them to find multiply-declared and undeclared variables Type checking

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

LC-3 Assembly Language

LC-3 Assembly Language LC-3 Assembly Language Programming and tips Textbook Chapter 7 CMPE12 Summer 2008 Assembly and Assembler Machine language - binary Assembly language - symbolic 0001110010000110 An assembler is a program

More information

X86-64 Architecture Guide

X86-64 Architecture Guide X86-64 Architecture Guide For the code-generation project, we shall expose you to a simplified version of the x86-64 platform. Example Consider the following Decaf program: class Program { int foo(int

More information

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands C Programming for Embedded Microcontrollers Warwick A. Smith Elektor International Media BV Postbus 11 6114ZG Susteren The Netherlands 3 the Table of Contents Introduction 11 Target Audience 11 What is

More information

Lecture 22: C Programming 4 Embedded Systems

Lecture 22: C Programming 4 Embedded Systems Lecture 22: C Programming 4 Embedded Systems Today s Goals Basic C programming process Variables and constants in C Pointers to access addresses Using a High Level Language High-level languages More human

More information

C Compiler Targeting the Java Virtual Machine

C Compiler Targeting the Java Virtual Machine C Compiler Targeting the Java Virtual Machine Jack Pien Senior Honors Thesis (Advisor: Javed A. Aslam) Dartmouth College Computer Science Technical Report PCS-TR98-334 May 30, 1998 Abstract One of the

More information

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer About The Tutorial C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.

More information

Introduction to Python

Introduction to Python Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment

More information

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Chapter 1. Dr. Chris Irwin Davis Email: cid021000@utdallas.edu Phone: (972) 883-3574 Office: ECSS 4.705. CS-4337 Organization of Programming Languages

Chapter 1. Dr. Chris Irwin Davis Email: cid021000@utdallas.edu Phone: (972) 883-3574 Office: ECSS 4.705. CS-4337 Organization of Programming Languages Chapter 1 CS-4337 Organization of Programming Languages Dr. Chris Irwin Davis Email: cid021000@utdallas.edu Phone: (972) 883-3574 Office: ECSS 4.705 Chapter 1 Topics Reasons for Studying Concepts of Programming

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

1 The Java Virtual Machine

1 The Java Virtual Machine 1 The Java Virtual Machine About the Spec Format This document describes the Java virtual machine and the instruction set. In this introduction, each component of the machine is briefly described. This

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program CS 2112 Lecture 27 Interpreters, compilers, and the Java Virtual Machine 1 May 2012 Lecturer: Andrew Myers 1 Interpreters vs. compilers There are two strategies for obtaining runnable code from a program

More information

1/20/2016 INTRODUCTION

1/20/2016 INTRODUCTION INTRODUCTION 1 Programming languages have common concepts that are seen in all languages This course will discuss and illustrate these common concepts: Syntax Names Types Semantics Memory Management We

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science updated 03/08/2012 Unit 1: JKarel 8 weeks http://www.fcps.edu/is/pos/documents/hs/compsci.htm

More information

MACHINE INSTRUCTIONS AND PROGRAMS

MACHINE INSTRUCTIONS AND PROGRAMS CHAPTER 2 MACHINE INSTRUCTIONS AND PROGRAMS CHAPTER OBJECTIVES In this chapter you will learn about: Machine instructions and program execution, including branching and subroutine call and return operations

More information

#820 Computer Programming 1A

#820 Computer Programming 1A Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement Semester 1

More information

Numbering Systems. InThisAppendix...

Numbering Systems. InThisAppendix... G InThisAppendix... Introduction Binary Numbering System Hexadecimal Numbering System Octal Numbering System Binary Coded Decimal (BCD) Numbering System Real (Floating Point) Numbering System BCD/Binary/Decimal/Hex/Octal

More information

Computer Programming I

Computer Programming I Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement (e.g. Exploring

More information

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go Debugging ESE112 Java Programming: API, Psuedo-Code, Scope It is highly unlikely that you will write code that will work on the first go Bugs or errors Syntax Fixable if you learn to read compiler error

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

Base Conversion written by Cathy Saxton

Base Conversion written by Cathy Saxton Base Conversion written by Cathy Saxton 1. Base 10 In base 10, the digits, from right to left, specify the 1 s, 10 s, 100 s, 1000 s, etc. These are powers of 10 (10 x ): 10 0 = 1, 10 1 = 10, 10 2 = 100,

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 20: Stack Frames 7 March 08 CS 412/413 Spring 2008 Introduction to Compilers 1 Where We Are Source code if (b == 0) a = b; Low-level IR code

More information

CSC230 Getting Starting in C. Tyler Bletsch

CSC230 Getting Starting in C. Tyler Bletsch CSC230 Getting Starting in C Tyler Bletsch What is C? The language of UNIX Procedural language (no classes) Low-level access to memory Easy to map to machine language Not much run-time stuff needed Surprisingly

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

M A S S A C H U S E T T S I N S T I T U T E O F T E C H N O L O G Y DEPARTMENT OF ELECTRICAL ENGINEERING AND COMPUTER SCIENCE

M A S S A C H U S E T T S I N S T I T U T E O F T E C H N O L O G Y DEPARTMENT OF ELECTRICAL ENGINEERING AND COMPUTER SCIENCE M A S S A C H U S E T T S I N S T I T U T E O F T E C H N O L O G Y DEPARTMENT OF ELECTRICAL ENGINEERING AND COMPUTER SCIENCE 1. Introduction 6.004 Computation Structures β Documentation This handout is

More information

6.S096 Lecture 1 Introduction to C

6.S096 Lecture 1 Introduction to C 6.S096 Lecture 1 Introduction to C Welcome to the Memory Jungle Andre Kessler Andre Kessler 6.S096 Lecture 1 Introduction to C 1 / 30 Outline 1 Motivation 2 Class Logistics 3 Memory Model 4 Compiling 5

More information

Java Basics: Data Types, Variables, and Loops

Java Basics: Data Types, Variables, and Loops Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

More information

A single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc

A single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc Other architectures Example. Accumulator-based machines A single register, called the accumulator, stores the operand before the operation, and stores the result after the operation. Load x # into acc

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

a storage location directly on the CPU, used for temporary storage of small amounts of data during processing.

a storage location directly on the CPU, used for temporary storage of small amounts of data during processing. CS143 Handout 18 Summer 2008 30 July, 2008 Processor Architectures Handout written by Maggie Johnson and revised by Julie Zelenski. Architecture Vocabulary Let s review a few relevant hardware definitions:

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER

ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER Pierre A. von Kaenel Mathematics and Computer Science Department Skidmore College Saratoga Springs, NY 12866 (518) 580-5292 pvonk@skidmore.edu ABSTRACT This paper

More information

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages ICOM 4036 Programming Languages Preliminaries Dr. Amirhossein Chinaei Dept. of Electrical & Computer Engineering UPRM Spring 2010 Language Evaluation Criteria Readability: the ease with which programs

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8

Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8 Comp 255Q - 1M: Computer Organization Lab #3 - Machine Language Programs for the PDP-8 January 22, 2013 Name: Grade /10 Introduction: In this lab you will write, test, and execute a number of simple PDP-8

More information

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms. COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms 1 Activation Records activation declaration location Recall that an activation

More information

Keil C51 Cross Compiler

Keil C51 Cross Compiler Keil C51 Cross Compiler ANSI C Compiler Generates fast compact code for the 8051 and it s derivatives Advantages of C over Assembler Do not need to know the microcontroller instruction set Register allocation

More information

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio. Organization of Programming Languages CS320/520N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Names, Bindings, and Scopes A name is a symbolic identifier used

More information

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, 2008. 1 Introduction 1. 2 Invoking Shell Scripts 2

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, 2008. 1 Introduction 1. 2 Invoking Shell Scripts 2 Unix Shell Scripts Norman Matloff July 30, 2008 Contents 1 Introduction 1 2 Invoking Shell Scripts 2 2.1 Direct Interpretation....................................... 2 2.2 Indirect Interpretation......................................

More information

Objective-C Tutorial

Objective-C Tutorial Objective-C Tutorial OBJECTIVE-C TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Objective-c tutorial Objective-C is a general-purpose, object-oriented programming

More information

An Assembly Language Programming Style Guide. by Ken Lambert. Naming Conventions. Use of Whitespace

An Assembly Language Programming Style Guide. by Ken Lambert. Naming Conventions. Use of Whitespace An Assembly Language Programming Style Guide by Ken Lambert The purpose of these style guidelines is to help the assembly language programmer to write readable, well- documented, maintainable programs.

More information

Interpreters and virtual machines. Interpreters. Interpreters. Why interpreters? Tree-based interpreters. Text-based interpreters

Interpreters and virtual machines. Interpreters. Interpreters. Why interpreters? Tree-based interpreters. Text-based interpreters Interpreters and virtual machines Michel Schinz 2007 03 23 Interpreters Interpreters Why interpreters? An interpreter is a program that executes another program, represented as some kind of data-structure.

More information

Computer Programming I & II*

Computer Programming I & II* Computer Programming I & II* Career Cluster Information Technology Course Code 10152 Prerequisite(s) Computer Applications, Introduction to Information Technology Careers (recommended), Computer Hardware

More information

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6)

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6) ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6) 1 COMPUTER LANGUAGES In order for a computer to be able to execute a program, the program must first be present

More information

Computer Programming Tutorial

Computer Programming Tutorial Computer Programming Tutorial COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Computer Prgramming Tutorial Computer programming is the act of writing computer

More information

Chapter 3. Input and output. 3.1 The System class

Chapter 3. Input and output. 3.1 The System class Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use

More information

Chapter 3 Operators and Control Flow

Chapter 3 Operators and Control Flow Chapter 3 Operators and Control Flow I n this chapter, you will learn about operators, control flow statements, and the C# preprocessor. Operators provide syntax for performing different calculations or

More information

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code 1 Introduction The purpose of this assignment is to write an interpreter for a small subset of the Lisp programming language. The interpreter should be able to perform simple arithmetic and comparisons

More information

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 04 Digital Logic II May, I before starting the today s lecture

More information

VHDL Test Bench Tutorial

VHDL Test Bench Tutorial University of Pennsylvania Department of Electrical and Systems Engineering ESE171 - Digital Design Laboratory VHDL Test Bench Tutorial Purpose The goal of this tutorial is to demonstrate how to automate

More information

Statements and Control Flow

Statements and Control Flow Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

Lab Experience 17. Programming Language Translation

Lab Experience 17. Programming Language Translation Lab Experience 17 Programming Language Translation Objectives Gain insight into the translation process for converting one virtual machine to another See the process by which an assembler translates assembly

More information

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl First CGI Script and Perl Perl in a nutshell Prof. Rasley shebang line tells the operating system where the Perl interpreter is located necessary on UNIX comment line ignored by the Perl interpreter End

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

C H A P T E R Regular Expressions regular expression

C H A P T E R Regular Expressions regular expression 7 CHAPTER Regular Expressions Most programmers and other power-users of computer systems have used tools that match text patterns. You may have used a Web search engine with a pattern like travel cancun

More information

DNA Data and Program Representation. Alexandre David 1.2.05 adavid@cs.aau.dk

DNA Data and Program Representation. Alexandre David 1.2.05 adavid@cs.aau.dk DNA Data and Program Representation Alexandre David 1.2.05 adavid@cs.aau.dk Introduction Very important to understand how data is represented. operations limits precision Digital logic built on 2-valued

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information