SlideShare a Scribd company logo
1 of 19
Download to read offline
Lesson 2
Functions, scanf and EOF
Introduction to Computer and Program Design
James C.C. Cheng
Department of Computer Science
National Chiao Tung University
The return of scanf
 The number of fields successfully converted and assigned
 In the case of an input failure before any data could be successfully
read, EOF is returned.
2
int a =1, b =2, c =3;
int n = scanf("%d %d %d", &a, &b, &c);
printf("%dn", n );
printf("%d, %d, %d", a, b, c);
Multiple input
 EOF: end of file
 usually EOF is defined as (-1)
 It is a signal to tell the system that no more data can be read from a
input source.
 In Windows, press Ctrl+Z and Enter
 In UNIX, Linux and Mac OS X, press Ctrl+D
3
int x = 0;
while( scanf("%d", &x) != EOF ){
…
}
Abnormal Input
 Please input a non-numeric line, ex: %T@#$@KI
 A non-stop loop occurred! Why?
 How to fix the problem?
4
int x = 0;
while( scanf("%d", &x) != EOF ){
…
}
Standard I/O Buffer
 Buffer:
 A memory block used to temporarily hold data while it is being moved
from one place to another.
 There three I/O memory buffers in the computer
 FILE* stdin : For the standard input device (generally, a keyboard).
 FILE* stdout : For the standard output device (generally, the screen).
 FILE* stderr : For output error and warning messages to the standard
output device
5
FILE* is a pointer to point a stream I/O buffer
0x 26E81E00
FILE* stdin
address data
26E81E00 04 A5 00 10
26E81E04 0B 00 56 4F
26E81E08 06 FF 00 00
26E81E0C B4 00 C7 FF
… …
6
The Reading Mechanism of scanf -- 1
 In the format string of scanf:
 Format specifiers (%):
 A sequence formed by an initial percentage sign (%) indicates a format specifier,
which is used to specify the type and format of the data to be retrieved from stdin
and stored in the locations pointed by the additional arguments.
 The basic usage of format specifier:
%[*][l]type
where type can be c, d, e, E, f, g, G, o, s, x, X
EX: %d
 Read but ignored
%*type
int x = 0;
while( scanf("%*d%d", &x) != EOF ){
printf("%dn", x); // ?
}
The basic data types
 There are 13 basic data types in C
 In C++, bool represents boolean value, true or false.
 The size of bool depends on compiler, 1 byte in most case. 7
Name Size (byte) Range
char 1 -128 to 127
unsigned char 1 0 to 255
short 2 -32768 to 32767
unsigned short 2 0 to 65535
int 4 -231 to 231 - 1
unsigned int 4 0 to 232 - 1
long 4 -231 to 231 - 1
unsigned long 4 0 to 232 - 1
__int64, long long 8 -263 to 263 – 1
unsigned __int64 8 0 to 264 - 1
float 4 ±(1.175494351e-38 to 3.402823466e38 )
double 8 ±(2.2250738585072014e-308 to
1.7976931348623158e308 )
long double 12 in DevC++, 8 in MSC The same as double
The type of format specifier
8
type Qualifying Input Type of argument
c
Single character: Reads the next character. If a width
different from 1 is specified, the function reads width
characters and stores them in the successive locations
of the array passed as argument. No null character is
appended at the end.
char *
d
Decimal integer: Number optionally preceded with a + or
- sign.
int *
e,E,f,g,G
Floating point: Decimal number containing a decimal
point, optionally preceded by a + or - sign and optionally
folowed by the e or E character and a decimal number.
Two examples of valid entries are -732.103 and 7.12e4
float *
o Octal integer. int *
s
String of characters. This will read subsequent
characters until a whitespace is found (whitespace
characters are considered to be blank, newline and tab).
char *
u Unsigned decimal integer. unsigned int *
x,X Hexadecimal integer. int *
9
The Reading Mechanism of scanf -- 2
 It starts after one string line inputted.
 a string which the last key is n
 In the format string of scanf:
 White-space characters, WC:
 blank (' '); tab ('t'); or newline ('n').
 一連串的WC可視為一個 WC
 一個在format string 的WC代表它可吸收零個以上的WC輸入
 輸入數值型態的資料時,前面可以鍵入零個以上的WC.
 The non-WCs in format, except the ’%’
 scanf 會從stdin 依輸入順序讀取字元,然後依序與format string 的非WC字元比較.
 若比較相同,輸入字元discarded,繼續下一字元.
 若比較不相同,scanf 失敗並結束,stdin剩下的資料包含現在比較失敗的字元都會
留在stdin
10
Standard Input in C
 How to clear the stdin?
 getchar()
 read a character from stdin
 Usage:
 #include <stdio.h>
 int getchar( void );
 Returns the input character
 Ex:
 int c = getchar();
 Using getchar() to clear stdin
int x=0;
scanf("%d", &x);
printf("%dn", x);
{ int c; while((c=getchar())!='n'&&c!=EOF); } // clear stdin
printf("press enter to exit");
getchar(); // Waiting an Enter key
EOF in Windows
 Ctrl + z (^Z) in Windows:
 ^Z要搭配n才有意義
 按下^Z之後可一連串按下任意鍵再按下n皆等同按下^Zn,如
^Z!@#!@$!$!@n等同^Zn甚至^Z後面接一堆空格再加n也等同^Zn
 他要能被當成EOF,之前除了一連串的n或^Z,不可按其它任何鍵。否
則按下n後是代表Substitute這個字元,ASCII code是26
 當要成為EOF前,^Z不產生任何ASCII code
 下列程式碼, ^Zn需按下兩次才能結束程式,為什麼?
11
int x=0, y=0;
while( scanf(" %d%d", &x, &y) != EOF ){
printf("%d, %dn", x, y);
}
a white space
EOF in Windows
 DO NOT let the last character of the format string be a WC
12
int x=0;
while( scanf("%d ", &x) != EOF ){
printf("%dn", x);
}
a white space
Exercises
 請根據指示輸入資料,並解釋為何會出現畫面上的結果?
13
int x=0, y=0;
while( scanf("%d,%d", &x, &y) != EOF ){
printf("%d, %dn", x, y);
}
int x=0, y=0;
while( scanf("%d , %d", &x, &y) != EOF ){
printf("%d, %dn", x, y);
}
請輸入下列資料:
1,2
3 ,4
5, 6
7 , 8
9 10
int x=0, y=0;
while( scanf("%d ,%d", &x, &y) != EOF ){
printf("%d, %dn", x, y);
}
14
Function declaration
 Syntax:
return type + function name + (parameters);
where the parameters are:
1. nothing or void
2. typename1, typename2, … typenameN
3. the names of parameters are not necessary
 Function name must be unique , except C++.
 Ex:
int F1(void);
int F2();
void F3(void);
void F3(int); // In C++, OK, but error in C
int F4(int, int, char);
or
int F4(int x, int y , char c);
15
Function declaration
 In C++, the function declaration must be placed before calling
int main( void ){
int MyF(int); // declaration
int x = 0;
printf("%dn", MyF(x));
return 0;
}
int MyF(int n){ return n+1 ;} // Function definition
16
Function definition
 Function definition
 Syntax:
return type + function name + (parameters){ … }
where the name of the parameters not be ignored.
 Function definition can not be placed in any block (except C++).
int MyF(int n){
return n+1 ;
}
17
Function definition
 Declaration, definition and invocation.
 Which of following are correct?
 In C, all of them are correct
 implicit declaration and the function is assumed to return int
 In C++, the third is failed
int MyF (int a);
int MyF(int a){ return a+1; }
int main( void ){
int x = MyF (1);
printf("1+1 = %dn", x);
return 0;
}
int MyF (int a);
int main( void ){
int x = MyF (1);
printf("1+1 = %dn", x);
return 0;
}
int MyF (int a){ return a+1;}
int main( void ){
int x = MyF (1);
printf("1+1 = %dn", x);
return 0;
}
int MyF (int a);
int MyF (int a){ return a+1; }
int MyF (int a){ return a+1; }
int main( void ){
int x = MyF (1);
printf("1+1 = %dn", x);
return 0;
}
int MyF (int a);
int MyF (int a){ return a+1; }
int MyF (int a);
int main( void ){
int x = MyF (1);
printf("1+1 = %dn", x);
return 0;
}
int MyF (int a){ return a+1; }
int main( void ){
int x = MyF (1);
printf("1+1 = %dn", x);
return 0;
}
Function definition
 Default argument
 Only C++ provides default argument for functions
 A default argument is a value given in the declaration that the compiler
automatically inserts if you don’t provide a value in the function call.
 A default argument cannot be placed before non-default argument
 The declaration of a default argument either in global function
declaration or in function definition.
 Local function declaration can has its own default argument list.
18
void F1(int a, int b =10, int c = 2){ … }
void F2(int a, int b =10, int c){ … } // Compiler error
void F3(int a, int b =10, int c=5); // Global function declaration
void F3(int a, int b =10, int c=5){ … } // Compiler error
int main(){
F1(1, 2, 3); // a = 1; b= 2; c =3
F1(1); // a = 1; b= 10; c =2
void F1(int a, int b =20, int c = 30); // Local function declaration
F1(1); // a = 1; b= 20; c =30
F1(1, ,3); // Compiler error
}
練習題
1. 設計一個function,名稱為CheckN
int CheckN(int n);
若 n > 0 且任兩個連續的digit相加皆相同,則return任兩個連續的digit之和,反
之return 0。10<=n<100則return兩個digit之和,n<10則return0。注意,不可
用字串處理方式。
2. 設計一個function,名稱為TileN
int TileN(int RoomW, int RoomH, int TileW, int TileH);
RoomW及RoomH: 分別代表房間的寬及長(公分)
TileW及TileH : 分別代表地磚的寬及長(公分)
假設地磚不可分割,所有地磚排列方式需一致,則TileN會return 該房間可貼的
最多地磚數量。
3. 設計一個function,名稱為IsPrime
int IsPrime(int n);
根據右列的理論來判斷n是否為質數
若n為質數,return 1,反之return 0 19
If n = ab, a <= b.
Assuming that a > . .
Then, n = ab >= aa > n causes contrary.
Therefore, a <= n
n

More Related Content

Similar to Funções, Scanf, EOF

C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
Amit Kapoor
 
Intro to c chapter cover 1 4
Intro to c chapter cover 1 4Intro to c chapter cover 1 4
Intro to c chapter cover 1 4
Hazwan Arif
 

Similar to Funções, Scanf, EOF (20)

Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
Cbasic
CbasicCbasic
Cbasic
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
2. operator
2. operator2. operator
2. operator
 
What is c
What is cWhat is c
What is c
 
C tutorial
C tutorialC tutorial
C tutorial
 
UNIT-II CP DOC.docx
UNIT-II CP DOC.docxUNIT-II CP DOC.docx
UNIT-II CP DOC.docx
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt
 
Cbasic
CbasicCbasic
Cbasic
 
Cbasic
CbasicCbasic
Cbasic
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Intro to c chapter cover 1 4
Intro to c chapter cover 1 4Intro to c chapter cover 1 4
Intro to c chapter cover 1 4
 
Functions
FunctionsFunctions
Functions
 
C Programming Language
C Programming LanguageC Programming Language
C Programming Language
 

Recently uploaded

Recently uploaded (20)

WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
WSO2CON 2024 - Not Just Microservices: Rightsize Your Services!
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in Uganda
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAMWSO2Con2024 - Organization Management: The Revolution in B2B CIAM
WSO2Con2024 - Organization Management: The Revolution in B2B CIAM
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AIWSO2CON 2024 Slides - Unlocking Value with AI
WSO2CON 2024 Slides - Unlocking Value with AI
 

Funções, Scanf, EOF

  • 1. Lesson 2 Functions, scanf and EOF Introduction to Computer and Program Design James C.C. Cheng Department of Computer Science National Chiao Tung University
  • 2. The return of scanf  The number of fields successfully converted and assigned  In the case of an input failure before any data could be successfully read, EOF is returned. 2 int a =1, b =2, c =3; int n = scanf("%d %d %d", &a, &b, &c); printf("%dn", n ); printf("%d, %d, %d", a, b, c);
  • 3. Multiple input  EOF: end of file  usually EOF is defined as (-1)  It is a signal to tell the system that no more data can be read from a input source.  In Windows, press Ctrl+Z and Enter  In UNIX, Linux and Mac OS X, press Ctrl+D 3 int x = 0; while( scanf("%d", &x) != EOF ){ … }
  • 4. Abnormal Input  Please input a non-numeric line, ex: %T@#$@KI  A non-stop loop occurred! Why?  How to fix the problem? 4 int x = 0; while( scanf("%d", &x) != EOF ){ … }
  • 5. Standard I/O Buffer  Buffer:  A memory block used to temporarily hold data while it is being moved from one place to another.  There three I/O memory buffers in the computer  FILE* stdin : For the standard input device (generally, a keyboard).  FILE* stdout : For the standard output device (generally, the screen).  FILE* stderr : For output error and warning messages to the standard output device 5 FILE* is a pointer to point a stream I/O buffer 0x 26E81E00 FILE* stdin address data 26E81E00 04 A5 00 10 26E81E04 0B 00 56 4F 26E81E08 06 FF 00 00 26E81E0C B4 00 C7 FF … …
  • 6. 6 The Reading Mechanism of scanf -- 1  In the format string of scanf:  Format specifiers (%):  A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from stdin and stored in the locations pointed by the additional arguments.  The basic usage of format specifier: %[*][l]type where type can be c, d, e, E, f, g, G, o, s, x, X EX: %d  Read but ignored %*type int x = 0; while( scanf("%*d%d", &x) != EOF ){ printf("%dn", x); // ? }
  • 7. The basic data types  There are 13 basic data types in C  In C++, bool represents boolean value, true or false.  The size of bool depends on compiler, 1 byte in most case. 7 Name Size (byte) Range char 1 -128 to 127 unsigned char 1 0 to 255 short 2 -32768 to 32767 unsigned short 2 0 to 65535 int 4 -231 to 231 - 1 unsigned int 4 0 to 232 - 1 long 4 -231 to 231 - 1 unsigned long 4 0 to 232 - 1 __int64, long long 8 -263 to 263 – 1 unsigned __int64 8 0 to 264 - 1 float 4 ±(1.175494351e-38 to 3.402823466e38 ) double 8 ±(2.2250738585072014e-308 to 1.7976931348623158e308 ) long double 12 in DevC++, 8 in MSC The same as double
  • 8. The type of format specifier 8 type Qualifying Input Type of argument c Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end. char * d Decimal integer: Number optionally preceded with a + or - sign. int * e,E,f,g,G Floating point: Decimal number containing a decimal point, optionally preceded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4 float * o Octal integer. int * s String of characters. This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab). char * u Unsigned decimal integer. unsigned int * x,X Hexadecimal integer. int *
  • 9. 9 The Reading Mechanism of scanf -- 2  It starts after one string line inputted.  a string which the last key is n  In the format string of scanf:  White-space characters, WC:  blank (' '); tab ('t'); or newline ('n').  一連串的WC可視為一個 WC  一個在format string 的WC代表它可吸收零個以上的WC輸入  輸入數值型態的資料時,前面可以鍵入零個以上的WC.  The non-WCs in format, except the ’%’  scanf 會從stdin 依輸入順序讀取字元,然後依序與format string 的非WC字元比較.  若比較相同,輸入字元discarded,繼續下一字元.  若比較不相同,scanf 失敗並結束,stdin剩下的資料包含現在比較失敗的字元都會 留在stdin
  • 10. 10 Standard Input in C  How to clear the stdin?  getchar()  read a character from stdin  Usage:  #include <stdio.h>  int getchar( void );  Returns the input character  Ex:  int c = getchar();  Using getchar() to clear stdin int x=0; scanf("%d", &x); printf("%dn", x); { int c; while((c=getchar())!='n'&&c!=EOF); } // clear stdin printf("press enter to exit"); getchar(); // Waiting an Enter key
  • 11. EOF in Windows  Ctrl + z (^Z) in Windows:  ^Z要搭配n才有意義  按下^Z之後可一連串按下任意鍵再按下n皆等同按下^Zn,如 ^Z!@#!@$!$!@n等同^Zn甚至^Z後面接一堆空格再加n也等同^Zn  他要能被當成EOF,之前除了一連串的n或^Z,不可按其它任何鍵。否 則按下n後是代表Substitute這個字元,ASCII code是26  當要成為EOF前,^Z不產生任何ASCII code  下列程式碼, ^Zn需按下兩次才能結束程式,為什麼? 11 int x=0, y=0; while( scanf(" %d%d", &x, &y) != EOF ){ printf("%d, %dn", x, y); } a white space
  • 12. EOF in Windows  DO NOT let the last character of the format string be a WC 12 int x=0; while( scanf("%d ", &x) != EOF ){ printf("%dn", x); } a white space
  • 13. Exercises  請根據指示輸入資料,並解釋為何會出現畫面上的結果? 13 int x=0, y=0; while( scanf("%d,%d", &x, &y) != EOF ){ printf("%d, %dn", x, y); } int x=0, y=0; while( scanf("%d , %d", &x, &y) != EOF ){ printf("%d, %dn", x, y); } 請輸入下列資料: 1,2 3 ,4 5, 6 7 , 8 9 10 int x=0, y=0; while( scanf("%d ,%d", &x, &y) != EOF ){ printf("%d, %dn", x, y); }
  • 14. 14 Function declaration  Syntax: return type + function name + (parameters); where the parameters are: 1. nothing or void 2. typename1, typename2, … typenameN 3. the names of parameters are not necessary  Function name must be unique , except C++.  Ex: int F1(void); int F2(); void F3(void); void F3(int); // In C++, OK, but error in C int F4(int, int, char); or int F4(int x, int y , char c);
  • 15. 15 Function declaration  In C++, the function declaration must be placed before calling int main( void ){ int MyF(int); // declaration int x = 0; printf("%dn", MyF(x)); return 0; } int MyF(int n){ return n+1 ;} // Function definition
  • 16. 16 Function definition  Function definition  Syntax: return type + function name + (parameters){ … } where the name of the parameters not be ignored.  Function definition can not be placed in any block (except C++). int MyF(int n){ return n+1 ; }
  • 17. 17 Function definition  Declaration, definition and invocation.  Which of following are correct?  In C, all of them are correct  implicit declaration and the function is assumed to return int  In C++, the third is failed int MyF (int a); int MyF(int a){ return a+1; } int main( void ){ int x = MyF (1); printf("1+1 = %dn", x); return 0; } int MyF (int a); int main( void ){ int x = MyF (1); printf("1+1 = %dn", x); return 0; } int MyF (int a){ return a+1;} int main( void ){ int x = MyF (1); printf("1+1 = %dn", x); return 0; } int MyF (int a); int MyF (int a){ return a+1; } int MyF (int a){ return a+1; } int main( void ){ int x = MyF (1); printf("1+1 = %dn", x); return 0; } int MyF (int a); int MyF (int a){ return a+1; } int MyF (int a); int main( void ){ int x = MyF (1); printf("1+1 = %dn", x); return 0; } int MyF (int a){ return a+1; } int main( void ){ int x = MyF (1); printf("1+1 = %dn", x); return 0; }
  • 18. Function definition  Default argument  Only C++ provides default argument for functions  A default argument is a value given in the declaration that the compiler automatically inserts if you don’t provide a value in the function call.  A default argument cannot be placed before non-default argument  The declaration of a default argument either in global function declaration or in function definition.  Local function declaration can has its own default argument list. 18 void F1(int a, int b =10, int c = 2){ … } void F2(int a, int b =10, int c){ … } // Compiler error void F3(int a, int b =10, int c=5); // Global function declaration void F3(int a, int b =10, int c=5){ … } // Compiler error int main(){ F1(1, 2, 3); // a = 1; b= 2; c =3 F1(1); // a = 1; b= 10; c =2 void F1(int a, int b =20, int c = 30); // Local function declaration F1(1); // a = 1; b= 20; c =30 F1(1, ,3); // Compiler error }
  • 19. 練習題 1. 設計一個function,名稱為CheckN int CheckN(int n); 若 n > 0 且任兩個連續的digit相加皆相同,則return任兩個連續的digit之和,反 之return 0。10<=n<100則return兩個digit之和,n<10則return0。注意,不可 用字串處理方式。 2. 設計一個function,名稱為TileN int TileN(int RoomW, int RoomH, int TileW, int TileH); RoomW及RoomH: 分別代表房間的寬及長(公分) TileW及TileH : 分別代表地磚的寬及長(公分) 假設地磚不可分割,所有地磚排列方式需一致,則TileN會return 該房間可貼的 最多地磚數量。 3. 設計一個function,名稱為IsPrime int IsPrime(int n); 根據右列的理論來判斷n是否為質數 若n為質數,return 1,反之return 0 19 If n = ab, a <= b. Assuming that a > . . Then, n = ab >= aa > n causes contrary. Therefore, a <= n n