Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.

Slides:



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

1 ICS103 Programming in C Lecture 5: Introduction to Functions.
For loops For loops are controlled by a counter variable. for( c =init_value;c
Introduction to C Programming
Functions a group of declarations and statements that is assigned a name effectively, a named statement block usually has a value a sub-program when we.
Chapter 6: User-Defined Functions I
1 Modularity In “C”. 2 What is Modularity?  Modularity, is the heart of the high level, structured languages.  Means breaking down a big problem into.
TK1913-C Programming1 TK1913-C Programming 1 C Library Functions C provides a collection of library functions for programmers If these library functions.
CS 201 Functions Debzani Deb.
Top-Down Design with Functions 4 What do programmer’s (not programs!) use as input to the design of a program? –Documentation Problem definition Requirements.
Programming Functions. A group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a value A sub-program.
Chapter 6: User-Defined Functions I
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
CPS120: Introduction to Computer Science Functions.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
C++ Lecture 2 Friday 11 July Chapter 3, Functions l built-in functions l function prototype, function definition and use l storage class and scope.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.
FUNCTION Dong-Chul Kim BioMeCIS UTA 12/7/
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 : Top Down Design with Functions By Suraya Alias.
1 ICS103 Programming in C Lecture 8: Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Functions Programming Applications. Functions every C program must have a function called main program execution always begins with function main any.
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
C Programming.
C++ Laboratory Instructor: Andrey Dolgin
EKT120: Computer Programming
Chapter 6: User-Defined Functions I
C++.
Programming Functions.
Functions, Part 2 of 2 Topics Functions That Return a Value
Functions Dr. Sajib Datta
Functions Department of Computer Science-BGU יום רביעי 12 ספטמבר 2018.
CSCI 161: Introduction to Programming Function
User-Defined Functions
Functions, Part 2 of 3 Topics Functions That Return a Value
A function with one argument
Chapter 6: User-Defined Functions I
Function.
In C Programming Language
Introduction to Problem Solving and Programming
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
Function.
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Presentation transcript:

Functions

Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program much easier to read and maintain  abstraction – we don’t have to know how a function is implemented to use it (printf, scanf, etc.). Generalize a repeated set of instructions  we don’t have to keep writing the same thing over and over.

Functions A group of declarations and statements that is assigned a name  effectively, a named statement block.  usually return a value A sub-program  when we write our program we always define a function named main  inside main we can call other functions  which can themselves use other functions, and so on…

Example - Square #include double square(double a) { return a*a; } void main() { double num; printf("enter a number\n"); scanf("%lf",&num); printf("square of %g is %g\n",num,square(num)); } This is a function defined outside main Here is where we call the function square

Characteristics of Functions returnType name(argType1 arg_name1, argType2,arg_name2, …) { function body; return value; }

Return Statement Return causes the execution of the function to terminate and usually returns a value to the calling function. The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type). If no value is to be returned, the return-type of the function should be set to ‘void’.

Factorial calculation example int factorial(int n) { int i, fact = 1; for (i=2; i<=n; i++) fact *= i; return fact; } void main() { int num; printf("enter a number\n"); scanf("%d",&num); printf(“The factorial of %d is %d\n",num,factorial(num)); } #include

A Detailed Example Write a program that receives a nominator and a denominator from the user, and displays the reduced form of the number. For example: if the input is 6 and 9, the program should display 2/3.

Example – solution (step I) #include int main(void) { int n, d; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); Calculate n’s and d’s Greatest Common Divisor printf("The reduced form of %d/%d is %d/%d", n, d, n/gcd, d/gcd); return 0; }

Example – solution (step II) #include int main(void) { int n, d, g; printf("Please enter nominator and denominator: "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form of %d/%d is %d/%d", n, d, n/g, d/g); return 0; }

Example – solution (step III) /* Returns the greatest common divisor of its two parameters. Assumes both are positive. The function uses the fact that if r = mod(y, x) then the gcd of y and x equals the gcd of x and r. */ int gcd(int x, int y) { int tmp; while(x > 0) { tmp = x; x = y % x; y = tmp; } return y; }

The Great Void Sometimes there’s no reason for a function to return a value In these cases, the function return type should be ‘void’ If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified. If the function receives no parameters, the parameter list should be replaced by ‘void’.

Pass-by-value Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables A change to the value of an argument in a function body will not change the value of variables in the calling function

Scope of variables The scope of a variable is the boundaries within which it can be used in a program. Normally variables are local in scope - this means they can only be used in the function where they are declared. A variable declared within a function is unrelated to variables declared elsewhere, even if they have the same name Global variables can be declared, which can be used in any function. Global variables are a BAD PRACTICE.

Wrong way to do it int add_one(int b) { a=b+1; } void main() { int a=34,b=1; add_one(b); printf("a = %d, b = %d\n", a, b); return 0; }

Function swap void swap(int x, int y){ int temp; temp = x; x = y; y = temp; } void main() { int a=7,b=8; printf("a = %d, b = %d\n", a, b); swap(a,b); printf("a = %d, b = %d\n", a, b); }

Bad global variable use example This program only prints ONE row of stars Variables here are global #include void printRow(int); int i, size; void main() { printf(“Please enter a size:\n”); scanf(“%d”, &size); for (i = 1; i <= size; i++) printRow(i); } void printRow(int length) { for(i = length; i <= size; i++) printf("*"); printf("\n"); }

Function Declaration Most software projects in C are composed of more than one file. We want to be able to define the function in one file, and to use it in all files. For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time. the declaration contains:  the function name.  the data types of the arguments (their names are optional).  the data type of the return value.

Function Declaration stdio.h actually contains a large set of function declarations The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called

Function Declaration - Prototype #include int factorial(int a); /* Function Declaration! – Prototype */ void main(){ int num; printf("enter a number\n"); scanf("%d",&num); printf("%d!=%d\n",num,factorial(num)); } int factorial(int a){ int i,b=1; for(i=1; i<=a; i++) b=b*i; return b; }

The math library A collection of mathematical functions Need to include the header file math.h (#include ) Use functions of the library, e.g. double s,p; s=sqrt(p); Declared in math.h : double sqrt ( double x );

The math library sin(x), cos(x), tan(x)  x is given in radians asin(x), acos(x), atan(x) log(x) sqrt(x) pow(x,y) – raise x to the yth power. ceil(x), floor(x) …and more

Passing arrays to functions Functions can accept arrays as arguments. Usually the array’s size also needs to be passed (why?). For example - int CalcSum(int arr[], int size); It is not necessary when the size of the array fix in a #define declaration. Within the function, arr is accessed in the usual way.

Passing arrays to functions Arrays can be passed to functions and have their values changed from within the function!  Unlike regular variables This is possible because an array variable is actually an address and the function receive this address.

Two Dimensional Arrays When passing a two-dimensional array to a function, it is necessary to indicate the size of the second dimension in the function header  But this does not mean the array’s size needn’t be passed as well int func(int arr[][4], int a);  Same was true when initializing the array double B[][2] = {{1,2}, {2,3}, {3,4}};