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.

Slides:



Advertisements
Similar presentations
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
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.
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
CS 201 Functions Debzani Deb.
Chapter 6: User-Defined Functions I
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
TK1913-C Programming1 TK1913-C Programming 1 C Library Functions C provides a collection of library functions for programmers If these library functions.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
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.
Chapter 6: User-Defined Functions I
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Introduction to C Programming
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
Programming Variables. Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They.
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Incremental operators Used as a short-hand i++ or ++i  ==  i = i + 1 i-- or --i  ==  i = i – 1 i += a  ==  i = i + a i -= a  ==  i = i - a i *=
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
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 C Programming Week 2 Variables, flow control and the Debugger.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Lecture 13: Working with Multiple Programmers. Headers Header files: Each standard library has a corresponding header. The function prototype for all.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
1 Programming a Computer Lecture Ten. 2 Outline  A quick introduction to the programming language C  Introduction to software packages: Matlab for numerical.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
1 ICS103 Programming in C Lecture 8: Functions I.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Programming Fundamentals Enumerations and Functions.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
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.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Simple C Programs.
Arithmetic Expressions
C++ Laboratory Instructor: Andrey Dolgin
Chapter 6: User-Defined Functions I
Functions Department of Computer Science-BGU יום רביעי 12 ספטמבר 2018.
User-Defined Functions
Formatted and Unformatted Input/Output Functions
Chapter 2 - Introduction to C Programming
Week 2 Variables, flow control and the Debugger
Chapter 6: User-Defined Functions I
In C Programming Language
Introduction to Problem Solving and Programming
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
CPS125.
Functions that return a value
Presentation transcript:

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 write our program we always define a function named main  inside main we can call other functions which can themselves call other functions, and so on…

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

Why Use Functions? Break the problem into smaller sub-problems  easier to solve complex problems Generalize a repeated set of instructions  we don’t have to keep writing the same thing over and over  printf and scanf are good examples… They make a program much easier to read and maintain

So Far Used  printf  scanf  putchar  getchar Wrote  main

Function Definition return-type name(parameter-list) { local-variables statements return statement } return-type: int, double, char, void,... parameter-list: type name, type name,..., type name Function variables = parameters + locals prototype

Return Statement Return causes the execution of the function to terminate and 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)

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

Void Calling ‘ return ’ at the end of a function returning void is not obligatory If the function receives no parameters, the parameter list should be replaced by ‘ void ’ (or just nothing)

Exercise Write the function int add(int a, int b); The function takes two numbers as its input and returns their sum Write a program that accepts as input two numbers from the user and adds them using the above function (a main function that calls the add function)

Solution int add(int a, int b) { return a + b; } int main(void) { int a,b; printf("Please enter two numbers\n"); scanf("%d%d", &a, &b); printf ("%d + %d = %d\n", a, b, add(a, b)); return 0; }

Remark int add(int a, int b) { int res; res = a + b; return res; } a + b;

Scope A function defines the scope for a variable A variable declared in a function is only visible within that function

Scope.c int do_something(void) { int a; printf("Entered do_something\n"); a = 7; printf("In do_something, a = %d\n", a); printf("Exiting do_something\n"); return a; } int main(void) { int res = 0, a = 34; printf("Entered main\n"); printf("In main, a = %d\n", a); res = do_something(); printf("do_something returned %d\n", res); printf("In main, a = %d\n", a); printf("Exiting main...\n"); return 0; }

Frames A frame is a structure containing function information at runtime A frame corresponds to a function call  new call → new frame

At Runtime double power(double base, int exponent) { int i = 0; double result = 1; for (i = 1; i <= exponent; i++) result = result * base; return result; } int main() { double result = power(2,20) + power(3,15) + power(5,17); printf("2^20 + 3^15 + 5^17= %g", result); return 0; } source codecall stack result main base exponent result i power = 2 = 20 = 3 = 15 = 5 = 17

Another Example main foo printf bar main foo printf bar printf

Call by Value Function arguments are passed 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

Call by Value - Example void multBy5(int b) { b *= 5; } int main(void) { int a = 34, b = 1; multBy5(b); printf("a = %d, b = %d\n", a, b); return 0; } a = 34, b = 1

The Right Way int multBy5(int b) { return b *= 5; } int main(void) { int a = 34, b = 1; b = multBy5(b); printf("a = %d, b = %d\n", a, b); return 0; } a = 34, b = 5

Exercise “Twin Primes” is a pair of prime numbers whose difference is 2. e.g. (3, 5), (11, 13) Write a program that receives as input a number from the user and outputs all the twins up to (and including) that number. For example: Input: 8 Output: (3, 5) (5, 7)

Hands Off The Keyboard!!!

How To Approach The problem? Make sure you understand the problem Outline the most simple algorithm for solution What are the subtasks of the solution? – each subtask will be a separate function.

Bad Idea #1 for all pairs (i,j) smaller-equal N if twin_primes(i, j) print (i, j)

Why Bad? Consider the implementation – Is it simple? – Is it efficient? – Do we really need to go over all pairs? – Do we need to check the pairness of each number twice?

Take 2 for all i ≤ N - 2 if (i, i + 2) are primes print (i, i + 2) What about this Solution?

Candidate Functions Identify reoccurring tasks in your solution  good candidates to become functions. Are there any in the proposed solution?

Prime Identification is_prime(n): for 2 <= i < n if i factor of n return false return true

Function Implementation Implement your functions. Try to abstract away from the task at hand. – What is the purpose of the function? – What information it needs to achieve its goal (input arguments) – What is the return value? Implement a function(s) that binds the basic blocks into a complete, specific algorithm. (usually main) – When do we need to use and which function? – What do we need to pass in as arguments? – Where do we store return values?

GO

Debugger - Reminder F9 – set breakpoint F5 – run in debug mode F10 – step over (execute a single command)  treat functions as single command F11 – step into (for stepping into functions)

Twin Primes Solution We’ll use the debugger to go over the solution

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

Function Declaration For this reason, the function must be declared in every file in which it’s used, before it is used for the first time the declaration contains (prototype) : return_type Function_name(argument-list);

Function Declaration #include /* Contains Standard IO functions declaration! */ int factorial(int a); /* Our Function Declaration! */ int main(void){ int num = 0; printf("enter a number\n"); scanf("%d", &num); printf("%d != %d\n", num, factorial(num)); return 0; } int factorial(int a){ int i, b = 1; for(i = 1; I <= a; i++) b = b*i; return b; }

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

/*** *stdio.h - definitions/declarations for standard I/O routines * * Copyright (c) Microsoft Corporation. All rights reserved. * ****/... /* Function prototypes */ _CRTIMP int __cdecl getc(FILE *); _CRTIMP int __cdecl getchar(void); _CRTIMP int __cdecl _getmaxstdio(void); _CRTIMP char * __cdecl gets(char *); _CRTIMP int __cdecl _getw(FILE *); _CRTIMP void __cdecl perror(const char *); _CRTIMP int __cdecl _pclose(FILE *); _CRTIMP FILE * __cdecl _popen(const char *, const char *); _CRTIMP int __cdecl printf(const char *,...); _CRTIMP int __cdecl putc(int, FILE *); _CRTIMP int __cdecl putchar(int); _CRTIMP int __cdecl puts(const char *); _CRTIMP int __cdecl _putw(int, FILE *); _CRTIMP int __cdecl remove(const char *); _CRTIMP int __cdecl rename(const char *, const char *); _CRTIMP void __cdecl rewind(FILE *); _CRTIMP int __cdecl _rmtmp(void); _CRTIMP int __cdecl scanf(const char *,...); _CRTIMP void __cdecl setbuf(FILE *, char *); _CRTIMP int __cdecl _setmaxstdio(int);...

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) – x to the power of y. ceil(x), floor(x) …and more

Exercise 1.Implement the following functions:  int is_digit(char c); - returns true if the character is a digit, false otherwise.  int is_lower(char c); - returns true if it’s a lowercase character, false otherwise.  int is_upper(char c); - returns true if it’s an uppercase character, false otherwise. 2.Implement a function int what_is_it(char c); The function takes a single character as input and return:  0 – if it’s a digit  1 – if it’s a lowercase letter  2 – if it’s an uppercase letter  -1 – otherwise 3.Write a program that reads characters from the user (until '\n') and converts lowercase letter to uppercase, uppercase to lowercase and digits into spaces. All other characters should be ignored. NOTE: You can define more functions if you find it necessary