Lecture 12 Modular Programming with Functions

Similar documents
AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Fundamentals of Programming Session 4

Computer Science & Engineering 150A Problem Solving Using Computers

Chapter 2, Part I Introduction to C Programming

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Lecture 2: C Programming Basic

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

CS16 Exam #1 7/17/ Minutes 100 Points total

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

6.096 Introduction to C++

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

C Programming for Engineers Functions

C Functions. 5.2 Program Modules in C

Fundamentals of Programming. Lecture 3: Introduction to C Programming

CC112 Structured Programming

(Refer Slide Time 01:41 min)

Chapter 7 Functions. Now consider a more advanced example:

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Programming for Engineers Introduction to C

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

APS105. Modularity. C pre-defined functions 11/5/2013. Functions. Functions (and Pointers) main. Modularity. Math functions. Benefits of modularity:

Question 2. [5 points] Given the following symbolic constant definition

1 Getting started with Processing

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore

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

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

Fundamentals of Programming & Procedural Programming

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #13. Loops: Do - While

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

CISC 1600 Lecture 3.1 Introduction to Processing

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

ANSI C Programming Simple Programs

PIC 10A. Review for Midterm I

CPE 101. Overview. Programming vs. Cooking. Key Definitions/Concepts B-1

Code Documentation.

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Question 1. Part (a) [2 marks] error: assignment of read-only variable x ( x = 20 tries to modify a constant) Part (b) [1 mark]

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

User Defined Functions

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Shut the Box. By the time you are done with this activity, you and your team should be able to:

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Computing and Statistical Data Analysis Lecture 3

First of all, it is a variable, just like other variables you studied

Program Organization and Comments

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

AMCAT Automata Coding Sample Questions And Answers

Introduction to Programming. Lecture 6: Functions & Program Structure

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

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?

QUIZ Lesson 4. Exercise 4: Write an if statement that assigns the value of x to the variable y if x is in between 1 and 20, otherwise y is unchanged.

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Fundamental of Programming (C)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

Some Computer Preliminaries

Lecture 04 FUNCTIONS AND ARRAYS

Full file at C How to Program, 6/e Multiple Choice Test Bank

Multiple Choice Questions ( 1 mark)

C Pointers 2013 Author Riko H i

Chapter 4: Basic C Operators

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Technical Questions. Q 1) What are the key features in C programming language?

M.CS201 Programming language

C++ for Java Programmers

Shorthand for values: variables

C Program Structures

METHODS. CS302 Introduction to Programming University of Wisconsin Madison Lecture 15. By Matthew Bernstein

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

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

WARM UP LESSONS BARE BASICS

CSE 333 Midterm Exam 7/29/13

COMP 111 PROGRAMMING I MODULARITY USING FUNCTIONS

Pointers, Arrays and Parameters

Variables, Data Types, and Arithmetic Expressions Learning Objectives:

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

Functions in C C Programming and Software Tools

C++ Support Classes (Data and Variables)

Programming for Engineers Functions

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

APCS Semester #1 Final Exam Practice Problems

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Lecture 16 Introduction To Structures

Logical Operators and switch

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

C Formatting Guidelines

Transcription:

Lecture 12 Modular Programming with Functions Learning Objectives: Understand the purpose of functions Understand how to use functions and the vocabulary Write your own functions 1

Modularity (the purpose of functions) 1. Doing the same thing more than once: Say you are writing a program that will need to calculate the factorial of a number in 25 different places in the program. If you write some code to calculate the factorial, you can copy it to the other 24 places. But what happens when you find an error in that code? You ve got to correct it in 25 different places. Plus, this can make your program very long. Instead, use a function for calculating the factorial. 2. Readability of your Program: Say you are writing a long program, such as MS-Word. What if you need to modify the part that underlines words. Do you want to scroll through thousands of lines of code to find the right area in the program to modify? Instead use functions and classes which separate the code into sections that you can easily find. This way, if your functions are named well, you can read main() and easily see how the whole program works. 2

What is a function? Some code located outside of main() that you can use within main(). You ve already used a lot of functions that C/C++ has available to you. Example: log(x) Returns the natural logarithm of x What do I mean by returns the ln? The function call becomes that number Here, x is the argument If we had the code: double y=2.3, a=1.2, answer; answer = log(y); printf( %lf \n, answer); answer = log(a); printf( %lf \n, answer); Would this work? When calling functions, you can use different variables for the arguments. For log(), use whatever variable or number you want to find the ln of. 3

Examples of other Functions that you ve seen 1. pow(x,i) Notice this has 2 arguments, both need to be numbers (double or integer = the base and the exponent) and it will return a double. 2. a.push_back(n); This is a function of the vector class, thus you call it with a dot. It doesn t return anything, but changes the vector by adding the value of n to it. 3. printf( n = %i, n); printf is a function that can have many arguments or just one. It also doesn t return anything. 4. i < a.size(); size() is a vector function that returns the current size of the vector. It has no arguments, but still needs the parentheses. Notice that functions always have parentheses 4 after them.

Example (The entire function is placed after the } at the end of the program) //This function calculates the i th Fibonacci number int fibonacci(int i) { } int prev2 = 0, prev = 1, f = 0; for(int j=1; j<i; j++) { } f = prev + prev2; prev2 = prev; prev = f; return f; Function Syntax Note: This is just like a mini program! Instead of int main(), you ve got your function header. 5

Function Syntax Calling this function from within main(): int f, a=10; f = fibonacci(a); Notice how the argument is not called i even though you used i within the function. This is just like calling log(a)! Remember that!!!! Function Header (1 st Line): Note that you declare your parameters(arguments) inside the parentheses in the function header. int fibonacci( int i ) type of value to return parameter type=declaration of i name of function (you decide this) parentheses needed even if no parameters variable name for parameter (you also decide this) 6

Function Prototype Most of the time, you put your functions below the main() function in your program. Problem: the program starts executing at main() and at this point hasn t seen the function, so will be confused when you call the function. To get around this, use a function prototype: A function prototype is just the function header (1 st line of your function) copied and placed above main(). The only thing you need to change is to add a semicolon at the end of the line. Since the function prototype is above main(), the whole program can use this function (including other functions besides main) Example: Function prototype for the function fibonacci: int fibonacci(int i); 7

How to Write a Function 1. Decide what you want your function to do. Does it calculate a value, does it print something out? This will determine the return type and the code in the function. 2. Decide what values it will need in order to complete its task. For example, if you are calculating the area of a circle, you will need a radius or diameter. This will determine your parameters/arguments. 3. Start below the last brace of main() and make your function header. 4. Put curly braces after the header. 5. Fill in the code 6. Copy the header to the area above main() and put a semicolon after it. 7. Call the function within main. 8. Test your function with known values! 8

#include <stdio.h> Another Example double cylindervolume(double r, double h); int main() { double rad=2.6, height=8.9; //radius and height } printf( The volume is %lf \n, cylindervolume(rad, height)); //This function will take a radius and height and calculate the volume of a cylinder. double cylindervolume(double r, double h) { return 3.14159*r*r*h; } 9

What if I don t want to return a value? use void //This function writes an error message to the screen: void errmessage() { printf( You ve entered an invalid number ); return; //note return used without a value after it } Note that return will end the function. void means the function is not returning a value. To use this within main: errmessage( ); This is just like calling printf()! Remember that!!!! 10

Examples Create a function prototype and write a line to call a function that: 1. Simulates rolling a die. 2. Calculates the area of a triangle. 3. Calculates the magnitude of a resultant vector 11