Binghamton University. CS-211 Fall Functions. The Basis of C

Similar documents
CS-211 Fall 2017 Test 1 Version Practice For Test on Oct. 2, Name:

CS-211 Fall 2017 Test 1 Version A Oct. 2, Name:

Overview (1A) Young Won Lim 9/25/17

PROGRAMMAZIONE I A.A. 2017/2018

Writing Functions in C

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

Overview (1A) Young Won Lim 9/14/17

Overview (1A) Young Won Lim 9/9/17

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Ch 4. Parameters and Function Overloading

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

Binghamton University. CS-211 Fall Variable Scope

Binghamton University. CS-211 Fall Variable Scope

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Binghamton University. CS-211 Fall Variable Scope

Dynamic memory allocation

Procedures, Parameters, Values and Variables. Steven R. Bagley

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

C:\Temp\Templates. Download This PDF From The Web Site

Variables and Functions. ROBOTC Software

Introduction to Programming (Java) 4/12

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

CSE 303: Concepts and Tools for Software Development

A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.

Pointers and scanf() Steven R. Bagley

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Function a block of statements grouped together, to perform some specific task

C-String Library Functions

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

CAAM 420 Daily Note. Scriber: Qijia Jiang. Date: Oct.16. Project 3 Due Wed 23.Oct. Two parts: debug code and library exercise.

An overview of Java, Data types and variables

CS16 Midterm Exam 1 E01, 10S, Phill Conrad, UC Santa Barbara Wednesday, 04/21/2010, 1pm-1:50pm

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CSC258: Computer Organization. Functions and the Compiler Tool Chain

Communication With the Outside World

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

CSE 374 Programming Concepts & Tools

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

Exercise Session 2 Systems Programming and Computer Architecture

Lab Session # 6 Functions. ALQUDS University Department of Computer Engineering

CS240: Programming in C

Program Organization and Comments

G52CPP C++ Programming Lecture 9

Week 3. This is CS50. Harvard University. Fall Cheng Gong

S Computer Architecture. Computer architecture assignment E1 A subroutine, which searches for given byte pattern from an byte array.

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Chapter 3 - Functions

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Operating System Interaction via bash

CS240: Programming in C

Common Misunderstandings from Exam 1 Material

Class #1. introduction, functions, variables, conditionals

Programming in C. What is C?... What is C?

CSC 2400: Computer Systems. Arrays and Strings in C

LSN 3 C Concepts for OS Programming

1 Lexical Considerations

Variables and literals

Turtle Tango (TT) Language Reference Manual

1 Getting started with Processing

CSE 333 Autumn 2014 Midterm Key

Managing Memory. (and low level Data Structures) Lectures 22, 23. Hartmut Kaiser.

Lab: Supplying Inputs to Programs

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

CSE 333 Lecture 3 - arrays, memory, pointers

CSE 333 Lecture 2 - arrays, memory, pointers

fedithead RichardJ.Mathar Generated by Doxygen Tue May :39:52

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

C++ Programming Chapter 7 Pointers

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4500/8506 Operating Systems Fall Programming Assignment 1 (updated 9/16/2017)

Programming and Data Structure

Arrays and Pointers (part 2) Be extra careful with pointers!

C++ Lab 03 - C++ Functions

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

CSC 2400: Computer Systems. Arrays and Strings in C

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

Arrays and Pointers (part 2) Be extra careful with pointers!

CS-220 Spring 2018 Test 1 Version A Feb. 28, Name:

Chapter 13. Functions and Parameter Passing (Part 2)

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

G Programming Languages - Fall 2012

Coursework 2: Basic Programming

SU2017. LAB 1 (May 4/9) Introduction to C, Function Declaration vs. Definition, Basic I/O (scanf/printf, getchar/putchar)

UNIVERSITY OF NEBRASKA AT OMAHA Computer Science 4500/8506 Operating Systems Summer 2016 Programming Assignment 1 Introduction The purpose of this

Roadmap. Java: Assembly language: OS: Machine code: Computer system:

CS-211 Fall 2017 Test 2 Version A November 29, Name:

Chapter 11 Introduction to Programming in C

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

primitive arrays v. vectors (1)

Transcription:

Functions The Basis of C 1

What is a function? Have you ever needed to convert from C to F? Demo: http://www.pronk.com/samples/projects/021$function_machine/fu nction_machine.html 2

Function in C float cent_to_far(float t) { } return (t*9.0)/5.0+32; 3

C Function Anatomy double cent_to_far(double t) { return (t*9.0)/5.0+32; } Name Parameter(s) Return Type Body 4

Function Arguments or Parameters Almost like Local Variable Declarations with no initialization Comma separated list of variables passed in to the function Each entry specifies the type and name of one parameter When a function is invoked, the invoker specifies the initial values of the arguments The parameter can be referenced by its name in the function body Values passed are COPIES of the arguments Changing a parameter does not change the caller s variable! 5

Argument vs. Parameter Really the same thing data passed into a function to work on The difference is the point of view Caller s point of view: Arguments float ftemp=cent_to_far(28.3); Called function ( callee ) point of view: parameter float cent_to_far(float t) { return (t*9.0)/5.0+32;

Function Body List of C statements that define how the function works Typically works on arguments to produce result May have side effects (other than producing a result) Write messages to the console Read information from a file Change a global variable value Result is specified by a return statement 7

Function Return Value Type specified in function definition Must specify some return type May specify void to indicate function returns nothing In this case, no return statement is required, or no value: return; Value specified in body by return statement return value; where value is an expression that evaluates to the return type 8

Function Invocation Invoke a function in a C expression by specifying: function_name ( argument_expression_list ) function_name : name of a previously declared function argument_expression_list : comma separated list of expressions to be used as arguments When a function is invoked, C will. 1. evaluate argument expressions, 2. Copy argument values into parameters 3. invoke the specified function (run it s body) 4. conceptually replace the function invocation with the returned value float warmer=cent_to_far(ctemp*1.10); 9

Functions for Abstraction Function Prototype: float cent_to_far(float t) Function Behavior: Convert Centigrade to Fahrenheit Function Embodiment: WHO CARES? As long as it works, we can ignore the embodiment! Code it once, test it, and then use it lots of times! 10

The main function Every C program must have a main function When C program is run, the OS invokes the main function When the main function returns, program ends Return value int Return value 0 indicates program worked OK Return value other than 0 indicates program failed main function arguments stay tuned main function may invoke lower level functions For now: int main() { ; return 0; } 11

Arguments to main When the operating system calls the main function, it: parses the command line, splitting at white space (blanks, tabs) >./converttemp 21.3 F C Counts the number of blank delimited words: argc=4 Creates an array of words or strings (really an array of arrays) argv[0]./converttemp argv[1] 21.3 argv[2] F argv[3] C Size=4

Parameters of main Typically use argc and argv as the names of the parameters to main int main(int argc, char **argv) { argc argument count the size of the argv array argv argument value (or vector) - a list of strings Each string is an array of characters So argv is an array of arrays of characters Almost (char[])[] argv argv is an array of (array of characters) (note: not char[][] argv not a two dimensional array of characters!) Can reference each string as argv[i] Can reference individual letters as argv[i][j] really (argv[i])[j]

C Declare before Use Rule In C, you cannot invoke a function which has not been declared One way to declare a function is to fully define the function This causes upside down code Lowest Level functions are first in the file Highest Level function (main) is last in the file 14

Example of Upside Down Code float freezingpoint(char scale) { } float boilingpoint(char scale) { } int validscale(char scale) { } float converttemp( ) { validscale( C ); boilingpoint( C ); freezingpoint( C ); } int main(int argc, char **argv) { converttemp( C2F,17.3) } 15

Function Prototype Declare Function Prototype: float freezingpoint(char scale) Prototype consists of return type, function name, & parameter list We can declare a function by specifying the prototype; Followed by a semi-colon Still need full function definition somewhere else Enables Right Side Up coding Function Prototypes at the top of the file Function definition for top level function (main) next Then function definitions for lower level functions 16

Example of RightSide Up Code float converttemp(char scale, ); int validscale(char scale); float boilingpoint(char scale); float freezingpoint(char scale); int main(int argc, char **argv) { } float converttemp(char scale, ) { } int validscale(char scale) { } float boilingpoint(char scale) { } float freezingpoint(char scale) { } Declarations Definitions 17

Writing Functions in C 1. Get the big picture what are we trying to do? 2. Choose a function name 3. Identify the argument list 4. Figure out the return type 5. Write the function prototype 6. Implement the function 7. Test the function

Demo We are working on CAD for house plans. Our customer has asked us to write a function, given the length and width of a wall in inches, figure out how many linear feet of board to the nearest foot will we need to cover the wall if the boards are 8 inches wide?

Big Picture height width Need ceil(height/8) boards, each width wide. Need ceil(boards * width/12) linear feet

Function Arguments? What values is the user willing to give us? What do we need to figure out the answer? What is the data type of each argument? What name will you use for each argument? Easy to type and remember Note: When you implement your function, you may change your mind. That s OK.

Return Type? What type of data does your user expect you to return? Does the data type reflect the precision of the inputs?

Resources Programming in C, Chapter 7 up to Functions Calling Functions Calling (p. 130) YouTube: Meat-a-Morphis Introduction to Functions (https://www.youtube.com/watch?v=vutxspfx-qq) WikiPedia: Subroutine (https://en.wikipedia.org/wiki/subroutine) WikiPedia: C Standard Library: (https://en.wikipedia.org/wiki/c_standard_library) ACM C Library Reference Guide (https://wwws.acm.illinois.edu/webmonkeys/book/c_guide/) 23