0% found this document useful (0 votes)
5 views

In Class Exercises 20210128 Turing

Uploaded by

othesub1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

In Class Exercises 20210128 Turing

Uploaded by

othesub1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CS2303 In Class Exercises

January 1, 2021

Abstract
Today’s goal is that you know the primitive data types in C, and how
to create your own non-primitive datatypes.

Name and WPI email:

1 Turing Machine Model


The Turing machine model of computation has a control, and a memory. We
will discuss the memory, and the idea that the control has a cursor positioned
at a specific point in the memory.

2 Memory in the Turing Machine Model


For each cell in the memory, there is an index number, called its address. Think
of memory as a roll of paper towels. Each sheet in the roll of paper towels
is indexed. The first sheet has index 0. The next sheet has index 1. Each
successive address is obtained by adding 1 to the current address.

Figure 1: The Turing machine models computation. There is a semi-infinite


memory. Think of it as a roll of paper towels that has a start, but no end. Each
sheet in the roll of paper towels has a number, starting with 0, and counting up
by 1.

1
Aloha BLM We are WPI

Figure 2: Some pins are for the address, and others are for data. Address pins
are countable.

3 A Memory Address
3.1 in Turing Machine
In a Turing machine, an address may be any of the natural numbers, starting
at 0. This is a countably infinite set.

3.2 in a Finite Machine


In machines we encounter, there will be an upper bound to the memory address.

3.3 in a Memory Chip


Memory chips have some number of address pins. The maximum address for
any given memory chip is given by all 1’s for the number of address pins it has.

4 A Pointer is an Address
In C, this address concept is very useful. It is renamed pointer. Think of the
control’s cursor in the Turing machine model diagram. The pointer “points
to” one sheet in the roll of paper towels. We associate the sheet in the roll of
paper towels with an addressable memory cell. Machines are typically byte-
addressable, so we associate the sheet in the roll of paper towels with a memory
cell containing 8 bits (called a byte). This means, the pointer corresponds to
the index, likewise the address, of that byte.
Pointers, addresses, are numbers. We can perform arithmetic with them.
Machines are byte addressable. If we add one to a byte address, we are
talking about the next byte.

LBGTQIA+
Aloha BLM We are WPI

Figure 3: The hotel staff point to a room. The room number, the “address”
of the room, is used to find the room. A hotel guest (Doe) is the content of
the room. When the name Doe is associated with room 123, room service can
be delivered to room 123 or Doe’s room, equivalently. If we add one to a hotel
room number, we are talking about the next room.

Addresses, pointers, are typed, that is, we declare them with a type, such as
int* for pointing to an integer. If we add one to an int*, we are talking about
the next integer.

5 Bytes
5.1 Binary Numbers, and Hexadecimal
Using the binary number system, it takes 4 bits to represent the numbers 0
through 15 inclusive. We like single digits, so after 0 through 9, we make use of
A through F to complete the idea of 0 through 15, but using single characters.
That way, we can also use 0 through 9, and A-F in the next “column”; this is
no longer the 10’s column, it is the 16’s column.
Fill in the remaining spots in the table. If you have any question about
how to do it, please ask. In subsequent lectures this material will be considered
background, so please take this opportunity to get it clarified.

LBGTQIA+
Aloha BLM We are WPI

Examples:
Word Decimal Binary Hexadecimal
Zero 0 0b0000 0x0
One 1 0b0001 0x1
Two 2 0b0010
Three 3 0b0011
Four 4 0b0100
Five 5
Six 6
Seven 7
Eight 8
Nine 9
Ten 10 0xA
Eleven 11 0xB
Twelve 12
Thirteen 13
Fourteen 14
Fifteen 15
It took 4 bits to represent 0 through 15 in the unit’s column, and 4 additional
bits to represent 0 through 15 in the 16’s column.
These 8 bits are called a byte, and they are the addressable unit in the
hardware.
Thought-provoking questions: Choose  X the best answer(s).

1. Given that a computing machine is byte-addressable, and that we can be


presented with only those eight bits, is that byte self-documenting about
whether it is a number or a letter?

 No, there is no way to know what the byte implies.


 No, we arbitrarily choose what a byte means after we receive it.
 No, but we assigned a meaning (number, letter, etc.) before we
started using the memory location where the byte is stored.
 No, but it does not matter, because we can interpret that byte how-
ever we like.
 No, because we can cast that byte into whatever datatype we want.
2. Given that a memory location contains a byte, if we overwrite an old value,
replacing it with a new value, can we undo that write, and thereby restore
the previous value?

 No, once a value is overwritten, it is gone.


 Not unless we use other memory elsewhere to save the former value,
from which we may be able to retrieve the former content.
 No, because that would require executing the code in reverse.

LBGTQIA+
Aloha BLM We are WPI

3. Given that a computing machine’s memory is byte addressable, is there a


way to change an individual bit?
 Yes, but it requires more than memory.
 The information of the initial byte, and the value of the bit to be
changed, and the location of that bit all need to be known.
 An arithmetic unit is used with the information in part B, to generate
the revised byte.

5.2 Numbers and Bytes


We shall defer numbers with fractional parts for now. Thinking on integers, in
mathematics they are classified as negative, zero or positive. In C, we have the
idea “unsigned”; in the set of “unsigned” bytes includes 0 through 255. If you
reflect on binary notation and the definition of byte as 8 bits, you will be able
to determine why 255 is the highest value of an unsigned byte.

5.3 Characters and Bytes


By keeping track elsewhere of the type of interpretation of a given byte, we can
use the eight bits within any given byte to mean one of several things. One
example is characters. In some smaller alphabets, such as the English alphabet,
the range 0 through 255 representable by one byte is sufficient to represent
the characters, and we have several codes, commonly we use the ASCII code.
Because each digit 0 through 9, and the letters A through F are all characters,
we can represent numbers as groups of characters. That implies there are at
least two ways to represent the hexadecimal digits: As binary numbers as seen
in the table above, but also as characters. When binary number representation
is used, 4 bits are enough. When using a character, 8 bits are used.
You can find the ASCII representation in many places, including https:
//www.ascii-code.com/ Fill in the remaining spots in the table. If you have
any question about how to do it, please ask. In subsequent lectures this material
will be considered background, so please take this opportunity to get it clarified.
Character ASCII
a 97
A 65
b 98
B 66
f 102
F
0 48
1
2

LBGTQIA+
Aloha BLM We are WPI

5.4 Signed Numbers, Two’s Complement


By contrast with unsigned numbers, we often want to be able to represent
negative numbers. An initial surmise is that one bit is reserved for the sign
(good idea). What might not be immediately imagined is that there is a good
reason for using the two’s complement form for representing negative numbers.
To understand two’s complement, consider that -1 is the number to which, when
we add 1, we get zero.
x+1=0
So, how might we best represent -1 with our byte? Consider, all of the eight
bits in the byte are 1. When we add 1 to that, each bit, starting on the right,
but carrying through all 8 bits, the 1 changes to a 0.
11111111
+00000001

00000000
and there is a “carry bit” that is one, which we can discard.
Thus, we added 1 to something, we got zero, so that something must be -1.

5.5 Using a byte to represent one of several possible ideas


Suppose there is some other memory keeping track of which interpretation is
being used for a given byte. Then we can look at a byte, augment it with an
interpretation, and see the idea that is being represented.
Fill in the remaining (empty) spots in the table. If you have any question
about how to do it, please ask. In subsequent lectures this material will be
considered background, so please take this opportunity to get it clarified.
Binary Unsigned Byte Signed Byte ASCII
00000000 zero zero Null character
00000001 one one don’t care
00000010 two two don’t care
... ... ... ...
01111110 126 126 don’t care
01111111 127 127 don’t care
10000000 128 -128 don’t care
10000001 don’t care
... ... ... ...
11111100 don’t care
11111101 don’t care
11111110 254 -2 don’t care
11111111 255 -1 don’t care

LBGTQIA+
Aloha BLM We are WPI

Figure 4: C datatypes, arranged, from


https://www.studytonight.com/c/datatype-in-c.php.

6 Using Multiple Bytes Together


C uses multiple bytes, grouped, to represent data. C uses the name datatype
to identify which group of bytes. Data could be from the set of integers that
goes higher than positive 255, and goes lower than negative 128. Multiple bytes
are needed to represent character sets with more than 256 members. Multiple
bytes are used to represent numbers with fractional parts.
To find out how many bytes C is using on your platform, use the operator
sizeof(). C supports multiple datatypes.
Though the diagram omits pointers, C also has pointers. For each of the
datatypes in C, there is a C datatype that is a pointer (address of) that datatype.
Are you wondering about this definition, that perhaps it does not have a ter-
mination condition? For example, suppose the datatype integer. The existence
of the datatype integer implies the existence of an address for any instance of
integer. Now that we have the datatype address-of-an-integer, (denoted int*),
we also must have the idea of an address for that address. It is denoted int**.
There is also the idea of address of one of those, and unsurprisingly it is
denoted int***. After a while, it becomes uninteresting to keep track of all
these levels of addresses. For those comfortable with the idea of RAM and other
memory chips, and the idea of a memory address register (MAR), consider the
integer to be located in RAM at some address, and consider that that address
is saved in RAM, with an address of its own. Then, we can access the address
in RAM, put the contents of the databus into the MAR, then use that value as
the address to get at the integer. We can do this process of using the data as
an address, as many times as we like.

LBGTQIA+
Aloha BLM We are WPI

Figure 5: The address of / pointer to a room would be denoted room*.

Figure 6: Where did I put (the key with) the room number? The address of /
pointer to where the room* is located is of type room**.

7 Variables
Variables do not have to remain constant. Pi remains constant, it is always
3.14159. . . . The amount of time before the next rain storm can be different.
When we have in mind (and in the computer) some information that could
change, and that we need to remember, we allocate some memory to hold that
information. That memory has an address, like hotel room 123, and we can
associate a name with it, like Doe. For the duration of Doe’s stay, Doe, and
guest at 123, are equivalent. No matter what datatype our byte, or group of
bytes, has, it is convenient to attach a name to it. You can write code that is
obscure to read by naming your data as var1, var2, var3 etc. Preferably, you
will choose names that convey something of the meaning of your data.
int numClasses = 5;
MovieTitle could be the name of a group of bytes that are being interpreted
as a list of characters. Of course there are movie titles of a single character. We
could write:

char movieTitle = ‘Z’;

When we have a collection of data, each datum of the same type, we can use
an array. We might have a collection of movie titles that we like, and another
collection of those we don’t.

LBGTQIA+
Aloha BLM We are WPI

char goodMovies[100][50];
char badMovies[100][50];

Each collection allows 100 movies, the names of which may each be as long
as 49 characters. (The last character is reserved to be ‘\0’.)
Then, to select at an element in the collection, we can use an index.
char favoriteMovie[50];
strcpy(favoriteMovie, goodMovie[3]); copies the fourth goodMovie into the
favorite, because strcpy is defined that way.

One idea about variables is that some memory has to be reserved for them
(so, they will have an address as a result of that reservation). We can also keep
track of their address if we wish.
float my2pi = 3.141 *2;

float* whereMy2piIs = &my2pi;

The amount of memory reserved depends upon the datatype. Variables that
are double take more bytes that variables that are float.

8 Pointers to Variables
Suppose we have two variables:
float my2pi = 3.141 *2;

and
double myOther2pi = 3.14159 *2;

We have pointers to these.


float* whereMy2piIs = &my2pi;

and
double* whereMyOther2piIs = &myOther2pi;

To access the memory just after that reserved for my2pi, the address of
my2pi is incremented:

*(whereMy2piIs+1)

refers to the next float after the float my2pi.


To access the memory just after that reserved for myOther2pi, the address
of myOther2pi is incremented:

*(whereMyOther2piIs+1)

LBGTQIA+
Aloha BLM We are WPI

refers to the next double after the double myOther2pi.


Recall that pointers are addresses, and addresses identify bytes. Recall that
double uses more bytes than float. It makes sense that pointers, which partici-
pate in pointer arithmetic, have a notion of the datatype to which they point.
Thought provoking questions:
Choose  X the best answer(s).
1. Suppose we have a datatype for building, and Fuller Labs is a building,
declared as:
Building fullerLabs;
Suppose further we keep in computer memory various attributes of Fuller
Labs, such as the number of lecture halls. Then, the address in memory
of that information is of type Building*.
Suppose we have multiple different buildings, each with its own address
and we have an “address book” that holds the addresses of all of our build-
ings.
Suppose we have a place where we keep our address book.
Suppose we leave a note for a friend, saying where the address book is.

 Each entry in the address book is a Building*. The address book


itself has an address of type Building**.
 We keep our address book at a place, that is of type Building**.
 The information in the note to our friend includes a Building**.
 The location of the note is a Building***.
 None of the above
2. A pirate prepares a treasure map, which includes the location of some
treasure. the datatype for the information in the map is Treasure*. The
pirate hides the map in a book in his library. The location of the book is a
Treasure**. The pirate leaves a note to an acquaintance, telling where the
book with the treasure map can be found. The datatype of information
in the note is Treasure**. The acquaintance puts the note in the pocket
of his overcoat. The datatype for the location of the note is Treasure***.
 The acquaintance’s wife send the coat to the cleaners. The location
of the coat is of datatype Treasure****.
 The cleaners present a ticket identifying the coat. The ticket contains
information of type Treasure****.
 The ticket is put in a box at the coat owner’s home. The location of
the ticket is of type Treasure*****.

9 Practice Declaring Variables of Primitive Datatypes


Variable names may not begin with digits. Variable names do not include spaces
or punctuation. Later (soon) we will see the use of the period.

LBGTQIA+
Aloha BLM We are WPI

It is a significantly good idea to initialize variables. The reason is, many


programmer errors arise from failure to initialize.
To initialize the value of a pointer, declare the variable to which it points,
first. If this is not suitable in the application, use 0; Either the pointer will be
set to some other value during execution, prior to being used to read, OR, if the
programmer makes a mistake, the code using the variable will try to read from
or write to address 0, which will cause a segmentation fault. This is readily
found and fixed. The alternative, which is using the variable uninitialized, will
cause random behavior, not necessarily recognized, which is a hassle to find
(This is bad.).
Fill in the remaining spots in the table. If you have any question about
how to do it, please ask. In subsequent lectures this material will be considered
background, so please take this opportunity to get it clarified.
Task: Datatype Variable Name Initialization
Declare and initialize int x =0;
a variable of type in-
teger
Declare and initial- char aLetter =’w’;
ize a variable of type
character
Declare and initial-
ize a variable of type
float
Declare and initial-
ize a variable of type
double
Declare and initial- int* xP =&x;
ize a variable of type
pointer to integer
Declare and initial-
ize a variable of type
pointer to character
Declare and initial-
ize a variable of type
pointer to float

10 Do It Yourself Datatypes
10.1 struct
Developers frequently have ideas that are expressible using aggregations of the
primitive datatypes in C. For example, contact information can include a per-
son’s name, address, birthday, shirt size, etc. Imagine have a datatype for
contact information, then a pointer to that datatype, and the ability to move
through a list of contacts by adding 1 to the pointer to the datatype.

LBGTQIA+
Aloha BLM We are WPI

Let’s make a simpler example to begin. Parts will be the same every time,
and the rest will be the decision of the developer.
typedef struct
{
int justACountingNumber;
double canHaveAFractionalPart;
char aLetterOrDigit;
long anIntegerThatCanBeBig;
} nameOfCustomType;

The first line, typedef struct, and the { after it, will be the same every
time.
The last line will always start with } will have some datatype name, and will
always end with a semicolon.
Here is an exercise. If you have any question about how to do it, please ask.
In subsequent lectures this material will be considered background, so please
take this opportunity to get it clarified.
Recall that complex numbers consist of two real numbers. For a real number,
use the C datatype double. Write a datatype for a complex number.

Imagine a datatype that combines an integer followed by a single letter. For


example 25B. Write a datatype for this.

To declare a variable of any datatype that is a struct, use the datatype name
and give a variable name.
For example, suppose we have:
typedef struct
{
int justACountingNumber;
double canHaveAFractionalPart;
char aLetterOrDigit;
long anIntegerThatCanBeBig;
} Motley4;

We can declare an instance of type Motley4; we need a variable name;


Motley4 m4;

To set values of m4, set the values of its component fields individually. For
example,

m4.justACountingNumber = 7;
m4.aLetterOrDigit = ’q’;

LBGTQIA+
Aloha BLM We are WPI

Practice: (If you have any question about how to do it, please ask. In
subsequent lectures this material will be considered background, so please take
this opportunity to get it clarified.)
Set values into variables of the type Complex you defined earlier.
We also might want to read values from the fields of a compound datatype.
Variable names to the left of the equal sign are getting assigned, just as when
we initialize. To read the value from a field, we identify the field we want on
the right hand side of the equal sign.
double someDouble = m4.canHaveAFractionalPart;

Practice: (If you have any question about how to do it, please ask. In
subsequent lectures this material will be considered background, so please take
this opportunity to get it clarified.)
Read a value from a field of a variable of the type Complex you defined
earlier, into a newly declared variable (which should be of the appropriate type).

10.2 enumerated types


Mathematics includes the idea of finite sets. Being finite, for a set, implies
that it is possible to enumerate the members of the set. This idea is useful
in programming, and C provides a means of specifying the members of such a
set. The members will be attached to distinguishable integers. The compiler
will perform this, and if the developer desires, the developer may specify the
integer to which a member is attached; the developer’s specification must allow
the members to be distinguishable using the integers.
Example:

typedef enum
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday = 100,
Saturday,
Sunday

}dayOfWeek;

11 Changing the Datatype of Data


It can happen that a variable has some content that makes sense in a datatype
different from the datatype of that variable. We can change the datatype that
is applied to the data. For example, we might have a character variable, and
wish to do some arithmetic with it. The Caesar cipher starts with a letter of the

LBGTQIA+
Aloha BLM We are WPI

(let us say, English) alphabet, and maps it to the letter offset by some integer.
Suppose we map a letter to the letter next after it. For ’z’, it becomes ’a’. So
we have a character, we want to think of it as a number, so that we can add 1
to it, so long as it is not a z. We can use the process of casting.

char aChar = ’a’;


int aCharI = (int) aChar;
int anotherInt = aCharI+1;
char anotherChar = (char)anotherInt;
printf("The resulting character is %c.\n", anotherChar);

Practice: (If you have any question about how to do it, please ask. In
subsequent lectures this material will be considered background, so please take
this opportunity to get it clarified.)
1. Using the code above, change it so that the letter is initially some alpha-
betic character other than a, but not w,x,y or z also not W,X,Y or Z. Also,
add 3 to it.

Note that, in ASCII, capital letters start at A=65, and small letters start
at a=97. Write code that will change a capital letter into the correspond-
ing lower case letter.
2. Create a datatype that is an enumerated type. In the datatype, list all
WPI buildings in which you have a class this term.

LBGTQIA+

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy