Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science II CS132/601* Lecture #C-1.

Similar presentations


Presentation on theme: "Computer Science II CS132/601* Lecture #C-1."— Presentation transcript:

1 Computer Science II CS132/601* Lecture #C-1

2

3 C language elements Preprocessor Directives Function main()
Begin and end point of a program

4 Preprocessor Directives
#include include the libraries #define define constant macro Comments make the program easy to understand

5 #include directive Syntax: #include <standard header file>
Example: #include <stdio.h> #include <math.h> Interpretation: tell the preprocessor where to find the meaning of standard identifiers used in the program.

6 #define directive Syntax: #define NAME value
Examples: #define PI #define MAX_LENGTH 100 Interpretation: the C preprocessor is notified that it is to replace each use of the identifier NAME with value.

7 Comments Comments provide supplementary information making it easier to understand the program, but comments are ignored by the C preprocessor and complier.

8 Function main Marks the beginning of the main function where program execution begins. Syntax: int main(void) { function body }

9 Declaration It is a part of a program tells the complier the memory cells of the data will be used in a program This can be generated according to the data requirements identified during the problem solving Examples: double kms, miles;

10 Executable statements
The main part of a program, derived from the algorithm, it is the real problem solving procedure. These program lines will be converted to machine language instructions and executed by the computer. Punctuations and special symbols are used. (, ; { } * + = etc)

11 Identifiers Reserved words Standard identifiers
Reserved, can not be used for other purpose Examples: int, double, break, return, void … Standard identifiers Reserved, not recommended for other purpose Examples: printf, scanf User-defined identifiers

12 User-defined identifiers
Chosen by ourselves to name memory cells that will hold data, operations and program results Syntax: Only letters, digits and underscores Can not begin with a digit Reserved words can not be used Better not using standard identifiers Valid for first 31 characters (already extended in most C implementation)

13 Examples Reserved Words Standard Identifiers User-defined int, void,
double, return printf, scanf KMS_PER_MILE, main, miles, kms

14 Variables Variable: a name associate with a memory cell whose value can change Variable declaration: a statement that communicate to the complier the names of variables in the program and the kind of information stored in each variable.

15 Declaration Syntax: int variable_list_1; double variable_list_2;
Examples: double miles; /* input: the distance in miles */ Interpretation: a memory cell is associated for each name in the variable list.

16 Data types A set of values and operations can be performed on those values. E.g. int, double, char Objects of a data type can be variables or constants. int type Originally, ANSI C: Now: E.g , 435, +15

17 Data types (Cont.) double type:
a real number has an integral part and a fractional part that are separated by a decimal point. We can also use C scientific notation such as 1.23e5. E.g , , 0.34e-4, 1.23e5

18 Data type (Cont.) Type char: represents an individual character value, a letter, a digit or a special symbol Examples: ‘A’, ‘z’, ‘3’, ‘=‘, ‘:’, ‘”’, ‘ ‘

19 Executable statements
Program in memory memory memory Machine language Miles-to-kms Conversion program Machine language Miles-to-kms Conversion program miles kms miles kms ? ? 10.00 16.09 a) before b) after

20 Input/output operations
All input/output operations in C are performed by special program units called input/output functions. The most common functions are supplied as C standard library. They can be accessed through stdio.h by using a function call.

21 Function formats Function name Function argument
printf(“That equals %f kilometers. \n”, kms) Print list Format string

22 Placeholder A placeholder always begins with the symbol %. Placeholder
Variable type Function use %c %d %f %lf char int double printf/scanf printf scanf

23 Newline escape sequence “\n” Display prompts:
printf(“Enter the distance in miles> “); scanf(%lf”,&miles);

24 Input The data transfer from the outside world into memory is called an input operation Two ways: Assignment to a variable Copying the data from an input device into a variable

25 scanf function Syntax: scanf(format string, input list); Example:
scanf(“%lf”, &miles); scanf(“%c%c%c”,&char1,&char2,&char3); & is address-of, in this context, the & tells scanf the memory address of each variable Copies the data typed at the keyboard by the user during program execution into memory.

26 output After a program finishes execution, the program results will be displayed to the users by an output operation.

27 printf function Syntax: printf(format string, print list);
Examples: printf(“hello world!”); Interpretation: Display the value of its format string after substituting in left-to-right order the values of the expressions in the print list for their placeholders in the format string and after replacing escape sequences such as \n.

28 return statement Syntax: return expression; Example: return (0);
The last list in the main function. Transfer control from your program to the operating system.

29 General Form of C Program
preprocessor directives main function heading { declarations executable statements }

30 C Programming in linux complier and linker for C programs.
ssh connect to a linux machine e.g. ssh inceptor.mcs.suffolk.edu Vi, pico edit the source file e.g. vi hello.c pico hello.c gcc complier and linker for C programs. e.g. gcc hello.c or gcc hello.c -o hello run the program

31 Data type of expressions
Depends on the type(s) of its operands. For int and double type data If both are int, the expression is int as well If contains both int and double (a mixed-type expression), the type is double The expression is evaluated before the assignment is made.

32 Examples int m, n; double x, y, p; If m=3, n=2, p=2.0,x=m/p, y=m/n
Then we get x=1.5, y=1.0 x=9*0.5 if x is int, x=4 if x is double, x=4.5

33 Type conversion This can be done by placing the desired type in parentheses before the expression (type cast). Example average=(double)(total_score/num);

34 Multiple operators Unary operators: only take one operand.
Examples: x = -y p = + x Binary operators: Multiple operators: Example: x / y * z + a / b

35 Rules for evaluating expressions
Parentheses rule: All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expressions evaluated first.

36 Rules for evaluating expressions (Cont.)
Operator precedence rule: operators in the same expression are evaluated in the following order: Unary +, - first x = -y; p = +x * y; *, /, % next Binary +, - last

37 Rules for evaluating expressions (Cont.)
Associativity rule: Unary operators in the same subexpression and at the same precedence level (such as + and -) are evaluated right to left (right associativity). Binary operators in the same subexpression and at the precedence level (such as + and -) are evaluated left to right (left associativity).

38 Example x * y * z + a / b – c * d can be represented by:
area = PI * radius * radius v = ( p2 – p1 ) / ( t2 – t1 ) z – ( a + b / 2) + w * -y

39 Mathematical Formulas

40 Case Study Evaluating a collection of coins Problem:
Your local bank branch has many customers who save their change and periodically bring it in for deposit. Write a program to interact with the bank’s customers and determine the value of a collection of coins

41 Data requirements Problem Input: char first, middle, last
int quarters int dimes int nickels int pennies Problem output: int dollars int change Additional value: int total_cents Formulas: 1 quarter= 25c; 1 dime=10c; 1 nickel= 5c, 1 penny= 1c

42 Design Get and display the customer’s initials
Get the count of each kind of coins Compute the total value in cents Find the value in dollars and change Display the value in dollars and change

43 #include <stdio.h>
int main(void) { char first, middle, last; /* input - 3 initials */ int pennies, nickels; /* input - count of each coin type */ int dimes, quarters; /* input - count of each coin type */ int change; /* output - change amount */ int dollars; /* output - dollar amount */ int total_cents; /* total cents */ /* Get and display the customer's initials. */ printf("Type in 3 initials and press return> "); scanf("%c%c%c", &first, &middle, &last); printf("Hello %c%c%c, let's see what your coins are worth.\n", first, middle, last); /* Get the count of each kind of coin. */ printf("Number of quarters> "); scanf("%d", &quarters); printf("Number of dimes > "); scanf("%d", &dimes); printf("Number of nickels > "); scanf("%d", &nickels); printf("Number of pennies > "); scanf("%d", &pennies); /* Compute the total value in cents. */ total_cents = 25 * quarters + 10 * dimes + 5 * nickels + pennies; /* Find the value in dollars and change. */ dollars = total_cents / 100; change = total_cents % 100; /* Display the value in dollars and change. */ printf("\nYour coins are worth %d dollars and %d cents.\n", dollars, change); return (0); }

44 Computer operation modes
Interactive Mode user interact with the program and supply the data Batch Mode the program get the data from a file using redirection, e.g. metric <mydata

45 Output redirection metric >myoutput Input/output redirections metric <mydata >myoutput

46 Program-controlled input/output files
File pointer: FILE *inp, *outp; fopen function inp=fopen(“distance.dat”, “r”); outp=fopen(“distance.out”, “w”); Access mode r, w, a fclose function fclose(inp); fclose(outp);

47 #include <stdio.h>
#define KMS_PER_MILE 1.609 int main(void) { double miles, kms; FILE *inp, *outp; /* open the input and output files */ inp = fopen(“distance.dat”,”r”); outp = fopen(“distance.out”,”w”); /* Get the distance in miles */ fscanf(inp,“%lf”,&miles); fprintf(outp, “The distance in miles is %.2f. \n”, miles); /* Convert the distance to kilometers */ kms= KMS_PER_MILE * miles; /* Display the distance in kilometers */ fprintf(outp,“That equals %f kilometers.\n”, kms); fclose(inp); fclose(outp); return (0); }

48 Program errors Syntax errors Run-time errors Undetected errors
Logic errors Debugging a program (error correcting process) is necessary

49 Library functions Code-reuse benefits: avoid redevelopment.
avoid errors. C providing many predefined functions that can be used to perform certain tasks. For example, mathematic computations. sqrt(x)

50 Example Display the square root of two numbers provided as the input data (first and second) and the square root of their sum.

51 /* * Perform three square root computation */ #include <stdio.h> #include <math.h> int main(void) { double first, second, /* input – two data value */ double first_sqrt; /* output – square root of first */ double second_sqrt; /* output – square root of second */ double sum_sqrt; /* output – square root of sum */ /* Get first number and display its square root */ printf(“Enter the first number> “); scanf(“lf”, &first); first_sqrt = sqrt(first); printf(“The square root of the first number is %.2f\n”,first_sqrt); /* Get second number and display its square root */ scanf(“lf”, &second); second_sqrt = sqrt(second); printf(“The square root of the second number is %.2f\n”,first_sqrt); /* display the square root of the sum */ sum_sqrt = sqrt(first+second); printf(“The square root of the sum is %.2f\n”,sum_sqrt); return (0); }

52

53 Example Using pow and sqrt functions to compute the roots of equation: ax2 + bx + c = 0 disc= pow(b,2) – 4 * a * c root_1 = ( -b + sqrt(disc)) / (2 * a) root_2 = ( -b - sqrt(disc)) / (2 * a) a2 = b2 + c2 – 2bc cos α

54 Functions without arguments
Function prototype: declare a function before use it, tells the C complier the data type of the function, the function name, and information about arguments The data type of a function is determined by the type of value returned by it. void function(void) example: void draw_circle(void)

55 Function definitions Define the function operations. Example:
/* Draw a circle */ void draw_circle(void) { printf(“ * \n”); printf(“ * * \n”); printf(“ * * \n”); }

56 Function syntax ftype fname(void) { local declarations
executable statements }

57 /* * Draw a triangle */ void draw_triangle(void) { draw_intersect(); draw_base(); }

58 Placement of functions
/* draw a stick figure */ #include <stdio.h> /* function prototypes */ void draw_circle(void) // draw a circle void draw_intersect(void) // draw a intersect void draw_base(void) // draw a base void draw_triangle(void) // draw a triangle int main(void) { /* draw a circle */ draw_circle(); /* draw a triangle */ draw_triangle(); /* draw intersecting lines */ draw_intersect(); return(0); } /* Draw a circle */ void draw_circle(void) printf(“ * \n”); printf(“ * * \n”); printf(“ * * \n”);

59 Order of execution of functions


Download ppt "Computer Science II CS132/601* Lecture #C-1."

Similar presentations


Ads by Google