1 / 60

COMP 1020: Structured Programming (2)

COMP 1020: Structured Programming (2). Instructor: Prof. Ken Tsang Room E409-R11 Email: kentsang @uic.edu.hk. Lecture 2.1 Introduction to C Structured Programming Instructor: Prof. K. T. Tsang. History of C. ALGOL early 1960’s 1 st language with block structure

jack
Download Presentation

COMP 1020: Structured Programming (2)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMP 1020:Structured Programming (2) Instructor: Prof. Ken Tsang Room E409-R11 Email: kentsang@uic.edu.hk

  2. Lecture 2.1 Introduction to C Structured Programming Instructor: Prof. K. T. Tsang

  3. History of C ALGOL early 1960’s 1st language with block structure BCPL 1967 for system software B 1970 early version of UNIX C 1972 with data-types, UNIX K&R C 1978 “The C Programming Language” ANSI C 1989 approved by ANSI 1990 approved by ISO C++ 1980s Bjarne Stroustrup

  4. Importance of C Platform independent and highly portable (compilers for Windows & UNIX) Well suited for structured programming Programs written in C are efficient and fast, easy to debug, test and maintain A well-maintained, large collection of library functions used by programmers Ability to extend the language by adding more library functions Give rise to modern languages like C++ & JAVA

  5. Steps to create a C/C++ program Use an text editor to create a “.c” (“.cpp” in C++) file, which is the C program itself Compile the *.c file by a compiler to produce a machine dependent object file (*.o) Locate all libraries package used in your C program Link the object file with the library to produce the executable (*.exe in DOS, or Window) Run the executable

  6. Compilation编译

  7. Steps to create an application步骤 Write or edit source code Fix bugs that emerge during compilation Compile source code Link object code Fix bugs that emerge during execution Run program

  8. To compile more complicated C/C++ program use the “make” utility to build and use a debugger to debug. In UNIX, create a “makefile” to contain all command line Actions to build the executable. Use debugger (dbx, sdb …) to debug.

  9. A simple C program that does nothing Return type “int” int main () { return 0; } Function name: main is called by OS Parameter/argument list Function body Program statement Last statement must return an int Return “0” to OS if successful

  10. Example: “Hello world” in C(K&R chapter 1) /* comments inside here */ #include <stdio.h> /*standard library header file*/ void main (void) { /*beginning of main*/ printf(“hello world\n”); /*call printf to print “hello world” on standard output*/ } /*end of main*/ /*note: printf() is introduced in the header file stdio.h*/ Return type “void” if no return

  11. Compiler Directive: #include • It refers to a header file of library functions or variables. • The compiler reads in the contents of the file before compiling the program. • The included file is compiled with the program. • There are two forms of #include: #include <stdio.h> // for pre-defined files #include "my_lib.h" // for user-defined files

  12. Library Function “printf” - introduced in header file stdio.h - does not supply a newline automatically printf(“hello world\n”); Equivalent to printf(“hello”); printf(“ world”); printf(“\n”); \n is an escape sequence, an instruction for printf to print a newline. (see p. 38 K&R)

  13. Just how to run this program depends on the system you are using. On the UNIX operating system you must create the program in a file whose name ends in “.c”, such as hello.c, then compile it with the command cc hello.c The compilation will proceed silently, and make an executable file called a.out. If you run a.out by typing the command a.out it will print hello world

  14. Or use this compiling command cc –ohello hello.c Execution command hello output: hello world

  15. A good program should contain many comments

  16. The importance of Software Maintenance

  17. “Hello World” in C++

  18. Compiling the program using the Free Software Foundation's g++ compiler

  19. Compiling the program using the UNIX CC compiler (GENERIC UNIX) % g++ -g -Wall -ohello hello.cpp

  20. Running the program

  21. Exercise: Try to reproduce the “ hello” program and run/execute it on your computer.

  22. Lecture 2.2 Variable and Data types Structured ProgrammingInstructor: Prof. K. T. Tsang

  23. C character set • Letters • Digits • Special characters : , . ; ? / ( ) [ ] { } _ = #... • White spaces

  24. In a passage of text (English), individual words and punctuation marks are called tokens 辞单元. In a C program, the smallest individual units are known as C-tokens. C-tokens are separated by white spaces or special symbols. C tokens Keywords Constants strings Operators -12.5 28 float if “ABC” “year 2000” + - * / Identifiers Special symbols temp amount () {} [] , ;

  25. Variables and constants – basic data objects in a program Variable can change its value during the execution of the program, while constant cannot. Both variables and constants have names/identifiers, made up of characters and digits. The first character must be a letter or underscore (‘_’). Examples: variable1 _var101 cost_of_book number_of_students

  26. Identifiers • An identifier is a name for variables, constants, functions, etc. • It consists of a letter or underscore followed by any sequence of letters, digits or underscores • Names are case-sensitive. The following are unique identifiers: Hello, hello, whoami, whoAMI, WhoAmI • Names cannot have special characters in them e.g., X=Y, J-20, #007, etc. are invalid identifiers. • C/C++ keywords cannot be used as identifiers. • Choose identifiers that are meaningful and easy to remember.

  27. Basic data type (built-in types) char hold 1 character size:1byte int an integer 4 bytes for most (UNIX) machine float single precision floating point usually 4 bytes double double precision floating point usually 8 bytes

  28. Type declaration & initialization Examples: char c0; char c1 = ‘y’; int student_number, days; float price_of_book; double distance; double PI = 3.14159 const float weight_in_kg = 68.45e2

  29. Variable Declarations • A variable is best thought of as a container/box for a value: Variable declaration syntax: <type> <identifier>; Examples: int nickel; int penny; • A variable must be declared before it can be used. int main(){ x = 5; /* illegal: x was not declared */ } • A variable can be initialized in a declaration: int x = 3; • Several variables of the same type can be declared in the same declaration (though it is better to put them on separate lines): double total_USD, area; • A variable must have only one type. For example, a variable of the type int can only hold integer values.

  30. Assignment Statements

  31. Constant Declarations • Constants represent permanent values. • Their values can only be set in the declaration: const double pi = 3.1415926; const int i, j = 1; /*error, i is not initialized*/ • They can make a program more readable and maintainable Constant declaration syntax: const <type> <identifier> = <constant Expression>; Examples: const double US2HK = 7.8; const double HK2Yuan = 1.013; const double US2Yuan = US2HK* HK2Yuan;

  32. Qualifiers: signed, unsigned Applied to char, int “unsigned int” is always positive or zero. “unsigned char” variables have values between 0 & 255. “signed char” variables between -128 & 127.

  33. Qualifiers: long, short “int” – natural size of the machine, hardware dependent, occupied 32 bits for most machine “short int” – often 16 bits or just “short” “long int” – often more than 32 bits or just “long” “long double” – machine dependent, more than 32bits. Examples: unsigned long seconds = 102344557896L;

  34. How large can “int” be? For most machines, an “int” occupies 4 bytes, i. e. 32 bits. An “signed int” varies from -2147483647 (2**31 – 1) to 2147483648. If you are dealing with numbers outside this range, use “long” instead, e. g. unsigned long seconds = 8877665544332211L;

  35. Number Systems Based 10 10 digital numbers : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 138 = 1*100 + 3*10 + 8 = 1*(10^2) + 3*(10^1) + 8*(10^0) Based 2 (Binary system): 2 digital numbers : 0, 1 10011 = 1*(2^4) + 0*(2^3) + 0*(2^2) + 1*(2^1) + 1*(2^0) = 19(based 10) = 1910 11001 = 1*(2^4) + 1*(2^3) + 0*(2^2) + 0*(2^1) + 1*(2^0) = 1*16 + 1*8 + 0*4 + 0*2 + 1*1 = 25(based 10) = 2510 “10^n” means 10 n

  36. Why base 2? Computers use “on” and “off” to represent numbers. “ON” represents 1. “OFF” represents 0. Basic unit of information in computer: bit (binary digit) 1 byte has 8 bits: 01110011 Question: how many different numbers can be represented in 1 byte? 2^8 = 256

  37. Bits of information as electronic signal in the CPU A bit (binary digit) has only TWO possible values or states : either 1 or 0. If we can place a probe onto the electronic circuits inside a computer and monitor the electronic signals, we will see square-shaped electrical waves like the one shown below: Unit machine cycle time On = 1 time Off = 0 0 0 1 1 0 1 0 1

  38. Other Number Systems Base 8 (Octal) 8 numbers: 0, 1, 2, 3, 4, 5, 6, 7 108 = 1*8 + 0 = 810 258 = 2*(8^1) + 5*(8^0) = 2110 Base 16 (Hexadecimal, or Hex) 16 numbers : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F 1016 = 1*16 + 0 = 1610 2516 = 2*(16^1) + 5*(16^0) = 3710 AF16 = 10 *(16^1) + 15*(16^0) = 17510

  39. Some Numbers to Remember

  40. Binary & octal conversion 10101110  10 101 110 binary  256 octal  0256 0377  11 111 111 binary Numbers start with “0” are octal constants. (p.193 K&R) In C, 0123 means 123(octal) or 83(decimal).

  41. Binary & hexadecimal conversion 10101110  1010 1110 binary  0xAE hex 0x9B  1001 1011 binary Numbers start with “0x”, or “0X” are hexadecimal constants. So “0x15” or “0X15”means 21(decimal). (p.193 K&R) We can write a literal integer constant in: decimal, octal or hexadecimal notation.

  42. Character Data Representation ASCII American Standard Code for Information Interchangemost widely used Reference: http://www.lookuptables.com/ ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose. Total characters: 128 [only 7 bits are used] Each character is stored in a 8 bits (1 byte) space. Example: ‘3’ is 00110011 or 0x33 ‘A’ 01000001 or 0x41 ‘a’ 01100001 or 0x61 EBCDIC Extended Binary Coded Decimal Interchange Code used by mainframe

  43. “char” constants (p. 37 K&R) char c1 = ‘w’, c2 = ‘\n’; char c3 = 48; /*same as char c3 = ‘0’ in ASCII*/ char c4 = 65; /*char c4 = ‘A’ */ char c5 = ‘\011’; /*3 octal digits -- horizontal tab*/ char c6 = ‘\014’; /*form feed, new page*/ char c7 = ‘\132’; /*Z*/ char c8 = ‘\172’; /*z*/ char c9 = ‘\x41’; /*2 hexadecimal digits – ‘A’*/ char c10 = ‘\x7A’; /*z*/ char c11 = ‘\xA’; /*new line*/

  44. Literal “char” constants Escape sequences are defined for non-printable & special characters in C/C++. Complete set of “escape sequences” is shown in p. 38 K&R. Characters can be represented as generalized “escape sequences” of the form \ooo using (up to 3) octal digits, or \xhh using (up to 2) hexadecimal digits. (p. Thus, ‘\n’ , ‘\012’, and ‘\xA’ all represent the new line character.

  45. Literal float or double constants float f1 = 1.33333; Regular notation Scientific notation means 1.333 x 10 float f2 = 1.333 e -3 -3 exponent mantissa Can be lower or upper case

  46. Enumeration constant enum enum_name { tag1, tag2, … }; where tag1, tag2, … will be assigned integers 0, 1, …etc. automatically, or explicitly assigned values. Examples : enum boolean { NO, YES }; enum escapes_char { BELL=‘\a’, BACKSPACE=‘\b’, TAB=‘\t’, NEWLINE=‘\n’, VTAB=‘\v’, RETURN=‘\r’ }; enum months { JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; enum months this_month = OCT; enum months last_month = 9; /*compiler error*/

  47. User-defined type C supports “type definition” defined by programmers. The user-defined new data type can be used to declare variables. typedef int scores; scores test_scores, test1, test2, final; typedef float degree; degree average_temperature, hi_temp;

  48. Code Example #include <stdio.h> char char1, char2, char3; /*declaration*/ int main () { char1 = ‘A’; /*assignment Actions*/ char2 = ‘B’; char3 = ‘C’; printf( “%c%c%c reversed is %c%c%c\n”, char1, char2, char3, char3, char2, char1); return 0; /*return value to OS if successful*/ } ABC reversed is CBA

More Related