ECE-1021 Course Review

31
ECE-1021 Course Review

description

ECE-1021 Course Review. Engineering Problem Solving. Define the problem clearly Work hand examples Develop the Algorithm Implement the Algorithm Test the Implementation. Top-Down Algorithm Development. Divide and Conquer Break Problem into smaller tasks. - PowerPoint PPT Presentation

Transcript of ECE-1021 Course Review

Page 1: ECE-1021 Course Review

ECE-1021 Course ReviewECE-1021 Course Review

Page 2: ECE-1021 Course Review

Engineering Problem SolvingEngineering Problem Solving

Define the problem clearlyDefine the problem clearly Work hand examplesWork hand examples Develop the AlgorithmDevelop the Algorithm Implement the AlgorithmImplement the Algorithm Test the ImplementationTest the Implementation

Page 3: ECE-1021 Course Review

Top-Down Algorithm DevelopmentTop-Down Algorithm Development

Divide and ConquerDivide and Conquer Break Problem into smaller tasks.Break Problem into smaller tasks. Define the interaction between tasks.Define the interaction between tasks. Recursively solve the individual tasks.Recursively solve the individual tasks. Build up the overall solution from the Build up the overall solution from the

pieces.pieces.

Page 4: ECE-1021 Course Review

Structured Programming ElementsStructured Programming Elements

SequencesSequences SelectionsSelections RepetitionsRepetitions

Page 5: ECE-1021 Course Review

Basic Flowchart SymbolsBasic Flowchart Symbols

Entry

ExitTask I/O Q?

T

F

Page 6: ECE-1021 Course Review

Logical ValuesLogical Values

FALSE: A value that is EXACTLY zero.FALSE: A value that is EXACTLY zero. TRUE: A value that is not FALSETRUE: A value that is not FALSE

TRAP: Use of floating point values.TRAP: Use of floating point values.

Page 7: ECE-1021 Course Review

Logical ExpressionsLogical Expressions

Evaluate to:Evaluate to: 0 if FALSE0 if FALSE 1 if TRUE (but recognize any nonzero value as TRUE)1 if TRUE (but recognize any nonzero value as TRUE)

Operators: Operators: ! - Logical NOT! - Logical NOT

Example: k = !j;Example: k = !j; && - Logical AND&& - Logical AND

Example k = i && j;Example k = i && j; || - Logical OR|| - Logical OR

Example k = i || j;Example k = i || j;

Page 8: ECE-1021 Course Review

C Programming ElementsC Programming Elements

SequencesSequences Statements execute in order presented.Statements execute in order presented. Control Structures override normal order.Control Structures override normal order.

SelectionsSelections One (or more) branches chosen based on a test.One (or more) branches chosen based on a test. if(), if()/else, switch()if(), if()/else, switch()

RepetitionsRepetitions Selection Structure that branches to a point above the Selection Structure that branches to a point above the

branch point.branch point. while(), do/while(), for()while(), do/while(), for()

Page 9: ECE-1021 Course Review

C is Function OrientedC is Function Oriented

function headerfunction header

{{

function bodyfunction body

}}

function header:function header:return-type function-name(param list)return-type function-name(param list) return-type: type of value returned by function.return-type: type of value returned by function. param list: variable declarations that are initialized with param list: variable declarations that are initialized with

the function call’s corresponding argument values.the function call’s corresponding argument values.

Page 10: ECE-1021 Course Review

Assignment ExpressionsAssignment Expressions

Normal Assignment Operator:Normal Assignment Operator:

a = b + c;a = b + c;

Abbreviated Assignment Operators:Abbreviated Assignment Operators:

a += b + c; /* same as a = a + b + c; */a += b + c; /* same as a = a + b + c; */

Evaluate to value assigned.Evaluate to value assigned.

Page 11: ECE-1021 Course Review

Increment/Decrement OperatorIncrement/Decrement Operator

Changes the value stored in a variable by one.Changes the value stored in a variable by one. Post-Increment/Post-DecrementPost-Increment/Post-Decrement

c++; c--;c++; c--; Evaluates to original value in variable.Evaluates to original value in variable.

Pre-Increment/Pre-DecrementPre-Increment/Pre-Decrement++c; --c;++c; --c; Evaluates to (original value +/- 1)Evaluates to (original value +/- 1)

Page 12: ECE-1021 Course Review

if() and if()/else statementsif() and if()/else statements

SyntaxSyntaxif(test)if(test){{ if_code;if_code;}}elseelse{{ else_code;else_code;}}

test?test?

if_codeif_code

if()if()

TT

FFtest?test?

if_codeif_code else_codeelse_code

if()...elseif()...else

FF

TT

Page 13: ECE-1021 Course Review

switch() statementswitch() statement

SyntaxSyntaxswitch(int_expr)switch(int_expr)

{{

case int_const1: code1;case int_const1: code1;

break;break;

case int_const2: code2;case int_const2: code2;

case int_const3: code3;case int_const3: code3;

break;break;

default: code4;default: code4;

}}

Compact way of writing certain Compact way of writing certain types of complex but common types of complex but common if()/else blocks.if()/else blocks.

(int_expr)(int_expr)

must evaluate to an integer value must evaluate to an integer value at at runtimeruntime..

(int_constN)(int_constN)

must evaluate to a must evaluate to a uniqueunique integerinteger constantconstant at at compilecompile time. time.

execution jumps to case whereexecution jumps to case where

(int_constN == int_expr) is TRUE.(int_constN == int_expr) is TRUE.

break;break;

terminates switch() execution.terminates switch() execution.

default casedefault case

Optional. Executes only if NO Optional. Executes only if NO other case executes.other case executes.

Page 14: ECE-1021 Course Review

Loop StructuresLoop Structures

Special case of Selection Statement One branch eventually leads back to the original selection statement. Permits a block of code to be executed repeatedly as long as some test

condition is satisfied.

C provides three different looping structures while(), do/while(), for() Only one is needed and any one is sufficient. Different structures are better matches for different logic. Using the “proper” one aides the programmer and anyone else reading the

code. The compiler doesn’t care and will often implement the code identically

regardless of which structure is used.

Page 15: ECE-1021 Course Review

while() loopwhile() loop

SyntaxSyntaxini_code // not part of loopini_code // not part of loop

while(test_expr)while(test_expr)

{{

loop_code;loop_code;

increment_code;increment_code;

}}

next_code; // not part of loopnext_code; // not part of loop

Features loop does not execute at all if test

fails the first time.

loop_codeloop_code

test?test?FF

TT

inc_codeinc_code

ini_codeini_code

next_codenext_code

Page 16: ECE-1021 Course Review

do/while() loopdo/while() loop

SyntaxSyntaxini_code // not part of loopini_code // not part of loop

dodo

{{

loop_code;loop_code;

increment_code;increment_code;

} while(test_expr);} while(test_expr);

next_code; // not part of loopnext_code; // not part of loop

Features loop will always execute at least

once, even if test fails the first time.

loop_codeloop_code

test?test?

FF

TT

inc_codeinc_code

ini_codeini_code

next_codenext_code

Page 17: ECE-1021 Course Review

for() loopfor() loop

SyntaxSyntaxfor(ini_code; test_expr; inc_code)for(ini_code; test_expr; inc_code)

{{

loop_code;loop_code;

}}

next_code; // not part of loopnext_code; // not part of loop

Features Just a while() loop with the initialization

and increment code formally incorporated into the syntax.

Can make a cleaner divide between the loop logic and the housekeeping logic.

Makes it harder to omit initialization code if loop is moved or copied.

loop_codeloop_code

test?test?FF

TT

inc_codeinc_code

ini_codeini_code

next_codenext_code

Page 18: ECE-1021 Course Review

MacrosMacros

Perform text replacement prior to compile.Perform text replacement prior to compile. Object-like macrosObject-like macros

Symbolic ConstantsSymbolic Constants Function-like macros:Function-like macros:

Two step replacement processTwo step replacement process Golden RulesGolden Rules

Surround ALL macro arguments with parentheses.Surround ALL macro arguments with parentheses. Surround entire macro body with parentheses.Surround entire macro body with parentheses. Ensures predictable evaluation.Ensures predictable evaluation.

Page 19: ECE-1021 Course Review

ASCII codeASCII code

Characters and control actions encoded as an Characters and control actions encoded as an integer value.integer value.

Standard ASCII - 7 bitsStandard ASCII - 7 bits Eleven subgroups (in addition to complete group):Eleven subgroups (in addition to complete group):

ASCII, CONTROL, PRINTING, GRAPHICALASCII, CONTROL, PRINTING, GRAPHICAL ALPHANUMERIC, PUNCTUATIONALPHANUMERIC, PUNCTUATION ALPHABETICAL, NUMERICALPHABETICAL, NUMERIC UPPERCASE, LOWERCASEUPPERCASE, LOWERCASE HEXADECIMAL, WHITESPACEHEXADECIMAL, WHITESPACE

Page 20: ECE-1021 Course Review

Bitwise OperationsBitwise Operations

Operators work on entire value.Operators work on entire value. Result is determined bit-by-bitResult is determined bit-by-bit Operators:Operators:

~ - bitwise NOT~ - bitwise NOT & - bitwise AND& - bitwise AND | - bitwise OR| - bitwise OR ^ - bitwise XOR^ - bitwise XOR

Page 21: ECE-1021 Course Review

Integer RepresentationInteger Representation

IntegerInteger Unsigned IntegersUnsigned Integers

Pure BinaryPure Binary Signed IntegersSigned Integers

Signed BinarySigned Binary Offset BinaryOffset Binary One’s ComplimentOne’s Compliment Two’s Compliment (most commonly used)Two’s Compliment (most commonly used)

C Standard does not allow use of offset binaryC Standard does not allow use of offset binary Positive integers must use same representation as Positive integers must use same representation as

unsigned integers.unsigned integers.

Page 22: ECE-1021 Course Review

Floating Point RepresentationFloating Point Representation

IEEE-754 Floating Point StandardIEEE-754 Floating Point Standard Value broken into three parts from left-to-rightValue broken into three parts from left-to-right

Sign Bit (0 for positive, 1 for negative)Sign Bit (0 for positive, 1 for negative) Exponent (used offset binary with 0111....1 mapping to zero)Exponent (used offset binary with 0111....1 mapping to zero) Mantissa MagnitudeMantissa Magnitude

Normalized with implied leading 1.Normalized with implied leading 1. Denormalized if exponent pattern is all 0.Denormalized if exponent pattern is all 0.

Special ValuesSpecial Values Exponent Pattern is all 1’sExponent Pattern is all 1’s +/- infinity if mantissa is all 0’s+/- infinity if mantissa is all 0’s NaN (Not-a-Number) if mantissa has any 1’sNaN (Not-a-Number) if mantissa has any 1’s

Page 23: ECE-1021 Course Review

RecursionRecursion

To be a successful, recursive function:To be a successful, recursive function: Must have a recursive pathMust have a recursive path Must have a non-recursive path (“base case”) Must have a non-recursive path (“base case”)

Often quicker to develop and debug.Often quicker to develop and debug. Generally slower.Generally slower. Generally consumes more memory Generally consumes more memory

resources.resources. Iterative alternative always exists.Iterative alternative always exists.

Page 24: ECE-1021 Course Review

File OperationsFile Operations

File interaction performed via FILE structure.File interaction performed via FILE structure. fopen(), fclose()fopen(), fclose() Primary Modes: “rt”, “wt”, “rb”, “wb”Primary Modes: “rt”, “wt”, “rb”, “wb” Should ALWAYS verify fopen() successShould ALWAYS verify fopen() success If FILE * returned by fopen is NULL:If FILE * returned by fopen is NULL:

Do NOTHING more with that file - NOTHING!Do NOTHING more with that file - NOTHING!

Close files as soon as they are no longer needed.Close files as soon as they are no longer needed.

Page 25: ECE-1021 Course Review

File I/OFile I/O

Two types of files - Text and BinaryTwo types of files - Text and Binary Text:Text:

Contents are expected to consist of one-byte ASCII codes.Contents are expected to consist of one-byte ASCII codes. Character I/O: putc(), getc(), puts(), gets()Character I/O: putc(), getc(), puts(), gets() Formatted I/O: fprintf(), fscanf()Formatted I/O: fprintf(), fscanf()

Binary:Binary: Direct copy between memory and file.Direct copy between memory and file. fread()/fwrite()fread()/fwrite() fseek(), fset(), ftell()fseek(), fset(), ftell() SEEK_SET, SEEK_CUR, SEEK_ENDSEEK_SET, SEEK_CUR, SEEK_END

Page 26: ECE-1021 Course Review

PointersPointers

A variable used to store memory addresses.A variable used to store memory addresses. The address were a data item is stored.The address were a data item is stored. Dereference to access the data.Dereference to access the data.

*ptr = variable + *ptr2;*ptr = variable + *ptr2; The address operator evaluates to the address where The address operator evaluates to the address where

an object is stored:an object is stored: ptr = &variable;ptr = &variable;

Pointer arithmetic:Pointer arithmetic: pointer +/- integerpointer +/- integer integer is number of elements (not bytes)integer is number of elements (not bytes)

Page 27: ECE-1021 Course Review

ArraysArrays

One or more variables stored:One or more variables stored: In one contiguous block of memory.In one contiguous block of memory. Array name is a pointer to start of block.Array name is a pointer to start of block. All variables are the same type.All variables are the same type.

Can access elements by way of pointer offsetCan access elements by way of pointer offset *(array+index) = value;*(array+index) = value; array[index] = value;array[index] = value;

Passed by reference in function calls.Passed by reference in function calls.

Page 28: ECE-1021 Course Review

StructuresStructures

Programmer-defined data type.Programmer-defined data type. One or more variables stored:One or more variables stored:

In one contiguous block of memory.In one contiguous block of memory. May be different data types.May be different data types.

Passed by value in function calls.Passed by value in function calls.

Page 29: ECE-1021 Course Review

Structure DeclarationsStructure Declarations

typedef struct pt3d PT3D;

struct pt3d{

int pt;double x, y, z;

};

int main(void){

int i;PT3D pt1;PT3D pt[5];....return 0;

}

Typedef can appearTypedef can appearbefore structure declarationbefore structure declaration

Structure declaration outsideStructure declaration outsideany function to make it haveany function to make it haveglobal scopeglobal scope

Page 30: ECE-1021 Course Review

Accessing ElementsAccessing Elements

By variable name:By variable name:

point.pt = 42;point.pt = 42;

j = point.pt + 3;j = point.pt + 3; By pointer to a structure variable:By pointer to a structure variable:

(*ptr).pt = 42;(*ptr).pt = 42;

ptr->pt = 42;ptr->pt = 42;

Page 31: ECE-1021 Course Review

Structure UtilizationStructure Utilization

Quasi-Object Oriented ProgrammingQuasi-Object Oriented Programming Structure contains data.Structure contains data. Primitive functions are ONLY functions to Primitive functions are ONLY functions to

directly access the structure’s data.directly access the structure’s data. Get()/Set() function pairs.Get()/Set() function pairs.

Utility Functions invoke primitive functions Utility Functions invoke primitive functions if they need to access the structure’s data.if they need to access the structure’s data.