93
ET2560 Introduction to C Programming ET2560 Introduction to C Programming id i MidTerm Review Instructor : Stan Kong Email : skong@itttech.edu Email : skong@itt tech.edu

ET2560 Introduction to C Programming - YPW · ET2560 Introduction to C Programming Mid‐Term Review Instructor : Stan Kong Email : skong@itt‐tech.edu

  • Upload
    vudieu

  • View
    233

  • Download
    0

Embed Size (px)

Citation preview

ET2560 Introduction to C ProgrammingET2560 Introduction to C Programming

id iMid‐Term Review

Instructor : Stan Kong

Email : skong@itt‐tech.eduEmail : skong@itt tech.edu

Computers and ProgramsComputers and Programs

• ComputerComputer– A machine that processes data under the control of a stored programof a stored program 

– Requires hardware, software, and data

• Program• Program– A series of instructions that guide a computer through a processthrough a process

Figure 1.3

fComponents of a Computer

Central Processing UnitCentral Processing Unit

• Central Processing Unit (CPU) has two roles:Central Processing Unit (CPU) has two roles: coordinating all computer operations and performing arithmetic and logical operationsperforming arithmetic and logical operations on data.

Main MemoryMain Memory

• Main memory stores programs, data and results.Main memory stores programs, data and results. Most computers have two types of main memory: random access memory (RAM) and read‐only memory (ROM).

• RAM which offer temporary storage of program and data. RAM is usually volatile memory, which means that everything in RAM will be lost when the computer is switched offcomputer is switched off. 

• ROM which stores programs or data permanently, it is not volatile The computer can read but cannotis not volatile. The computer can read, but cannot write information in ROM.

Secondary Storage DevicesSecondary Storage Devices

• Computer systems provide storage in additionComputer systems provide storage in addition to main memory for two reason. 

• First computers need storage that is• First, computers need storage that is permanent so that information can be retained during a power loss of whenretained during a power loss of when computer is turn off.

S d i ll• Second, systems typically store more information than will fit in memory.

Input/Output DevicesInput/Output Devices

• Input/output devices are use to communicateInput/output devices are use to communicate with the computer. Specifically they allow us to enter data for a computation and toto enter data for a computation and to observe the results of that computation.

• For example keyboard is an input device and• For example, keyboard is an input device and a monitor is an output device. 

UserThe operating system is a set of system software

Application program

a set of system software routines that interface between an application Application programbetween an application program and the hardware. It is 

Operating systemresponsible to manage processor resource and 

d

Computer Hardware

memory resource and load program into memorymemory.

Machine languages are the only languagesthe only languagesunderstood by computers. While easily co pute s e eas yunderstood by computers, machine languages are almost impossible for humans to 

b th i tuse because they consist entirely of numbers. A compiler converts each

Library

A compiler converts each source statement to one or more machine‐level  Linker

instructions (machine languages). 

Executable Program

Begin and End ShapesBegin and End Shapes

These shapes are used to begin and end aThese shapes are used to begin and end a flowchart

The beginning shape has the algorithm nameThe beginning shape has the algorithm name as its label

Th d h i h d “E d”The end shape contains the word “End”

Rectangle Shape – Actionsg p

Rectangle has one entry and one exit

The text in the rectangle is pseudo‐code corresponding to one step in the algorithm

Diamond Shape – Decision Pointp

One entry two exits (one for “yes” the otherOne entry, two exits (one for  yes , the other for “no”)

Contains one question with yes/no answerContains one question, with yes/no answer

Selection ShapeSelection is an extension of the decision pointpoint

Instead of a question, the diamond contains a valuecontains a value

The value selects which branch to take

One “other” branch is used for all other values that don’t have a branch

Connector Shape – On‐pageUse for a connection on same pageShape shows connection from one point to another

Left shape can be used multiple timesRight shape, used once, shows the destination of connection

Shapes Combine to Create Structures

Straight‐line structure

Single‐sided branch

Double‐sided branchDouble‐sided branch

Selection structure

Until loop

While loop

Do‐while loop

Straight‐line Structureg

Single‐sided Branchg

Double‐sided Branch

Selection StructureSelection structure is an extension of the branchbranch

All branches must converge together at the endend

First C ProgramFirst C Program

#include <stdio h> /* printf scanf definitions */#include <stdio.h>  /  printf, scanf  definitions  /      

Int main(void)Int main(void)

{

printf( “Hello World .\n");

return (0);( );

}

General Form of a C programGeneral Form of a C program

preprocessor directivespreprocessor directives

main function heading

{{

declarations

executable statements

}}

Function mainFunction main

• The point at which program execution beginsp p g g• Contains declarations and executable statements

• Standard format is:int main(void) {

/*d l i *//*declarations*/

/*executable statements*// executable statements /return (0);

}

Preprocessor DirectivesPreprocessor Directives

• Provide instructions to the preprocessor.

• Begin with #Begin with #– #includeUsed to load a library such as a standard librar– Used to load a library, such as a standard librar#include <stdio.h> /* library needed for scanf, prinf function */for scanf, prinf function /

– #defineUsed to define a constant macro– Used to define a constant macro#define PI 3.14159

CommentsComments• Comments can be written anywhere in the code: any characters between /* and */ arecode: any characters between /* and */ are ignored by the compiler and can be used to make the code easier to understandmake the code easier to understand. 

• For example :  portion of 1st line begin with /* */to */ are comments    

#include <stdio.h>    /* printf, scanf  library definitions */        

I i ( id)Int main(void)

{

printf( “Hello World \n");printf(  Hello World .\n );

return (0);

}

Declarations Statement‐ Variable declarations

• The memory cells used for storing a program’s inputThe memory cells used for storing a program s input data, output data and its computational results are called variables.

• The variable declarations tell the C compiler the names of all variables and what kind of information will be stored in each variable.

• The general format for variable declaration is:

Data type  variable name or variable list;

Example :  int count; 

where int is data type of integer and count is the variable name.

Data typeData type

• Common data typeCommon data type

• int       ‐‐‐ store integer 

h i l h• char     ‐‐ store single character

• Double – store real number/floating number

String Constants DefinedString Constants DefinedA string constant is zero or more characters– (A string constant can be empty)

Each character takes one byte in memory– (An extra zero byte is used in memory at the end of a string)

Each character is encoded using the ASCII code

A string constant must begin and end with a double‐quote– (The quote characters are not stored in memory)

String Constants ‐ ExamplesString Constants  Examples

"Hello World"

"Hello" and "Hello " are different

"134 5" is not a number it's a string"134.5" is not a number,  it s a string

"!@#$%;" is a string containing punctuation h tcharacters

"" is the empty string

" " is a string consisting of a space; it's not emptyp y

"AF" and  "af" are different ‐ case sensitive

String Escape SequencesString Escape Sequences

Put special characters in a string or character constantp gSequence of characters, starting with backslash   \Put quote or double‐quote in a string or character constant"\"Hi!\", we said." Single string of 15 charactersPut a backslash in a string or character constantPut a backslash in a string or character constant"\\" A string with one backslash characterPut special codes in a string or character constantp g"\n" Makes console output start a new line"\t" Outputs a tab character'\g' Make a "beep" noise from the speaker'\g' Make a  beep  noise from the speaker

The printf( ) FunctionThe printf( ) FunctionFunction accepts one or more inputs (called arguments)arguments)First argument is a string (called format string)Format string can contain:g– Text– One or more format placeholders, mixed in with text– The official name of a format placeholder is a conversion– The official name of a format placeholder is a conversion specifier

Format placeholders begin with a % characterPl h ld l d d b i f i i 1stPlaceholders are only understood by printf, in its 1stargumentThe formatted text prints on the console screenp

Conversion Specifiers for printf( )Formatting an int:– %d Format as decimal integer 27– %b Format as binary integer 11011%b Format as binary integer 11011– %x Format as hexadecimal integer 1b– %X Format as hex integer using uppercase 1B

Formatting a float or doubleFormatting a float or double:– %f Format as decimal fraction 0.125– %e Format as scientific notation 1.25e‐1– %E Same as %e but with capital E 1.25E‐1

Formatting a character:%c Format as a single character x– %c Format as a single character x

Formatting a string:– %s Format as a string xyzzyg y y

For a '%' character ‐must use %%

Variables/User Defined IdentifiersVariables/User Defined Identifiers

• A variable may be defined using any uppercase orA variable may be defined using any uppercase or lowercase character, a numerical digit (0 through 9), and the underscore character (_). The first character of the variable may not be a numerical digit or underscore. C reserved word cannot be used as an variable name. Variable names are case sensitive. 

• Valid identifiers  – letter_1, cent, Hello, …Invalid identifier Reason  invalid

1Letter Begin with a letter

double Reserve worddouble Reserve word

Two*Four Character * not allowed

big  mac Space is not allowed

C Reserved WordsC Reserved Words

auto double include staticauto double include static

break elif int struct

case else long switchcase else long switch

char enum main typedef

const extern register unionconst extern register union

continue float return unsigned

default for short voiddefault for short void

define goto signed volatile

do if sizeof whiledo if sizeof while

C Program Example with variablesC Program Example with variables• #include <stdio.h>           /* library definition needed for scanf, prinf function */ 

/* */• #define PI 3.14159           /* Constant needed for circle */

• /*This program accepts the radius of a circle, calculates the area, and outputs the radius and the area */the radius and the area. /

int main(void) {double radius;   /*Stores the radius entered by the user*/; / y /double area;      /*Stores the area after the calculation*/

return (0); }

Executable StatementsExecutable Statements

• An assignment Statements store a value orAn assignment Statements store a value or computational result in a variable, and is used to perform most arithmetic operations in ato perform most arithmetic operations in a program.

• Example : abc = 25; /* assign abc to 25 */• Example :  abc = 25;  /* assign abc to 25 */

abd  = abc + 5 ; 

kms = KMS_PER_MILE * miles;

Input/output functionsInput/output functions

• printf ‐ an output function from the I/Oprintf  an output function from the I/O (input/output) library (defined in the file stdio h)stdio.h).

• scanf ‐ an input function from the I/O (input/output) library (defined in the file(input/output) library (defined in the file stdio.h).

scanf Function

scanf(format string, input list);

For example : scanf("%lf", &miles);

Read the floating value into the address of the ll f d b th i bl ilmemory cell referenced by the variable name miles.

Use %d for integer variable and %lf for floating point number variable The name of each variable that is tonumber variable. The name of each variable that is to be given in value is proceeded by & character.

printf FunctionPrinf(format string, print list);

Prinf(format string);

function arguments

printf("That equals %f kilometers.\n", kms);

function name format string print listg

That equals 16.090000 kilometersThat equals 16.090000 kilometers

C Program ExampleC Program Example#include <stdio.h>#define PI 3.14159#define PI 3.14159

/*This program accepts the radius of a circle, calculates the area, and outputs the radius and the area.*/

int main(void) {/*declarations*/d bl di /*St th di t d b th */double radius;   /*Stores the radius entered by the user*/double area;      /*Stores the area after the calculation*/

/*executable statements*/printf("Enter the radius of the circle>"); /* output prompt */printf( Enter the radius of the circle> ); /  output prompt  /scanf("%lf", &radius);                    /* input radius in floating point format */ area = PI * radius * radius;  /*Calculates the area as PI X radius X radius and   stores the results in area*/printf("The area of a circle with a radius of %f is %f\n", radius, area);return (0); 

}

The Software Development h dMethod

1. Specify the problem requirements.

2 A l h bl2. Analyze the problem.

3. Design the algorithm to solve the problem.

4. Implement the algorithm.p g

5. Test and verify the completed program.

6 Maintain and update the program6. Maintain and update the program.

Algorithm to ProgramAlgorithm to Program

• Include required librariesInclude required libraries• Define constants• Declare variables• Declare variables• Get the inputP f t t f i t i t th• Perform process to transform input into the outputDi l t t• Display output

• Refine the program

Arithmetic Operatorsp

Table 2 6Table 2.6 

Unary vs. Binary OperatorsUnary vs. Binary Operators

Unary Operators Binary OperatorsUnary Operators• Take one operand

Negation ( ) operator

Binary Operators• Take two operands

Subtraction– Negation (‐) operator

– Plus (+) operator

• Examples

– Subtraction

– Addition

– Multiplication• Examplesx = -y;p = +x * y;

p

– Division

• Examplesp y; px = y + z;z = y – z;

Rules of Precedence

• Parentheses rule– Expressions in parentheses are evaluated separately.– Nested parentheses are evaluated from the inside out.

• Operator precedence rule• Operator precedence rule1.unary +, ‐2.*, /, %b3.binary +, ‐

• Associativity rule– Unary operators at the same level are evaluated rightUnary operators at the same level are evaluated right to left.

– Binary operators at the same level are evaluated left to right.g

Expression AssignmentExpression Assignment

Assignment can cause data to be lost if targetAssignment can cause data to be lost if target variable is of a data type more narrow than the expressionexpression

double x;iint n;x = 9 * 0.5; 4.5 4

x n

n = 9 * 0.5;

Data Type Expression ExampleData Type Expression Example

m = 3;

n = 2;n  = 2;

p  = 2.0;

x  = m / p;

y = m / n;y    m / n;

Casting a Variable's Typeg yp

Formatting Output of Type inti i f t t f tiuse in prinf output function

Table 2.11

Displaying 234 and ‐234 Using Different Placeholders

Formatting Output of Type doubleuse in prinf output function

Table 2.13

Interactive Mode vs. Batch ModeInteractive Mode vs. Batch Mode

Interactive Mode Batch ModeInteractive Mode• Accepts input from users

Batch Mode• Accepts input from a fileusers

• Sends output to the display

filemetric <mydata

• Should echo inputdisplay Should echo input  using printf

• Might output data to a g pfilemetric >myoutput

Input redirection/output redirection

• Redirect input from file instead of keyboardRedirect input from file instead of keyboard

EXAMPLE : metric

i dmetric <mydata

• Redirect output to a file

EXAMPLE :   metric >myoutput

Program‐Controlled input and output Files

• Declare a file pointer variable in which to storeDeclare a file pointer variable in which to store the information necessary to permit access to a file File pointer variable are of type FILE *a file. File pointer variable are of type FILE  .

• Example :

FILE *i /* i i fil */FILE *inp,   /* pointer to input file */

*opt; /* pointer to output file */

Prepare file to open for read, write

inp = fopen("distance dat" "r");inp   fopen( distance.dat ,  r );

opt = fopen("distance.out", "w");

Interactive program examplep g p• /* Converts distances from miles to kilometers.   */

• #include <stdio.h>    /* printf, scanf     definitions         */

• #define KMS_PER_MILE 1.609 /* conversion constant  */

• Int main(void)

• {

• double miles, /* distance in miles */

• kms;   /* equivalent distance in kilometers */

• /* Get and echo the distance in miles. */

• printf("Enter Distance in miles is ");

• scanf( "%lf", &miles);

• printf("The distance in miles is %.2f.\n", miles);

• /* Convert the distance to kilometers. */

• kms = KMS_PER_MILE * miles;

• /* Display the distance in kilometers. */p y

• printf( "That equals %.2f kilometers.\n", kms);

• return (0);

• }

Syntax ErrorsSyntax Errors

• Code violates a grammar error of CCode violates a grammar error of C• Compiler locates syntax errors during translationtranslation

• Examples:– Missing semicolonMissing semicolon– Undeclared variables– Unclosed commentsUnclosed comments– Mismatched open and close braces, quotation marks, or parentheses

R ti ERuntime Error

• Detected during program execution

• Caused by an attempt to perform an illegal operation

Logic Errors

• Errors in the algorithmErrors in the algorithm

• Causes program to give incorrect results

A id b d k h ki l ith b f• Avoid by desk‐checking algorithm before coding

Top‐Down DesignTop Down Design

• A problem‐solving method in which you firstA problem solving method in which you first break a problem into its major subproblems and then solve the subproblems to derive theand then solve the subproblems to derive the solution to the original problem.

• Structure Chart A documentation tool that• Structure Chart – A documentation tool that shows the relationships among the subproblems of a problemsubproblems of a problem.

C Language Elements in il il iMiles‐to‐Kilometers Conversion Program

1‐59

Relational and Equality Operatorsq y p

Table 4‐1

Sample ConditionsSample Conditions

Table 4‐2

Logical OperatorsLogical Operators

• And &&• And  &&(temperature > 90) && (humidity > 0.90)

O ||• Or   ||(salary < MIN_SALARY) || (dependents > 5)

• Not   !!(0 <= n && n <= 100)

Operator PrecedenceOperator PrecedenceTable 4.6

Sequential Flowq

A set of steps that are executed sequentially{{

statement; statement

statement;statement;

statement

statement} statement

Selection Control StructureSelection Control Structure

E ec tion path changes based on a conditionExecution path changes based on a condition

ConditionF T

DoDo this

Do something 

else

Character ComparisonsCharacter Comparisons

Table 4.8

if Statement with One Alternativeif Statement with One Alternative 

if (condition)ti t f if taction to perform if true;

if (R != 0.0)current = voltage / R;current voltage / R;

if Statement with Two Alternativesif Statement with Two Alternativesif (condition)

action to perform if true;action to perform if true;elseaction to perform if false;action to perform if false;

if (voltage > 3 3 )if (voltage > 3.3 )printf(“A digital High is present!"\n);

lelseprintf(“A digital Low is present!\n");

BlocksBlocks

if (condition){

if (condition) {statement;

statement;statement;

}

statement;}l {}

else{

else {statement;statement;{

statement;statement;

statement;}

}

Nested if StatementsNested if Statements

if (x > 0)num = num + 1;

else {

if (x < 0)num_neg = num_neg + 1;

else /* x equals 0 */num zero = num zero + 1;

}

_ _ ;

Multiple Alternative if StatementsMultiple Alternative if Statements/* Display perception of noise loudness */

if (noise_db <= 50)

printf(“%d‐decibel noise is quiet.\n”, noise_db);

else if (noise_db <=70)

printf(“%d‐decibal noise is intrusive. \n”, noise_db);

l if ( i db 90)else if (noise_db <= 90)

printf(“%d‐decibel noise is annoying.\n”, noise_db);

else if (noise db <= 110)else if (noise_db <= 110)

printf(“%d‐decibel noise is very annoying. \n”, noise_db);

else

printf(“%d‐decible noise is uncomfortable. \n”, noise_db);

Switch Statement• The switch statement  is used in C to select one of several alternatives. 

The switch statement is especially useful when the selection is based on the value of a single variable or a simple expression ( called the controlling 

i ) Th l f hi i b f i h bexpression). The value of this expression may be of type int or char, but not of type double.

• SYNTAX:  switch (controlling expression) {

label set1label set1 

statements1,

break;

label set2  

statements2,

break;

label setn  

statementsn,

break;                      

default : statementsddefault : statementsd,

break;      

}                                          label setn is  ‐ case constant value :                  

Switch and FlowchartSwitch and Flowchart

double discount; // Usually code would be read in char code = 'B' ; switch ( code ){{

case 'A': discount = 0.0; break;

'B'case 'B': discount = 0.1; break;

case 'C':discount = 0.2; break;

default: discount = 0 3;discount = 0.3;

}

Basics of LoopsBasics of Loops

• Programming loops are iterative code structuresg g p

– A set of instructions is repeated a number of times

• Loops are controlled by a condition, or loop test

• A loop is preceded by an initialization

– Sets up the loop condition for initial execution

• A loop contains an increment

– Determines whether the loop continues or stops

• Loops without a loop test repeat indefinitely

– Useful for control systems or systems that "runUseful for control systems or systems that  run continuously"

Loop Structures ‐ The "while" LoopLoop Structures  The  while  Loop

• Loop test is done first at "top" of loopLoop test is done first, at  top  of loop

• May or may not execute once or more

int count;count = 0; /* Initialization action */count = 0; /* Initialization action */while (count < 5) { /* Loop test (condition) */

/* Loop body - action to repeat */++count; /* Loop increment */

}}

Loop Structures ‐ The "do‐while" LoopLoop Structures  The  do while  Loop

• Loop test is done last, at "bottom" of loop

• Always executes at least once

int count;count = 0; /* Initialization action */d {do {

/* Loop body - action to repeat */++count; /* Loop increment */; / p /

} while (count < 5); /* Loop test (condition) */

Loop Structures ‐ The "for" LoopLoop Structures  The  for  Loop

• The "for" loopThe  for  loop– Contains initialization, loop test, and increment all in one placein one place

int count;int count;for (count = 0; count < 5; ++count) {

/* Loop body - action to repeat */}}

Different Loops for Different PurposesDifferent Loops for Different Purposes• Counter‐controlled loop

– Loops a specific number of times as a counter increments

• Conditional loop– Loops until a specific condition becomes true

• Sentinel‐controlled loopProcesses data until a special value signals the end– Processes data until a special value signals the end of data

Modifying Loop ExecutionModifying Loop Execution

• The "break" statement break;The  break  statement break;

– This is an immediate exit from a loop

Only used under unusual circumstances– Only used under unusual circumstances

• The "continue" statement continue;

– Used to stop the current loop iteration

– Begins a new loop execution immediately

Structured CodeStructured Code

• Design principle for codeDesign principle for code– Entry at top of section

Exit at bottom of section– Exit at bottom of section

• "Never" use the "goto" statement

• Very rare circumstances need "break" or "continue" in loop

• Avoid "spaghetti code" ‐ tangled, poorly written code

FunctionsFunctions

• Functions are easy to use; they allowFunctions are easy to use; they allow complicated programs to be parcelled up into small blocks each of which is easier to writesmall blocks, each of which is easier to write, read, and maintain.

• We have already encountered the function• We have already encountered the function main and made use of I/O and mathematical routines from the standard libraries Now let'sroutines from the standard libraries. Now let s look at some other library functions, and how to write and use our ownto write and use our own. 

Calling a functionCalling a function

• The call to a function in C simply entails referencing its p y gname with the appropriate arguments. 

• The C compiler checks for compatibility between the arguments in the calling sequence and the definition of the function. 

• Library functions are generally not available to us in source form. Argument type checking is accomplished through the use of header files (like stdio h) whichthrough the use of header files (like stdio.h) which contain all the necessary information. For example, as we saw earlier, in order to use the standardwe saw earlier, in order to use the standard mathematical library you must include math.h via the statement .     #include <math.h>

Figure 3.6  Function sqrt as a “Black Box”g q

1‐84

Figure 3.7  Square Root Programg q g

1‐85

Figure 3.7  Square Root Program (cont’d)g q g ( )

1‐86

Writing Your Own Functions ‐ 1Writing Your Own Functions  1

• A function has the following layout:A function has the following layout:return‐type function‐name ( argument‐list‐if‐necessary ) 

{ local declarations{ ...local‐declarations... 

...statements... 

t t lreturn return‐value;

Figure 3.23  Function scaleg

1‐88

Figure 3.24  Testing Function scaleg g

1‐89

Figure 3.24  Testing Function scale (cont’d)g g ( )

1‐90

Writing Your Own Functions ‐2Writing Your Own Functions  2

• A function may simply perform a task withoutA function may simply perform a task without returning any value, in which case it has the following layout:following layout: 

• void function‐name ( argument‐list‐if‐necessary ) 

{ local declarations{ ...local‐declarations...

...statements... 

}}

Figure 3.12  Function draw circleg _

1‐92

Figure 3.15  Flow of Control Between the main gFunction and a Function Subprogram

1‐93