Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.

Slides:



Advertisements
Similar presentations
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #3 Control.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
/* program to find area of a ring */ #include int main() { float a1,a2,a,r1,r2; printf("Enter the radius : "); scanf("%f",&r1); a1 = 3.14*r1*r1; printf("Enter.
1 CS 161 Introduction to Programming and Problem Solving Chapter 9 C++ Program Components Herbert G. Mayer, PSU Status 10/20/2014.
Chapter 6: User-Defined Functions I
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
0 Chap. 4 Functions and Program Structure 4.1 Basics of Functions 4.2 Functions Returning Non-integers 4.3 External Variables 4.4 Scope Rules 4.5 Header.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
Chapter 6: User-Defined Functions I
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
C++ for Engineers and Scientists Third Edition
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Chapter 4 Functions and Program Structure Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Runtime Environments Compiler Construction Chapter 7.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
1 Homework / Exam Finish up K&R Chapters 3 & 4 Starting K&R Chapter 5 Next Class HW4 due next class Go over HW3 solutions.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
CPS120: Introduction to Computer Science Functions.
Engineering Computing I Chapter 4 Functions and Program Structure.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Chapter 12: Programming in the Large By: Suraya Alias 1-1.
Chapter 3: User-Defined Functions I
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Functions Dilshad M. Shahid New York
2Object-Oriented Program Development Using C++ 3 Function Declarations and Definitions Analogize functions to methods –Share same basic features –Unlike.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Objectives: How to define and call functions. Function declarations and how they differ from function definitions. How arguments are passed to functions.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
Functions and Program Structure CSE 2031 Fall June 2016.
Unit 10 Code Reuse. Key Concepts Abstraction Header files Implementation files Storage classes Exit function Conditional compilation Command-line arguments.
What Is? function predefined, programmer-defined
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
C Functions -Continue…-.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Functions and Structured Programming
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Programmazione I a.a. 2017/2018.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
Functions and Program Structure
Register Variables Declaring a variable as a "register" variable is an advisory to the compiler to keep the normal location of the variable in a register,
Functions and Modular Programming
Functions and Program Structure
Function.
Homework Finish up K&R Chapters 3 & 4
Functions and Program Structure
What Is? function predefined, programmer-defined
Function.
Presentation transcript:

Functions and Program Structure Chapter 4

Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of operation from parts of the program that don’t need to know about them  Thus clarifying the whole  And easing the pain of making changes C has been designed to make functions efficient and easy to use C programs generally consist of many small functions rather than a few big ones A program may reside in one or more source files

Basics of Function return-type function-name (argument declarations) { declarations and statements } Various parts may be absent A minimal function is: dummy( ) { } Which does nothing and returns nothing Sometimes useful as a place holder during program development Functions declaration must be used

Basics of Function Contd. A program is just a set of definitions of variables and functions Communication between the functions is by  Arguments  Values returned by the functions, and  Through external variables The functions can occur in any order in the source file

Basics of Function Contd. The source program can be split into multiple files The return statement is the mechanism for returning a value from the called function to its caller return expression;

Basics of Function Contd. The calling function is free to ignore the returned value There need be no expression after return  In that case, no value is returned to the caller  Control also returns to the caller with no value when execution "falls off the end", i.e., “}”

External Variable External variables are globally accessible They provide an alternative to function arguments and return values for communicating between functions If a large number of variables must be shared among functions, external variables are more convenient and efficient than long argument list

External Variable Contd. However, this reasoning should be applied with some caution External variables are also useful because of their greater scope and lifetime Internal variables come into existence when the function is ended If two functions must share some data, yet neither calls the other, it is often most convenient to use external variables rather than passed in and out via arguments

External Variable: Where needed? #define MAXVAL 100 int sp = 0; double val [MAXVAL]; void push (double f){ if (sp < MAXVAL) val [sp++] = f; else printf (“Overflow”); } double pop (){ if (sp > 0) return val [--sp]; else { printf (“Under flow”); return 0.0; }

Scope Rules The source text of the program may be kept in several files The concerns are  Variable declaration Properly declared Only one copy Initialization The scope of a name is that part of the program within which the name can be used

Scope Rules Contd. For local variables For external variables or a function (from that point) If an external variable is to be referred to  before it is defined, or  if it is used in different source file from where it is used  then extern declaration is mandatory  No storage allocation

Extern Declaration There must be only one definition of an external variable among all the files There may also be extern declaration in the file containing definition Array size must be specified with the definition but are optional with an extern declaration Initialization of an external variable goes only with definition

Header Files If certain functions will be pretty common and be useful to many programs a head  Then those functions can be kept in a header file (extension is.h) and put in the library directory  Think about the necessity of the functions defined in stdio.h

Static Variables Unlike automatic variables static variables remain in existence between functions calls Static variables provide private, permanent storage within a single function The static variable is initialized only the first time the block is entered static int i = 0;

Register Variables register int x; A register declaration advises the compiler that the variable will be heavily used Register variables are to be placed in machine registers  Result in faster programs  The index of the innermost loop can be register variable It is not possible to take the address of a register variable It specific restrictions on number and types of register variables vary from machine to machine

Block Structure Variables can be declared in any block “{}” Variables declared in this way hide any identically named variables in outer block An automatic variable declared and initialized in a block is initialized each time the block is entered The static variable is initialized only the first time the block is entered Automatic variables, including formal parameters also hide external variables and functions of the same name

Initialization Automatic and register variables External and static variables Initializing arrays

Recursive Function A function may call itself When a function call itself recursively, each invocation gets a fresh set of all the automatic variables Recursion may provide no saving in storage nor will be faster  Because of stack entry But recursive code is more compact and often much easier to write  Recursion is especially convenient for recursively defined data structures (tree)

Criteria of Recursive Function A terminating condition Recursive definition

Factorial has a recursive definiton int facti(int n){ int i, product = 1; for(i = 2; i <= n; i++) product *= i; return product; } int factr(int n){ if(n == 0) return 1; //terminating condition else //recursive definition return n*factr(n-1); }

Itoa void itoa (int n, char s[ ]){ if ((sign = n) < 0) n = -n; /* make it positive */ i = 0; do{ s [i++] = n % 10; + ‘0’; } while ((n /= 10) > 0); if (sign < 0) s [i++] = ‘-’; s [i] = ‘\0’; reverse (s); } void itoa(int n, char s[]){ static int i; if(n/10){ itoa(n/10,s); //recursive definition s[i++] = n % 10 + '0'; s[i + 1] = 0; } else{ s[i++] = n % 10 + '0'; //terminating return; }

int binsearch(int x, int v[ ], int n){ int low, high, mid; low = 0; high = n -1; while(low <= high){ mid = (low + high)/2; if (x < v[mid]) high = mid – 1; else if(x > v[mid]) low = mid + 1; else return mid; } return -1; } int bsearch(int x, int v[], int low, int high){ static mid; if(low > high) return -1; mid = (low + high)/2; if(x < v[mid]) return bsearch(x, v,low,mid-1); else if(x > v[mid]) return bsearch(x, v, mid + 1, high); else return mid; }

The C Preprocessor The first step in compilation  File inclusion  Macro substitution  Conditional inclusion

File Inclusion #include “filename” #include

Macro Substitution #define name replacement text Normally the replacement text is the rest of the line A long definition can be continued to several lines by placing a \ Array declaration #define ARRAYLIMIT 20 char str[ARRAYLIMIT];

Macro Substitution Contd. #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) x = MAX(p+q, r+s); There is no need to define different MAX for different data types

Macro Substitution Contd. #define MAX(X, Y) ( ( X ) > ( Y ) ? ( X ) : ( Y ) ) x = MAX(p+q, r+s); There is no need to define different MAX for different data types

Macro Substitution Contd. #define MAX(X, Y) ( (X) > (Y) ? (X) : (Y) ) x = MAX(p+q, r+s); There is no need to define different MAX for different data types

Macro Substitution Contd. MAX(i++, j++); //wrong #undef getchar int getchar(){ }

Macro Substitution Contd. # in the replacement text #define DPRINT(EXP) printf(#EXP “ = %g\n”, EXP) DPRINT(x/y); is expanded printf(“x/y” “ = %g\n ”, x/y); The two strings are concatenated like printf(“x/y = %g\n ”, x/y);

Macro Substitution Contd. The ## provides a way to concatenate actual arguments during macro expansion #define CON(FRONT, BACK) FRONT##BACK CON(12, 34)

Conditional Inclusion #if !defined(HDR) #define HDR …..\ …. #endif