Functions. Systems Programming Concepts

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

C Functions. 5.2 Program Modules in C

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

CSE123. Program Design and Modular Programming Functions 1-1

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

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

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Lecture 04 FUNCTIONS AND ARRAYS

Chapter 3 - Functions

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

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

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

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

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

C Functions Pearson Education, Inc. All rights reserved.

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Lecture 04 FUNCTIONS AND ARRAYS

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Functions and Recursion

Introduction to Programming

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Methods: A Deeper Look

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

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

ECET 264 C Programming Language with Applications

C Programs: Simple Statements and Expressions

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Function Call Stack and Activation Records

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Introduction to C Language

Chapter 5 C Functions

Chapter 3 - Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ Programming Lecture 11 Functions Part I

Unit 7. Functions. Need of User Defined Functions

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Fundamentals of Programming & Procedural Programming

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

Programming for Engineers Functions

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

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

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

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Lecture 9 - C Functions

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

6.5 Function Prototypes and Argument Coercion

CT 229 Java Syntax Continued

Computer Science & Engineering 150A Problem Solving Using Computers

(created by professor Marina Tanasyuk) FUNCTIONS

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

1001ICT Introduction To Programming Lecture Notes

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Assoc. Prof. Dr. Tansu FİLİK

ANSI C Programming Simple Programs

Fundamentals of Programming Session 12

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Programming in C Quick Start! Biostatistics 615 Lecture 4

CS101 Introduction to computing Function, Scope Rules and Storage class

Downloaded from Chapter 2. Functions

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

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

CS3157: Advanced Programming. Outline

Computer Systems Lecture 9

C++ Overview. Chapter 1. Chapter 2

C Functions. Object created and destroyed within its block auto: default for local variables

C Programming for Engineers Functions

Lab Instructor : Jean Lai

Computers in Engineering. Moving From Fortran to C Michael A. Hawker

C Review. SWE2004: Principles in Programming Spring 2014 Euiseong Seo

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

Visual Studio. Visual Studio is an extremely complex interactive development environment capable of handling many languages and tools.

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls

OBJECTIVE QUESTIONS: Choose the correct alternative:


Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

A Fast Review of C Essentials Part I

Object Oriented Methods : Deeper Look Lecture Three

Chapter 14 - Advanced C Topics

from Appendix B: Some C Essentials

Computers Programming Course 5. Iulian Năstac

Functions and Recursion

Lecture 3: C Programm

Model Viva Questions for Programming in C lab

Computers Programming Course 6. Iulian Năstac

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

C: How to Program. Week /Apr/16

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Operators and Expressions:

Beginning C Programming for Engineers

Data types, variables, constants

Transcription:

Functions Systems Programming Concepts

Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value and Call by Reference Scope (global and local) Call by Value Example Static Variables Systems Programming Functions 2

Simple Function Example char isalive ( int i) { if (i > 0) return 'A'; else return 'D'; } int main () { int Peter, Paul, Mary, Tom; main C programs start execution at main. is simply another function. All functions have a return value. Peter = 1; Paul = 2; Mary = -1; Tom = 0; printf("peter is %c Paul is %c\nmary is %c Tom is %c\n", isalive (Peter), isalive (Paul), isalive (Mary), isalive (Tom)); return 0; } %./dora Peter is A Paul is A Mary is D Tom is D Systems Programming Functions 3

Function Declarations char isalive ( int i); int main () { int Peter, Paul, Mary, Tom; function prototype Peter = 1; Paul = 2; Mary = -1; Tom = 0; printf("peter is %c Paul is %c\nmary is %c Tom is %c\n", isalive (Peter), isalive (Paul), isalive (Mary), isalive (Tom)); return 0; } char isalive ( int i) { if (i > 0) return 'A'; else return 'D'; } function placed after reference Systems Programming Functions 4

5.2 Program Modules in C Functions {also referred to as routines or subroutines} Modules in C Programs combine user-defined functions with library functions. C standard library has a wide variety of functions. Function calls Invoking functions Provide function name and arguments (data). Function performs operations or manipulations. Function returns results. 2007 Pearson Ed -All rights reserved. Systems Programming Functions 5

5.3 Math Library Functions Math library functions perform common mathematical calculations. #include <math.h> Format for calling functions FunctionName ( argument ); If multiple arguments, use comma-separated list. printf( "%.2f", sqrt( 900.0 ) ); Calls function sqrt, which returns the square root of its argument. All math functions return data type double. Arguments may be constants, variables, or expressions. 2007 Pearson Ed -All rights reserved. Systems Programming Functions 6

Fig. 5.2 Commonly used math library functions. (Part 1) Function Description Example sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 exp( x ) exponential function e x exp( 1.0 ) is 2.718282 exp( 2.0 ) is 7.389056 log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 1.0 ) is 0.0 log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 fabs( x ) absolute value of x fabs( 5.0 ) is 5.0 fabs( 0.0 ) is 0.0 fabs( -5.0 ) is 5.0 ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 2007 Pearson Ed -All rights reserved. Systems Programming Functions 7

Fig. 5.2 Commonly used math library functions. (Part 2) Function Description Example floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 pow( x, y ) x raised to power y (x y ) pow( 2, 7 ) is 128.0 pow( 9,.5 ) is 3.0 fmod( x, y ) remainder of x/y as a floatingpoint number fmod( 13.657, 2.333 ) is 1.992 sin( x ) cos( x ) tan( x ) trigonometric sine of x (x in radians) trigonometric cosine of x (x in radians) trigonometric tangent of x (x in radians) sin( 0.0 ) is 0.0 cos( 0.0 ) is 1.0 tan( 0.0 ) is 0.0 2007 Pearson Ed -All rights reserved. Systems Programming Functions 8

5.4 Functions Functions Modularize a program. All variables defined inside functions are local variables. Known and accessed only in defined function. Parameter list Communicate information between functions. Local variables of the function. Benefits of functions Software reusability Use existing functions as building blocks for new programs. Abstraction - hide internal details (library functions). Avoid code repetition 2007 Pearson Ed -All rights reserved. Systems Programming Functions 9

5.5 Function Definitions Function definition format return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier. Return-value-type: data type of the result (default int) void indicates that the function returns nothing. Parameter-list: comma separated list, declares parameters. A type must be listed explicitly for each parameter unless, the parameter is of type int. 2007 Pearson Ed -All rights reserved. Systems Programming Functions 10

5.5 Function Definitions Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } Definitions and statements: function body (block) Variables can be defined inside blocks (can be nested). Functions cannot be defined inside other functions! Returning control If nothing returned return; or, until reaches right brace If something returned return expression; 2007 Pearson Ed -All rights reserved. Systems Programming Functions 11

5.6 Function Prototypes Function prototype Function name Parameters what the function takes in. Return type data type function returns. (default int) Used to validate functions. Prototype only needed if function definition comes after use in program. Promotion rules and conversions Promotion :: temporary conversion to the highest type in the expression. Converting to lower types can lead to errors. 2007 Pearson Ed -All rights reserved. Systems Programming Functions 12

Fig. 5.5 Promotion Hierarchy Data type printf conversion specification scanf conversion specification Long double %Lf %Lf double %f %lf float %f %f Unsigned long int %lu %lu higher long int %ld %ld unsigned int %u %u int %d %d unsigned short %hu %hu short %hd %hd char %c %c lower 2007 Pearson Ed -All rights reserved. Systems Programming Functions 13

5.7 Function Call Stack and Activation Records Function call stack ( or program execution stack) A stack is a last-in, first-out (LIFO) data structure. Anything put into the stack is placed on top. The only data that can be taken out is the data on top. C uses a program execution stack to keep track of which functions have been called. When a function is called, it is placed on top of the stack (pushed onto the stack). When a function ends, it is taken off the stack (popped off the stack) and control returns to the function immediately below it. Calling more functions than C can handle at once is known as a stack overflow error. 2007 Pearson Ed -All rights reserved. Systems Programming Functions 14

5.8 Headers Header files Contain function prototypes for library functions. e.g., <stdlib.h>, <math.h> Load with #include <filename> #include <math.h> Custom header files Create file with functions. Save as filename.h Load in other files with #include "filename.h" This facilitates functions reuse. 2007 Pearson Ed -All rights reserved. Systems Programming Functions 15

Fig. 5.6 Standard Library Headers (Part 3) Standard library header Explanation <stdio.h> <stdlib.h> <string.h> <time.h> Contains function prototypes for the standard input/output library functions, and information used by them. Contains function prototypes for conversions of numbers to text and text to numbers, memory allocation, random numbers, and other utility functions. Contains function prototypes for string-processing functions. Contains function prototypes and types for manipulating the time and date. Systems Programming Functions 16

5.10 Random Number Generation rand function Load <stdlib.h> Returns a "random" number between 0 and RAND_MAX (at least 32767). i = rand(); Pseudo random Preset sequence of "random" numbers Same sequence for every function call Scaling To get a random number between 1 and n. i = 1 + ( rand() % n ) rand() % n returns a number between 0 and n 1. Add 1 to make random number between 1 and n. i = 1 + ( rand() % 6) number between 1 and 6 2007 Pearson Ed -All rights reserved. Systems Programming Functions 17

Random Number Example 1 /* Fig. 5.7: fig05_07.c 2 Shifted, scaled integers produced by 1 + rand() % 6 */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 6 /* function main begins program execution */ 7 int main( void ) 8 { 9 int i; /* counter */ 10 11 /* loop 20 times */ 12 for ( i = 1; i <= 20; i++ ) { 13 14 /* pick random number from 1 to 6 and output it */ 15 printf( "%10d", 1 + ( rand() % 6 ) ); 16 17 /* if counter is divisible by 5, begin new line of output */ 18 if ( i % 5 == 0 ) { 19 printf( "\n" ); 20 } /* end if */ 21 22 } /* end for */ 23 24 return 0; /* indicates successful termination */ 25 26 } /* end main */ Generates a random number between 1 and 6 Use of modulo operator is a standard trick to print output in column format. 6 5 6 1 5 1 5 5 6 3 6 6 2 4 2 6 2 3 4 1 2007 Pearson Ed -All rights reserved. Systems Programming Functions 18

Call by Value When arguments are passed by the calling routine to the called routine by value, A copy of each argument s value is passed to the called routine. Hence, any changes made to the passed argument by the called routine DO NOT change the original argument in the calling routine. This avoids accidental changes known as side-effecting. Systems Programming Functions 19

Call by Reference When arguments are passed by the calling routine to the called routine by reference, The original argument is passed to the called routine. Hence, any changes made to the passed argument means that this changes remain in effect when control is returned to the calling routine. Systems Programming Functions 20

C Argument Passing Rules In C, all arguments (by default) are passed by value. * Call by reference is simulated in C by using the address operator (&) and the indirection operator (*). Array arguments are automatically passed by reference! {Much more about all this when we introduce pointers.} Systems Programming Functions 21

Scope (simple) In C, the scope of a declared variable or type is defined within the range of the block of code in which the declaration is made. Two simple examples: 1. declarations outside all functions are called globals. They can be referenced and modified by ANY function. {Note this violates good programming practice rules}. Systems Programming Functions 22

Scope (simple) 2. Local variables declarations made inside a function mean that variable name is defined only within the scope of that function. Variables with the same name outside the function are different. Every time the function is invoked the value of local variables need to be reinitialized upon entry to the function. Local variables have the automatic storage duration by default (implicit). auto double x, y /* explicit auto */ Systems Programming Functions 23

Call by Value Example /* Example shows call-by-value and the scope of a global variable 'out' */ int out = 100; /* out is a global variable */ /* byval modifies local, global and variables passed by value. */ int byval ( int i, int j) { int tmp; tmp = 51; i = tmp - 10*i - j; out = 2*out + i + j; global is changed j++; tmp++; printf("in byval: i = %2d, j = %2d, tmp = %2d, out = %3d\n", i, j, tmp, out); return i; } Systems Programming Functions 24

Call by Value Example (cont) int main () { int i, j, tmp, s; } tmp = 77; j = 1; for (i = 0; i < 2; i++) { s = byval(i,j); out = out + s - j; printf("in main : i = %2d, j = %2d, tmp = %2d, out = %3d, s = %d\n", i, j, tmp, out, s); } return 0; global is changed Systems Programming Functions 25

Call by Value Example int main () { int i, j, tmp, s; tmp = 77; j = 1; $./byval In byval: i = 50, j = 2, tmp = 52, out = 251 In main : i = 0, j = 1, tmp = 77, out = 300, s = 50 In byval: i = 40, j = 2, tmp = 52, out = 641 In main : i = 1, j = 1, tmp = 77, out = 680, s = 40 } for (i = 0; i < 2; i++) { s = byval(i,j); out = out + s - j; printf("in main : i = %2d, j = %2d, tmp = %2d, out = %3d, s = %d\n", i, j, tmp, out, s); } return 0; Systems Programming Functions 26

Static Variables Local variables declared with the keyword static are still only known in the function in which they are defined. However, unlike automatic variables, static local variables retain their value when the function is exited. e.g., static int count = 2; All numeric static variables are initialized to zero if not explicitly initialized. Systems Programming Functions 27

Static Variables /* An Example of a Static Variable */ float nonstat ( float x) { int i = 1; i = 10*i; x = i - 5.0*x; return x; } float stat (float y) { static int i = 1; i = 10*i; y = i - 5.0*y; return y; } Systems Programming Functions 28

Static Variables $./static int main() var1 = 2.00, var2 = 2.00 { var1 = 0.00, var2 = 0.00 int i; var1 = 10.00, var2 = 100.00 float var1, var2; var2 = var1 = 2.0; var1 = -40.00, var2 = 500.00 printf(" var1 = %9.2f, var2 = %9.2f\n", var1, var2); } for ( i = 1; i <= 3; i++) { var1 = nonstat(var1); var2 = stat(var2); printf(" var1 = %9.2f, var2 = %9.2f\n", var1, var2); } return 0; Systems Programming Functions 29

Review of Functions The important concepts introduced in this Powerpoint session are: Functions Libraries Header Files Call by Value Call by Reference Scope (global and local) Static Variables Systems Programming Functions 30