73
APS105 Introduction 1 Textbook Chapter1

APS105 - Electrical & Computer Engineering

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: APS105 - Electrical & Computer Engineering

APS105

Introduction

1

Textbook Chapter1

Page 2: APS105 - Electrical & Computer Engineering

Welcome

• To University and UofToronto

• To Engineering

• To APS105

2

Page 3: APS105 - Electrical & Computer Engineering

About your Prof

• Prof. Greg Steffan

– PhD Computer Science, Carnegie Mellon, 2003

– BASc/MASc, ECE, UofToronto, 1995/1997

• Research

– Making multicores and FPGAs easier to program

• Contact:

[email protected]

– Office: EA321

– Office hours: wed 12-1pm (after class)

3

Page 4: APS105 - Electrical & Computer Engineering

Why Learn About Programming

and C?

4

Page 5: APS105 - Electrical & Computer Engineering

Why Learn Programming?

• Computers: our most powerful technology

– Learn to command them to do your bidding!

• For love of design

– Programming is pure design with few limitations

– “only slightly removed from pure thought-stuff”

• Entrepreneurial opportunities

– Start a company in your bedroom with no $$$

• Many engineering jobs involve programming

– Simulations, databases, websites

– Whether civil, electrical, mechanical…

5

Page 6: APS105 - Electrical & Computer Engineering

Why Learn C? • Lots of other newer, “hotter” languages

– Java, Python, Ruby, javascript

• Benefits of C:

– “Compiled language”, not “interpreted”

• Close to the hardware with no layers between

• Easier to understand what is happening

• Important building-block for later computing courses

– C/C++ still very common

• In high-performance applications

• In low-level code like operating systems, databases,…

– C-like-syntax found in many of above languages

6

Page 7: APS105 - Electrical & Computer Engineering
Page 8: APS105 - Electrical & Computer Engineering
Page 9: APS105 - Electrical & Computer Engineering

Why Attend Lectures?

• To see someone else think through problems

– Different than simply seeing the solution

• Learn “why”, not just “how”

– how course material fits in with “big picture”

• Will provide proper emphasis and pacing

– Highlight key material

– Overview-only sundry material

• Will teach material in order of importance

– Eg., order that you need it for labs

• Ideally more entertaining than reading manual

– Else Prof-fail.

9

Page 10: APS105 - Electrical & Computer Engineering

Administration

10

Page 11: APS105 - Electrical & Computer Engineering

Evaluation

• Labs: 17%

– 8 total

• Quizzes: 8%

– 4 total

– Given in last 20mins of some tutorials

– Based on lecture material since last quiz

• Midterm: 25%

– October 17, 2013, 6:00pm-8:00pm

• Final Exam: 50%

– Emphasis on 2nd half of course

11

Page 12: APS105 - Electrical & Computer Engineering

Course Website

• Portal.utoronto.ca

– APS105 (All Sections)

• Any Handouts

– Lab Assignments

– Past Exams

– Petition Form for missed labs/quizzes

– Form for regrade request for misgraded midterm

• Discussion Board

• These lecture slides!

– (but with blanks to fill...more later)

12

Page 13: APS105 - Electrical & Computer Engineering

Labs (programming assignments)

• There are 8 of them in total

– You will always be working on one

• First lab (lab1) available asap

– Can submit to test, but not graded

– But do submit to test/practice!!

• Must run properly on ECF systems

– Even if it runs fine elsewhere

• Must output exactly as prescribed

– Close isn’t good enough

• Marks for functionality and style

– Proper style will be defined throughout term

13

Page 14: APS105 - Electrical & Computer Engineering

Course Meetings • Lecture Periods:

– three one-hour lectures per week

– Start at 10mins after the hour

• Tutorial Periods:

– One per week, run by TAs

– 4 tutorials have quizzes during last 20mins (see schedule)

– Attendance optional, unless there is a quiz

• Weekly Optional Lecture:

– review of regular lecture material

– attendance recommended for non-experts

– Tuesdays starting Sep18 (entire course invited)

• Lab Periods:

– Two hours per week

– TAs available to answer questions

– Attendance "mandatory" 14

Page 15: APS105 - Electrical & Computer Engineering

Course Textbook

• “An Introduction to Computer Science

Using C”, 2nd Edition

– by John Carter

– Published by McGraw Hill-Ryerson

• How to get a copy:

– UofT bookstore

– basement of Sandford Fleming Building

– Amazon etc.

15

Page 16: APS105 - Electrical & Computer Engineering

Lecture Slides and Note-Taking

• Electronic slides with fill-in-the-blanks

– A hybrid between powerpoint and chalkboard

• Pptx/pdf available on www prior to lecture

– Please bring to class (printed, on tablet,etc)

• The filled-in “blanks” are only during class

– Filled-in slides will not be published

– I will try to publish med-large code examples

• The symbol that indicates a blank to fill

16

Page 17: APS105 - Electrical & Computer Engineering

Cheating/Copying

• Easy to do, equally easy to catch!

– “cheater-beater” software

• Automatically compares all submissions

– we do actually do this, and do follow through!

• the interview and punishment process is painful for all!

• You only cheat yourself

– Labs worth 1.6% each

– The practice you get by doing them is invaluable

– The consequences for being caught are harsh

• See Engineering Calendar for details

17

Page 18: APS105 - Electrical & Computer Engineering

Getting Help

• See course info handout

• Meet some friends: “study groups”

– Collaborating vs cheating

• Ask questions in class

– Point out confusing things and mistakes!

• Get help quickly if you get into trouble

– First-year office (1st floor Galbraith Building)

– www.calss.utoronto.ca

• Help with academics, personal

18

Page 19: APS105 - Electrical & Computer Engineering

In-Class Etiquette

• Be on time

– Class starts at 10mins after the hour

• Quiet please!

– Silence yourself and all electronic devices!

• Pay attention

– Eg., watching youtube on laptop distracts others

• Ask questions and point out errors!

– Raise your hand

– Say “question!” if I don’t notice

19

Page 20: APS105 - Electrical & Computer Engineering

How to Succeed at APS105

• Attend lectures

– take notes, ask questions

• Do labs yourself, on-time

– Practice/experience is invaluable

• Review lecture material regularly

– Be better prepared for quizes/midterm/final

– Avoid last-minute cramming

• Prepare for midterm/final

– Practice by trying past midterms/finals

– Practice by filling lecture slides on your own

• Both available on www 20

Page 21: APS105 - Electrical & Computer Engineering

How to Succeed at Skule (computing)

• Learn to keyboard properly!

• Learn linux basics

– see the linux handout (labs section of www)

• has details on how to log in from home

• Consider learning some javascript

– For programming www page features

– Has C-like syntax in many aspects

• Write a simple app for your own use

– Eg., for your laptop or iphone

21

Page 22: APS105 - Electrical & Computer Engineering

Computer Systems Basics

22

Page 23: APS105 - Electrical & Computer Engineering

Computer Systems Stack

Applications

Java (and others)

Java interpreter (JVM, and others)

C (and others) APS105

C Compiler

Processors

Logic gates

Transistors

Electrons and materials

23

Page 24: APS105 - Electrical & Computer Engineering

How We Tell a Processor What to Do

Programmer Machine Instructions

Add r3,r3,r1

Cmp r3,r1

Bge 0x3340a

Mulu r3,r5,r2

Sub r1,r3,r4

int

Foo (int x){

return x + 5;

}

Compiler

Processors execute machine

instructions encoded in binary

Processor

0100101

24

Page 25: APS105 - Electrical & Computer Engineering

A TYPICAL PC

Motherboard

(CPU, MEMORY) Hard drive

CD/DVD R/W

USB Connectors

Graphics card

Monitor

Keyboard

Mouse

Power Supply

25

Page 26: APS105 - Electrical & Computer Engineering

Simple View of a Motherboard

Memory

(RAM)

CPU

• Memory: – holds bits

– can be read from or written to

• CPU: – datapath: arithmetic/logic units (add, sub), etc.

– control circuitry

26

Page 27: APS105 - Electrical & Computer Engineering

C

27

Page 28: APS105 - Electrical & Computer Engineering

About C

• Invented in Bell Labs (in 1970s)

– by Dennis Ritchie

– Inherits from earlier language

• called “B”

• C++

– an extension of C

– Supports “object oriented programming”

Dennis Ritchie

28

Page 29: APS105 - Electrical & Computer Engineering

Hello World

#include <stdio.h>

// This program prints: Hello, world

int main (void)

{

printf("Hello, world\n");

return 0;

}

Include this “library” of standard I/O functions including “printf”

Comments

rest of line

(not executed,

documentation)

Every C program

Has a “main”

function

Print “Hello, world” to the screen

Main should return 0 if program finished normally

‘\n’ means carriage return

‘\’ is an “escape”

Page 30: APS105 - Electrical & Computer Engineering

Alternative Hello World

#include <stdio.h>

// This program prints: Hello, world

int main (void){printf("Hello, world\n");return 0;}

Note: this works too; whitespace mostly doesn’t matter in C.

but it is very ugly and hard to read

and doesn’t execute any faster than the nicer formatting

so don’t write programs this way!

Page 31: APS105 - Electrical & Computer Engineering

GCC

• gcc

– Means “GNU C compiler”

– A program that converts C to 0’s & 1’s • Stored in a file called an “executable”

• Type this command to compile hello.c gcc hello.c

• Generates the executable file a.out

• Insteady you could type: gcc –o hello hello.c

• Generates the executable file hello

Page 32: APS105 - Electrical & Computer Engineering

Value Representation

32

Page 33: APS105 - Electrical & Computer Engineering

Bits and Bytes

• “bit” is short for “binary digit”

– A bit can be 0 or 1

• Why do computers use bits?

– Composed of transistors, which are switches,

either on/off, hence zero/one

• A byte is a group of 8 bits

– 1 byte can be written as 1B

Page 34: APS105 - Electrical & Computer Engineering

RECALL: BASE 10 (decimal) • 956

= 9 * 10^2 + 5 * 10^1 + 6 * 10^0

= 9*100 + 5 * 10 + 6 * 1

= 956

• NOTE: not all languages/cultures use base10 – Ndom, Frederik Hendrik Island: base6

– nimbia: base12

– Huli, Papua New Guinea: base15

– Tzotzil, Mexico: base20

– Computers use base2 (binary)

Page 35: APS105 - Electrical & Computer Engineering

USING BINARY (BASE 2)

• denoted by ‘0b’ (in this course, in C-code)

• Converting from binary to decimal:

• 0b1011

= 1*2^3 + 0 *2^2 + 1 *2^1 + 1 *2^0

= 1*8 + 0*4 + 1*2 + 1*1

= 8 + 2 + 1

= 11

3 2 1 0

Page 36: APS105 - Electrical & Computer Engineering

Questions

• How many decimal numbers can you

represent with N bits?

– Answer: 2N eg., 2bits => 4nums, 4bits => 16nums

• NOTE:

– computers can only represent finite numbers!

Page 37: APS105 - Electrical & Computer Engineering

Byte Size

• 1byte = 1B = 8bits

• 8bits has 28 possible values

– 28 =256 possible values

– Example: 0,1,2,3..255 = 0.. 28-1

Page 38: APS105 - Electrical & Computer Engineering

What is this?

10010010

• ascii character

• integer value (positive or negative?)

• floating point value

• audio sample

• image code

• video code

• Punchline: need to know its “type”!

Page 39: APS105 - Electrical & Computer Engineering

Types

39

Page 40: APS105 - Electrical & Computer Engineering

Types

• Data Type:

– tells computer how to interpret a group of bits

– Without a type they are just bits!

• C has types:

– Basic data types: built-in, already defined for you

– User-defined types: name your own! (later)

• Basic data types:

– A single value of a certain size (bytes)

– Example: a number or a character

40

Page 41: APS105 - Electrical & Computer Engineering

Integer Types

• int: 32bits, values: -231 .. 231-1

– We will almost always use int in this class

• Other integer types:

– unsigned int: 32bits, values 0.. 232-1

– short: at least 16bits

– long: at least 32bits

– long long: at least 64bits

– what does "at least" mean?

• the actual size can depend on the system!!!!!

41

Page 42: APS105 - Electrical & Computer Engineering

Floating Point Types

• How to use binary to represent real numbers?

– Eg., 1.3333333333333….

– Can’t: approximate, with limited accuracy

• Floating-point: a common approximation

– A value (mantissa) and an exponent

• 1234e-3

– Flexible: can represent very big or very small

• Eg., 2.1313*1020 or 2.1313*10-20

– We don’t need to know the details for this class

42

Page 43: APS105 - Electrical & Computer Engineering

Floating Point Types in C

• double: at least 64 bits

• We will almost always use double in this class

• float: at least 32 bits

43

Page 44: APS105 - Electrical & Computer Engineering

Character Type

• representing keyboard characters:

– Eg: a,b,c,d…A,B,C,D, !@#$%

– Standard encoding called ASCII:

• eg., ‘A’ = 65 = 0100 0001 (binary)

• char: 8 bits, typically ASCII-encoded

• Note1: char holds only a single character

– How can we represent a “string” of characters?

• Note2: recall “escapes”

– Eg., ‘\n’ represents the return character

• Encoded as a single ASCII value

44

Page 45: APS105 - Electrical & Computer Engineering

Boolean Type

• Often you want to represent true/false

– The old way: use int values 0 and 1

– The new way: use the bool type

• bool type

– Has values ‘true’ and ‘false’

– Note: you have to include the bool library

• in program (at top): #include <stdbool.h>

45

Page 46: APS105 - Electrical & Computer Engineering

Identifiers and Variables

46

Page 47: APS105 - Electrical & Computer Engineering

Identifiers

• Identifiers give names to things

– Choosing good names is a key skill!

• Rules: identifiers can be

– any length (any number of characters)

– upper & lower case letters, digits, ‘_’

– First character cannot be a digit

– Cannot match a C “reserved” word (like “int”)

47

Page 48: APS105 - Electrical & Computer Engineering

Choosing Identifiers: Good Style

• Use upper-case to separate words:

– myExampleIdentifier

• Or use underscores to separate words:

– my_example_identifier

• Avoid easily-confused characters:

– Eg., 0 and O, 1 and l and I

Page 49: APS105 - Electrical & Computer Engineering

Choosing Identifiers: Good Style

• Choosing good identifiers is an art:

– Too short: eg., “x”:

• Leads to hard-to-understand code

– Too long: eg., “thisIsMyExampleAPS105Identifier”

• Leads to cluttered hard-to-read code

• World’s worst identifier:

– data

• World’s second-worst identifier

– data2

Page 50: APS105 - Electrical & Computer Engineering

Declaring Variables • Variable: storage of a value of a certain type

• Variable declaration:

– specifies that you plan to use a variable

– and you would like it to be a certain type

– Note: the C-compiler creates storage for it

• General form:

<type> <identifier list>;

50

Page 51: APS105 - Electrical & Computer Engineering

Declaring Variables: Examples

• Example declarations: int height; // in centimetres

double length, width; // sides of a rectangle

char term; // ‘F’ means fall, ‘S’ means spring

• Question: what value does height have?

– garbage: we did not “initialize” it to a certain value

– compiler should warn if use it without initializing

Location Value

height

length

width

term

Memory

Page 52: APS105 - Electrical & Computer Engineering

Assigning Values

• Can assign a value at declaration, or later

• Example assignment at declaration:

int height = 183; // in centimeters

bool weLoveAPS105 = true;

• Example assignment at a later point:

int height; // in centimeters

height = 183;

Location Value

height 183

weLoveAPS105 1

Memory

Location Value

height 183

Memory

Page 53: APS105 - Electrical & Computer Engineering

Output

53

Page 54: APS105 - Electrical & Computer Engineering

Printing to the Screen on PC

Motherboard

(CPU, MEMORY) Hard drive

CD/DVD R/W

USB Connectors

Graphics card

Monitor

Keyboard

Mouse Power Supply

NOTE: Actually many complex steps:

1) Each char is sent to the OS

2) OS converts char into a pixelmap

3) Pixelmap is sent to graphics card

4) Graphics card adds pixelmap to the frame buffer

5) Frame buffer sent to monitor (eg., VGA encoded)

Use printf()

Page 55: APS105 - Electrical & Computer Engineering

Printing Values

• the printf function prints to the screen

printf(“hi mom\n”);

// prints: “hi mom” and a return to the screen

• printf can also print variable values

int age = 39;

printf(“I am %d years old\n”,age);

// prints: “I am 39 years old\n”

printf(“I am %d years old\n”,age);

conversion specification variable to print

Page 56: APS105 - Electrical & Computer Engineering

Printing Integers

• decimal (base10)

– %d: print the decimal using space as necessary

– %4d: print the decimal using at least 4 spaces

• Example:

int age = 39;

printf(“I’m %4d\n”,age);

// prints: “I’m 39\n”

Page 57: APS105 - Electrical & Computer Engineering

Printing chars

• char

– %c: print a single character

• Example:

char letter = ‘A’

printf(“%c is for apple\n”,letter);

// prints “A is for apple”

Page 58: APS105 - Electrical & Computer Engineering

Printing doubles

• %lf

– means “long float” (d is already used!)

– by default prints 6 digits right of the decimal

– cheat: can use %f instead, does the same thing

• %.2lf

– print 2 digits right of the decimal

• %6.2lf

– minimum of 6 digits, 2 right of decimal

• %e

– use exponent form: ±x.xxxxxxe±nn

58

Page 59: APS105 - Electrical & Computer Engineering

Printing doubles: Examples

• Examples:

double age = 39.12345;

printf("I'm %lf\n",age);

printf("I'm %.2lf\n",age);

printf("I'm %e\n",age);

// prints:

// I'm 39.123450

// I'm 39.12

// I'm 3.912345e+01

Page 60: APS105 - Electrical & Computer Engineering

Printing bool

• No conversion specification for bool

– Just use %d (decimal)

– Prints 0 for false and 1 for true

• Example:

bool weAreTheEngineers = true;

printf(“%d\n”,weAreTheEngineers);

// prints “1\n”

Page 61: APS105 - Electrical & Computer Engineering

Special Cases

• How do you print ‘%’?

– The ‘%’ is the ‘escape’ for conversion specs!

– Answer: use ‘%%’

• Example:

double grade = 82.5;

printf(“My grade is %.1f%%\n”,grade);

// prints: “My grade is 82.5%\n”

• How do you print ‘\’?

– The ‘\’ is also an ‘escape’ character

– Answer: use ‘\\’

Page 62: APS105 - Electrical & Computer Engineering

Input

62

Page 63: APS105 - Electrical & Computer Engineering

Input from the Keyboard

Motherboard

(CPU, MEMORY) Hard drive

CD/DVD R/W

USB Connectors

Graphics card

Monitor

Keyboard

Mouse Power Supply

NOTE: Actually many complex steps:

1) Program “sleeps” awaiting a keypress

2) Keypress sends key value to CPU via USB

3) USB port “interrupts” CPU

4) OS is invoked on CPU, handles interrupt

5) CPU copies value from OS (recoding it?)

6) Sleeping program is eventually awoken

Use scanf()

Page 64: APS105 - Electrical & Computer Engineering

Input from the Keyboard: scanf

• the scanf function inputs from the keyboard

• example1:

int age;

scanf(“%d”,&age); // await enter

• example2:

double grade;

scanf(“%lf”,&grade); // await enter

control string says:

input an int

into the memory location of the following identifier

the reason why we need this is complex---more later

Page 65: APS105 - Electrical & Computer Engineering

Inputting Multiple Values

• scanf automatically skips whitespace

– eg., spaces, tabs, newlines

• scanf(“%d%d%d”,&x,&y,&z);

– works for this input:

22 33 44

– also works for this input:

22

33

44

• Note: only works if digits and whitespace

– eg., won’t work for input: 22.0 33.0 44.0

Page 66: APS105 - Electrical & Computer Engineering

Consuming Whitespace

• If input string is:

– “ 22 33 44”

• And I execute:

– scanf(“%d%d”,&x,&y);

• The next scanf call would start at this point:

– “ 22 33 44”

– scanf of %d or %lf consumes “leading” whitespace

– but does not consume “trailing” whitespace

Page 67: APS105 - Electrical & Computer Engineering

Skipping Characters

• Can manually skip specific characters

– eg., non-whitespace

– include them in the control string

• Example:

scanf(“APS%d”,&courseCode);

– input: “APS105” would set courseCode to 105

Location Value

courseCode 105

Memory

Page 68: APS105 - Electrical & Computer Engineering

Inputting Chars • Example:

int year;

char term;

scanf(“%d%c”,&year,&term);

• Note: %c does not skip whitespace!

• Example input: 2011F

gives year=2011, term=‘F’

• Example2 input: 2011 F

gives year=2011, term=‘ ’

• Example3 input: 2011

F

gives year=2011, term=‘\n’

Page 69: APS105 - Electrical & Computer Engineering

Constants

69

Page 70: APS105 - Electrical & Computer Engineering

Constants

• A constant is a value that does not change

– possibly used in multiple places in your program

• Literal constant:

– the value is written directly in your code

– example: int age = 2;

• named constant:

– assign a constant value an identifier

– then use the identifier in your code

– Named constants make for easier-to-read code!

70

Page 71: APS105 - Electrical & Computer Engineering

Named Constants Example

• With literal constant:

double radius = 5.0;

double circumf = 2 * 3.14159 * radius;

• With named constant:

const double PI = 3.14159;

double radius = 5.0;

double circumf = 2 * PI * radius;

“magic number”;

bad style!!

More readable;

Page 72: APS105 - Electrical & Computer Engineering

Two Methods for Named Constants

• Using the const attribute

– General form:

const <type> <identifier> = <value>;

const double PI = 3.14159;

– Using the const attribute means that the value

of PI is not allowed to change

72

Page 73: APS105 - Electrical & Computer Engineering

Named Constants for Good Style

• avoid magic numbers in your code

– numbers which have no meaning to others

– use of magic numbers will cost you points in labs!

• avoid multiple copies of the same value

– if you must update the value, only have to do it in

one place in the code

• Convention/Good-Style:

– use capital letters for named constant identifiers

– eg., PI and MAX_ATTEMPTS

73