Week 3 Part I Kyle Dewey. Overview Odds & Ends Constants Errors Functions Expressions versus statements.

Slides:



Advertisements
Similar presentations
Week 1 Part II Kyle Dewey. Overview Lab The art of programming Basic data types Variable declaration and initialization Data representation.
Advertisements

CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Lecture 2 Introduction to C Programming
Introduction to C Programming
CS16 Week 2 Part 2 Kyle Dewey. Overview Type coercion and casting More on assignment Pre/post increment/decrement scanf Constants Math library Errors.
C Language Elements (II) H&K Chapter 2 Instructor – Gokcen Cilingir Cpt S 121 (June 22, 2011) Washington State University.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
CS1061 C Programming Lecture 2: A Few Simple Programs A. O’Riordan, 2004.
If You Missed Last Week Go to Click on Syllabus, review lecture 01 notes, course schedule Contact your TA ( on website) Schedule.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
CS 201 Functions Debzani Deb.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Basic Elements of C++ Chapter 2.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Variables in Java Part 2. ICS-3M1 - Mr. Martens - Variables Part 2 Recall the “int” Data Types When you divide one integer by another – you always get.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
General Programming Introduction to Computing Science and Programming I.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
CSC 107 – Programming For Science. Announcements  Textbook available from library’s closed reserve.
© 2006 Pearson Education 1 Obj: cont 1.3 and 1.4, to become familiar with identifiers and to understand how programming languages work HW: p.51 #1.8 –
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
The Java Programming Language
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
Testing. 2 Overview Testing and debugging are important activities in software development. Techniques and tools are introduced. Material borrowed here.
Lecture 1 Introduction Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
CPS120: Introduction to Computer Science Decision Making in Programs.
Errors “Computer says no..”. Types of Errors Many different types of errors new ones are being invented every day by industrious programming students..
Java Data Types Assignment and Simple Arithmetic.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Introduction to Programming
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 3 Top-Down Design with Functions Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Week 7 Part I Kyle Dewey. Overview Code from last time Array initialization Pointers vs. arrays Structs typedef Bubble sort (if time)
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
End of the beginning Let’s wrap up some details and be sure we are all on the same page Good way to make friends and be popular.
Principles of Programming CSEB134 : BS/ CHAPTER Fundamentals of the C Programming Language.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Last week: We talked about: History of C Compiler for C programming
Introduction to Computing Science and Programming I
User-Written Functions
CSC201: Computer Programming
Lecture 1 Introduction Richard Gesick.
Completing the Problem-Solving Process
ICS103 Programming in C Lecture 3: Introduction to C (2)
User-Defined Functions
Program Breakdown, Variables, Types, Control Flow, and Input/Output
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
An Overview of C.
Chapter 1 c++ structure C++ Input / Output
Instructor: Alexander Stoytchev
Presentation transcript:

Week 3 Part I Kyle Dewey

Overview Odds & Ends Constants Errors Functions Expressions versus statements

Pre-Lab

Underflow & Overflow Note

Constants

Values which never change Specific values are constants ‘a’ “foobar”

Constants Specifically in the program text Constant in that 52 always holds the same value We cannot redefine 52 to be 53

Symbolic Constants Usually when programmers say “constant”, they mean “symbolic constant” Values that never change, but referred to using some symbol i.e. π (pi ) Mapping between symbol and value is explicitly defined somewhere

In C Use #define By convention, constants should be entirely in caps #define PI int x = PI * 5;

Mutability Constants are, well, constant! Cannot be changed while code runs #define PI PI = 4; // not valid C!

What #define Does Defines a text substitution for the provided symbol This text is replaced during compilation by the C preprocessor (cpp)

Example #1 #define PI int x = PI * 5; Code int x = 3.14 * 5; After Preprocessor

Example #2 Code 3.14 = 4; After Preprocessor #define PI PI = 4;

Best Practices Generally, all constants should be made symbolic Easier to change if needed later on Gives more semantic meaning (i.e. PI is more informative than ) Possibly less typing

Errors

Generally, expected result does not match actual result Four kinds of errors are relevant to CS16: Syntax errors Linker errors Runtime errors Logic errors

Errors Four kinds of errors are relevant to CS16: Syntax errors Linker errors Runtime errors Logic errors

Syntax Error A “sentence” was formed that does not exist in the language For example, “Be an awesome program” isn’t valid C

Syntax Error Easiest to correct Compiler will not allow it *Usually* it will say where it is exactly

On Syntax Errors...sometimes the compiler is really bad at figuring out where the error is #include int main() { printf( "moo" ) printf( "cow" ); return 0;}

Reality #include int main() { printf( "moo" ) printf( "cow" ); return 0;} Missing semicolon at line 4

GCC #include int main() { printf( "moo" ) printf( "cow" ); return 0;} syntax.c: In function ‘main’:syntax.c:5: error: expected ‘;’ before ‘printf’

Ch #include int main() { printf( "moo" ) printf( "cow" ); return 0;} ERROR: multiple operands together ERROR: syntax error before or at line 5 in file syntax.c ==>: printf( "cow" ); BUG: printf( "cow" )<== ???

The Point Compilers are just other programs Programs can be wrong Programs are not as smart as people

Errors Four kinds of errors are relevant to CS16: Syntax errors Linker errors Runtime errors Logic errors

Recall Linking 1: somethingFromHere(); 2: somethingFromElsewhere(); 3: somethingElseFromHere(); somethingFromHer e somethingElseFromHer e somethingFromElsewh ere

Recall Linking somethingFromHer e somethingElseFromHer e somethingFromElsewhere

Linker Errors What if somethingFromElsewhere is nowhere to be found? Missing a piece Cannot make the executable

Example int something();int main() { something(); return 0;} int something(); tells the compiler that something exists somewhere, but it does not actually give something

Example int something();int main() { something(); return 0;} Undefined symbols for architecture x86_64: "_something", referenced from: _main in ccM6c8aW.old: symbol(s) not found for architecture x86_64

Errors Four kinds of errors are relevant to CS16: Syntax errors Linker errors Runtime errors Logic errors

Runtime Errors Error that occurs while the code is running Compilation and linking must have succeeded to get to this point

Examples Overflow unsigned char x = 255; x = x + 1; Underflow unsigned char x =0; x = x - 1;

Examples Divide by zero (especially for integers!) unsigned int x = 5 / 0; Wrong printf placeholder printf( “%s”, 57 );

Errors Four kinds of errors are relevant to CS16: Syntax errors Linker errors Runtime errors Logic errors

Logic Errors It works!...but it doesn’t do what you wanted Like getting the wrong order at a restaurant

Examples Transcribed an equation incorrectly Using the wrong variable Lack of understanding of problem etc. etc. etc...

Logic Errors By far, the most difficult to debug It might be done almost correctly This is why testing is so important!

Functions Divide and Conquer Revisited

Divide and Conquer Break a problem down into distinct subproblems, solve them individually, and finally combine them

Divide and Conquer Program Input Output

Divide and Conquer Subprogram 1 Input Output Subprogram 2 Output / Input

Divide and Conquer Input Output Subprogram 2 Subprogram A Subprogram B Output / Input

Input and Output Intentionally left ambiguous This general model is widely applicable Program Input Output

Relation to Functions Consider the function printf printf Formatting string, variables to print Something on the terminal

printf Function printf( “%i\n”, myInteger ) printf “%i\n” myInteger >

Functions A way of breaking down programs into (more or less) independent units Can be tested individually Easier to think about

Function Input / Output Input: parameters (more on this later) Output: return value

Functions Input Output Function C Function A Function B Output / Input

Functions Input Output Function C Function A Function B Output / Input functionC( functionA( Input ), functionB( Input ) )

Using Functions in C Function names have the same rules as variables Functions are called like so: noArguments(); printf( “hi” ); printf( “%i”, myInteger );

Making Functions in C Function definition template ( p = parameter): returnType functionName(p1,p2,...,pN) { // function body }

Returning Functions can optionally return values using the return reserved word This is a special output mechanism

Examples int toSecondPower( int number ) { return number * number; } double doubleIt1( double number ) { return number + number; } double doubleIt2( double number ) { return number * 2; }

Bigger Example int craziness( double number ) { int x = (int)(number * 2); double y = x + 2; int z = (int)(y * y) + x; return z; }

Question Return type doesn’t match what’s returned What happens? int mismatch( double number ) { return number; }

Answer Treated as a cast to the return type int mismatch( double number ) { return number; } int main() { // prints out 5 printf( “%i\n”, mismatch( 5.5 ) ); return 0; }

Question Two returns - What happens? int craziness2( double number ) { int x = (int)(number * 2); return x; double y = x + 2; int z = (int)(y * y) + x; return z; }

Answer Functions can return at most once Everything past the first one is ignored int craziness2( double number ) { int x = (int)(number * 2); return x; double y = x + 2; int z = (int)(y * y) + x; return z; }

Question There is no explicit return What happens? int craziness3( double number ) { int x = (int)(number * 2); double y = x + 2; int z = (int)(y * y) + x; }

Answer It will return something...but who knows what Undefined behavior gcc will give a warning if given the - Wall flag gcc -Wall myProgram.c

“May Return” Functions don’t necessarily need to return values Can still be useful

void Return Type If a function has a return type of void, this mean it does not return anything int globalVariable = 0; void incrementGlobal() { globalVariable++; }

void and Return return can still be used with void functions Simply ends the execution of the function Important in discussing control flow void something() { return; }

Question Returning something with void What happens? void function() { return 5; }

Answer Nothing is returned gcc gives a warning about this void function() { return 5; }

Function Prototypes Needed to tell the compiler a function exists Without them, functions have to be ordered carefully or the compiler can get confused

Without Prototypes void something() { return; } int getFive() { something(); return 5; } Compiles fine

Without Prototypes int getFive() { something(); return 5; } void something() { return; } prototypes.c:6: warning: conflicting types for ‘something’prototypes.c:2: warning: previous implicit declaration of ‘something’ was here

Function Prototypes Look just like the definition, but they lack a body returnType functionName(p1,p2,...,pN) ;

Prototype Example int getFive(); void something(); int getFive() { something(); return 5; } void something() { return; } Compiles fine

Parameters Revisited int addTen( int input ) { return input + 10; }... addTen( 5 );

Parameters Revisited int addTen( int input ) { return input + 10; }... addTen( 5 ); Formal Parameter Actual Parameter

Putting it All Together

Example A program reads in a signed integer The program adds 50 to the integer The program prints the result out to the user functionExample.c