Numbers In, Numbers Out

Similar documents
These are reserved words of the C language. For example int, float, if, else, for, while etc.

Computer System and programming in C

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Reserved Words and Identifiers

Data types, variables, constants

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

COMP Primitive and Class Types. Yi Hong May 14, 2015

Operators and Expressions:

Work relative to other classes

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Lecture 3 Tao Wang 1

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

C Programming

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Arithmetic Expressions in C

Programming and Data Structures

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

The C++ Language. Arizona State University 1

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Information Science 1

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

UNIT- 3 Introduction to C++

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Fundamental of Programming (C)

Chapter 2: Overview of C++

CS102: Variables and Expressions

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture 3. More About C

ARG! Language Reference Manual

Use of scanf. scanf("%d", &number);

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Declaration and Memory

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Engineering Problem Solving with C++, Etter/Ingber

Data Types. Data Types. Integer Types. Signed Integers

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Fundamentals of Programming

Chapter 2 Elementary Programming

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

H192 Midterm 1 Review. Tom Zajdel

Expressions and Casting

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Operators. Java operators are classified into three categories:

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Floating Point. CSE 351 Autumn Instructor: Justin Hsia

Programming for Engineers Introduction to C

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details.

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

C/C++ Programming for Engineers: Working with Integer Variables

Floating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754

CS313D: ADVANCED PROGRAMMING LANGUAGE

download instant at Introduction to C++

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Objectives. In this chapter, you will:

ANSI C Programming Simple Programs

Datatypes, Variables, and Operations

Full file at

(2-1) Numeric Expressions in C H&K Chapter 2. Instructor - Andrew S. O Fallon CptS 121 (August 27, 2018) Washington State University

Information Science 1

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Table : IEEE Single Format ± a a 2 a 3 :::a 8 b b 2 b 3 :::b 23 If exponent bitstring a :::a 8 is Then numerical value represented is ( ) 2 = (

2. Numbers In, Numbers Out

Chapter 2, Part III Arithmetic Operators and Decision Making

2. Numbers In, Numbers Out

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Visual C# Instructor s Manual Table of Contents

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CMSC 104 -Lecture 6 John Y. Park, adapted by C Grasso

Bits, Words, and Integers

Basics of Java Programming

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

printf( Please enter another number: ); scanf( %d, &num2);

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

Floating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754

Basics of Programming

Giving credit where credit is due

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Full file at

Chapter 2: Basic Elements of C++

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Full file at C How to Program, 6/e Multiple Choice Test Bank

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Python Programming Exercises 1

Giving credit where credit is due

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Unit 3. Operators. School of Science and Technology INTRODUCTION

Programming Lecture 3

A Fast Review of C Essentials Part I

Syntax and Variables

Transcription:

Programming, Problem Solving, and Abstraction Chapter Two Numbers In, Numbers Out c The University of Melbourne, 2018 Lecture slides prepared by Alistair Moffat

Chapter 2 2.2 Constants and variables and expressions statements

Chapter 2 Identifiers, variables and constants. Type hierarchy. Arithmetic operators and expression types. Precedence. Input using scanf and format descriptors. Output using printf and format descriptors.

An identifier is a name for a value. Identifiers must begin with a letter or underscore ( ) character They can then use any combination of letters, digits, and underscore They may not contain any other characters. Use meaningful identifiers, so that names reflect the quantities being manipulated.

Some words are reserved because they have special significance. For example, int and while were used in addnumbers.c. There are about two dozen such special words in C.

2.2 Constants Constants are fixed values that do not change. They are introduced using the #define facility: #define SEC_PER_MIN 60 #define MIN_PER_HOUR 60 #define EXAM_PERCENTAGE 60 #define PROJECT_PERCENTAGE (100 - EXAM_PERCENTAGE) #define KM_PER_MILE 1.609 Use symbolic constants for all fixed values, to improve readability and modifiability. Use different names for different concepts, even if they have the same value.

Variables can change value during program execution. Assignment statements store into variables the values generated by a corresponding expression. nitems = nitems+1; miles = km/km_per_mile; tot_seconds = (hours*min_per_hour + mins)*sec_per_min + secs; final_mark = (exam_mark*exam_percentage + project_mark*project_percentage)/100;

2.2 Exercise 1 Using suitable identifiers, write assignment statements to compute (a) the total surface area and (b) the total edge length, of a rectangular prism of edge lengths a, b, and c.

Variables must be declared before they are used. Each variable in a program has a type associated with it. Variables must then be assigned values before they can be used in expressions. Use of uninitialized variables is a common error.

2.2 Integers Variables of type int store integer-valued numbers in a constrained range, often 2 31 = 2,147,483,648 to +2 31 1 = +2,147,483,647. These bounds are a consequence of 32-bit words. overflow.c Beware. Integer overflow in C programs results in incorrect values propagating through a computation without warning messages being produced.

2.2 Doubles The type double can store fractional parts, and numbers over a wider range, but may not store them exactly. rounding.c addorder.c Care must be taken that rounding errors do not affect the usefulness of computed values.

2.2 Int versus double Constants also have types. If there is a. or an e (exponent part), it is a double. If not, it is an int. Label each of these constants with its type. Then put them in to order, from smallest to largest. -1.5e6, 3.14e1, -66.7e-1, 6.67e1-1.5, 30e0, -30, 667, 1e4, 100000

2.2 Constants and variables Each subexpression of an expression has a type dictated by the types of the operands. Use constants that match the variables they are being combined with. double energy, mass, velocity; /* BEWARE -- incorrect code */ energy = (1/2)*mass*velocity*velocity;

and expressions The precedence rules specify operator order. In the absence of parentheses, (all) the multiplicative operators are evaluated first. The expression 2+3*4 is 14, which might (or might not be) what your calculator gives. The remainder (or modulus) operator %, which must have two int arguments, is also a multiplicative operator.

2.3 Exercise 2 What are the values of: 6*7-8*9/10 2*3*4+5*6%7 5*6/4%3*5?

and expressions When both operands are of type int, the result is an int. If either operand is of type double, the result is a double. int n_pass, class_size; double pass_percent; /* BEWARE -- incorrect code */ pass_percent = n_pass/class_size*100;

and expressions Can use the type rules to ensure a correct calculation: pass_percent = 100.0*n_pass/class_size; Or can use an explicit cast: pass_percent = (double)n_pass/class_size*100;

and expressions When doubles are assigned to int variables the value is truncated. To get rounding, add 0.5 just before the assignment occurs: int n_pass, class_size, pass_percent; pass_percent = (int)(0.5 + 100.0*n_pass/class_size);

2.3 Exercise 3 What are the types and values of: (1+8/3*4.0/5+6)/2 (2.0*5*6/3)*(2/3) (int)(5*(double)6/8)?

2.3 Program layout Program layout is free-form. All whitespace is removed during the compilation process, except within strings. Semi-colons are used to terminate statements. Long statements may be broken over multiple lines. Thoughtful choice of identifiers makes programs readable. Comments should explain each block of code.

2.3 Divide by zero Integer division by zero usually results in program termination, with an error message like Floating exception. Floating point division by zero may result in the value inf being generated, or an arbitrary value. C systems might also make use of the double value nan (not a number), for example, when taking the square root of a negative number. Be sure you know what your C system does.

To read numbers into a program, use scanf: scanf( control string, list of variable addresses ) The control string specifies how the values are to be read: int n_pass, class_size, pass_percent; double mass, velocity, force; scanf("%d%d", &n_pass, &class_size); scanf("%lf%lf%lf", &mass, &velocity, &force);

To read an int, use %d. To read a double, use %lf. To read a float (reduced precision floating point), use %f. To read an char, use %c. Note the use of operator & prior to each variable name.

For the numeric types, leading white space characters are skipped. If an input character cannot form part of the current variable, it is assumed to mark the beginning of the next variable. If that input character cannot be part of the next variable, reading halts and no further variables are assigned values.

The number of variables successfully assigned is returned by the scanf and can be captured and used: num = scanf("%d %f %c", &n, &z, &c); printf("there were %d values successfully read\n", num); It is easy to make mistakes with scanf. Always echo back values after reading.

General structure: printf( control string, list of expressions ) Both double and float values are printed using %f the %lf format descriptor is used only for input. The descriptor %s is used to print strings.

Field widths control the layout. Positive values give right-aligned values, negative give left-aligned output. format.c

statements The general form of the assignment statement is: variable = expression Shorthand forms: sum=sum+next can be shortened to sum+=next, and n=n+1 to n+=1. Similarly, n/=2 divides n by 2. The postincrement and postdecrement operators go one step further: n++ and n-- add and subtract one from n.

statements Variables of type char are a restricted form of int, and character values like a are int constants. The ASCII mapping dictates the correspondence between integers and characters. The lowercase letters form a contiguous block starting at 97. The uppercase letters are a block starting at 65; the digits (from 0 ) at 48.

statements If an expression has a different type to the receiving variable, it is cast on assignment. mixedvals.c

Write a program that reads in the radius of a sphere, in meters, and calculates and outputs the volume of that sphere, in cubic meters. The volume of a sphere of radius r is given by 4 3 πr 3. spherevol.c

Some general advice when writing programs: Echo the input data Keep it simple Keep it neat Build it incrementally Test it at every stage. Programs should always be written presuming that the user will either deliberately or accidentally abuse them.

2.7 Exercise 4 Write a program that reads in a weight in pounds, and outputs the corresponding weight in kilograms. One kilogram is 2.2046 pounds. What is the metric equivalent of a 90-pound weakling?

Chapter 2 Use #define for all constants. declare and initialize all variables. int arithmetic will overflow silently int op int yields int, even if op is division. With float and double, operation order and rounding can affect the result Each type has corresponding input and output format descriptors. For double, %lf on input, and %f on output.