Week 1, continued. This is CS50. Harvard University. Fall Anna Whitney

Similar documents
Sources: On the Web: Slides will be available on:

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

So far we have considered only numeric processing, i.e. processing of numeric data represented

Pemrograman Dasar. Basic Elements Of Java

Informatica e Sistemi in Tempo Reale

Computer Programming Tutorial

The programming language C. sws1 1

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CS 106 Introduction to Computer Science I

arrays C Programming Language - Arrays

Variables, Constants, and Data Types

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Lecture 2 Notes: Flow of Control

J a v a Quiz (Unit 3, Test 0 Practice)

Moving from CS 61A Scheme to CS 61B Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

The Answer to the 14 Most Frequently Asked Modbus Questions

Chapter One Introduction to Programming

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Computers. Hardware. The Central Processing Unit (CPU) CMPT 125: Lecture 1: Understanding the Computer

VHDL Test Bench Tutorial

Microcontroller Systems. ELET 3232 Topic 8: Slot Machine Example

Base Conversion written by Cathy Saxton

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Programming Project 1: Lexical Analyzer (Scanner)

6. Control Structures

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Statements and Control Flow

Number Representation

Tutorial on C Language Programming

Java Basics: Data Types, Variables, and Loops

Introduction to Java

C++ Language Tutorial

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 3. Input and output. 3.1 The System class

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping

TIP: To access the WinRunner help system at any time, press the F1 key.

Programming Languages CIS 443

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

VB.NET Programming Fundamentals

Outline Basic concepts of Python language

Object Oriented Software Design

C++ INTERVIEW QUESTIONS

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

Introduction to Data Structures

Object Oriented Software Design

Pseudo code Tutorial and Exercises Teacher s Version

Python Loops and String Manipulation

Repetition Using the End of File Condition

Introduction to Visual C++.NET Programming. Using.NET Environment

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

Example of a Java program

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Iteration CHAPTER 6. Topic Summary

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

An Incomplete C++ Primer. University of Wyoming MA 5310

#include <Gamer.h> Gamer gamer; void setup() { gamer.begin(); } void loop() {

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6)

Comp151. Definitions & Declarations

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Selection Statements

C++ Programming Language

Decision Logic: if, if else, switch, Boolean conditions and variables

Python Programming: An Introduction To Computer Science

Stacks. Linear data structures

ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER

Storing Measurement Data

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

COMP 110 Prasun Dewan 1

Conditionals: (Coding with Cards)

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

ELEG3924 Microprocessor Ch.7 Programming In C

To convert an arbitrary power of 2 into its English equivalent, remember the rules of exponential arithmetic:

River Dell Regional School District. Computer Programming with Python Curriculum

The C Programming Language course syllabus associate level

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Encoding Text with a Small Alphabet

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

ECE 0142 Computer Organization. Lecture 3 Floating Point Representations

DNA Data and Program Representation. Alexandre David

1 Abstract Data Types Information Hiding

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Introduction to Python

Cobol. By: Steven Conner. COBOL, COmmon Business Oriented Language, one of the. oldest programming languages, was designed in the last six

Transcription:

This is CS50. Harvard University. Fall 2015. Anna Whitney Table of Contents 1. Imprecision... 1 2. Announcements... 2 3. C... 2 4. Types... 3 4.1. Conditions... 4 4.2. Loops... 6 4.3. Integer Overflow... 7 4.4. Loops, continued... 8 4.5. Variables... 8 4.6. Functions and Arguments... 9 5. Problem Set 1... 11 1. Imprecision Last week, we saw in imprecision.c 1 that 1.0/10.0 does not in fact equal 0.1 as expected. Well, actually it does equal 0.1, of course - but the computer gets it a little bit wrong. Computers only have a finite amount of memory, so they have to pick and choose what values they re going to support. If we only have 8 bits, we can only represent 256 values (and since we use one of those values for zero, the greatest number we can represent is 255). Floating point values are stored a little differently, but the computer still only uses typically either 32 or 64 bits to store a floating point number so it can t possibly represent infinitely many values. 1 http://cdn.cs50.net/2015/fall/lectures/1/f/src1f/imprecision.c 1

When we get these inaccuracies after many decimal places, we re running up against the hardware limitations of the computer. Paying attention to how numbers are stored in your code can be critical this clip from Modern Marvels 2 shows how disasters can result when numerical imprecision isn t taken into account in high-precision systems. 2. Announcements Supersections this weekend; they will be filmed and streamed live for those unable to attend. Problem Set 1 is live on the course website, and due next Thursday. Office hours will take place Monday through Thursday this week. 3. C Let s return to our canonical program from last time: #include <stdio.h> int main(void) printf("hello, world"\n); Recall that #include <stdio.h> allows us to use the functions of the standard I/O library, written by other programmers in the past, and declared in a file called stdio.h elsewhere in our system. We introduced main last week as the analog of Scratch s [ when [green flag] clicked ] block. In C and several other languages, your first function must be called main. We ll explain later what int and void are doing here. printf is a function that prints out a formatted string. It takes one or more arguments (also known as parameters or simply inputs). The first is a string - a word or phrase or even a whole essay - which you usually want to terminate with a \n to ensure that the output ends with a newline. Subsequent arguments tell printf what values to 2 http://youtu.be/7yfh7v6xmto?t=4m1s 2

fill in for any format strings (such as %f for a floating-point number) that you included in the first string argument. # \n in the above is what s known as an escape character - rather than being interpreted literally as a backslash and the letter n, it tells the compiler to do something else. In this case, that "something else" is starting a new line. Semicolons indicate the end of statements, and curly braces delineate blocks of code (like the structures of control puzzle pieces in Scratch). Volunteer Kopal acts as the printf function, accepting input from David (acting as the hello program that calls printf ) written on a piece of paper and writing the input given on the touchscreen, simulating the effect of printf. Another volunteer, Ife, represents the GetString function. Kopal, as printf, writes "State your name" on the touchscreen. Ife then gets a name from the audience and brings it back. David stores the returned name, "Nik", in a variable called s (by writing it on a sheet of paper labeled s ). David now gives Kopal/ printf a sheet of paper that says hello, %s\n and the sheet of paper containing the value of s. He fills in the name stored in the variable s, "Nik", in place of the placeholder %s. This same model of message passing underlies all the code we write, as outputs of functions are passed as inputs to other functions and so on. 4. Types We ve been talking mostly about strings thus far, but values in C can have a few other types: # char, a single character (like a or 7 or % ), which takes up one byte, or 8 bits; uses a printf format code of %c # float, a floating-point value (a number with a decimal point, like 10.0 or 3.14159 ), which takes up 32 bits (four bytes); %f # double, a floating-point number that takes up twice as much space as a float (so 64 bits/8 bytes); also %f # int, an integer, also 32 bits/4 bytes, meaning that the largest integer we can represent is roughly 4 billion; %i or %d # longlong, a 64 bit integer (which can represent much larger values!); '%lld` 3

And from the CS50 Library, found in cs50.h : # bool, true or false # string, a sequence of characters We can also use various escape sequences in printf format strings: # \n for a newline # \t for a tab character # \" to include a double-quote in the middle of a printf format string (since a bare double-quote would make the compiler think it had reached the end of the string!) In the CS50 Library, we provide functions like GetString, GetInt, GetFloat, GetLongLong and so on, that let you get input of a specific type from the user. These functions include error checking to prevent the user from providing invalid input. 4.1. Conditions Conditions have the following structure: if (condition) The // in line 3 marks a comment, English words directed at yourself or other readers of your code. Lines starting with // (or multi-line blocks beginning with /* and ending with */ ) tell the compiler not to look for actual instructions here. There can also be two exclusive branches: if (condition) else // do that Or three: 4

if (condition) else if (condition) // do that else other thing Boolean expressions (the conditions inside the conditional) can be combined with && as "and", and as "or": if (condition && condition) if (condition condition) Switches express the same thing as certain if / else if / / else constructs, but can be more elegant and involve fewer curly braces. They provide no additional functionality that can t be done with regular conditionals, but can sometimes be stylistically preferable. You can use a switch whenever all the conditions of your conditional would be of the form expression == value for the same expression but different values. 5

switch (expression) case i: break; case j: // do that break; default: other thing break; 4.2. Loops One type of loop in C is the for loop, which has the following basic structure: for (initializations; condition; updates) again and again A specific example: for (int i = 0; i < 50; i++) printf("%i\n", i); # In this case, int i = 0 is the initialization of the loop, telling it to start counting at zero by creating a variable called i and assigning it the value 0. # i < 50 is the condition of the loop: immediately after the initialization, and at the start of every step of the loop thereafter, the condition is checked, and the code in the body of the loop will only be executed if the condition evaluates to true. # i++ is the update of the loop, which will be executed after the body of the loop to move to the next step. 6

# We ve put printf("%i\n", i); in the body of the loop, so this code will print the numbers from 0 to 49 (not 50, because when we update to i = 50, the condition i < 50 evaluates to false and the body of the loop is not executed). # The curly braces are not syntactically required if the body of the loop is only one line, but we will always use them in class (and we request that you do too!) for clarity and to prevent mistakes. 4.3. Integer Overflow Just as floating point values have limits on their precision, integers have limits on the size of values they can represent. For a 32-bit integer, the maximum value is roughly 4 billion. When a binary number overflows, we go from a value like this (255 stored in 8 bits): 128 64 32 16 8 4 2 1 1 1 1 1 1 1 1 1 To a value like this:?? 128 64 32 16 8 4 2 1 1 0 0 0 0 0 0 0 0 But this is still only an 8-bit value, so there s nowhere to put the leading 1, and instead we get: 128 64 32 16 8 4 2 1 0 0 0 0 0 0 0 0 We can see the effects of these limits on integers in various software: # In the video game Lego Star Wars, the number of coins you can collect is capped at 4 billion exactly - from which we can infer that the original developer for this game used a 32-bit integer to store the user s number of coins. # In the original Civilization game, each world leader was assigned an aggressiveness score, and Gandhi was given the lowest score of 1. If a nation transitioned to democracy in the game, the leader s aggressiveness score was decreased by 7

2. However, the aggressiveness scores were stored in unsigned 8-bit integers (meaning they couldn t be negative) - so decreasing Gandhi s aggressiveness score to -1 had the effect of looping around to 255 (so Gandhi became the most aggressive leader in the game!) # The Boeing 787 would lose all power after 248 days of continuous operation due to an integer overflow in the control units of its power generators (the workaround solution is to reboot the plane more often than that!) 4.4. Loops, continued Slightly different from a for loop, we have a while loop, that merely depends upon a single condition which is checked before every iteration of the loop: while (condition) again and again Similarly, in a do-while loop, the condition is checked after every iteration of the loop (as indicated by the syntax): do again and again while (condition); 4.5. Variables As we ve discussed, a variable in C has a particular type, which must be declared when the variable is created. Here, the first line creates a new variable of the type int, and the second assigns a value of 0 to it. The declaration of the variable and assigning it a value can happen as far away from each other in code as you like, but for clarity it s best to keep them close together. int counter; counter = 0; 8

A more succinct way to write the above code: int counter = 0; 4.6. Functions and Arguments Functions are followed by parentheses, which contain any arguments that are being passed to the function: string name = GetString(); printf("hello, %s\n", name); In function-0.c 3, we show how to define your own function: #include <cs50.h> #include <stdio.h> // prototype void PrintName(string name); int main(void) printf("your name: "); string s = GetString(); PrintName(s); /** * Says hello to someone by name. */ void PrintName(string name) printf("hello, %s\n", name); Separating out this logic in PrintName is a form of abstraction, hiding the low-level implementation details of how we print the name. Similarly, in function-1.c 4, we can use the return value of a function: 3 http://cdn.cs50.net/2015/fall/lectures/1/f/src1f/function-0.c 4 http://cdn.cs50.net/2015/fall/lectures/1/f/src1f/function-1.c 9

#include <cs50.h> #include <stdio.h> // prototype int GetPositiveInt(); int main(void) int n = GetPositiveInt(); printf("thanks for the %i!\n", n); /** * Gets a positive integer from a user. */ int GetPositiveInt(void) int n; do printf("please give me a positive int: "); n = GetInt(); while (n < 1); return n; The int in int GetPositiveInt(void), as well as the void in void PrintName(string name), indicates the return type of the function. PrintName doesn t return anything (it just prints a name to the screen, which is a side effect), so its return type is void. GetPositiveInt returns an int - the first positive integer value the user enters - using the return command. Any non-void function must have a return value (if you don t have a return command, your return value is assumed to be 0, for reasons we ll discuss later in the course). In return.c 5, we have another example of returning a value from a function: 5 http://cdn.cs50.net/2015/fall/lectures/1/f/src1f/return.c 10

#include <stdio.h> // function prototype int cube(int a); int main(void) int x = 2; printf("x is now %i\n", x); printf("cubing...\n"); x = cube(x); printf("cubed!\n"); printf("x is now %i\n", x); /** * Cubes argument. */ int cube(int n) return n * n * n; In this case, this function both accepts an input argument (an int, which we re calling n ) and outputs, or returns, a value. 5. Problem Set 1 On this problem set, you ll implement in C an ASCII version of Mario s pyramid (or a more challenging version in the hacker edition!) You ll also implement a greedy algorithm for determining the coins necessary when giving change, and investigate rates of water flow. 11