cs102: introduction to computer science - cooper...

Post on 16-Mar-2018

223 Views

Category:

Documents

4 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CS102:Introduction to Computer Science

LESSON 3:

© 2016 Sean CusackAll rights reserved.

© Foxtrot© XKCD

Some Defaults & Locations

● Also, ssh to students, and cp this to your homedirectory, from my home directory:cp /home/c/cusack/.profile

● Then go to your lab directory, in prep for today(and the equivalent for future weeks):cd cs102*/lab-3

Recap

● Flood gates and canals● Binary● Translators (Pseudo-English to Computer-Speak)● Assemble

Disassembly

● That's well and good, but there are two reasons not to write inAssembler:

– It's really long and messy

– No one could decide on a standard, so each machine you workon has a completely different syntax for everything

● So instead, there came languages like C. These languages are:

– Much more concise and easy to read

– Very very similar from architecture to architecture

● And the work of turning C into Assembler is done by a program calledthe “Compiler”

● What's C?

Thought I wrote that myself, didja?

● It's the better way of writing that example. Copy from mydirectory:cp /home/c/cusack/prog.c ./prog.c

● Here's the part we want to focus on:a = 1;b = a;c = a;d = b + c;

● Now, let's make the “compiler” turn it into “Assembler language”(note the capital-S next to the dash):gcc -S prog.c -o ./prog.s

● Side note, to interject a quick new UNIX program and prove thisto ourselves (there's no difference):diff /home/c/cusack/prog.s ./prog.s

Translator

English Babylonian

ProgrammingLanguage

(C, assembler)

ComputerLanguage(Binary)

Translator

GCC

New Translator for Hire

● This means that C is another language used for writing rules for acomputer (like English)

● Those rules are translated into Assembler instructions by aCompiler (from English to Babylonian)

● And Assembler instructions are converted into machine languageby the Assembler (and from Babylonian to Latin)

● The final result is a binary file, the program itself (like Latin)

● This is the only thing the computer knows how to do: theinstructions in a program

● To avoid removing the wrong pens or rotating them around thewrong axis, we have to provide an unambiguous language...

Syntax

● C syntax, or grammar, is meant to be a marriageof English and mathematical constructs

● There are variables, constants, vectors, andfunctions, just like math

● And you can also look at them like nouns andverbs just like English

Statements

● Just like in English or math, the main “unit” of Cis a “statement”

● Do X, set memory Y to 0101, add 0101 and 1000and put them in memory Z... these are allstatements—individual instructions

● In C, all statements end with a semicolon:;

Variables

● In English, we might say “I need a place to keepsome information, so let there be a container Athat can hold a number for me”

● In math, “let A be an integer”● In C:

int A;

● From that point on, A will mean some place inmemory that can store an integer

Other Variables

● In addition to integers, there are characters andfloating-point numbers (real numbers):char B;float C;

● Since the cornerstone of a program running is thefloodgates and moving memory around, it isimportant to set up all the variables you wantfirst, before anything else

● In C, you must “declare” all variables beforedoing other stuff, even using them

Shapes of Variables

● So “declaring” (creating) a variable, is likemaking a place to put it:int y;

● And assigning to it puts something into it:y = 5;

y

y5

Shapes of Variables 2

● Regarding “y”...● It's “name” is “y”.● It's “type” (shape/color of the bucket) is “int”.

That means only “int” things can go in there.Luckily 5 is an “int”.

● It's “value” is currently 5, but it might change.

Setting and Getting Variables

● In English, we might write “put the number onein the location marked A”; in math, “let A = 1”

● In C:A = 1;

● To make a copy of what's in another variable:Q = A;

● Note that variables are scalars● And note that you can create and set an initial

value all at once:int X = 99;

Assignment, not equality

● It's very important to differentiate between"assigning" and "equating", this:

A = B;in our programming language means "make acopy of whatever is in B right now, wipe outthe contents of A, and put it there"

● It does not mean "A and B should stay equal"● Also, a reminder that assignment goes leftwards● Which means you will never see this:

A + 1 = B;

Assignment, not equality 2

● A = B;

A5

B4

COPY

4

A5

B4

COPY

4

A5

B4

A4

B4

Assignment, not equality 3

● A = 3;

A5

B4

A4

B4

3

A5

B4

A3

B4

Untouched

Operators

● Most mathematical constructs can be used inconjunction with variables to manipulatenumbers and store the results someplace:A = 1 + 2 + 3;B = A / 2 - C;C = A * B;

● Some operators are more esoteric; look at yourK&R book or google for a full listing, i.e.:A = B % 12;C = 0x01a9 ^ 0x9b67;

Truth or Dare

● There are also operators that are used for pure-logiccomparisons, i.e. T intersection F = F, T union F = T

● In C, any number that is non-zero is “True” for purposesof logic, and zero is false:TRUE = 1;FALSE = 0;TRUE_INTERSECTION_FALSE = TRUE && FALSE;TRUE_UNION_FALSE = TRUE || FALSE;

● Note: in C, extra spaces or newlines don't matter in themiddle of statements... CaSe dOeS, tHoUgH: TRUE isnot the same variable as tRuE.

&& | |

Truth Tables

AND T F

T T F

F F F

OR T F

T T T

F T F

NAND T F

T F T

F T T

NOR T F

T F F

F F T

XOR T F

T F T

F T F

No Comments from the Peanut Gallery

● Comments are text that have absolutely no effect on the programwhatsoever

● They start with “/*” and end with “*/” and can span lines, i.e.:/* this is a comment */

● Why use them, then? Clarity. It is best to put periodic commentsin your program that explain what you're doing, so the nexttime you look at it, you can tell by reading English and notcode.

● Also:/* Sean Cusack Assignment -1 Sept 32, 2050 */

Boxes

● We can't draw boxes (or"blocks" around thingsusing just text, todistinguish between:

Do these things 5 times:FirstSecondThird

● And this:

Do these things 5 times:FirstSecondThird

© Ron Wheeler, cartoonworks.com

So... Braces! (No not that kind)

Braces

● So we do it this wayinstead:

Do these things 5 times:{FirstSecond}Third

● And this:

Do these things 5 times:{FirstSecondThird}

Because it reminds us of math...and we call it a "block"

x={y<0, 10; y>=0, 20

}

Functions

● Functions are shortcuts, they mean “perform a bunch ofcommands that have already been written elsewhere”

● They are useful for encapsulating a list of commonly-done commands into one larger command

● You mom never told you to “walk to the bathroom, pickup your toothbrush, put toothpaste on the bristles,open your mouth, apply brush to teeth in an up-and-down fashion” before you go to bed

● Instead, she taught you what actions went into “brushyour teeth” and referred to that set of actions as oneaction

Function Definition

● In English, we might say “when I say triplesomething, I mean multiply that something bythree and refer to the result”

● In math, we say “triple(x) = x * 3”● In C (we'll get into this syntax more later):

int triple( int x ) { return x * 3; }

Notice the braces, or blocks

Function Usage

● In English, now that we've defined “triplesomething”, we can say “triple the number 6and put it in the place marked X”

● In math, “let X = triple(6)”● And in C:

X = triple(6);

● Note that like in math, where f(x,y) can have twoarguments, so can C functions... arguments areseparated by commas

Function Usage 2

● Regarding “triple”● It's “name” is “triple”● It's “type” is “function that takes one integer and

produces one integer” – we will get back tothis another class, but it does have a “type”

● It has a “value”, too, but that is beyond the scopeof this class

Function Usage 3

● triplevstriple(6)

● One “names” the function and one “uses” or“executes” it

● If you don't have parentheses there, you're not“using” the function

Function Usage 4

● x = cut_in_half

x

Function Usage 5

● x = cut_in_half(6)

x

63

Pre-made functions

● Some functions in C aren't used to evaluate numbers, butrather to take an action of some sort

● One important one has already been written for you, andyou can use it immediately:

fprintf( stdout, "hello, world!\n" )

● Note that it takes two arguments, some esoteric stdoutthing and something in quotes that is reminiscent ofyour assembler programs

● But you'll never see:

x = fprintf( stdout, "hello, world!\n" )

Cryptic Syntactic Sugar

#include <stdio.h>

int main( int argc, char **argv )

{

... whatever variables and commands you want ...

return 0;

}

Notice the braces, or blocks

Create Buckets Before Anything Else

#include <stdio.h>

int main( int argc, char **argv )

{

int a;

int x; /* etc */

/* for loops, assign variables, printing,

everything else */

return 0;

}

Recap of the Translator Dance

● If your file full of C statements is called file.c:gcc file.c -S -o file.swill “translate” (we call it “compile”) it intoanother language, Assembler, and put that intofile.s

● And if you do just like last week and assemblethat result (file.s) into machine language, thatis put into the runnable file “file”:gcc file.s -o file./file

Translator

English SumerianE/T Translator BabylonianS/B Translator

C AssemblerGCC -S BinaryGCC

A Matter of Automation

● Before we continue with learning the syntax ofC, let's step back and think about why weprogram.

● Humans make mistakes (look at all the typos inmy lectures), but computers don't, they do whatthey're told, flawed or not, perfectly.

● Humans are slow. Count to a billion and it takes30 years. A computer will do this in a matter ofseconds.

Department of Redundancy Department

● We've gone over variables to describe how we utilizeprogramming to manage precise tasks like math (plususing characters, an aside for now).

● Now we go over how to do repetitious tasks. If youwanted to add up the numbers from 1 to 5 using C,would you type them all in? 1+2+3+4+5...? Maybe.

● How about adding the numbers from 1 to 10000?

● So how can we have the program do more things thanwe type? Simple. Tell it to repeat itself.

For

● In English, we might tell someone “while youare not done cleaning your room, keepcleaning”, or in a more mathy example “whilethe number I is less than 5, keep doingsomething”

● In math, this is similar to summation:i<5

Σ do somethingi=0

For [cont'd]● In C, we don't have fancy symbols, we have to do it one piece at a

time. If we want to do something 5 times “keep track of howmany times we have done something, and do it while keepingtrack, and stop when we've hit that number"

● In C:int i;

for( i=0; i<5; i=i+1 ){ /* do something */ }

Notice the braces, or blocks

While● Or

● In C:int i = 0;

while( i < 5 ){ /* do something */ i = i + 1;}

Notice the braces, or blocks

While [cont'd]● If we want to add the numbers from one to ten, one way of saying

that would be “add a number to our sum, starting from 1,increasing the number by 1 each time, until the number we'readding is 5”

● In C:int i = 1;int sum = 0;while( i < 5 ){ sum = sum + i; i = i + 1;}

Previous slide's program as a"checklist" or spreadsheet

i sum while-loopi=1 1sum=0 1 0i < 5 1 0 yessum = sum + i 1 1i = i + 1 2 1i < 5 2 1 yessum = sum + i 2 3i = i + 1 3 3i < 5 3 3 yessum = sum + i 3 6i = i + 1 4 6i < 5 4 6 yessum = sum + i 4 10i = i + 1 5 10

FlowchartSTART

sum = sum + 1

i = i + 1

i < 5TRUE

END

FALSE

for /while

Whoops

● Did we actually sum the numbers between 1 and5 inclusive?...

Common Oopsies

● Off-by-one errors● Rampaging semicolons● Never getting anywhere● Never caring where you've gotten to● Counting before you've noted what you're

counting

Off by One

i=1;while(i<50){ /* do something */ i=i+1;}

i=1;while(i<=50){ /* do something */ i=i+1;}

i=0;while(i<=50){ /* do something */ i=i+1;}

i=0;while(i<50){ /* do something */ i=i+1;}

While Always

int i = 1;

while( i < 3 )

{

/* do something */

}

While Always - Fix

int i = 1;

while( i < 3 )

{

/* do something */

i = i + 1;

}

While Always 2

int i = 1;

while( i < 3 );

{

/* do something */

i = i + 1;

}

Never a semicolonafter the parenthesesfor “while”, “for”,

or “if”.

It essentially means{ }

which is the sameproblem as in

“While Always 1”

While Always 2 - Fix

int i = 1;

while( i < 3 )

{

/* do something */

i = i + 1;

}

STOP!

● If you are running a program and it won't stop,hit CTRL-C

● It usually means you did one of those “WhileAlways” things, or something similar

While Oops

int i = 1;

while( i < 3 )

{

i = i + 1;

}

while( i < 3 )

{

i = i + 1;

}

While Oops - Fix

int i = 1;

while( i < 3 )

{

i = i + 1;

}

i = 1;

while( i < 3 )

{

i = i + 1;

}

While Oops 2

int i = 1;

int sum = 0;

while( i < 3 )

{

i = i + 1;

sum = sum + i;

}

While Oops 2 - Fix

int i = 1;

int sum = 0;

while( i < 3 )

{

sum = sum + i;

i = i + 1;

}

The Big “If”

● In English, we can say “ifsome case is true, doone thing”, otherwisedo anoth, like “if thesum is 55, put 1 intovariable X”, otherwiseput 2 in variable X

● Also notice the braces /blocks

● In C:if( sum == 15 ){ X = 1;}else{ X = 2;}

The Big “If” + “Else”

● In English, we can say “ifsome case is true, doone thing, otherwise doanother”, like “if thesum is 55, put 1 intovariable X, otherwiseput 2 in variable X”

● Also notice the braces /blocks

● In C:if( sum == 15 ){ X = 1;}else{ X = 2;}

Comparisons

● In order to compare two values, notice theprevious slide's "=="

● There are several:==, !=, >=, >, <=, <

● "==" is not "="!● And no, you can't do this in C:

x < y < z● It has to be:

x < y && y < z

Lab Assignment 1

● Write a basic “hello world” program, that has the“cryptic stuff” surrounding just the one fprintf()function call to print "hello, world\n" in lab1.c

● Compile that program into assembler, assemble theassembler code into machine code, and run itgcc -S lab1.c -o lab1.sgcc lab1.s -o lab1./lab1

● [Approx 6 lines – order of magnitude discussion]

Lab Assignment 1a

● Copy lab1.c to lab1a.c● Repeat the fprintf line 10 times (cut-n-paste)● Compile, assemble, run● [Just a cut-n-paste of 9 lines]

Lab Assignment 2

● Copy lab1a.c to lab2.c● Edit the program to have it print 10 times. This

time, don't type 10 fprintf()'s - use for or while● Compile, assemble, run● Note: programming tip – have two windows

open, one for pico or notepad and one for unix.Use the pico/notepad one to make changes toyour file and save, but don't exit. Use the otherwindow to compile and run.

● [Approx 10 lines total – 4 different than lab 1]

Lab Assignment 3

● Copy lab2.c to lab3.c● Print hello 10 times like before, but then also

print goodbye (or something else) 10 times,also using a loop (for or while)

● Compile, assemble, run● [Approx 15 lines total – 5 different than lab 2]

Homework Prep

● Make sure to COPY your repetitive.txt andsimpler.txt to your current lab directory:

#> pwd/home/c/cusack/cs102*/lab-3#> cp ../homework-1/repetitive.txt ./● And the same for simpler.txt● Now, you have a separate copy that you can look

at, without editing your original homework

top related