Introduction to Computer Programming (C language) - Chapter 2: C Program Structure and its Components - Võ Thị Ngọc Châu
Bạn đang xem 20 trang mẫu của tài liệu "Introduction to Computer Programming (C language) - Chapter 2: C Program Structure and its Components - Võ Thị Ngọc Châu", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên
Tài liệu đính kèm:
- introduction_to_computer_programming_c_language_chapter_2_c.pdf
Nội dung text: Introduction to Computer Programming (C language) - Chapter 2: C Program Structure and its Components - Võ Thị Ngọc Châu
- Ho Chi Minh City University of Technology Faculty of Computer Science and Engineering Chapter 2: C Program Structure and its Components Introduction to Computer Programming (C language) TS. Võ Thị Ngọc Châu (chauvtn@cse.hcmut.edu.vn, chauvtn@hcmut.edu.vn) 2017 – 2018, Semester 2
- Course Content C.1. Introduction to Computers and Programming C.2. C Program Structure and its Components C.3. Variables and Basic Data Types C.4. Selection Statements C.5. Repetition Statements C.6. Functions C.7. Arrays C.8. Pointers C.9. File Processing 2
- References [1] ―C: How to Program”, 7th Ed. – Paul Deitel and Harvey Deitel, Prentice Hall, 2012. [2] “The C Programming Language”, 2nd Ed. – Brian W. Kernighan and Dennis M. Ritchie, Prentice Hall, 1988 and others, especially those on the Internet 3
- Content Introduction A Sample C Program Coding Styles Data and Standard Output Function Data and Standard Input Function Data Processing: Simple Example Summary 4
- Introduction ―In our experience, C has proven to be a pleasant, expressive, and versatile language for a wide variety of programs. It is easy to learn, and it wears well as one’s experience with it grows.‖ [2], Brian W. Kernighan and Dennis M. Ritchie versatile = able to be used for many different purposes 5
- Introduction Design of Library Library program (Header: *.h) (Object code: *.lib; *.dll; *.so) Editor Preprocessor Compiler Linker Executable Program Source code Enhanced source code Object code *.h + *.c *.h + *.c (*.cpp) *.obj (*.cpp) gcc; g++ Integrated Development Environment (IDE): Visual Studio; Eclipse; Qt Creator; Code block; Online tool; etc Programming tasks using the C language 6
- Introduction Design of Library Library program (Header: *.h) (Object code: *.lib; *.dll; *.so) Editor Preprocessor Compiler Linker Executable Program Source code Enhanced source code Object code *.h + *.c *.h + *.c (*.cpp) *.obj (*.cpp) gcc; g++ Integrated Development Environment (IDE): Visual Studio; Eclipse; Qt Creator; Code block; Online tool; etc Programming tasks using the C language 7
- A Sample C Program A source code file named C2_example1.c Purpose: display our university’s name and course’s name on the screen 8
- A Sample C Program A source code file named C2_example1.c Purpose: display our university’s name and course’s name on the screen 9
- A Sample C Program Every C program requires the specific function named ―main‖ exactly. The body of the ―main‖ function is enclosed in the brackets { }. The body of the The specific ―main‖ function is A source code file named C2_example1.c extension of made to serve the C source specific purpose. Purpose: display our university’s name code files and course’s name on the screen 10
- A Sample C Program A directive to the C preprocessor before the program is compiled. is used for standard input/output library functions such as the output function printf() and the input function scanf(). This global definition section is used for external headers. Comments in /* */ or after // A source code file named C2_example1.c Purpose: display our university’s name and course’s name on the screen 11
- A Sample C Program File name: following the naming conventions supported by the OS with the .c extension Not include some special symbols: *, /, \, Avoid using special symbols even if they are allowed Prefer descriptive names The ―main‖ function All the files and libraries are compiled into a single executable program file with exactly one ―main‖ function. The starting point for the execution of a C program Note: The C language is case-sensitive. MAIN vs. Main vs. main 12
- A Sample C Program The ―main‖ function void main(){ Open bracket ―{― to start the body section } Corresponding close bracket ―}― to end the body section int main(void){ } Place for specifying the parameters of the function Empty or void: no parameter is specified Data type of the value returned by the ―main‖ function int: a status value: 0 = no error; 1 = error EXIT_SUCCESS = 0; EXIT_FAILURE = 1 void: no value is returned 13
- A Sample C Program The ―main‖ function void main(){ printf("Ho Chi Minh City University of Technology\n"); statement printf("Introduction to Computer Programming\n"); statement } Each statement - ended with a semicolon (;) - stretched on multiple lines with a backslash \ at the end - able to be grouped in the brackets {} - not consider spaces Several statement types - sequence: function calling, assignment, break, continue, return, - selection: if, if else, switch - repetition: for, while, do while 14
- A Sample C Program In addition to ―main‖, there are keywords/reserved words in the C language. [1], p. 42 15
- A Sample C Program The global definition section Lines beginning with # The #include directive tells the preprocessor to include the contents of another file. . #include ―myHeader.h‖ . A personal header file in the current directory . #include . A standard library file in the standard directory \include The #define directive to set up symbolic replacements The #if test at compile-time to look at the symbols in #define and turn on and off which lines the compiler uses Function prototypes to validate function calls Global variable declarations 16
- A Sample C Program Comments /* */: multi-line comment // : single-line comment 17
- A Sample C Program How to get the program run for the specified purpose? *.c => a machine code file (e.g. *.exe) A source code file named C2_example1.c Purpose: display our university’s name and course’s name on the screen 18
- A Sample C Program Edit: C2_example1.c Compile: gcc –Wall C2_example1.c –o C2_example1 -Wall: display all the warning types along with the errors if any -o C2_example1: specify a name for the resulting executable program Run: C2_example1 19
- A Sample C Program GCC = GNU Compiler Collection The free GNU C++: gcc.gnu.org/install/ binaries.html GCC is available for most platforms, including Linux, Mac OS X (via Xcode) and Windows—via tools like Cygwin (www.cygwin.com) and MinGW (www.mingw.org) Free IDEs: Micrsoft Visual Studio Express Editions, CodeBlock, Dev C++, 20
- Coding Styles Which (A) one do you prefer? (B) (C) 21
- Coding Styles The three different formatted examples for the same purpose return the same result: What problems might we face with (A)? What problems might we face with (B)? What problems might we face with (C)? What else if the program is not defined with just a few lines; instead, with thousands of lines? 22
- Coding Styles Alignment Statements are aligned level by level based on the block {} that they are contained. Separation (White space) Each statement should placed on a single line. Blank lines should be used for more clarity. Comment A comment is added at any level for explanation, marking, tracking, Comments from the pseudo code helpful for program development Never abuse comments to make a program clear 23
- Coding Styles Naming conventions Descriptive Classified Consistent Agreements if any Easy to remember, easy to be referred, easy to be communicated Less error-prone 24
- Coding Styles Naming conventions What can you name in a C program except file names? Function: your defined modular processing unit Variable: a location in memory where a value can be stored for use by a program Symbolic constant: constant represented as a symbol (a string) that will be replaced with the value it stands for A name should reflect the content and role of the thing you define in a C program. 25
- Coding Styles Naming conventions Create a name made up of at most 31 letters, digits, underscore ―_‖ and starting with a letter Consider verbs, nouns, phrases, Consider a length of each name: short/long Consider lower-case/upper-case letters Consider prefix/suffix parts Function: verb, phrase Variable: noun, lower-case letters, short for loops . Global variable: prefix g_ . Data type: suffix _ptr for pointers Symbolic constant: upper-case letters, underscores 26
- Coding Styles Should Should not X check_for_errors() error_checking() dump_data_to_file() is_any_upper_case() any_upper_case_test() get_an_upper_case() return_an_upper_case() set_first_upper_case() change_first_upper_case() Student *student_prt; Student * student; int g_thread_number; int thread_number; static const double PI static const double Pi = = 3.14; 3.14; #define SIZE 10 #define size 10 27
- Coding Styles How to make the following program clearer? 28
- Coding Styles How to make the following program clearer? 29
- Coding Styles Check your naming conventions in your pseudo code How many names would you like to rename? What else have you changed on your pseudo code? How clearer is your pseudo code? 30
- Coding Styles Practice the formatting rules and conventions to be part of your own coding habit Make sure that your submitted programs are always well-formatted Make sure that your future programs are readable, interpretable, able to be maintained, reused, and extended More information about coding styles at: 31
- Data and Standard Output Function Standard output function: printf() #include Output the data to the standard output stream A sequence of bytes flows from main memory to an output device: display screen, printer, disk drive, network connection, and so on. Normally and automatically, the standard output stream is connected to the screen. Examples: 32
- Data and Standard Output Function Formatting capabilities of the printf function Rounding floating-point values to an indicated number of decimal places. Aligning a column of numbers with decimal points appearing one above the other. Right justification and left justification of outputs. Inserting literal characters at precise locations in a line of output. Representing floating-point numbers in exponential format. Representing unsigned integers in octal and hexadecimal format. Displaying all types of data with fixed-size field widths and precisions. 33
- Data and Standard Output Function - format-control-string describes the output format. - other-arguments (optional) correspond to each conversion specification in format-control-string. Each conversion specification begins with a percent sign (%) and ends with a conversion specifier. There can be many conversion specifications in one format control string. Examples: The 1st conversion specification: %5.2f => argument: x nd The 2 conversion specification: %5.2f => argument: y 34
- Data and Standard Output Function format-control-string is summarized as follows: %[flag][width][.precision]specifier specifier = d/i, u, o, x/X, f/F, e/E, g/G, a/A, c, s, p, n, % precision = .number, .* width = number, * flag = +, -, space, #, 0 35
- Data and Standard Output Function 36
- Data and Standard Output Function c Display a character. s Display a sequence of characters until a terminating null \0 character is encountered. 37
- Data and Standard Output Function Flags to supplement its output formatting capabilities, placed immediately to the right of the percent sign 38
- Data and Standard Output Function 39
- Data and Standard Output Function 40
- Data and Standard Output Function 42
- Data and Standard Input Function Standard input function: scanf() #include Input the data from the standard input stream A sequence of bytes flows from an input device: keyboard, disk drive, network connection, and so on to main memory. Normally and automatically, the standard input stream is connected to the keyboard. format-control-string describes the formats of the input. other-arguments are pointers to variables in which the input will be stored. 43
- Data and Standard Input Function The conversion specifiers used to input all types of data 44
- Data and Standard Input Function The conversion specifiers used to input all types of data 45
- Data and Standard Input Function The conversion specifiers used to input all types of data Input data flow from an input device to main memory. Input device = keyboard Input Input Main memory ≈ variable ? 46
- Data and Standard Input Function How to refer to the place in main memory where the input data will be stored? Memory is addressable contiguously. Address is used! Input a string: Input Input a character: A Input an integer: -123 Input device = keyboard Input device = keyboard Input device = keyboard Input A -123 Input A -123 Main memory ≈ variable Main memory ≈ variable Main memory ≈ variable Varying size: user-predefined Fixed sizes: character = 1 byte, integer = 4 bytes, 47
- Data and Standard Input Function Input a string: Input Input a character: A Input an integer: -123 Input device = keyboard Input device = keyboard Input device = keyboard Input A -123 Input A -123 Main memory ≈ variable Main memory ≈ variable Main memory ≈ variable Varying size: user-predefined Fixed sizes: character = 1 byte, integer = 4 bytes, char aString[5]; char aChar; int anInteger; scanf(―%s‖, aString) scanf(―%c‖, &aChar) scanf(―%d‖, &anInteger) printf(―%s‖, aString) printf(―%c‖, aChar) printf(―%d‖, anInteger) In C, a string is defined as an array (sequence) of characters. The memory of this array is referred by the address of the first character represented by the name of the array. 48
- Data and Standard Input Function Put them altogether 49
- Data and Standard Input Function Put them altogether 50
- Data and Standard Input Function Input a date in the form of: dd/mm/yyyy 51
- Data and Standard Input Function Input a date in the form of: dd Month yyyy ??? 52
- Data Processing: Simple Example Program for computing the distance between the center and a given point in a 2D space Input: x, y as a coordinate of a given point Output: the distance along with the given point on screen y (3, 2) 0 x Distance (i.e. the length of the blue line) = 3.605551 53
- Data Processing: Simple Example Program for computing the distance between the center and a given point in a 2D space Input: x, y as a coordinate of a given point Output: the distance along with the given point on screen 54
- Data Processing: Simple Example printf() stdio.h Function calling: scanf() stdio.h sqrt() math.h system() stdlib.h 55
- Summary Start programming with the C language The components of a standard C program Input & Output vs. Read & Write vs. scanf & printf Make your programs not only executable but also readable Coding styles 56
- Chapter 2: C Program Structure and its Components 57