Lab_1_Numbers_Expressions_Simple_Programs

Download Report

Transcript Lab_1_Numbers_Expressions_Simple_Programs

Introduction to Computer
Science
Lab 1: Numbers and Arithmetic
Numbers and Arithmetic

Simple Expressions
(+ 5 5)
(+ -5 5) (+ 5 -5)
(- 5 5) (* 3 4)
(/ 8 12)
Numbers and Arithmetic

As in arithmetic or algebra, we can nest
expressions:
(* (+ 2 2) (/ (* (+ 3 5) (/ 30 10)) 2))
Numbers and Arithmetic
(* (+ 2 2) (/ (* (+ 3 5) (/ 30 10)) 2))
= (* 4 (/ (* 8 3) 2))
= (* 4 (/ 24 2))
= (* 4 12)
= 48
Numbers and Arithmetic

1.
2.
3.
4.
5.
advanced mathematical operations on
numbers
(sqrt A) computes (A) expt. 1/2;
(expt A B) computes A expt. B;
(remainder A B) computes the remainder of
the integer division A/B;
(log A) computes the natural logarithm of A;
and
(sin A) computes the sine of A radians.
Variables and Programs

In algebra we learn to formulate
dependencies between quantities
using VARIABLE EXPRESSIONS

A variable is a placeholder that stands
for an unknown quantity. For example, a
disk of radius r has the approximate area
pi * r * r
Variables and Programs

Expressions that contain variables are rules
that describe how to compute a
number when we are given values for the
variables

A program is such a rule. It is a rule that tells
us and the computer how to produce data from
some other data

(define (area-of-disk r)
(* 3.14 (* r r)))
Variables and Programs

The two lines say that area-of-disk is a
rule, that it consumes a
single INPUT, called r, and that the
result, or OUTPUT, is going to
be (* 3.14 (* r r)) once we know what
number r represents.
Variables and Programs
(area-of-disk 5)
(area-of-disk 5)
= (* 3.14 (* 5 5))
= (* 3.14 25)
= 78.5
Variables and Programs

Many programs consume more than one
input. Say we wish to define a program
that computes the area of a ring, that is,
a disk with a hole in the center:
Variables and Programs
(define (area-of-ring outer inner)
(- (area-of-disk outer)
(area-of-disk inner)))
Variables and Programs
;; 1. Contract: area-of-ring : number number -> number
;; 2. Purpose: to compute the area of a ring whose radius is
;; outer and whose hole has a radius of inner
;; 4. Definition
(define (area-of-ring outer inner)
(- (area-of-disk outer)
(area-of-disk inner)))
;; 3. Tests:
(check-expect (area-of-ring 5 3) 50.24)