midterm review 2014

28
CSE240 – Intro to Programming Languages Midterm Review

Upload: atkawa7

Post on 17-May-2017

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Midterm Review 2014

CSE240 – Intro to

Programming LanguagesMidterm Review

Page 2: Midterm Review 2014

Overview of Midterm

Chapter 01 (Common Aspects of Programming Languages)

Chapter 02 (Imperative Paradigm)

Tips and Hints:

Review Slides, HW, Quizzes

Do the extra exercises on website: https://sites.google.com/a/asu.edu/cse240/

Some questions will try to trick you on the exam

This presentation is only an overview, study a lot more after this

Page 3: Midterm Review 2014

The Structure of Programs

Lexical: the building blocks of the programming language

Variable name, symbol, {…};

Error example: starting a variable name with a number

Ex. int 0num; char 1letter;

Syntactic: describes how to put lexical units together

if…then…else… switch, for… Do structures

Error example:

Missing a semicolon(;) at the end of a statement

Missed parenthesis or bracket to match another one

Page 4: Midterm Review 2014

The Structure of Programs

Contextual: defines semantics before dynamic instruction

Variable type and initialization, type checking

Error example: expression lacks type consistency

string str = “abc”;

int I = 1 + str; (syntactically correct, but contextually incorrect)

Error example: use of a variable that was never declared

Error example: calling an object’s method that does not exist

Compiler can check for Lexical, Syntactic and Contextual errors!

Page 5: Midterm Review 2014

The Structure of Programs

Semantic: describes the meaning of the program

Semantic errors are also called “logic errors”

The code below compiles

if(head = NULL) {

head = newEntry;

}

Vs.

if(head == NULL) {

head = newEntry;

}

Semantic errors cannot be found by the compiler!

Page 6: Midterm Review 2014

Syntactic Analysis: Backus-Naur Form

Terminal vs Non-terminal symbols:

Terminal: can be seen in your code / actual program

Ex. % ; “ * 0, 1, …9

Non-Terminal: symbols representing the grammar of a language

Ex. <digit>, <object>, <statement>

Page 7: Midterm Review 2014

BNF Example

<Phone Number> ::= (<Area Code>) <Prefix> - <Suffix> |

<Area Code> - <Prefix> - <Suffix> |

911 | 511

<Area Code> ::= 602 | 480 | 623

<digits> ::= 0 | 1 | 2 |… | 9

<start digits> ::= 1 | 2 | … | 9

<Prefix> ::= <start digits><digits><digits>

<Suffix> ::= <start digits><digits><digits><digits>

Based on this BNF,

Valid numbers: 602-123-4567, (480)327-9999, 911

Invalid numbers: 923-123-4567, (480)027-0999, (480) – 123 - 4567

Page 8: Midterm Review 2014

Syntactic Analysis: Syntax Graphs Defines syntax, NOT logic (COMMON MISTAKE)

This is why the syntax graph for a while/for loop does not need an arrow going

back

if (condition) statements ;

else statements ;

if (a < 0) return -a;

if (a < 0) return -a; else return a;

Page 9: Midterm Review 2014

Syntactic Analysis: Syntax Graph

switch (expr) { case value: statements ;

default: statements;

}

switch (ch) {case '+': x = a + b; break;case '-': x = a - b; break;case '*': x = a * b; break;case '': x = a / b; x = round(x); break; default: printf("invalid operator"); break;

}

For-loop example (in class exercise solution) available in the course website

https://sites.google.com/a/asu.edu/cse240/

Page 10: Midterm Review 2014

Macros vs Functions

Macros

Done in pre-processing phase of compilation

Eliminate function call overhead, or cost (better performance)

Why?

Can introduce side-effects if not done correctly

A macro simply replaces the text with what is defined. For example:

#define MAC(a) a + 3 * 5

int j = MAC(2)

will become

int j = 2 + 3 * 5

Page 11: Midterm Review 2014

Macros Example

For x = 3 and y = 4, get the output for the following

randomMacro(x++, --y);

randomFunction(x++, --y);

WRITE IT OUT. It helps during the test to avoid mistakes

Answer: Function should return 3 and the macro should return 4

What happens to the x and y variables?

#define randomMacro(x, y) ((x <= y) ? x : y)

int randomFunction(int x, int y){

return ((x <= y) ? x : y);

}

Page 12: Midterm Review 2014

Type Equivalence

Type checking: ensuring the operands of an operator are of legal type

Coercion (implicit):

float num = 1.23 + 4;

Implicity converts the integer into a float type

Casting (explicit):

int num = (int) num + 5;

Strongly typed vs Weakly typed

Page 13: Midterm Review 2014

Arrays and Strings

Strings are arrays of characters in C

Analysis:

char name[] = “Bob”;

4 elements: ‘B’ ‘o’ ‘b’ ‘\0’

The NULL character

char name[3] = {‘B’, ‘o’, ‘b’};

The null character does not exist

Printf will have side effects when trying to print a string (try it!)

Pointers:

char *name = “Bob”

Still 4 elements (including NULL character)

Page 14: Midterm Review 2014

Pointers

& - Referencing – returns the address value of the variable it precedes

Called the R-value

* - Dereferencing – returns the value / name of the address it precedes

Called the L-value

Analogy: Mailbox/Addresses

Every mailbox has an address that can lead people to it (R-Value)

Mailboxes have envelopes/mail that can be placed inside of it(L-Value)

Page 15: Midterm Review 2014

Pointers

#include <stdio.h>

int main() {

int i1 = 0, i2 = 10, *p1, *p2, **p3;

p1 = &i1;

p2 = &i2;

p3 = &p2;

**p3 = 20;

}

• &i1 = 5; &i1 is not a modifiable value

• 7000 = 5; again, 7000 is not modifiable

• *(7000) = 5; invalid: 7000 is not a pointer type

• *(&i1 ) = 5; Works, but redundant / bad code

• What is &p1?

• p3 = &p1;

Page 16: Midterm Review 2014

Pointers

#include <stdio.h>

int main() {

int ma[2][4], *p;

p = ma;

*p = 5; // What is the value of ma?

*(p + 2) = 10; // What is the value of ma?

*(p + 5) = 20; // What is the value of ma?

return 0; ma =

} 5 10

20

Page 17: Midterm Review 2014

Constants

Constants in C

Macro: Can substitute values for constant definitions at pre-processing

Faster execution, save a memory access

Const qualifier: may be a ‘variable’ that the program cannot modify

Slower, have to access memory

Modifying constants

Can be modified through pointers

Use the ampersand (&) function to find its address

Not good programming practice!

Page 18: Midterm Review 2014

Structs, Unions

Structure

Collection of variables under a single name

Memory allocation as large as the variables inside combined/added together

Don’t forget about structure padding!

Union

Region of shared memory that can contain different types of values

Takes the largest required memory allocation from the largest variable

Page 19: Midterm Review 2014

Linked List

#include <stdio.h>

#include <string.h>

#include <stdlib.h> // used by malloc

struct contact { // define a node holding a person's details

char name[30];

int phone;

char email[30];

struct contact *next; // pointer to contact structure

} *head = NULL; //head is a global pointer to the first entry

void branching(char c); // function forward declaration

int insertion();

struct contact *search();

void delete();

Page 20: Midterm Review 2014

Linked List

int insertion() { // insert a new entry

struct contact *p;

p = (struct contact *) malloc(sizeof(struct contact));

if (p == 0) {

printf("out of memory\n"); return -1;

}

printf("Enter name, phone, email: \n");

scanf("%s", p->name);

scanf("%d", &p->phone);

scanf("%s", p->email);

p->next = head; // Where is the new node inserted?

head = p;

return 0;

}

Page 21: Midterm Review 2014

Linked List

How to modify the insertion code so that the new node is inserted upon the

sorted?

Joe

1122334

[email protected]

next

John

1122556

[email protected]

head

Tom

1122667

[email protected]

p

temp

temp->next = p;

Zac

1122889

[email protected]

0

p->next = temp->next;

21

Page 22: Midterm Review 2014

Linked List

else { while (temp->next != 0) {

if (stricmp(p->name, temp->next->name) <=0) {

p->next = temp->next;

temp->next = p;

return;

} else

temp = temp->next;

}

p->next = 0;

temp->next = p;

}

}

22

Joe

1122334

[email protected]

next

John

1122556

[email protected]

head

Tom

1122667

[email protected]

p

temp

temp->next = p;

Zac

1122889

[email protected]

0

p->next = temp->next;

Page 23: Midterm Review 2014

Different Parameter Types

Call-by-value

Formal parameter is a local variable in function (copy)

foo(int m, int n)

Call-by-reference

Aka call by alias

Formal parameter is an alias name of the actual parameter

foo(int& m, int& n)

C++ only

Call-by-address

Aka Call by pointer

Address of the actual parameter is passed into a local variable in function

foo(int *m, int* n)

Advantages? Disadvantages?

Page 24: Midterm Review 2014

Recursion

Four step approach for solving recursive problems

1. Formulate the size-n problem

2. Find the stopping condition and the corresponding return value

3. Formulate the size-m problem and find m. In may cases, m = n-1;

4. Construct the solution of size-n problem from size-m problem

Page 25: Midterm Review 2014

Recursion

Example: Factorial

1. Size n problem:

int factorial(int n)

2. Stopping condition:

if (n == 0) return 1;

3. Formulate size m:

factorial(n-1)

4. Construct the solution to the size-n problem

n*factorial(n-1)

Page 26: Midterm Review 2014

Recursion

Fibbonaci – try this example and build it

2)2()1(

11

00

)(

nnfibnfib

n

n

nfib

Page 27: Midterm Review 2014

Recursion

Tail-recursion resembles a regular while loop

while-loop

12n

condition

Jump to

tail-

recursion

part 1

12n

recursive call

condition

loop-body

Page 28: Midterm Review 2014

Good Luck!

Study further than these slides