Functions that return a value

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Fungsi Risanuri Hidayat, Ir., M.Sc.. Functions C usually consist of two things: instance variables and functions. All C programs consist of one or more.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
Functions Quick Review What is a Function? A module of code that performs a specific job. Examples: Function that determines the maximum of two numbers.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
 2000 Prentice Hall, Inc. All rights reserved. Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Functions in C Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files.
Iterative Constructs Review l What are named constants? Why are they needed? l What is a block? What is special about declaring a variable inside a block?
CMSC 1041 Functions II Functions that return a value.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Introduction As programmers, we don’t want to have to implement functions for every possible task we encounter. The Standard C library contains functions.
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
Lecture 05 Functions II, Storage Class, Scope, rand() METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Chapter INTRODUCTION Data Types and Arithmetic Calculations.
L131 Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips rand( ) math library functions Reading Sections.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
UMBC CMSC 104 – Section 01, Fall 2016
Chapter 9: Value-Returning Functions
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
Lesson #6 Modular Programming and Functions.
INC 161 , CPE 100 Computer Programming
Lesson #6 Modular Programming and Functions.
C Functions Pepper.
TMF1414 Introduction to Programming
Functions, Part 2 of 2 Topics Functions That Return a Value
Quiz 11/15/16 – C functions, arrays and strings
Iterative Constructs Review
Chapter 5 Function Basics
Quiz 2.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Functions Department of Computer Science-BGU יום רביעי 12 ספטמבר 2018.
Programming Fundamentals Lecture #7 Functions
Deitel- C:How to Program (5ed)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
Scope, Parameter Passing, Storage Specifiers
Functions Declarations CSCI 230
Final Exam Final Exam: Thursday Dec 13th, 2001 at 8:30 pm in SS-111, the regular classroom.
Chapter 6 - Functions Outline 5.1 Introduction
Functions, Part 2 of 3 Topics Functions That Return a Value
Assignment Operators Topics Increment and Decrement Operators
Assignment Operators Topics Increment and Decrement Operators
A First Book of ANSI C Fourth Edition
Chapter 9: Value-Returning Functions
Lesson #6 Modular Programming and Functions.
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
Introduction to C Programming
Assignment Operators Topics Increment and Decrement Operators
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 42 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

Functions that return a value Functions II Functions that return a value

The Purpose of a Function To perform some encapsulated task. A task “delegated” from the main program. To isolate the main program from complex details. To break details into manageable units.

Functions in Everyday Life Changing the oil in your car Bounded task Isolate complexity (and mess). Often delegated (British-American Motors) Grocery shopping

Returned Values and Side Effects Two types of functions Those that return a value Those that produce side effects. A “side effect” is an effect on something external to the program and its data, e.g. printer, CRT, sound card. printf() is called for its side effects. getchar() is called for its return value.

A function that returns a value /*************************************************** ** AverageTwo ** calculates and returns the average of num1 and num2 ****************************************************/ float AverageTwo (int num1, int num2) { float average; average = (num1 + num2) / 2.0; return average; }

Using AverageTwo #include <stdio.h> float AverageTwo (int num1, int num2); main ( ) { float average; int num1 = 5, num2 = 8; average = AverageTwo (num1, num2); printf (“The average of %d and %d is %f\n”, num1, num2, average); } float AverageTwo (int num1, int num2) average = (num1 + num2) / 2.0; return average;

Function as Data Transformation Arguments Result A function is a method to transform arguments into results

Functions as Local Environments Functions have their own scope Variables defined within a function are “local” to the function. They are not defined outside the function. They are usually re-initialized each time the function is executed.

Arguments Arguments are passed “by value” The function gets the value of the argument, not its name or storage location. Functions can’t change the value of their arguments. The argument values are matched to the formal parameters in the order they are passed The parameters are declarations of variables known only inside the function. The values passed are assigned to those variables.

Arguments #include <stdio.h> int foo(int arg, int new); main() { int res, arg=3; /* a demonstration value*/ res = demo(arg, 7); printf(“arg: %d, res: %d\n”, arg, res); return(); } int foo(int arg, int new) arg = new; return (arg);

Okay, I Lied There are ways to pass values back through parameters, but they require “pointers”, a topic for a later lecture.

Local Variables Generally, functions “see” only their own local variables. This includes main ( ) The parameters of a function are declarations of local variables. Other local variables can be declared within the function

Local Variables The variables a,b,c,x,y are known only in foo. /* this is a function */ int foo(int a, int b) { int c; float x, y; ...<lots of stuff>... return(result); } a,b,c,x,y undefined out here The variables a,b,c,x,y are known only in foo.

Local Variables #include <stdio.h> float AverageTwo (int a, int b) float AverageTwo (int num1, int num2); { main ( ) float average; { float average; average = (a + b) / 2.0; int num1 = 5, num2 = 8; return average; } average = AverageTwo (num1, num2); printf (“The average of “); printf (“%d and %d is %f\n”, num1, num2, average); num1 num2 average a b average 5 8 int int float int int float

More about Local Variables #include <stdio.h> void AddOne (int num1); main () { int num1 = 5; printf (“num1 = %d\n”, num1); AddOne (num1); printf (“In main: “); exit(); } void AddOne(int num) { int num1; num1 = num++; printf(“In AddOne: num1 = %d\n”, num1); return; } In main: num1 = ? In AddOne: num1 = ?

Data Types and Conversion Specifiers Data Type printf scanf conversion conversion float %f %f double %f %lf long double %Lf %Lf int %d %d long int %ld %ld unsigned int %u %u unsigned long int %lu %lu short int %hd %hd char %c %c

Header Files Header files contain function prototypes for all of the functions found in the corresponding library It also contains definitions of constants and data types used in that library

int gradeSmasher(int Midt, int Proj, int HW, int Final); Prototype An example function call telling the compiler the number and type of arguments to expect int gradeSmasher(int Midt, int Proj, int HW, int Final);

Commonly Used Header Files header file Contains function prototypes for <stdio.h> the standard input/output library functions & information used by them <math.h> the math library functions (sin, cos, etc) <stdlib.h> the conversion of number to text, text to number, memory allocation, random numbers and other utility functions <time.h> manipulating time and date <ctype.h> functions that test characters for certain properties and that can convert case others see page 159 of text

Math Library double sqrt (double x); returns the square root of x double pow (double x, double y) x raised to the y power pow (3.0, 2.0) is 9.0 pow (8.0, 0.33) is 2.0 double sin (double x) trigonometric sine of x (x in radians) All math library functions take doubles as arguments and return doubles others on page 151 of text Remember these functions don’t compute actual values, but rational approximations. Usually very close, but ...

Common stdlib functions void exit (int x); prematurely ends program execution void srand (unsigned int x); “seeds” the random number generator with an unsigned integer that is used to start the calculations that generate the pseudo-random number srand (200); int rand (void); returns an unsigned pseudo-random integer in the range of 0 to 65535 or 0 to 4294967295 depending on the size of an integer on the system your on num = rand();

Computers Don’t Generate Random Numbers Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin. -- Jon von Neuman

Manipulating what rand() returns Since rand() returns unsigned integers in a large range, we often have to manipulate the return value to suit our purposes Suppose we want only random numbers in the range from 0 to 5 num = rand () % 6 How about 1 to 6? num = 1 + rand( ) % 6; How about 5 to 20? num = 5 + rand ( ) % 16;

srand ( ) and rand ( ) The pseudo-random number generator needs an unsigned int as it’s seed Although it produces what appear to be random numbers, if we use the same seed, we get the same sequence of random numbers To get different random numbers each time we run our program, we have to give a different seed each time

srand ( ) and rand ( ) The pseudo-random number generator needs an unsigned int as its seed Although it produces what appear to be random numbers, if we use the same seed, we get the same sequence of random numbers To get different random numbers each time we run our program, we have to give a different seed each time

srand ( ) and rand ( ) #include <stdio.h> #include <stdlib.h> #define SEED 67 main ( ) { int i, num; srand (SEED); for (i = 0; i < 5; i++) num = rand ( ); num = 1 + num % 6; printf (“%d\n”, num); } Since we are always using the value 67 as the seed for our pseudo-random number generator, the same sequence of numbers will be produced whenever we run our program.

<time.h> One of the most useful functions in the time library is the time() function It returns the time of day as seconds Since this number is different every time we call it, it’s greatest use is as a seed for the random number generator Each time we run our program, a different sequence of random numbers will be produced srand (time ( NULL) );

The Joys and Uses of Pseudo-Randomness Modeling and simulation Cryptography Randomness is bad in: debugging: set a constant seed so you can trace constant errors. repetitive simulation: testing the same model with slightly different parameters.