Functions in C.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

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.
Recursion (II) H&K Chapter 10 Instructor – Gokcen Cilingir Cpt S 121 (July 25, 2011) Washington State University.
 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.
 2007 Pearson Education, Inc. All rights reserved C Functions.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
Procedural programming in Java Methods, parameters and return values.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Methods We write methods in our programs for many reasons:
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "___________________" in Java Purpose –Reuse code –Modularize.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
C++ Programming Lecture 12 Functions – Part IV
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Function – I What is a function Why we need functions?
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
Data Type and Function Prepared for CSB210 Pemrograman Berorientasi Objek By Indriani Noor Hapsari, ST, MT Source: study.
5.13 Recursion Recursive functions Functions that call themselves
IS Program Design and Software Tools Introduction to C++ Programming
RECURSION.
Lecture 7: Repeating a Known Number of Times
Methods Chapter 6.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Programming Fundamentals Lecture #7 Functions
Programming Fundamentals Lecture #7 Functions
Deitel- C:How to Program (5ed)
CS1061 C Prgramming Lecture 11: Functions
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
Formatted and Unformatted Input/Output Functions
C-Programming, continued
Chapter 5 - Functions Outline 5.1 Introduction
Arrays, For loop While loop Do while loop
Chapter 6 - Functions Outline 5.1 Introduction
Functions Recursion CSCI 230
Defining methods and more arrays
Functions with arrays.
Function.
1-6 Midterm Review.
Recursive Algorithms 1 Building a Ruler: drawRuler()
Functions Reasons Concepts Passing arguments to a function
Function.
Presentation transcript:

Functions in C

Modularity in Car Each component in car is independently manufactured and tested Can be fitted to any car

Used in Every Day Life When a marriage is organized Catering, decoration, music, seating arrangements, travel, boarding are modules Each one is done independently Rice + Dhal -> Idli Can be separated to two modules Preparing wet flour Wet flour to Idlis

Tic Tac Toe - State of Board Problems Given the board configuration of the tic tac toe game, determine if the board is in either of the following states: empty, player1 wins, player2 wins, draw or intermediate. The board is said to be in initial state if all the cells contain ‘-1’, player1 uses ‘1’ as his coin and player2 uses ‘2’ as his coin. The game is draw when the board is full and no one has won the game. The game is in intermediate state when no one has won and board is not full

Drawbacks of Previous Code Previous code was 65 lines long Difficult to understand and determine error Better if it can be done through smaller modules Part of code can be reused

Modules Tic Tac Toe - State of Board Problems Read state of board Count number of empty cells Check if same coin is in a row Check if same coin is in a column Check if same coin is placed diagonally

Modules in Isogram Problem Module to find factorial of a number

Modules in Accident Problem Module to read values Module to find mean of values Module to find difference between values and mean Print the values

Modules in Accident Problem Module to read values Module to find mean of values Module to find difference between values and mean Print the values

Functions in C Modularity is supported in C by functions All variables declared inside functions are local variables Known only in function defined Parameters Communicate information between functions Local variables

Syntax for Function Declaration ftype fname (void); void draw_circle(void); Declarations and statements: function body (block) Functions can not be defined inside other functions

Syntax for Function Definition function header { statements } Syntax of function header return_type function_Name(parameter_List)

Passing Arguments Call by value Call by reference Copy of argument passed to function Changes in function do not effect original Use when function does not need to modify argument Avoids accidental changes Call by reference Passes original argument Changes in function effect original Only used with trusted functions

Return Statement return; return expression; Unlike Python C can return only value

Pass by Value

Pass by Address or Reference Address of variable is passed Pointer variables are used in function declaration and definition Address of variable is got by prefixing variable name with an ‘&’ Pointer variables are declared with a ‘*’ in front An integer pointer variable is declared as int* a; Value of an address is got by using ‘*’ operator

Isogram Problem with Functions

Default Passing Mechanisms Primitive data types such as int, float, long, double, char are passed by value – so changes do not reflect in calling function Arrays are passed by address – so changes reflect in calling function

Pass a Single Dimensional Array as Argument Passed by reference or address by default Changes made in function gets reflected in main() Three ways to pass arrays in C all are same Way1 Way2 Way3 void myFunction(int *a) { . . . } void myFunction(int a[10]) void myFunction(int a[]ls )

Passing 2D Array to Functions #include <stdio.h> const int n = 3; void print(int arr[3][3], int m) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", arr[i][j]); } int main() int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr, 3); return 0;

Second Dimension is Optional #include <stdio.h> const int n = 3; void print(int arr[][n], int m) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", arr[i][j]); } int main() int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; print(arr, 3); return 0;

As a Single Dimensional Array #include <stdio.h> void print(int *arr, int m, int n) { int i, j; for (i = 0; i < m; i++) for (j = 0; j < n; j++) printf("%d ", *((arr+i*n) + j)); } int main() int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int m = 3, n = 3; print((int *)arr, m, n); return 0;

Recursion Recursive functions Functions that call themselves Can only solve a base case

Consider a Big Classroom

Recursion in Real Life John is seated in the last row of a very big classroom. Mike is sitting in last but one row of the same classroom. John wants to know how many rows are there in the classroom. John: Hi Mike! Can you please say me in which row you are seated? Mike: Yes… Of course John. Mike ask the same question to Patil who is seated in front of him and so on… till Alice who is seated first row is asked the question  Alice: Alice can answer as one to Jack who is seated in the second row  This is the base case  Jack adds 1 to Alice's answer and tells it to Jill who is in the third row and so on… until the answer reaches John

Factorial using Recursion

Fibonacci series 0, 1, 1, 2, 3, 5, 8... int fibonacci( int n ) { if (n == 0 || n == 1) // base case return n; else return fibonacci( n - 1) + fibonacci( n – 2 ); }

Recursion vs. Iteration Repetition Iteration: explicit loop Recursion: repeated function calls Termination Iteration: loop condition fails Recursion: base case recognized Both can have infinite loops Balance Choice between performance (iteration) and good software engineering (recursion)

In Lab Practice Problems Find length of a string using recursion Recursive function to find sum of successive integers starting at 1 and ending at n (i.e., find_sum(n) = (1 + 2 + . . . + ( n − 1) + n ) Write function to perform set operations like union, difference, intersection and so on

In Lab Practice Problems A palindrome consists of a word or deblanked, unpunctuated phrase that is spelled exactly the same when the letters are reversed. Write a recursive function that returns a value of 1 if its string argument is a palindrome. Notice that the words level, deed, sees, and Madam I’m Adam (madamimadam) are palindromes