Chapter 2 Overview of C Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.

Slides:



Advertisements
Similar presentations
Chapter 6 Modular Programming J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
Introduction to C Programming
C Language Elements (II) H&K Chapter 2 Instructor – Gokcen Cilingir Cpt S 121 (June 22, 2011) Washington State University.
1 ICS103 Programming in C Lecture 4: Data Types, Operators & Expressions.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
The scanf Function The scanf function reads input from the standard input device into one or more variables Example: scanf(“%lf”, &miles); Reads a real.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
1 CS 201 Introduction to C (2) Debzani Deb. 2 Overview C Arithmetic Expressions Formatting Numbers in Program Output Interactive Mode, Batch Mode, and.
Introduction to C Programming
By Dr. Awad Khalil Computer Science & Engineering Department
Chapter 2 Overview of C Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Chapter 2 : Overview of C By Suraya Alias. /*The classic HelloWorld */ #include int main(void) { printf(“Hello World!!"); return 0; }
Chapter 2 Overview of C++ Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Pengantar C/C++. 2 Outline  C overview  C language elements  Variable declarations and data types  Executable statements  General form of a C program.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Chapter 7 Simple Date Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Input, Output, and Processing
Chapter 2: Using Data.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
C++ Programming: Basic Elements of C++.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Chapter 5 Repetition and Loop Statements J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Chapter 2 Overview of C++. 2 Overview  2.1 Language Elements  2.2 Reserved Words & Identifiers  2.3 Data Types & Declarations  2.4 Input/Output 
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Overview of C. C—a high-level programming language developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories. We will discuss: –the elements of a.
1 ELE118 lecture 3 Dr. Mehmet Demirer Dr. Seniha Esen Yuksel.
CISC105 – General Computer Science Class 2 – 6/7/2006.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Principles of Programming CSEB134 : BS/ CHAPTER Fundamentals of the C Programming Language.
 Most C programs perform calculations using the C arithmetic operators (Fig. 2.9).  Note the use of various special symbols not used in algebra.  The.
Introduction to Algorithmic Processes CMPSC 201C Fall 2000.
C Language Elements Preprocessor Directives # (sign for preprocessor directive commands) #include Standard header file (.h) Library.
Topics Designing a Program Input, Processing, and Output
ICS103 Programming in C Lecture 4: Data Types, Operators & Expressions
Revision Lecture
ICS103 Programming in C Lecture 3: Introduction to C (2)
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 part #3 C++ Input / Output
INPUT & OUTPUT scanf & printf.
Introduction to C++ Programming
Lecture3.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 2 part #3 C++ Input / Output
Chapter 2: Overview of C++
Chapter 2 Primitive Data Types and Operations
Chapter 1 c++ structure C++ Input / Output
Computer Science II CS132/601* Lecture #C-1.
Presentation transcript:

Chapter 2 Overview of C Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of Technology

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-2 Arithmetic Expressions

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-3 Arithmetic Expressions -- Operators / and % When applied to two positive integers, the division operator (/) computes the integral part of the result of dividing its first operand by its second. If the / operator is used with a negative and a positive integer, the result may vary from one C implementation to another. –avoid using division with negative integers In m % n, the operation is undefined when n is zero and varies from one implementation to another if n is negative.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-4 Arithmetic Expressions -- Operators / and % (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-5 Arithmetic Expressions -- Operators / and % (Cont’) m equals (m / n) * n (m % n) 7 equals (7 / 2) * 2 + (7 % 2) equals 3 * equals (299 / 100) * (299 % 100) equals 2 *

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-6 Arithmetic Expressions -- Operators / and % (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-7 Arithmetic Expressions -- Operators / and % (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-8 Arithmetic Expressions -- Operators / and % (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-9 Arithmetic Expressions -- Data Type of an Expression The data type of an expression depends on the type(s) of its operands. “ace arithmetic_operator bandage” is of type int if both ace and bandage are of type int; otherwise, it is of type double. mixed-type expression –an expression with operands of different types The data type of such a mixed-type expression will be double.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-10 Arithmetic Expressions -- Mixed-Type Assignment Statement When an assignment statement is executed, the expression is first evaluated; then the result is assigned to the variable listed to the left of the assignment operator (=). mixed-type assignment –the expression being evaluated and the variable to which it is assigned have different data types

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-11 Arithmetic Expressions -- Mixed-Type Assignment Statement (Cont’) The expression is evaluated before the assignment is made, and the type of the variable being assigned has no effect whatsoever on the expression value. E.g. If m and n are type int and p, x, and y are type double: m = 3; n = 2; p = 2.0; x = m / p; y = m / n;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-12 Arithmetic Expressions -- Mixed-Type Assignment Statement (Cont’) Assignment of a type double expression to a type int variable causes the fractional part of the expression to be lost since it cannot be represented in a type int variable. E.g. x = 9 * 0.5; n = 9 * 0.5;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-13 Arithmetic Expressions -- Type Conversion through Casts type cast –converting an expression to a different type by writing the desired type in parentheses in front of the expression

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-14 Arithmetic Expressions -- Type Conversion through Casts (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-15 Arithmetic Expressions -- Expressions with Multiple Operators unary operator –an operator with one operand binary operator –an operator with two operands

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-16 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’) Rules for Evaluating Expressions –a. Parentheses rule: All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expression evaluated first. –b. Operator precedence rule: Operators in the same expression are evaluated in the following order: unary +, - first *, /, % next binary +, - last

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-17 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’) –c. 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 same precedence level (such as + and -) are evaluated left to right (left associativity).

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-18 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-19 Figure 2.8 Evaluation Tree for area = PI * radius * radius;

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-20 Figure 2.9 Step-by-Step Expression Evaluation

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-21 Arithmetic Expressions -- Expressions with Multiple Operators (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-22 Figure 2.10 Evaluation Tree and Evaluation for v = (p2 - p1) / (t2 - t1);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-23 Figure 2.11 Evaluation Tree and Evaluation for z - (a + b / 2) + w * -y

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-24 Arithmetic Expressions -- Writing Mathematical Formulas in C

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-25 Arithmetic Expressions -- Writing Mathematical Formulas in C (Cont’) The points illustrated in these examples can be summarized as follows: –Always specify multiplication explicitly by using the operator * where needed (formulas 1 and 4). –Use parentheses when required to control the order of operator evaluation (formulas 3 and 4). –Two arithmetic operators can be written in succession if the second is a unary operator (formula 5).

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-26 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. ANALYSIS –get the count of each type of coin from a customer. –determine the total value of the coins in cents –do an integer division using 100 as the divisor to get the dollar value –remainder of this division will be the leftover change

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-27 CASE STUDY -- Evaluating a Collection of Coins (Cont’) DATA REQUIREMENTS –Problem Inputs char first, middle, last /* a customer's initials */ int quarters /* the count of quarters */ int dimes /* the count of dimes */ int nickels /* the count of nickels */ int pennies /* the count of pennies */ –Problem Outputs int dollars /* value in dollars */ int change /* leftover change */ –Additional Program Variables int total_cents /* total value in cents */

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-28 CASE STUDY -- Evaluating a Collection of Coins (Cont’) DESIGN –INITIAL ALGORITHM 1.Get and display the customer’s initials. 2.Get the count of each kind of coin. 3.Compute the total value in cents. 4.Find the value in dollars and change. 5.Display the value in dollars and change.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-29 CASE STUDY -- Evaluating a Collection of Coins (Cont’) –REFINEMENT Step 3 Refinement –3.1 Find the equivalent value of each kind of coin in pennies and add these values. Step 4 Refinement –4.1 dollars is the integer quotient of total_cents and 100. –4.2 change is the integer remainder of total_cents and 100.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-30 Figure 2.12 Finding the Value of Coins

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-31 Figure 2.12 Finding the Value of Coins (cont’d)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-32 Formatting Numbers in Program Output -- Formatting Values of Type int field width –the number of columns used to display a value E.g. –printf("Results: %3d meters = %4d ft. %2d in.\n", meters, feet, inches); –Results: 21 meters = 68 ft. 11 in.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-33 Formatting Numbers in Program Output -- Formatting Values of Type int (Cont’) Displayed right-justified, preceded by blank spaces –For negative numbers, the minus sign is included in the count of digits displayed. –%2d to display any integer value between -9 and 99 –%4d works for values in the range -999 to 9999 Expands the field width if it is too small for the integer value displayed.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-34 Formatting Numbers in Program Output -- Formatting Values of Type int (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-35 Formatting Numbers in Program Output -- Formatting Values of Type double For a type double value, we must indicate both the total field width needed and the number of decimal places desired. –at least one digit before the decimal point %n.mf –n is a number representing the total field width –m is the desired number of decimal places

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-36 Formatting Numbers in Program Output -- Formatting Values of Type double (Cont’) E.g. %6.2f –The values displayed are rounded to two decimal places and are displayed right-justified in six columns. It is legal to omit the total field width in the format string placeholder, such as %.mf, which will be printed with no leading blanks.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-37 Formatting Numbers in Program Output -- Formatting Values of Type double (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-38 Formatting Numbers in Program Output -- Formatting Values of Type double (Cont’)

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-39 Interactive Mode, Batch Mode, and Data Files interactive mode –a mode of program execution in which the user responds to prompts by entering (typing in) data batch mode –a mode of program execution in which the program scans its data from a previously prepared data file

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-40 Interactive Mode, Batch Mode, and Data Files (Cont’) Input Redirection –metric <mydata Follow the call to scanf with the echo statement to display the value just stored as a record of the data manipulated by the program. Output Redirection –metric >myoutput Interacting with the running program as above will be difficult because all program output, including any prompting messages, will be sent to the output file. –metric myoutput

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-41 Figure 2.13 Batch Version of Miles-to-Kilometers Conversion Program

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-42 Interactive Mode, Batch Mode, and Data Files -- Program-Controlled Input and Output Files file pointer –store the information necessary to permit access to a file –FILE*inp, /* pointer to input file */ *outp; /* pointer to output file */ Prepare a file for input or output before permitting access. –inp = fopen("distance.dat", "r"); –outp = fopen("distance.out", "w");

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-43 Interactive Mode, Batch Mode, and Data Files -- Program-Controlled Input and Output Files (Cont’) use of the functions fscanf and fprintf –fscanf(inp, "%lf", &miles); –fprintf(outp, "The distance in miles is %.2f.\n", miles); File closing –fclose(inp); –fclose(outp);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-44 Figure 2.14 Miles-to- Kilometers Conversion Program with Named Files

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-45 Common Programming Errors Murphy’s Law, “If something can go wrong, it will.” Bugs debugging –removing errors from a program Three kinds of errors –syntax errors –run-time errors –logic errors

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-46 Common Programming Errors -- Syntax Errors syntax error –a violation of the C grammar rules, detected during program translation (compilation) A compiler listing is a listing created by the compiler during program translation that shows each line of the source program (preceded by a line number) and any syntax errors detected by the compiler. –E.g. Fig 2.15

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-47

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-48 Common Programming Errors -- Syntax Errors (Cont’) The line marked for an error is not always the line containing the programmer’s mistake. –Line 274, from line 271 One mistake of the programmer leads to the generation of multiple error messages. –miles

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-49 Common Programming Errors -- Syntax Errors (Cont’) Mistyped close-comment character sequence –The compiler is unaware that there is a problem until it comes to the end of the source file without having encountered a } to end the program! –When you begin getting error messages that make you think your compiler isn’t seeing part of your program, recheck your comments carefully. –Mistyping the open-comment sequence /* ? Correct the errors in the declaration part of a program first, then recompile the program before you attempt to fix other errors.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-50 Common Programming Errors -- Run-Time Errors run-time error –an attempt to perform an invalid operation, detected during program execution Dividing a number by zero Fig. 2.16

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-51 Figure 2.16 A Program with a Run-Time Error

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-52 Common Programming Errors -- Undetected Errors Errors may not prevent a C program from running to completion, but they may simply lead to incorrect results. Input of a mixture of character and numeric data

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-53 Figure 2.17 Revised Start of main Function for Coin Evaluation

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-54 Common Programming Errors -- Undetected Errors (Cont’) Inputs: –2003 BMC Expected result: Hello BMC, let's check your coins' value in Actual result: Hello BM, let's check your coins' value in 2003.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-55 Common Programming Errors -- Undetected Errors (Cont’) Further problems –Read on next "scanf(“%lf”, &quarters);" will fail Repair the program –insert a space before the first %c placeholder –scanf(" %c%c%c", &first, &second, &third);

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-56 Figure 2.18 A Program That Produces Incorrect Results Due to & Omission

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-57 Common Programming Errors -- Logic Errors logic error –an error caused by following an incorrect algorithm Logic errors may not cause run-time errors and do not display error messages. To prevent logic errors, carefully desk check the algorithm and the program.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-58 Chapter Review Every C program has preprocessor directives and a main function. The main function contains variable declarations and executable statements. Variable names must begin with a letter or an underscore (the latter not recommended) and consist of letters, digits, and underscore symbols. A reserved word cannot be used as an identifier.

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-59 Chapter Review (Cont’) C’s data types enable the compiler to determine how to store a particular value in memory and what operations can be performed on that value. Three standard data types are int, double, and char. The data type of each variable must be declared. The executable statements are derived from the algorithm and are translated into machine language. Assignment statements are used to perform computations and store results in memory. Function calls are used to get data (functions scanf and fscanf) and to display values stored in memory (functions printf and fprintf).

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-60 New Constructs

Copyright ©2004 Pearson Addison-Wesley. All rights reserved.2-61 New Constructs (Cont’)