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

COMP 1020: Structured Programming (2)

  • Upload
    jack

  • View
    82

  • Download
    3

Embed Size (px)

DESCRIPTION

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. ALGOLearly 1960’s1 st language with block structure - PowerPoint PPT Presentation

Citation preview

Page 1: COMP 1020: Structured Programming (2)

1

COMP 1020:

Structured Programming (2)

Instructor: Prof. Ken Tsang Room E409-R11 Email: [email protected]

Page 2: COMP 1020: Structured Programming (2)

Lecture 2.1Introduction to C

Structured ProgrammingInstructor: Prof. K. T. Tsang

2

Page 3: COMP 1020: Structured Programming (2)

History of C

ALGOL early 1960’s 1st language with block structureBCPL 1967 for system softwareB 1970 early version of UNIXC 1972 with data-types, UNIXK&R C 1978 “The C Programming

Language”ANSI C 1989 approved by ANSI

1990 approved by ISOC++ 1980s Bjarne Stroustrup

3

Page 4: COMP 1020: Structured Programming (2)

Importance of C

Platform independent and highly portable (compilers for Windows & UNIX)

Well suited for structured programmingPrograms written in C are efficient and fast, easy

to debug, test and maintainA well-maintained, large collection of library

functions used by programmersAbility to extend the language by adding more

library functionsGive rise to modern languages like C++ & JAVA

4

Page 5: COMP 1020: Structured Programming (2)

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

5

Page 6: COMP 1020: Structured Programming (2)

Compilation编译

6

Page 7: COMP 1020: Structured Programming (2)

Steps to create an application步骤Write or edit source code

Compile source code

Link object code

Run program

Fix bugs that emerge duringcompilation

Fix bugs thatemerge duringexecution

7

Page 8: COMP 1020: Structured Programming (2)

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.

8

Page 9: COMP 1020: Structured Programming (2)

A simple C program that does nothing

int main (){

return 0;}

Return type“int” Function name: main is called by OS

Parameter/argument list

Function body

Program statementLast statement must return an intReturn “0” to OS if successful

9

Page 10: COMP 1020: Structured Programming (2)

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

10

Page 11: COMP 1020: Structured Programming (2)

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

11

Page 12: COMP 1020: Structured Programming (2)

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)

12

Page 13: COMP 1020: Structured Programming (2)

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 commandcc hello.c

The compilation will proceed silently, and make an executable file called a.out. If you run a.out by typing the commanda.outit will print hello world

13

Page 14: COMP 1020: Structured Programming (2)

Or use this compiling commandcc –ohello hello.c

Execution commandhello

output:hello world

14

Page 15: COMP 1020: Structured Programming (2)

A good program should contain many comments

15

Page 16: COMP 1020: Structured Programming (2)

The importance of Software Maintenance

16

Page 17: COMP 1020: Structured Programming (2)

“Hello World” in C++

17

Page 18: COMP 1020: Structured Programming (2)

Compiling the program using the FreeSoftware Foundation's g++ compiler

18

Page 19: COMP 1020: Structured Programming (2)

Compiling the program using the UNIX CC compiler (GENERIC UNIX)

% g++ -g -Wall -ohello hello.cpp

19

Page 20: COMP 1020: Structured Programming (2)

Running the program

20

Page 21: COMP 1020: Structured Programming (2)

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

21

Page 22: COMP 1020: Structured Programming (2)

22

Page 23: COMP 1020: Structured Programming (2)

Lecture 2.2Variable and Data types

Structured Programming Instructor: Prof. K. T. Tsang

23

Page 24: COMP 1020: Structured Programming (2)

C character set

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

24

Page 25: COMP 1020: Structured Programming (2)

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

Identifiers

Constants strings

Special symbols

Operatorsfloatif

tempamount

-12.528

“ABC”“year 2000”

+ - * /

() {} [] , ;

25

Page 26: COMP 1020: Structured Programming (2)

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_var101cost_of_booknumber_of_students

26

Page 27: COMP 1020: Structured Programming (2)

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

Page 28: COMP 1020: Structured Programming (2)

Basic data type (built-in types)

char hold 1 character size:1byte

int an integer4 bytes for most (UNIX) machine

float single precision floating pointusually 4 bytes

doubledouble precision floating pointusually 8 bytes

28

Page 29: COMP 1020: Structured Programming (2)

Type declaration & initialization

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

29

Page 30: COMP 1020: Structured Programming (2)

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

Page 31: COMP 1020: Structured Programming (2)

Assignment Statements

31

Page 32: COMP 1020: Structured Programming (2)

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

Page 33: COMP 1020: Structured Programming (2)

Qualifiers: signed, unsignedApplied 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

Page 34: COMP 1020: Structured Programming (2)

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

Page 35: COMP 1020: Structured Programming (2)

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

Page 36: COMP 1020: Structured Programming (2)

Number Systems

Based 10 10 digital numbers : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9138 = 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 10n36

Page 37: COMP 1020: Structured Programming (2)

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: 01110011Question: how many different numbers can

be represented in 1 byte? 2^8 = 256

37

Page 38: COMP 1020: Structured Programming (2)

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:

0 1 0 0 1 1 0 1

time

Unit machine cycle timeOn = 1

Off = 0

38

Page 39: COMP 1020: Structured Programming (2)

Other Number Systems

Base 8 (Octal)8 numbers: 0, 1, 2, 3, 4, 5, 6, 7108 = 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, F1016 = 1*16 + 0 = 1610

2516 = 2*(16^1) + 5*(16^0) = 3710

AF16 = 10 *(16^1) + 15*(16^0) = 17510

39

Page 40: COMP 1020: Structured Programming (2)

Some Numbers to Remember

40

Page 41: COMP 1020: Structured Programming (2)

Binary & octal conversion

10101110 10 101 110 binary 256 octal 02560377 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

Page 42: COMP 1020: Structured Programming (2)

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

Page 43: COMP 1020: Structured Programming (2)

Character Data RepresentationASCII American Standard Code for Information Interchange

most widely usedReference: 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 Codeused by mainframe

43

Page 44: COMP 1020: Structured Programming (2)

44

Page 45: COMP 1020: Structured Programming (2)

“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*/

45

Page 46: COMP 1020: Structured Programming (2)

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.

46

Page 47: COMP 1020: Structured Programming (2)

Literal float or double constants

float f1 = 1.33333;

float f2 = 1.333 e -3

mantissa exponent

means1.333 x 10 -3

Scientific notation

Can be lower or upper case

Regular notation

47

Page 48: COMP 1020: Structured Programming (2)

Enumeration constantenum 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*/

48

Page 49: COMP 1020: Structured Programming (2)

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;

49

Page 50: COMP 1020: Structured Programming (2)

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

50

Page 51: COMP 1020: Structured Programming (2)

“printf” functionprintf( “string to be printed”, v1, v2, v3, …)

To format “string to be printed”, see p.13 K&R.

Examples:printf( “The answer is %d\n”, interger1);

printf( “The input is %d\n the answer is %6.2f\n”, int2, flo1);

51

Page 52: COMP 1020: Structured Programming (2)

Format in printf (p.350 S Kochan)

i or d integeru unsigned integero octal integerx or X hex integerf or F floating-point number (6 decimal places by default)e or E floating-point number in exponential formatc single characters null-terminated character stringp pointer

Example: %d %x %6.2f %f %e

52

Page 53: COMP 1020: Structured Programming (2)

53

Page 54: COMP 1020: Structured Programming (2)

54

Page 55: COMP 1020: Structured Programming (2)

55

Page 56: COMP 1020: Structured Programming (2)

Example using format in printf#include <stdio.h> int main() {

char c1=‘A‘, c2=‘z’;printf("%c %d %o %x %X\n", c1, c1, c1, c1, c1);printf("%c %d %o %x %X\n", c2, c2, c2, c2, c2);

int i1=598, i2=3847;printf(“%d %o %x %X\n", i1, i1, i1, i1);printf(“%d %o %x %X\n", i2, i2, i2, i2);

system("pause");return 0;

}

A 65 101 41 41z 122 172 7a 7A598 1126 256 2563848 7407 f07 F07

56

Page 57: COMP 1020: Structured Programming (2)

C++ style Input & Output#include <iostream>using namespace std;int main(){// constant declaration — this is a comment lineconst double Pi = 3.14159;// variable declarations – c++ style commentdouble radius;double area;

// assignment statementscout << "Enter circle radius in cm: ";cin >> radius;area = Pi * radius * radius;cout << "Area : " << area << “ sq. cm” << endl;return 0;

}

57

Page 58: COMP 1020: Structured Programming (2)

Difference between C & C++ in IO

“printf” needs header file “stdio.h”, takes time to format.

Console input in C is more complicate.

“cout” & “cin” need header file “iostream”, easier to receive console input , more flexible to format.

58

Page 59: COMP 1020: Structured Programming (2)

C++ style Input & Output: example 2

#include <iostream>using namespace std;int main(){

cout << “Enter two integers: “ << endl;

int v1, v2;cin >> v1 >> v2;cout << “The sum of “ << v1 << “ and

“ << v2 << “ is “ << v1 + v2 << endl;return 0;

}

59

Page 60: COMP 1020: Structured Programming (2)

Mixing C & C++ style IO: example

#include <iostream>#include <stdio.h>using namespace std;int main(){

printf(“Enter two integers: \n“);int v1, v2;cin >> v1 >> v2;cout << “The sum of “ << v1 << “ and

“ << v2 << “ is “ << v1 + v2 << endl;return 0;

}

60