P1S2 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

How to Code: Simple Data

Introduction:
The techniques you will learn in this course can be used with any other programming
language you may learn in the future. To help you do that the course uses a specially
designed programming language called Beginning Student Language or BSL.

BSL is designed to have the core functionality of essentially all other programming
languages, but in a simple lean package that makes it easy to learn.

So by using BSL will be able to learn the language quickly. And then we have more time to
focus on learning the design method. Focusing on BSL for two reasons that One, because
it's simple. We'll learn it quickly. And two, and more importantly, is because it has the
core features of nearly all other languages by learning this technique using BSL it'll make
it easier for you to move it to other languages in the future.

Beginning Student Language or BSL


Beginning Student Language (BSL) is a specially designed programming language. So by
using BSL will be able to learn the language quickly. And then we have more time to focus
on learning the design method.

Expressions
An expression is an element of a program that is evaluated to produce a value or An
expression is combination of symbols that represents a value. Every language has its own
set of rules that are define whether an expression is valid or invalid in that language.

Example: 3, x, sqrt 2, x+5, bx+2, a+b+2, a*b+c-5

Operand is the value which operator is applied. Normally, Operators use constants and
variables to form as expression.

Types of Expressions:
Infix Expression: It is the most commonly used type of expression in which the operator is
placed in between the operands. Example: a=b-c
Prefix Expression: In this type of expression, the operator is placed before the operands.
Example: a=+ b c
Postfix Expression: In this type of expression, the operator is placed after the operands.

1|Page
Example: a=b c +

Comments:
Comments are the non-executable statements in a program. They are just added to
describe the statements in a program code. Comments make the program easily readable
and understandable by the programmer as well as the other users who are seeing the
code.

In BSL, “;” begins as a comment.

Note: A program can have any number of comments.

Operators:
Operators are the constructs that are used to manipulate the values of operands. Some
basic operators are include +,-,* and /. In an expression, an operator is used on
operands ( values to manipulated.). For example, in an expression sum=a+b, a and b are
operands and + is operator.

Values:
A value is a data element, such as 1, "foo", (make-cat 10 20) etc.

Numbers: 1, 3.5, 1/2, #i1.4142135623730951, ...

Strings: "Marvolo", "Black", "carrot", ...

Images: , ,...

Booleans: true, false

Compound data: (make-person "Claude" "Monet"), ...

Lists: empty, (cons 2 (cons 1 empty)), (cons "x" (cons "y" (cons "z" empty))), ...

Primitive Operations

2|Page
A primitive is a basic building block provided by BSL that we use when we design our
programs. BSL provides primitive data and primitive operations on data.

Example
+, -, *, / ...
string-append, string-length, substring ...
circle, square, overlay, above, beside...
not, =, <, >, string=?, string<?, cons, first, rest, empty?, cons?

Problems:
1) Assume that the two short sides of a right triangle have length 3 and 4. What is the
length of the long side? Recall that the Pythagorean Theorem tells us that:

Write a BSL expression that produces the the value of ? for this triangle where the
other two sides have lengths 3 and 4.

2) If you see #i2.718281828459045 appear in the interaction pane, it means:


a) It's an imaginary number.
b) Someone just sent a strange tweet.
c) It's a number very close to 2.718281828459045. correct
d) I thought you said there wouldn't be much math!

Explanation: Because computers are finite, DrRacket displays irrational numbers as


inexact numbers by adding #i to the front.

3) Identify which of the following are expressions:


A) sqr
B) (+ 2 3)
C) +
D) (sqrt 2)
E) #i1.4142135623730951
F) 1
G) )

3|Page
Explanation: At this point in the course an expression is either a value, or of the form
(<primitive> <expression> ...).

4) Which of the following are values:

sqr

(+ 2 3)

(sqrt 2)

#i1.4142135623730951

Explanation: Examples of values are numbers, strings, and images. Consult the language
tab for more information on values and how to form expressions.

5) What would be the result of evaluating the following expression:

(/ (* 2 3) (- 3 1))

18
6
2
3 correct

Explanation
Evaluating (* 2 3) produces 6, and evaluating (- 3 1) produces 2. 6 divided by 2 is 3.

6) Note that questions 6 and 7 go together; you may want to read both before
answering either.

Recall that the average of a set of numbers is the sum of the numbers divided by how
many numbers there are.

Which of these expressions produces the average of the numbers 4, 6.2 and -12? Check
ALL that are correct.
(/ 3 (+ 6.2 -12 4))

(/ (+ -8 6.2) 3)

4|Page
(/ (+ 4 6.2 -12) 3)

-0.6

Explanation
(+ 6.2 -12 4), (+ -8 6.2) and -.6 all evaluate to -0.6, so all three produce the correct result.

7) Which of these expressions most clearly expresses the idea that it computes the
produces the average of the numbers 4, 6.2 and -12?

(/ 3 (+ 6.2 -12 4))

(/ (+ -8 6.2) 3)

(/ (+ 4 6.2 -12) 3) correct

-0.6

Explanation
(/ (+ 6.2 -12 4) 3) shows the process being the math of averaging without skipping any
steps.

8) Why are we using Beginning Student Language in this course? Select all answers that
apply.

It is simple to learn, allowing you to focus your attention on the design methods
It is commonly used in industry, so you can get a job programming in BSL
It forms the core of many other languages, which will help you transfer what you
learn to other languages
There are so many popular programming languages that no single language will be
enough to learn

Explanation
BSL is very simple, so you will have a strong understanding of it. This allows us much
more time to focus the design recipes. Industry standard languages change all the time,
but the design methods can be applied to any language, helping you write well-structured
programs that are easy to read and easy to modify.

Exercise:
1) Write two expressions that multiply the numbers 3, 5 and 7.
The first should take advantage of the fact that * can accept more than 2 arguments.
The second should build up the result by first multiplying 3 times 5 and then multiply the
result of that by 7.

5|Page
Evaluation:
1) Consider the following expression:

(* (- 4 2) 3)

Select all calls to primitives.

(* (- 4 2) 3)

(- 4 2)

Explanation
(* (- 4 2) 3) and (- 4 2) are primitive calls because they are expressions that start with
open parenthesis and the name of a primitive operation.

2) Consider the following expression:

(* (- 4 2) 3)

Select all operators.

(* (- 4 2) 3)

(- 4 2)

Explanation

6|Page
* is the operator in the primitive call (* (- 4 2) 3), and - is the operator in the primitive
call (- 4 2).

3) Consider the following expression:

(* (- 4 2) 3 )

Select all operands.

(* (- 4 2) 3)

(- 4 2)

Explanation
Operands are all expressions that follow the primitive operator. So (- 4 2), 3 are operands
to *, and 4, 2 are operands to -.

4) What is the next step in the following evaluation?

Step 0: (/ (* 3 4) (+ (- 7 4) 3))

Step 1: (/ 12 (+ ( - 7 4) 3))

Step 2: (/ 12 (+ 3 3)) Answer

Explanation
The second operand to / is an expression, so it must be evaluated. And the first operand to
+ is an expression, so it must be evaluated. All of the operands to - are values, so - can be
called with 7 and 4 as arguments. This replaces the - call expression with 3.

5) What is the next step in the following evaluation?

7|Page
Step 0: (/ (* 3 4) (+ (- 7 4) 3))

Step 1: (/ 12 (+ (- 7 4) 3))

Step 2: (/ 12 (+ 3 3))

Step 3: (/ 12 6)

Explanation:
All of the operands to + have been evaluated, so + can be called with the arguments 3
and 3.

6) What is the next step in the following evaluation?

Step 0: (/ (* 3 4) (+ (- 7 4) 3))

Step 1: (/ 12 (+ (- 7 4) 3))

Step 2: (/ 12 (+ 3 3))

Step 3: (/ 12 6)

Step 4: 2

Explanation:
All of the operands to / have been evaluated, so the primitive can be called with the
arguments 12 and 6.

Exercise:
1) Write out the step-by-step evaluation for the following expression:

(+ (* 2 3) (/ 8 2))

Solution:
(+ (* 2 3) (/ 8 2))
(+ 6 (/ 8 2))
(+ 6 4)
10

2) Write out the step-by-step evaluation for the following expression:

8|Page
(* (string-length "foo") 2)

Solution:
(* (string-length "foo") 2)
(* 3 2)
6

Numbers:
Numbers refers to a numeric value.

Example: 2, 25 etc

Some Basic Predefined Functions BSL:


1) (number? v) : Returns #t if v is a number, #f otherwise.
Example: (number? 1) [Output: #t]
(number? "hello") [Output: #f]

2) (complex? v): Returns (number? v), because all numbers are complex numbers.

3) (real? v): Returns #t if v is a real number, #f otherwise

4) (rational? v): Returns #t if v is a rational number, #f otherwise.

5) (integer? v): Returns #t if v is a number that is an integer, #f otherwise.

Example:
(integer? 1)
#t
(integer? 2.3)
#f
(integer? 4.0)
#t
(integer? +inf.0)
#f
(integer? 2+3i)
#f
(integer? "hello")
#f

6) (zero? z): Returns (= 0 z).


Example:
> (zero? 0)
#t

> (zero? -0.0)


#t

9|Page
7) (positive? x): Returns (> x 0).
Examples:
> (positive? 10)
#t

> (positive? -10)


#f

> (positive? 0.0)


#f

8) (negative? x): Returns (< x 0).


Examples:
> (negative? 10)
#f

> (negative? -10)


#t

> (negative? -0.0)


#f

9) (even? n): Returns (zero? (modulo n 2)).


Examples:
> (even? 10.0)
#t

> (even? 11)


#f

10) (odd? n): Returns (not (even? n)).


Examples:
> (odd? 10.0)
#f

> (odd? 11)


#t

11) (quotient n m) : Returns (truncate (/ n m)).


Examples:
> (quotient 10 3)
3

> (quotient -10.0 3)


-3.0

12) (remainder n m): Returns the remainder

10 | P a g e
Examples:
> (remainder 10 3)
1

> (remainder -10.0 3)


-1.0

> (remainder 10.0 -3)


1.0

> (remainder -10 -3)


-1

13) (quotient/remainder n m) : Return both quotient as well as remainder


Example:
> (quotient/remainder 10 3)
3
1

14) (modulo n m) : Returns the remainder value


Examples:
> (modulo 10 3)
1

> (modulo -10.0 3)


2.0

> (modulo 10.0 -3)


-2.0

> (modulo -10 -3)


-1

15) (max x ...+) : Returns the largest of number .

Examples:
> (max 1 3 2)
3

> (max 1 3 2.0)


3.0

16) (min x ...+): Returns the smallest number.


Examples:
> (min 1 3 2)
1

11 | P a g e
> (min 1 3 2.0)
1.0

17) (gcd n ...) : Returns the greatest common divisor (a non-negative number) of the ns
Examples:
> (gcd 10)
10

> (gcd 12 81.0)


3.0

> (gcd 1/2 1/3)


1/6

18) (lcm n ...) : Returns the least common multiple (a non-negative number) of the ns;

Examples:
> (lcm 10)
10

> (lcm 3 4.0)


12.0

> (lcm 1/2 2/3)


2

19) (round x) : Returns the integer closest to x.

Examples:
> (round 17/4)
4

> (round -17/4)


-4

> (round 2.5)


2.0

> (round -2.5)


-2.0

20) (floor x) : Returns the largest integer that is no more than x.


Examples:
> (floor 17/4)
4

> (floor -17/4)

12 | P a g e
-5

> (floor 2.5)


2.0

> (floor -2.5)


-3.0

21) (ceiling x): Returns the smallest integer that is at least as large as x.

Examples:
> (ceiling 17/4)
5

> (ceiling -17/4)


-4

> (ceiling 2.5)


3.0

> (ceiling -2.5)


-2.0

22) (numerator q): Coerces q to an exact number, finds the numerator of the number
expressed in its simplest fractional form, and returns this number coerced to the
exactness of q.

Examples:
> (numerator 5)
5

> (numerator 17/4)


17

23) (denominator q) :
Coerces q to an exact number, finds the denominator of the number expressed in its
simplest fractional form, and returns this number coerced to the exactness of q.
Examples:
> (denominator 5)
1

> (denominator 17/4)


4

Number Comparison:
24) (= z w ...) : Returns #t if all of the arguments are numerically equal, #f otherwise.

13 | P a g e
Examples:
> (= 1 1.0)
#t

> (= 1 2)
#f

25) (< x y ...) : Returns #t if the arguments in the given order are strictly increasing, #f
otherwise.
Examples:
> (< 1 1)
#f

> (< 1 2 3)
#t

Powers and Roots


26) (sqrt z) : Returns the principal square root of z. The result is exact if z is exact and z’s
square root is rational.
Examples:
> (sqrt 4/9)
2/3

> (sqrt 2)
1.4142135623730951

27) (log z [b]): Returns the natural logarithm of z. The result is normally inexact, but it is
exact 0 when z is an exact 1. When z is exact 0,exception is raised.

Examples:
> (log (exp 1))
1.0

> (log 2+3i)


1.2824746787307684+0.982793723247329i

> (log 1)
0

> (log 100 10)


2.0

> (log 8 2)
3.0

> (log 5 5)

14 | P a g e
1.0

Trigonometric Functions

28) (sin z): Returns the sine of z, where z is in radians. The result is normally inexact, but it
is exact 0 if z is exact 0.
Examples:
> (sin 3.14159)
2.65358979335273e-06

29) (cos z): Returns the cosine of z, where z is in radians.


Examples:
> (cos 3.14159)
-0.9999999999964793

30) (tan z): Returns the tangent of z, where z is in radians. The result is normally inexact,
but it is exact 0 if z is exact 0.
Examples:
> (tan 0.7854)
1.0000036732118496

31) (asin z): Returns the arcsine in radians of z. The result is normally inexact, but it is
exact 0 if z is exact 0.
Examples:
> (asin 0.25)
0.25268025514207865

32) (acos z): Returns the arccosine in radians of z.


Examples:
> (acos 0.25)
1.318116071652818

33) (atan z)
Examples:
> (atan 0.5)
0.4636476090008061

> (atan 2 1)
1.1071487177940904

> (atan -2 -1)


-2.0344439357957027

Constants:
34) An approximation of π, the ratio of a circle’s circumference to its diameter.
Examples:
> pi

15 | P a g e
3.141592653589793

> (cos pi)


-1.0

35) (sqr z): Returns (* z z).

Strings and Images:


String: A string is a fixed-length array of characters. (A String is a group of characters). A
string is a data type used in programming which represent text rather than numbers. It is
comprised of a set of characters that can also contain spaces and numbers.

Example:
“Apple”, “I ate 3 Ice creams”, “12345”

Some Basic Functions:


1) (string? v): Returns #t if v is a string, #f otherwise.
Example:

2) (string-length str): Returns the length of str.

3) (substring str start [end]): Returns a new substring that that contains the same
characters as str from start inclusive to end exclusive. The first position in a string
corresponds to 0, so the start and end arguments must be less than or equal to the length
of str, and end must be greater than or equal to start, otherwise the exn:fail:contract
exception is raised.

16 | P a g e
4) (string-copy str): Returns the copy of the strings starts from 0 to end.
Example:

> (define s1 "Yui")

> (define pilot (string-copy s1))

> pilot
“yui”

5) (string-append str ...): Returns a new mutable string that is as long as the sum of the
given strs’ lengths, and that contains the concatenated characters of the given strs. If no
strs are provided, the result is a zero-length string.

6) (string=? str1 str2 ...): Returns #t if all of the arguments are equal?.

7) (string<? str1 str2 ...): Returns #t if the arguments are lexicographically sorted
increasing, where individual characters are ordered by char<?, #f otherwise.

8) (string<=? str1 str2 ...): Like string<?, but checks whether the arguments are

17 | P a g e
nondecreasing.

9) (string>? str1 str2 ...): Like string<?, but checks whether the arguments are decreasing.

10) (string>=? str1 str2 ...): Like string<?, but checks whether the arguments are
nonincreasing.

11) (string-upcase str): Returns a string whose characters are the upcase conversion of
the characters in str.

18 | P a g e
12) (string-downcase string): Like string-upcase, but the downcase conversion.

13) (string-foldcase string): Like string-upcase, but the case-folding conversion.

Exercise

1) What is the value of the expression below?

(substring "hello" 1 3)

"hello"

"hel"

"ell"

"el" correct

"he"

Explanation
Remember strings use zero-based indexing. The first number represents the character to
start at. In this case, 1. The second number represents the character to go up to but not
including. As shown below, 1 is the the 'e', and 3 is the second 'l'. Since substring starts at
'e' and goes up to but not include the second 'l' the answer is "el".
"01234"
"hello"

2) Will the following produce any errors?

(string-append "1" "2")

Yes
No correct

19 | P a g e
Explanation
"1" and "2" are both strings, so the expression above will not produce any errors. Just
because inside the "" looks like a number doesn't mean that "1" is a number. It is a string.
1 is a number.

3) Which primitive is required in the following expression to produce the stop sign
image below?

(_______ (text "STOP" 48 "white")

(regular-polygon 60 8 "solid" "red"))

above

beside

overlay correct

append

4) Which image will the following expression produce?

(beside (square 20 "outline" "blue")


(above (circle 15 "solid" "red")
(triangle 20 "solid" "green")))

correct

5) Assume that the image below shows an entire program file. Why does running the
program produce the following error?

20 | P a g e
We didn't define a function named above in the program.
We didn't include (require 2htdp/image) at the beginning of the program. correct
above does not accept a square as an argument.

6) We have revised the program now, why are we still getting an error?

We still need to define a function named above


We need to find the collection "2htpd"
We misspelled the name of the required module, so we need to replace "2htpd" with
"2htdp" correct

Images
Basic Images: prepare basic images by write code in BSL.

Example 1:
(require 2htdp/image)
(circle 30 "outline" "red")
(circle 20 "solid" "blue")
(circle 20 100 "blue")

21 | P a g e
Example 2

Example 3:

22 | P a g e
Example 4:

Example 5:

Constant Definitions:
To form of constant definition:
syntax: (define <name(id)> <expression>)

Defines a variable called name(id) with the the value of expression. The variable name’s
cannot be the same as that of another function or variable, and name itself must not
appear in expression.

Variable: variables are reserved memory locations that stores values. Or Variable is
memory location that can store any piece of information. Variables play a very important
role in most programming languages. Variables are nothing but just parts of your

23 | P a g e
computer’s memory where information is stored. To be identified easily each variable is
given an appropriate name. Every variable is assigned a name which can be used to refer
the value in the program.

Example for name (variable) declaration:


(define x 10)
(print x)
Output: 10

Identifiers: Identifiers as the name suggests, are name given to identify something like
variables , functions, objects etc.

There are some basic rules that you must follow for naming of identifiers:
1) ( ) [ ] { } " , ' ` ; # | \ and including a space characters are not allowed as a Identifiers.
2) Identifier name can be any sequence of characters such that “a to z”, “A to Z” “0 to 9” ,
!, @, $, %, ^, &, *, _,-, =,?,<,> etc.

Examples for Identifier:


Hfuhruhurr
integer?
pass/fail
john-jacob-jingleheimer-schmidt
a-b-c+1-2-3

Exercise:
Example 1:

24 | P a g e
Example 2:
Program to display data of different values using variables(names).

Example 3:
Program to reassign values to a variable.

2)

25 | P a g e
Input/Output Operation:
Output:
We use the print() function to output data to the standard output device (screen). Println
function is like print, but appends a newline to the end of the printed message.

Input: To take input from the users, Drracket makes use of (read) and (read-line)
functions. The (read) function prompts the user to provide some information on which
the program can work and give the result.

Example:

Assignment – I

1) What is BSL? What are the benefits of BSL?


2) What is an Expression and explain with example of Expression and evalution?
3) What is comment? Why we use comments? How to write comment in a program?
4) Define primitive? Explain primitive operations?
5) Define operator with example?
6) What is the value? Write an example for the value?
7) Write any 10 Mathematical operation functions with examples?
8) Define string? Explain any 5 string functions with examples?
9) Write a code for the following image?

10) Define variable with one example?


11) Explain identifier in detail?

26 | P a g e
12) Write a program to calculate area of triangle using Heron’s formula? (Hint: area =
sqrt(s*(s-a)*(s-b)*(s-c))
13)Write a program to calculate the distance between two points?
14) Write a program to print the digit’s at one’s place of number?
15)Write a program to enter two integers and then perform all arithmetic operations on
them.
16) Write a program to perform string concatenation?
17) Write a program to read a string in uppercase and then print it in lowercase?
18) Write a program to calculate simple interest?
19) Write a program that prompts users to enter two integers x an y. The program then
calculate and display xy.
20) Write a program that prompts user to enter his first name and last name and then displays a
message “Greeting!!! First Name Last Name”.
21) Write a program that calculate number of seconds in a day.

Functions:
A function is a set of expressions that’s only evaluated when call on at runtime. A
function can take arguments as input, and return values as output. Functions help break
our program into smaller and modular chunks. As our program grows larger and larger,
functions make it more organized and manageable. It avoids repetition and makes code
reusable.

Syntax:
(define (<function_name> <expression>)
(<body_of_expression>))

Or

(define (<function_name> <parameters> )


(<body_of _expression>))

or

27 | P a g e
Syntax to call the function:
(<name-of-the-defined-funciton> <arguments/operands>)

Basically, we can divide functions into the following two types:


1. Built-in functions
2. User-defined functions

1. Built-in Functions
Functions that come built into the BSL itself are called built-in functions and are readily
available to us.
Functions like print, read, read-line, display, println etc.

2. User-defined functions
Functions that we define ourselves to do certain specific task are referred as user-defined
functions.

Parameter is variable in the declaration of function.

Argument is the actual value of this variable that gets passed to function.

If a function is created with define, it uses an identifier for its name. functions are also
called procedures.

Example:
1. Write a program that add two numbers using a function.
(define (plus x y) (+ x y))
(plus 30 12)

Output: 42

2. Write a program that substract two numbers using a function.


(define (sub x y) (- x y))
(sub 30 12)

Output: 18

3. Write a program that arithmetic operation on two numbers using function.


(define (add x y) (+ x y))
(define (sub x y) (- x y))
(define (mul x y) (* x y))
(define (div x y) (/ x y))
(add 20 10)
(sub 30 10)
(mul 10 5)

28 | P a g e
(div 100 20)

Output:
30
20
50
5

4. Write a program that prompts users to enter two integers x an y. The program then
calculate and display xy using function.

(define (power x y) (expt x y))


(print “Enter a value”)
(define a (read))
(print “Enter b value”)
(define b (read))
(power a b)

5. Why should you use function definitions?

To be lazy
To make the code easier to read
To avoid duplicated code
All of the above

Explanation
All of these are good reasons because we would like to avoid redundancy and duplicate
code as programs get big, mainly so we can easily understand and navigate the code.

6. Suppose we want a function that will give the length of the hypotenuse of any right angle
triangle. Which of the following would achieve that?
Remember that the expression we used when the side lengths were 3 and 4 was:
(sqrt (+ (sqr 3) (sqr 4)))

(define (pythag 3 4)
(sqrt (+ (sqr 3) (sqr 4))))

(sqrt (+ (sqr a) (sqr b)))

29 | P a g e
(define c (sqrt (+ (sqr a) (sqr b))))

(define (pythag a b)
(sqrt (+ (sqr a) (sqr b))))

Explanation
The side lengths of the right angle triangle can vary, so we can write the following
function:
(define (pythag a b)
(sqrt (+ (sqr a) (sqr b))))

Where parameters a and b stand for the changing values.

7. What should we do to fix the following error:

Define i in the program


Include (require 2htdp/image) at the beginning of the program
Replace i with img, which is the name of the parameter for this function

8. Given the function:

(define (foo a b)
(+ (* 3 a)
b
(* b a)))

What is the first step of the evaluation of (foo (+ 1 1) 4), and what is the result of that
step?

Replace a and b with (+ 1 1) and 4 everywhere.


(define (foo (+ 1 1) 4)
(+ (* 3 (+ 1 1))
4

30 | P a g e
(* 4 (+ 1 1)))

(foo 2 4)

Replace (foo 2 4) with the body of foo in which we replace all occurrences of a with (+ 1
1), and b with 4.
(+ (* 3 2)
4
(* 4 2))

Evaluate (+ 1 1) and replace it in the function call of foo.


(foo 2 4)

Explanation
Because (+ 1 1) is an expression, not a value, it is first evaluated to 2 before moving on
with the evaluation of foo.

9. After the previous step of the evaluation we are left with:

What is the next step of the evaluation and what does that leave us with?

Replace a and b with 2 and 4 everywhere.

(define (foo 2 4)
(+ (* 3 2)
4
(* 4 2)))

(foo 2 4)

Replace (foo 2 4) with the body of foo in which we replace all occurrences of a with 2,
and b with 4.

(+ (* 3 2)
4
(* 4 2))
correct

31 | P a g e
Replace (foo 2 4) with the body of foo.

(+ (* 3 a)
b
(* b a))

Explanation
According to the rules for evaluating function calls, the first step is to replace the function
call by the body of the function in which every occurrence of the parameters a and b are
replaced by the corresponding arguments 2 and 4.

10. After the previous step of the evaluation we are left with:

What is the next step of the evaluation and what does that leave us with?

(* 3 2) is replaced with 6 and (* 4 2) is replaced with 8.


(+ 6
4
8)

(* 4 2) is replaced with 8.
(+ (* 3 2)
4
8)

(* 3 2) is replaced with 6.
(+ 6
4
(* 4 2))

Explanation
We now simply evaluate the expression (+ (* 3 2) 4 (* 4 2)) in left to right, inside to
outside order, so (* 3 2) evaluates to 6.

32 | P a g e
11. After the previous step of the evaluation we are left with:

What is the next step of the evaluation and what does that leave us with?

6 and 4 are added to produce 10.


(+ 10
(* 4 2))

(* 4 2) is replaced with 8.
(+ 6
4
8)
correct

(* 4 2) is replaced with 8 and 4, 6, and 8 are added together.


18

Explanation
Next, the expression (* 4 2) evaluates to 8.

12. After the previous step of the evaluation we are left with:

33 | P a g e
What is the next step of the evaluation and what does that leave us with?

6 and 4 are added to produce 10.


(+ 10
8)

6, 4, and 8 are added to produce 14.


14

6, 4, and 8 are added to produce 18.


18

Explanation
Finally, the expression (+ 6 4 8) evaluates to 18.

Exercise:
1. Write a user-define function to find the Max of three numbers.
2. Write a user-define function to multiply any five numbers.
3. Write a program to calculate simple interest using function?
4. Write a program find the area of circle using function.
5. Write a program to find sum of natural numbers from 1 to given number using
functions.

Boolean Expression:
A boolean expression is an expression that has relational and/or logical operators
operating on values or variables. A boolean expression evaluates that results in a value of
either TRUE or FALSE.

For example, the expression (< 2 5) (2 is less than 5) is a Boolean expression because the
result is TRUE.

Boolean expressions are also called comparison expressions, conditional expressions and
relational expressions.

List of all comparison and boolean operators.


Operator Description Operator
And true if both expressions are true
Logical
Or false if both expressions are false
operators
Not true if expression is false

34 | P a g e
= true if expressions are equal
< true if left expression is less than right
> true if right expression is greater than right Relational
<> true if expression are not equal operators

<= true if left is less than or equal to right


>= true if left is greater than or equal to right

Boolean Expression Truth Table of Logical Operators

1) And Truth Table

A B A and B
True True True
True False False
False True False
False False False

Syntax of and operator:


(and <expression1>, <expression2>, ….)

Description: all expression must produce Boolean value(true/false)

To evaluate and expression:


 Evaluate <expression> one at a time:
o If an <expression> produces false immediately produce false.
o If all expressions produce true then produce true.

2) OR Truth Table

A B A or B
True True True
True False True
False True True
False False False

Syntax of or operator:

35 | P a g e
(or <expression1>, <expression2>, ….)

Description: or operator produces true if any expression is true.

3) Not Table

A not A
True False
False True

Syntax of not operator: (not <expression>)

MCQ
1. What is the value of the expression below?
(> 10 5)
true correct
false
"true"
"false"
Explanation
10 is greater than 5 so the answer is true. Remember boolean values are not strings and
are case sensitive.

2. What about this one?


(> 5 5)
true
false correct
"true"
"false"
Explanation
5 is not greater than 5 so the answer is false. Again, remember boolean values are not
strings and are case sensitive.

3. Which of the following are predicates? Select all that apply.


+
= correct
string=? correct
string-append
correct

36 | P a g e
Explanation
Predicates are primitives or functions that produce a boolean value, so = and string=? are
examples of predicates.

If Expression
An if expression is a selection expression based on the value of given Boolean/conditional
expression. if has one conditional expression(Boolean expression) followed by two result
expression - the first is evaluated if the condition is true, otherwise the second is
evaluated.

Syntax: (if <expression (Conditional or Boolean expression) >


<expression>
<expression>)

OR

Flowchart

37 | P a g e
Example Program:
1) Write a program to determine whether a person is eligible to vote?

2) Write a program to find larger of two numbers?

3) Write a program to find whether the given number is even or odd?

4) Write a program to find the greatest number from the three numbers?

38 | P a g e
5) Write a program to determine whether a person is eligible to vote or not. If his is not eligible,
display how many years are left to be eligible?
Note: if you need multiple expressions in a branch, you can put them inside an empty let.

MCQ

1. What is the value of the if expression below?

(if (> (string-length "hello") 10)


"long"
"short")

true

false

"long"

"short" correct
39 | P a g e
Explanation

The question in the if expression is not a value, so we evaluate it and replace it with false.
Since the question is false, we replace the entire ifexpression with the false-answer
expression, which is just the value "short".

2. What is the value of the expression below?

(or (< 2 1)
(> 3 2)
(= 4 4))

true correct
false

3. Which comparisons are performed when the expression below is


evaluated?

(or (< 2 1)
(> 3 2)
(= 4 4))

Just the <


Just the >
The < and the > correct
All three <, >, =

4. Given:

(define B1 true)
(define B2 false)
What is the value of the expression below?

(or (not B1) B2)

true
false correct

40 | P a g e
When Expression:
Evaluate only one branch, use when. Like if, when starts with a conditional
expression(Boolean expression). Unlike if, the body of when can contain any number of
expressions. If the condition is true, the last body expression is returned as the result. If
the condition is false, the whole when expression returns void, a special constant used to
signal the absence of a result.

Syntax
(when <condition-boolean> <expression1> <expression2>…..)

Example:

Note: 1) Must include a basic package(library - require racket) on top of the program,
then only DrRacket supports the when expression.

Cond Expression:
The cond form is a multiway if expression. Cond supports any numbers of condition branches, and
an optional else branch. Cond evaluates the condition on the left side of each branch, and stops
at the where ever condition evaluated as true, followed by expression executed. Like when, the
right side can have any number of expressions, and only the last expression is returned as the
result. If no branches match, you get <#void>.

Syntax:
(cond [(condition1) <expr1> <expr2> ….]
[(condition2) <expr1> <expr2>….]
.
.
.
.
.
.
.
[else <expression>] )

41 | P a g e
Assignment – II
1) Define function and give its advantages?
2) What are user-defined functions? With the help of an example illustrate how you can have
such functions in your program.
3. Write a user-define function to find the Max of three numbers.
4. Write a user-define function to multiply any five numbers.
5. Write a program to calculate simple interest using function?
6. Write a program find the area of circle using function.
7. Write a program to find sum of natural numbers from 1 to given number using functions.
8. What is a Boolean expression and give an example?
9. Explain if expression along with syntax & flowchart? Write any program using if expression?
10. Explain when expression with an example?
11. Explain cond expression with an example?
12. Write a program that prompts the user to enter a number between 1-7 and then displays
the corresponding day of the week?
13. Write a program to input two numbers and check whether they are equal or not.
14. Write a program to enter the marks of a student in four subjects. Then calculate the total
and aggregate and display the grade obtained by the student. If the student scores an
aggregate greater than 75%, then the grade is Distinction. If aggregates is 60>= and <75, then
the grade is First Division. If aggregate is 50>= and <60, then grad is Second Division. If
aggregate is 40>= and <50, then the grade is Third Division. Else the grade is Fail.
15. Write a program to check whether a number is negative, positive or zero.
16. Write a program to check whether a number is divisible by 5 and 11 or not.
17. Take values of length and breadth of a rectangle from user and check if it is square or not.
18. Make a program that asks the number between 1 and 10. If the number is out of range the
program should display "invalid number".

Stepper:
What is the Stepper?
DrRacket includes a " stepper," a tool which proceeds through the evaluation of a set of

42 | P a g e
definitions and expressions, one step at a time. This evaluation shows the user how DrRacket
evaluates expressions and definitions, and can help in debugging programs.

Debugging: Programming errors are called bugs and the process of tracking them down and
correcting them is called debugging.

Loops:
Iterations are used to repeat the execution of list of expressions. Drracket supports for
iteration or for loop.

For loop: The for loop provides a mechanism to repeat a task until a particular condition
is True. The For loop is usually known as a determine or definite loop because the
programmer knows exactly how many times the loop will repeat. The number of times
the loop has to be executed can be determined mathematically checking the logic of the
loop.

Flowchart:
Condition
variable in False
specified range

True

Loop Body
List of Expressions

end
The basic for loop has two mandatory ingredients: an iterator binding, consisting of an identifier
and a sequence of values, and a body of one or more expressions. On each pass of the loop, the
next value from the sequence is assigned to the identifier, and the body of the loop is evaluated.
The loop exits when the iterator runs out of values.

Syntax:
(for ([id sequence-expr])
body of for loop)

43 | P a g e
in-range: The in-range function generates a sequence of numbers, given an optional starting
number (which defaults to 0), a number before which the sequence ends, and an optional step
(which defaults to 1).

Example 1 (in-range):
(for ([i (in-range 3)])
(print i))
Output: 012

Example 2 (in-range):
(for ([i (in-range 1 4)])
(print i))
Output: 123

Example 3 (in-range):
(for ([i (in-range 1 4 2)])
(print i))
Output: 13

Example 4 (in-range):
(for ([i (in-range 4 1 -1)])
(display i))
Output: 432

Example:
1) Design a program print 1 to 10 numbers using for loop?

2) Design a program print Hello world ten times using for loop?

44 | P a g e
Assignment – III
1) Write a short note on for loop (definition, syntax, flowchart, example) ?
2) Define stepper? What is the use of stepper in Drracket?
3) Define bug and debugging?
4) Write a program using for loop to calculate the average of first n natural numbers?
5) Write a program to print the multiplication table of n, where n is entered by the user?
6) Write a program using for loop to print all the numbers from m-n thereby classifying them
even or odd?
7) Write a program using for loop to calculate factorial of a number?
8) Write a program to calculate pow(x,n)?
9) Write a program to sum the series – 1+ 1/2 + 1/3 + ---- + 1/n.
10) Write a program to sum the series - 1 + 1/22 + 1/32 + ----+ 1/n2.
11) Write a program to sum the series – 1/2 + 2/3 + 3/4 +-----------+ n/(n+1).
12) Write a program to sum the series -1/1+ 22/2+32/3+ -------------n2/n.
13) Write a program to calculate sum of squares of numbers from 1 to n.
14) Write a program to calculate sum of cubes of numbers from 1 to n.
15) Write a program to sum of squares of even numbers from m to n?
16) Write a program to print 20 horizontal asterisks(*)?
17) Write a program to calculate the sum of numbers from m to n.
18) Write a program to print 20 vertical asterisks(*)?
19) Write a program to print all even numbers between 1 to 100.
20) Write a program to print all odd numbers between 1 to 100.
21) Write a program to find sum of all even numbers between 1 to n.
22) Write a program to find sum of all odd numbers between 1 to n.

45 | P a g e

You might also like