40
C Program Design Introduction to C Programming 主主主 主主主

C Program Design Introduction to C Programming 主講人:虞台文

Embed Size (px)

Citation preview

Page 1: C Program Design Introduction to C Programming 主講人:虞台文

C Program DesignIntroduction to C Programming

主講人:虞台文

Page 2: C Program Design Introduction to C Programming 主講人:虞台文

Content Background Main Parts of C Programs 標準輸出入裝置與輸出入函式 標準輸出入函式 算術運算子 (Arithmetic Operators) 關係運算子 (Relation Operators) 邏輯運算子 (Logical Operators) 巨集 The #define Preprocessor

Page 3: C Program Design Introduction to C Programming 主講人:虞台文

C Program DesignIntroduction to C Programming

Background

Page 4: C Program Design Introduction to C Programming 主講人:虞台文

C History

Developed between 1969 and 1973 along with Unix

Due mostly to Dennis Ritchie

Designed for systems programming– Operating systems

– Utility programs

– Compilers

– Filters

Evolved from B, which evolved from BCPL

The Development of the C Language

Page 5: C Program Design Introduction to C Programming 主講人:虞台文

Computer Architecture

ALUALU

ControlControl

CPU

InputInput OutputOutput

MemoryMemory

InputDevice

OutputDevice

Page 6: C Program Design Introduction to C Programming 主講人:虞台文

C Program DesignIntroduction to C Programming

Main Parts of

C Programs

Page 7: C Program Design Introduction to C Programming 主講人:虞台文

Our First C Program Hello World

Page 8: C Program Design Introduction to C Programming 主講人:虞台文

Our First C Program Hello World

/* HelloWorld.cpp Our first program */

#include <iostream>using namespace std;

/* function main begins program execution */main(){

cout << "hello, world\n";}

/* HelloWorld.cpp Our first program */

#include <iostream>using namespace std;

/* function main begins program execution */main(){

cout << "hello, world\n";}

Page 9: C Program Design Introduction to C Programming 主講人:虞台文

Some Common Escape Sequences

Escape sequence Description

\n Newline. Position the cursor at the beginning of the next line.

\t Horizontal tab. Move the cursor to the next tab stop.

\a Alert. Sound the system bell.

\\ Backslash. Insert a backslash character in a string.

\" Double quote. Insert a double-quote character in a string.

Page 10: C Program Design Introduction to C Programming 主講人:虞台文

Editing Compiling Linking Execution

Page 11: C Program Design Introduction to C Programming 主講人:虞台文

C Program DesignIntroduction to C Programming

算術運算子 (Arithmetic Operators)

Page 12: C Program Design Introduction to C Programming 主講人:虞台文

Arithmetic Operators

C opetration Arithmetic operator

Algebraic expression

C expression

Addition + f + 7 f + 7

Subtraction – p – c p - c

Multiplication * bm b * m

Division / / or or x

x y x yy

x / y

Remainder % r mod s r % s

Page 13: C Program Design Introduction to C Programming 主講人:虞台文

Precedence of Arithmetic Operators

Operator(s) Operation(s) Order of evaluation (precedence)

( ) Parentheses

Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.

* / %

Multiplication Division

Remainder

Evaluated second. If there are several, they are evaluated left to right.

+ -

Addition Subtraction

Evaluated last. If there are several, they are evaluated left to right.

Page 14: C Program Design Introduction to C Programming 主講人:虞台文

範例 : y = 2x2+3x+7// PolynormialEval.cpp

#include <cstdlib>#include <iostream>

using namespace std;

int main(int argc, char *argv[]){ int x, y;

cout << "x = "; /* prompt */ cin >> x; /* read x */

/* Evaluate y = 2x^2 + 3x + 7 */ y = 2 * x * x + 3 * x + 7;

cout << "y = 2 * " << x << " * " << x ; cout << " + 3 * " << x << " + 7 = " << y << endl;

system("PAUSE"); return EXIT_SUCCESS;}

// PolynormialEval.cpp

#include <cstdlib>#include <iostream>

using namespace std;

int main(int argc, char *argv[]){ int x, y;

cout << "x = "; /* prompt */ cin >> x; /* read x */

/* Evaluate y = 2x^2 + 3x + 7 */ y = 2 * x * x + 3 * x + 7;

cout << "y = 2 * " << x << " * " << x ; cout << " + 3 * " << x << " + 7 = " << y << endl;

system("PAUSE"); return EXIT_SUCCESS;}

y = 2 * x * x + 3 * x + 7;

Page 15: C Program Design Introduction to C Programming 主講人:虞台文

範例 : y = 2x2+3x+7

y = 2 * x * x + 3 * x + 7;

Page 16: C Program Design Introduction to C Programming 主講人:虞台文

C Program DesignIntroduction to C Programming

關係運算子(Relation Operators)

Page 17: C Program Design Introduction to C Programming 主講人:虞台文

Relation Operators in C

Standard algebraic equality operator or relational operator

C equality or relational operator

Example of C condition

Meaning of C condition

Equality operators

== x == y x is equal to y

!= x != y x is not equal to y

Relational operators

> x > y x is greater than y

< x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

The result of a relation operation is true (nonzero) or false (zero).

Page 18: C Program Design Introduction to C Programming 主講人:虞台文

Statements

Simple Statementslower = 0;

upper = 300;

step = 20;

fahr = lower;

Null Statement; // a null statement

Compound Statements (block statements){

celsius = (5.0/9.0) * (fahr-32.0);printf("%3.0f %6.1f\n", fahr, celsius);fahr = fahr + step;

}

4 simple statements

1 compound statement

Page 19: C Program Design Introduction to C Programming 主講人:虞台文

If-Else Statement

if (expression)

statement1

else

statement2

Page 20: C Program Design Introduction to C Programming 主講人:虞台文

If-Else Statement

if (expression)

statement1

else

statement2

expression

If expression is evaluated to true (nonzero),

statement1 is executed;

otherwise, statement2 is executed.

If expression is evaluated to true (nonzero),

statement1 is executed;

otherwise, statement2 is executed.

startstart

endend

expressionexpression

statement1statement1 statement2

statement2

true false

Page 21: C Program Design Introduction to C Programming 主講人:虞台文

If-Else Statement

if (expression)

statement1

else

statement2

expressionstartstart

endend

expressionexpression

statement1statement1 statement2

statement2

true false

option

Page 22: C Program Design Introduction to C Programming 主講人:虞台文

If-Statement

if (expression)

statement

expressionstartstart

endend

expressionexpression

statementstatement

true

false

Page 23: C Program Design Introduction to C Programming 主講人:虞台文

範例 : Decision Making (I)// pass1.cpp#include <cstdlib>#include <iostream>

using namespace std;

int main(int argc, char *argv[]){ int threshold = 75; int score; cout << "Enter your score, please\n"; cin >> score; if (score >= threshold){ cout << "Incredible, you passed with a merit\n"; }

system("PAUSE"); return 0;}

// pass1.cpp#include <cstdlib>#include <iostream>

using namespace std;

int main(int argc, char *argv[]){ int threshold = 75; int score; cout << "Enter your score, please\n"; cin >> score; if (score >= threshold){ cout << "Incredible, you passed with a merit\n"; }

system("PAUSE"); return 0;}

Page 24: C Program Design Introduction to C Programming 主講人:虞台文

範例 : Decision Making (II)// pass2.cpp#include <cstdlib>#include <iostream>

using namespace std;

int main(int argc, char *argv[]){ int threshold = 75; int score; cout << "Enter your score, please\n"; cin >> score; if (score >= threshold){ cout << "Incredible, you passed with a merit\n"; } else{ cout << "You failed, unlucky\n"; } system("PAUSE"); return 0;}

// pass2.cpp#include <cstdlib>#include <iostream>

using namespace std;

int main(int argc, char *argv[]){ int threshold = 75; int score; cout << "Enter your score, please\n"; cin >> score; if (score >= threshold){ cout << "Incredible, you passed with a merit\n"; } else{ cout << "You failed, unlucky\n"; } system("PAUSE"); return 0;}

Page 25: C Program Design Introduction to C Programming 主講人:虞台文

While-Statement

while(expression)

statement

expressionstartstart

endendexpressionexpression

statementstatement

true

false

Page 26: C Program Design Introduction to C Programming 主講人:虞台文

範例:華氏攝氏

59 ( 32)C F

Page 27: C Program Design Introduction to C Programming 主講人:虞台文

範例:華氏攝氏59 ( 32)C F

Page 28: C Program Design Introduction to C Programming 主講人:虞台文

範例:華氏攝氏59 ( 32)C F

#include <cstdlib>#include <iostream>

using namespace std;

/* print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300 */int main(int argc, char *argv[]){ int fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature scale */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; cout << fahr << "\t" << celsius << endl; fahr = fahr + step; }

system("PAUSE"); return 0; }

#include <cstdlib>#include <iostream>

using namespace std;

/* print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300 */int main(int argc, char *argv[]){ int fahr, celsius; int lower, upper, step; lower = 0; /* lower limit of temperature scale */ upper = 300; /* upper limit */ step = 20; /* step size */ fahr = lower; while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; cout << fahr << "\t" << celsius << endl; fahr = fahr + step; }

system("PAUSE"); return 0; }

Page 29: C Program Design Introduction to C Programming 主講人:虞台文

練習1. Using

2. Redo the same task but with the starting number, ending number, and step being given by a user.

Page 30: C Program Design Introduction to C Programming 主講人:虞台文

練習3. Write a C program which asks a user to input a

positive integer. The program then reports the minimum factor of that number in 2, 3, 5, 7, 11 if available. Otherwise, reports “fail to find any factor in 2, 3, 5, 7, 11.”

4. The same as above, but the program reports all factors of that number in 2, 3, 5, 7, 11.

5. The same as above, but the program reports all possible factors of that number.

Page 31: C Program Design Introduction to C Programming 主講人:虞台文

C Program DesignIntroduction to C Programming

邏輯運算子(Logical Operators)

Page 32: C Program Design Introduction to C Programming 主講人:虞台文

Logical Operators

&& ( logical AND ) – Returns true if both conditions are true

|| ( logical OR ) – Returns true if either of its conditions are

true

! ( logical NOT, logical negation )– Reverses the truth/falsity of its condition– Unary operator, has one operand

Page 33: C Program Design Introduction to C Programming 主講人:虞台文

Truth Tables expression1 expression2 expression1 && expression2

0 0 0

0 nonzero 0

nonzero 0 0

nonzero nonzero 1

expression1 expression2 expression1 || expression2

0 0 0

0 nonzero 1

nonzero 0 1

nonzero nonzero 1

expression !expression

0 1

nonzero 0

Page 34: C Program Design Introduction to C Programming 主講人:虞台文

Examples

if((celsius >= 25.0) && (celsius <= 28.0))printf("It is very comfortable\n");

if((celsius >= 25.0) && (celsius <= 28.0))printf("It is very comfortable\n");

if((celsius < 20.0) || (celsius > 32.0))printf("It is bad\n");

elseprintf("It is comfortable\n");

if((celsius < 20.0) || (celsius > 32.0))printf("It is bad\n");

elseprintf("It is comfortable\n");

if(!(celsius <= 18.0))printf("It is not very cold\n");

elseprintf("It is better to take a jacket\

n");

if(!(celsius <= 18.0))printf("It is not very cold\n");

elseprintf("It is better to take a jacket\

n");

Page 35: C Program Design Introduction to C Programming 主講人:虞台文

注意事項

int total, count;. . . . . . . . .if(total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

count若為零將產生divide by zero 之exception.

Page 36: C Program Design Introduction to C Programming 主講人:虞台文

注意事項int total, count;. . . . . . . . .if(total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(total / count >= 60 && count > 0)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(total / count >= 60 && count > 0)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(count > 0 && total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(count > 0 && total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

Why?

Page 37: C Program Design Introduction to C Programming 主講人:虞台文

注意事項int total, count;. . . . . . . . .if(total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(total / count >= 60)

printf("Passed\n");else

printf("Failed\n");

int total, count;. . . . . . . . .if(total / count < 60 || count == 0)

printf("Failed\n");else

printf("Passed\n");

int total, count;. . . . . . . . .if(total / count < 60 || count == 0)

printf("Failed\n");else

printf("Passed\n");

int total, count;. . . . . . . . .if(count == 0 || total / count < 60)

printf("Failed\n");else

printf("Passed\n");

int total, count;. . . . . . . . .if(count == 0 || total / count < 60)

printf("Failed\n");else

printf("Passed\n");

Why?

Page 38: C Program Design Introduction to C Programming 主講人:虞台文

練習main(){ int x=1,y=2,z=3; int p,q; p = (x>y) && (z<y); /* False i.e. 0 */ q = (y>x) || (y>z); /* True i.e. 1 */ printf(" %d && %d = %d\n",p,q,p&&q); printf(" %d || %d = %d\n",p,q,p||q); /* Can mix "logical" values and arithmetic */ printf(" %d && %d = %d\n",x,q,x&&q); printf(" %d || %d = %d\n",p,y,p||y); /* Exercise the NOT operator */ printf(" ! %d = %d\n",p,!p); printf(" ! %d = %d\n",q,!q); /* NOT operator applied to arithmetic */ printf(" ! %d = %d\n",z,!z);}

main(){ int x=1,y=2,z=3; int p,q; p = (x>y) && (z<y); /* False i.e. 0 */ q = (y>x) || (y>z); /* True i.e. 1 */ printf(" %d && %d = %d\n",p,q,p&&q); printf(" %d || %d = %d\n",p,q,p||q); /* Can mix "logical" values and arithmetic */ printf(" %d && %d = %d\n",x,q,x&&q); printf(" %d || %d = %d\n",p,y,p||y); /* Exercise the NOT operator */ printf(" ! %d = %d\n",p,!p); printf(" ! %d = %d\n",q,!q); /* NOT operator applied to arithmetic */ printf(" ! %d = %d\n",z,!z);}

1. 預測以下程式將產生何種結果2. 實作以下程式視預測是否正確

Page 39: C Program Design Introduction to C Programming 主講人:虞台文

C Program DesignIntroduction to C Programming

巨集The #define Preprocessor

Page 40: C Program Design Introduction to C Programming 主講人:虞台文

#define

#include <stdio.h>#define PI 3.14159main(){ double radius;

printf("Enter the radius of a circle:"); scanf("%lf", &radius);

printf("The perimeter of the circle: %lf\n", 2.0 * PI * radius);

printf("The area of the circle: %lf\n", PI * radius * radius);

}

#include <stdio.h>#define PI 3.14159main(){ double radius;

printf("Enter the radius of a circle:"); scanf("%lf", &radius);

printf("The perimeter of the circle: %lf\n", 2.0 * PI * radius);

printf("The area of the circle: %lf\n", PI * radius * radius);

}

for text substitution