please pick up an attendance question and submit in 5 minutes cs 1003 lecture #3 sept 12, 2006...

40
Please pick up an attendance question and submit in 5 minutes CS 1003 Lecture #3 Sept 12, 2006 Knarig Arabshian

Post on 21-Dec-2015

218 views

Category:

Documents


2 download

TRANSCRIPT

Please pick up an attendance question and submit in 5 minutes

CS 1003Lecture #3

Sept 12, 2006Knarig Arabshian

Announcements

• Check assigned readings on the web• HW1 is on the class website.

– Need both lectures this week for the homework.– Due in 2 weeks. – Will be submitted electronically. Instructions posted

on the class website.

• Post all HW questions on the web board but make sure you don’t give solutions away!

Agenda

• Binary numbers

• Types, operators and expressions

• Control Statements

• Loops

• Go over attendance question

Binary Numbers

• A computer’s internal storage techniques are different from the way people represent information in lives

• Information inside a digital computer is stored as a collection of binary data (0’s and 1’s)– why?

• Each memory location that a 0 or 1 is stored in is called a bit for binary digit

• A collection of 8 bits = 1 byte

Decimal Numbering System

• Base-10• There are 10 distinct single digits

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

• Do you remember this from elementary school? – Ones place– Tens place– Hundreds place– etc.

• Each position is a power of 103052 = 3 x 103 + 0 x 102 + 5 x 101 + 2 x 100

Binary Numbering System• Base-2• There are 2 distinct digits

0, 1• Each position is a power of 2

– Ones place– Twos place– Fours place– Eights place– Sixteens place– etc.

• In order to get the decimal representation of a binary number you multiply1101 = 1 x 23 + 1 x 22 + 0 x 21 + 1 x 20

• Binary-to-decimal algorithm:– Whenever there is a 1 in a column, add the positional value of that column to a

running sum and whenever there is a 0 in a column, add nothing• Given n bits, what is the maximum number stored?

– 2n – 1• Given a number n, what is the maximum number of bits needed?

– Floor(log2 n) + 1

Conversion Table

Binary Addition

• Is much easier to do than in decimal

• Rules that define arithmetic addition only needs 2 x 2 = 4 entries instead of

10 x 10 = 100– 0 + 0 = 0– 0 + 1 = 1– 1 + 0 = 1– 1 + 1 = 10 (0, with a carry of 1)

Binary Addition

• Adding the numbers 7 and 14 is as follows:

1110

00111

+ 01110

------------

10101

carry digit

How about signed numbers?

• First bit represents the sign (+) or (-)

• 0 means positive, 1 means negative

1110001

- 49

How about signed numbers?

• How does the computer know if the number 1110001 represents -49 rather than the unsigned whole number 113?– Computer does not know. It depends on how the number is used– If the integer variable is declared as a signed integer, then the

number 1110001 represents -49– If the integer variable is declared as an unsigned integer then

the number 1110001 represents 113– Considering the context in which it is used is the only way to

determine– Real life examples:

• The word ball can either be a round object used to play games or an elegant formal party

• Only way to know which definition it represents is to see how the word is used in a sentence

Some problems…

• What happens with the following number? 1000000

• Is this 0 or -0? • Will result in programs executing in different

ways on different machines• To avoid this problem, computer designers use

two’s complement representation– Given a certain number of bits, write out every

combination of 0’s and 1’s– Numbers starting with a 1 are (-), numbers starting

with 0 are (+)

Let’s look at an example for 3 bits

000

001

010

011

100

101

110

111

(0)

(-1)

(-2)

(-3)

(-4)

(+3)

(+2)

(+1)

Given n bits, what’s the range?

Two’s Complement Representation

• Given n bits, what’s the range?– 2(n-1) to 2(n-1) -1– There will be one more negative number– Not ideal, but better than having two types of 0s!

• Try adding any two numbers in 2’s complement (3) + (-3) 011 + 101 = 000 = 0

-2 + 1110 + 001 = 111 = -1

What’s the algorithm for getting two’s complement?

010 110

001 111

1001101 0110011•Take the binary number•Get the 1’s complement (flip the digits)•Add 1 to the result to get the 2’s complement

010 101 + 1 110001 110 + 1 1111001101 0110010 + 1 0110011

Binary Numbers

• Any Questions?

• More on binary numbers in the next class…

Types, operators and expressions

Variables • Store values used during computation• Conceptually similar to a mathematical variable, but need to provide

more information• Variables must first be declared• A variable declaration announces the type of information that the

variable will hold– Example: int x; char c;– x is a variable that will hold an integer value– c is a variable that will hold a character value

• Different types are:– int– char– float

• Single precision floating point– double

• Double precision floating point

Types• int

– short int = 16 bits– long int = 32 bits – It depends on the compiler and machine which type of integer

“int” will default to. For unix it will default to long int-216 to 216-1 ~ -2 billion to 2 billion

• char– A single byte, capable of holding one character in the local

character set– Also a small integer char c = 5; valid expression

• Can specify if a type is unsigned or signed for chars and any integer– unsigned int will have range 0 to 232 -1– Why?

Assignment

• Once we’ve declared our variables, we will assign them to values– x = 5

• This can also be done during declaration time– int x = 5;

• Make sure variables are initialized before usage!

Arrays

• We may want to store a list of variables all of the same type• Instead of declaring 100’s of integer variables with different names,

we can use arrays

int a[100];

. . .

a[0]a[1]a[2]a[3]

a[99]

We access each element by its Index:

•a[0] is the 1st element•a[1] is the 2nd element•a[99] is the 100th element

• The declaration: int numArray[100]; is equivalent to declaring 100 integervariables one after the other:

int num1;int num2; …int num100;

memory

Arrays

• Data manipulation with arrays is usually done using loops• Example program: summing a list of integers

main() {

int n[100];

int sum, i;

i = sum = 0;

while (i < 100) {

sum = sum + n[i]

}

}

Array Assignments

• During declaration– int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}– char str[10] = {‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘!‘}

• Later onint a[10]; int i = 0;while (i < 10) {

a[i] = i++;}

• Make sure arrays are initialized before usage!

Operators

• Mathematical operators– +, -, *, /– precedence rules apply!– x = (a + b) * (c + d) / 2

• Assignment operators– =, +=, -=, ++, --– x = 5 store value of 5 in x– x++ increase the value of x by 1– x += 1 does the same thing– x = x + 1 and yet again the same thing– More later…

Constants

• We don’t need to declare variables for everything; we can just put numbers in place– printf(“%d”, 10+15)

• We can also declare variables as constants– const double PI = 3.141592654;– const char str[15] = “Hello!“;

• A string constant or literal – sequence of zero or more characters surrounded by double

quotes: “Hello!“– Technically it is an array of characters ending with the null

character ‘\0‘– strlen() function returns the length of a string excluding the ‘\0‘

character: strlen(str) returns 5H e l l o \0!

str [0] [1] [2] [3] [4] [5] [6]

Type Conversions

• Automatic conversions convert a narrower operand into a wider one without losing information– integer to floating point number f + i – char to integer c + I

• Conversions that will not always work– From wide to narrow

• long int to short int may have loss of information

Type Conversions

• Convert strings to numeric values– int num = atoi(“1234“)– long int longNum = atol(“1234“);– double floatNum = atof(“123.4“);

• Convert char to intchar c = ‘5‘; represents an integer value which

is a number in the machine’s character set

int n = c – ‘0‘; Subtract the ASCII value of ‘0‘ from the

ASCII value of ‘5‘

Types

• Any Questions?

• More on types in the next class…

Control statements• Program needs to adjust behavior based on situation

– Real life example: if it is raining, take an umbrella; else if it is sunny, take sunglasses;and so on..

– Similar in programming if (expression1)

statement1 else if (expression2)

statement2else statement3

• Example: /* Check to see if user input is greater than 5 */

int input = 0;printf(“Please enter a number \n“);scanf(“%d”, &input);if (input > 5)

printf(“Input is greater than 5\n”);else

printf(“Input is not greater than 5\n”);

Control Statements

• Scope

if (expr1) statement1;else statement2;

if (expr2){ statement1; statement2;} else { statement3; statement4;}

if (expr2){ statement1; statement2;} else { statement3; statement4;}

Make sure you indent!

Relational and Logic Operators

• Relational Operators– Equals: ==– Greater than: >– Less than: <– Greater than or equal to: >=– Less than or equal to: <=– Does not equal: !=

• Logic Operators– And: &&– OR: ||– Not: !

Relational and Logic Operators

• Examples: – Check if an integer variable is between the numbers 1

and 5 or the numbers 10 and 15

– Check if something is valid

int x = 3; if ( ((x >=1) && (x <= 5)) || ((x >= 10) &&(x <=15)) ) printf(“In correct range \n“);

int valid = 0;if (!valid) printf(“Not valid \n“);

Relational and Logic Operators

• Precedence– && is higher than ||, but both are lower than

relational and equality operators

int x, y, z;x = 1;y = 13;z = 9;if (x < 5 && y != 20 || z > 10) printf(“Numbers are correct\n”);else printf(“Numbers are not correct\n”);

What will this print out?

Relational and Logic Operators

• Remember: “==“ is *NOT* the same as “=“– “=“ is an assignment operator, while “==“ is

a boolean test– If you make this mistake in a control

statement, the condition will always be true because you are just assigning a value

What will this print out?

int x = 3;if (x = 5 )

printf(“x is 5!\n“);else printf(“x is not 5\n“);

Control Statements

• Any Questions?

• More on control statements in the next class…

Loops

• Sometimes you may need to repeat a set of statements (remember the very first algorithm you learned?)

• Do a set of statements until a condition is true

• Traverse a list and do an operation on each element

• Etc.

Loops

• while– Condition in parentheses is tested– If it is true, the body of the loop is executed: can be one or more

statements– Then the condition is re-tested– If true, the body is executed again– When the test becomes false, the loop ends and execution

continues at the statement that follows the loop– Body

• if it has more than one statement, it needs to be enclosed in { }• if it only has one statement braces are not necessary, but correct

indentation is necessary to ease readability

while (i < j) i = 2 * i;

while (i < j) i = 2 * i; Both work, but first one is cleaner code

Loops

• while– infinite loops happen when the condition in

the while loop is always true– make sure your loop ends (unless it is meant

to run infinitely…)– most common error:

• keeping a counter and forgetting to increment the counter (attendance question)

Loops

• Any Questions?

• More on loops in the next class…

Attendance Question

#include <stdio.h>

main() { int i = 0; while (i <= 5) { printf("Hello, world!\n); }}