Representation of Data Types Comparing double and int data types Using integers are faster and more precise round-off errors when using doubles The range.

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

Chapter 3 Top-Down Design with Functions Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
C Language Elements (II) H&K Chapter 2 Instructor – Gokcen Cilingir Cpt S 121 (June 22, 2011) Washington State University.
Sizes of simple data types sizeof(char) = 1 size(short) = 2 sizeof(int) = 4 size(long) = 8 sizeof(char) = 1 size(short) = 2 sizeof(int) = 2 size(long)
1 ICS103 Programming in C Lecture 4: Data Types, Operators & Expressions.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
CS 201 Functions Debzani Deb.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
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.
1 CSC 1401 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CS 201 Functions Debzani Deb.
1 CS 201 Introduction to C (2) Debzani Deb. 2 Overview C Arithmetic Expressions Formatting Numbers in Program Output Interactive Mode, Batch Mode, and.
1 ICS103 Programming in C Lecture 2: Introduction to C (1)
Introduction to C Programming
Representation and Conversion of Numeric Types 4 We have seen multiple data types that C provides for numbers: int and double 4 What differences are there.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
Programming Variables. Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They.
Chapter 2 Getting Started in C Programming
A First Book of ANSI C Fourth Edition
Chapter 2 : Overview of C By Suraya Alias. /*The classic HelloWorld */ #include int main(void) { printf(“Hello World!!"); return 0; }
1 Introduction to Computers II Lecture 4 Dr. Mehmet Demirer Dr. Seniha Esen Yuksel.
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
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.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
Input, Output, and Processing
C++ Programming: Basic Elements of C++.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 5, Lecture 1 (Monday)
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
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.
Arithmetic OperatorOperationExample +additionx + y -subtractionx - y *multiplicationx * y /divisionx / y Mathematical FormulaC Expressions b 2 – 4acb *
1 ICS103 Programming in C Lecture 8: Functions I.
CISC105 – General Computer Science Class 2 – 6/7/2006.
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.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
1 Lecture Three I/O Formatting and Arithmetic Dr. Sherif Mohamed Tawfik.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Variables, Operators, and Expressions
Arithmetic Expressions
Topics Designing a Program Input, Processing, and Output
CS1001 Programing Fundamental Lecture 5 Top-Down Design with Functions
ICS103 Programming in C Lecture 4: Data Types, Operators & Expressions
INSPIRING CREATIVE AND INNOVATIVE MINDS
TMF1414 Introduction to Programming
ICS103 Programming in C Lecture 3: Introduction to C (2)
Representation of data types
Arithmetic Operator Operation Example + addition x + y
Lecture3.
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
DATA TYPES There are four basic data types associated with variables:
Computer Science II CS132/601* Lecture #C-1.
Presentation transcript:

Representation of Data Types Comparing double and int data types Using integers are faster and more precise round-off errors when using doubles The range of double is from to The storage area of type int contains one binary number The storage area of type double has two parts: Mantissa is binary between (-)0.5 to (-)1 Exponent is an integer number => real number = mantissa * 2 exponent

Numerical Inaccuracies Certain fractions cannot be represented in a decimal system: 1/3 = …. Representational errors (round-off error) depends on the number of bits in mantissa => more bits smaller error Equality comparison of two double types can lead to surprising result Representational error affects the result when there is repeated computations: = 5 ?

Numerical Inaccuracies Cancellation error can be seen as a result of manipulating very large and small numbers: Manipulating two small numbers may result arithmetic underflow Manipulating two large number may result arithmetic overflow: specially for int data type (- 32,767 to 32,767) => using longint instead of int

ACSII Representation of Char Data Type Digits (‘0’-’9’) have the code values of Uppercase letters have consecutive decimal codes from 65 to 90 Lowercase letters have consecutive code values from 97 to 122 Printable characters from 32 to 126 int x; x = ‘1’; printf(“ %d”, x); Result is: 49

Arithmetic Expressions Arithmetic expressions uses arithmetic operators for int and double data types. Operators: + and - (can be used also as unary operators),*,/ and %(reminder or mod, which is used only for integer operands) The result type is determined by the operands: = * 2 = * 2.0 = 10.0

Operators / and % 7.0 / 2 is 3.5 but 7 / 2 is 3 7 / -2 depends on C compiler 7 / 0 is undefined % returns the integer remainder of division m = (m/n) * n + (m % n) (m % n ) < n 15 % 5 = 0 15 % 6 =3 15 % -7 depends on compiler 15 % 0 is undefined

Data Type of Expression If all operands have same data type, the type of expression is same as the type of operands If at least one operand is double, the type of expression is double too The expression, in which the operands are in different data types, is called a mixed-type expression In mixed type assignment (variable = expression) first, the expression is evaluated and then the value of expression is assigned to a variable x = 9 * 0.5 what is the result, if x defined as int? => 4 (only the integral part of 4.5)

Rules for Evaluating the Expressions with Multiple Operators What is the result of: (2 + 2) * 4 = ? and * 4 = ? Parenthesis rule All the expressions in the parentheses must be evaluated separately. In the nested parenthesized expressions the inner most expression must be evaluated first. Operator precedence rule: unary +, - first *, /, % next binary +,- last

Rules for evaluating Expressions a – b / c * d is evaluated as: a – ((b/c) * d ) Order of execution for the operators in the same precedence group is known as associativity Associativity rule: Unary operators in the same sub-expression at the same precedence level are right associative. It means the evaluation is from right to left. Binary operator in the same sub-expression and in the same precedence level (+ and –,for example) are left associative. It means the evaluations is from left to right

Rules for evaluating Expressions 2+2*8 Evaluation tree? | | | | * + PI * radius * radius (p2 – p1) / (t2 – t1) 8 – (3 + 9 / 2) + 2 * - (-5) is equal to: 11

Writing Mathematical formula in C Always specify multiplication explicitly with *. For example: b 2 – 4acb * b – 4 * a * c Use parenthesis to control the order of operator evaluation. For example for division: (a + b) / (c + d) Two arithmetic operators can be written in succession if the second is unary operator a × - (b + c)a * - (b + c)

Conversion of Data Types What are the results: double z = 5 / 4 => z = 1.0 int n = 1.2 * 1.2 => n = 1 double avg = (double) 15 / 6 => avg = 2.5

Conversion of Data Types Automatic conversion  In an expression, if one operand is double, then the result is a double  In an assignment statement variable = expression, if variable is double and expression is int, then the result will be converted to double If variable is int and expression is double the result converted to int and fractional part is lost

Conversion of Data Types Explicit conversion or cast has the highest precedence double x; x = 15 / 6; => x= 2.0 x = (double) 15 / (double) 6; => x=2.5 x := (double) 15 / 6 ; => x= 2.5 x = (double) (15 / 6); => x=2.0

/* Computes a test average */ #include int main(void) { int total_score, num_students; double average; printf("Enter sum of students' scores> "); scanf("%d", &total_score); printf("Enter number of students> "); scanf("%d", &num_students); average = (double)total_score / (double)num_students; printf("Average score is %.2f\n", average); return (0); } Enter sum of students' scores> 1822 Enter number of students> 25 Average score is 72.88

Case Study: Quality Control in Manufacturing Flat Washers Problem: Establish an initial quality control check for ½-inch flat washers. The program will compute the difference between the expected and observed areas and will print the difference as a percentage of the expected area.

Case Study: Quality Control Analysis: Data Requirements: Constants: PI WASHER_DIAMETER (1.0/2.0) OUTER_DIAMETER (17.0/16.0) Input: double observed_area; Output: double pct_differ; Program Variables: double washer_radius; double outer_radius;double rim_area; Relevant Formulas: area =PI * radius ^2, radius = 0.5 diameter, percentage difference of 2 areas: = ((expected area – observed area) / expected area) * 100 (relative error)

Case Study: Quality Control Design Initial Algorithm: 1. Get observed area of washer rim 2. Compute expected area of rim 2.1 compute washer_radius 2.2 compute outer-radius 2.3 compute rim-are = PI * outer-radius *outer-radius – PI * washer_radius* washer_radius 3.Compute percentage difference between expected and observed area 3.1 pct_differ = ((expected area – observed area) / expected area) * Display percentage difference Implementation

#include #define WASHER_DIAMETER (1.0/2.0) /* diameter in inches of a flat washer (diameter of the hole) */ #define OUTER_DIAMETER (17.0/16.0) /* diameter of edge of outer rim of a WASHER_DIAMETER-inch flat washer */ #define PI int main(void) { double observed_area; /* input - observed_area (in square inches) of a washer rim */ double pct_differ; /* output - amount of difference between observed and expected rim size, as a percentage of expected size*/ double washer_radius; /* expected washer_radius (radius of hole) */ double outer_radius; /* expected radius of washer rim's outer edge */ double rim_area; /* expected area of washer rim */ /* Get observed_area of washer rim */ scanf("%lf", &observed_area);

printf("Observed_area = %.4f sq. in.\n", observed_area); /* Compute expected area of rim */ washer_radius = 0.5 * WASHER_DIAMETER; outer_radius = 0.5 * OUTER_DIAMETER; rim_area = PI * outer_radius * outer_radius - PI * washer_radius * washer_radius; /* Compute percentage difference between expected and observed rim area */ pct_differ = (rim_area - observed_area) / rim_area * 100; /* Display percentage difference */ printf("Expected area differs from observed area by %.2f percent.\n", pct_differ); return (0); } Observed area = sq. in. Expected area differs from observed area by percent.

Case Study: Quality Control Testing: Run with a data file containing a few different observed sizes Output should be modified as: printf("Expected area (%.4f sq. in ) differs from”, rim_area); printf(“observed area by %.2f percent. \n”, pct_differ);

Function Implementation How we can translate the expressions with Sqrt and Absolute value in C? ( for example: ax 2 + bx + c = 0, a 2 = b 2 + c 2 – 2bc sin(α) program units called functions Using functions allows reusing of other programs. Functions act as black boxes that get input (input arguments) and produce a result (function result) For example: #include(math,h) a = sqrt(first) b = sqrt(second) c= sqrt(a + c)

/* Performs three square root computations */ #include /* definitions of printf, scanf */ #include /* definition of sqrt */ int main(void) { double first, second, /* input - two data values*/ first_sqrt, /* output - square root of first input value*/ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum*/ /* Get first number and display its square root.*/ printf("Enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("The square root of the number is %.2f\n", first_sqrt);

/* Get second number and display its square root.*/ printf("Enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("The square root of the second number is %.2f\n", second_sqrt); /* Display the square root of the sum of the two numbers.*/ sum_sqrt = sqrt(first + second); printf( "The square root of the sum of the two numbers is %.2f\n", sum_sqrt); return (0); } Enter a number> 9.0 The square root of the number is 3.00 Enter a second number> 16.0 The square root of the second number is 4.00 The square root of the sum of the two numbers is 5.00

Predefined Functions NamePurpose Argument(s) Return type fabs(x) Returns the absolute value of x double double abs(x) Returns the absolute value of x int int rand() Returns a random integer none int between 0 and RAND_MAX a constant defined in stdlib,h

User-Defined Functions Allows programmers to define special purpose functions with the same advantages of C’s library functions. Some of the advantages of using functions are: Changing the program into separate pieces Code reusing Easier modification and maintenance of the program More understandable program

User-Defined Functions A function is a grouping of program statements into a single program unit. It must be declared before it can be referenced. One way of declaration is to insert a function prototype before the main function Function prototype defines the data type of that function (type of the return value), function name and information about the arguments that the function expects.

User-Defined Functions The format for defining a function prototype is: ftype fname(argument list); For example: void instruct(void) is placed before the main function and shows instruct function that has no arguments and return value (void) Inside the main function, instruct can be called as: instruct (); Function definition, which is placed after the main function, specifies the function operation.

User-Defined Functions The function definition has the same heading as function prototype except for “;” symbol ftype fname(argument list) { executable statements; } Example: void print_star(void) { printf(“ ************* \n”);}

/*Performs three square root computations*/ #include /* definitions of printf, scanf */ #include /* definition of sqrt */ void instruct(void); /* Displays user instructions */ int main(void) { double first, second, /* input - two data values*/ first_sqrt, /* output - square root of first input value */ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum*/ /* Display instructions.*/ instruct(); /* Get a number and display its square root.*/ printf("Enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("The square root of the number is %.2f\n", first_sqrt);

/* Get second number and display its square root.*/ printf("Enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("The square root of the second number is %.2f\n",second_sqrt); /* Display the square root of the sum of the two numbers.*/ sum_sqrt = sqrt(first + second); printf( "The square root of the sum of the two numbers is %.2f\n", sum_sqrt); return (0); }

/* * Displays user instructions */ void instruct(void) { printf("This program demonstrates the use of the \n"); printf("math library function sqrt (square root).\n"); printf("You will be asked to enter two numbers --\n"); printf("the program will display the square root of \n"); printf("each number and the square root of their sum.\n\n"); }

User-Defined Functions Transfer of Control in function call When the computer executes a function call statement, it transfers control to the function definition. In the function definition after execution of the last statement in the function body, computer returns the control to the main program and executes the next statement after the function call. Example : instruct();  instruct (void) prinf(“Enter a number> “)  { ……}

User-Defined Functions Common programming errors with functions Not using #include preprocessor directive for the predefined functions Not defining a prototype before the main and definition after the main for the user defined functions Not using the correct order and type for the arguments of the functions Dividing by zero in the function body

#include int main(void) { int first, second; double temp, ans; printf("Enter two integers> "); scanf("%d%d", &first, &second); temp = second / first; ans = first / temp; printf("The result is %.3f\n", ans); return (0); } Enter two integers> 14 3 Arithmetic fault, divide by zero at line 272 of routine main Or in another environment the wrong result can be print: Enter two integers> 14 3 The result is 1.#IO