Programming Functions.

Slides:



Advertisements
Similar presentations
Maths & Trig, Statistical functions. ABS Returns the absolute value of a number The absolute value of a number is the number without its sign Syntax ◦
Advertisements

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.
1 ICS103 Programming in C Lecture 13: Arrays II. 2 Outline Review on One-dimensional Arrays Using array elements as function arguments  Examples Using.
1 Gentle Introduction to Programming Session 4: Arrays, Sorting, Efficiency.
11.3 Function Prototypes A Function Prototype contains the function’s return type, name and parameter list Writing the function prototype is “declaring”
TK1913-C Programming1 TK1913-C Programming 1 C Library Functions C provides a collection of library functions for programmers If these library functions.
1 Gentle Introduction to Programming Session 3: Higher Order Functions, Recursion.
1 Gentle Introduction to Programming Session 3: Recursion.
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
1 Gentle Introduction to Programming Session 2: Functions.
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Programming Arrays. Example 1 Write a program that reads 3 numbers from the user and print them in reverse order. How many variables do we need to store.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
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 *=
Lecture 15: Control Flow (cont). 2 Lecture Contents: t Design and implementation of programs illustrating linear algorithms, branch algorithms and loop.
1 C Programming Week 2 Variables, flow control and the Debugger.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
Functions What is a function –“sub” program, with an isolated set of statements –Accepts parameters, returns a result (perhaps) –Think of it as its own.
1 Today: Functions. 2 Some General Tips on Programming Write your code modularly Compile + test functionality in the process.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
C Programming.
Function – I What is a function Why we need functions?
UMBC CMSC 104 – Section 01, Fall 2016
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
C++ Laboratory Instructor: Andrey Dolgin
Topic 6 Recursion.
Zhang Hongyi CSCI2100B Data Structures Tutorial 3
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Functions, Part 2 of 2 Topics Functions That Return a Value
Pointers Department of Computer Science-BGU יום שלישי 31 יולי 2018.
Functions Department of Computer Science-BGU יום רביעי 12 ספטמבר 2018.
INC 161 , CPE 100 Computer Programming
Functions.
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
מבוא כללי למדעי המחשב תרגול 2
Formatted and Unformatted Input/Output Functions
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Control Structures Lecture 7.
Looping.
FOR LOOPS.
Programming application CC213
While Loop Design ENGI 1020 Fall 2018.
בקרת קלט #include int main () { int num; printf("Enter number(0-100)\n"); if (scanf("%d",&num) != 1) printf(“Input Error\n”); return 1; } printf("Very.
ICS103 Programming in C Lecture 13: Arrays II
Functions Recursion CSCI 230
Functions, Part 2 of 3 Topics Functions That Return a Value
A function with one argument
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Incremental operators
Week 2 Variables, flow control and the Debugger
Extra Practice for Recursion
Introduction to Problem Solving and Programming
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
Recursion.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
ICS103 Programming in C Lecture 11: Recursive Functions
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 42 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
Presentation transcript:

Programming Functions

Example: Factorial #include <stdio.h> int factorial(int n) { int i, fact = 1; for (i=2; i<=n; i++) fact *= i; return fact; } int main() { int num, res; printf("enter a number\n"); scanf("%d",&num); res = factorial(num); printf("%d!=%d\n",num, res); return 0; }

Exercise: Fibonacci (@class) Input: An integer n Output: The n’th fibonacci number Note – Use an appropriately defined function

Reminder – Fibonacci series 0 1 1 2 3 5 8 13 21 34 … 0 1 1 0 1 1 2 3 5 8 13 21 34 0 1 1 2 0 1 0 1 1 2 3 5 8 13 21 + + +

Reminder – Fibonacci series int fib1 = 0, fib2 = 1, fib_next = 0, ... // create next element fib_next = fib1 + fib2; fib1 = fib2; fib2 = fib_next;

Solution fibonacci_func.c

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 <stdio.h> int main() { 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", n, d, n/gcd, d/gcd); return 0; }

Example – solution (step II) #include <stdio.h> int main() { 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", 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. */ int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; }

GCD – step by step int main() { int n, d, g; printf("Please enter … : "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form of %d/%d is %d/%d\n", n, d, n/g, d/g); return 0; } n d g 6 9 ---

GCD – step by step int main() { int n, d, g; printf("Please enter … : "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form of %d/%d is %d/%d\n", n, d, n/g, d/g); return 0; } n d g 6 9 ---

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 ---

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 6

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 6

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 5

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 5

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 4

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 4

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 3

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 3

GCD – step by step int gcd(int x, int y) { int i; for (i=x; i>0; i--) if (x%i == 0 && y%i ==0) return i; } x y i 6 9 3

GCD – step by step int main() { int n, d, g; printf("Please enter … : "); scanf("%d%d", &n, &d); g = gcd(n, d); printf("The reduced form %d/%d is %d/%d\n", n, d, n/g, d/g); return 0; } n d g 6 9 3

Example Newton was the first to notice that for any positive n, and when x0=1, the following series converges to : Use this fact to write a program that accepts a positive number and outputs its square root. Hint: The 1000th element of Newton’s series is a good-enough approximation.

sqrt - solution /* This program uses the Newton method to calculate a number's square root */ #include <stdio.h> double sqrt(double num) { int i; double result = 1; for (i=0; i<1000; i++) result = (result + num/result)/2; return result;

sqrt – solution cont. int main () { double num; printf("Please enter positive number: "); scanf("%lf", &num); if (num < 0) { printf(“No square root for a negative number!\n"); return 1; } printf("The square root of %g is %g\n", num, sqrt(num)); return 0;

Pass-By-Value: Example int add_one(int b) { b=b+1; return b; } int main() int a=34, b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0;

add_one – step by step int add_one(int b) Main() memory state { b=b+1; return b; } int main() int a=34, b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; Main() memory state a b 34 1

add_one – step by step int add_one(int b) Main() memory state { b=b+1; return b; } int main() int a=34, b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; Main() memory state a b 34 1

add_one – step by step int add_one(int b) Main() memory state { b=b+1; return b; } int main() int a=34,b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; Main() memory state a b 34 1 add_one memory state b 1

add_one – step by step int add_one(int b) Main() memory state { b=b+1; return b; } int main() int a=34, b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; Main() memory state a b 34 1 add_one memory state b 2

add_one – step by step int add_one(int b) Main() memory state { b=b+1; return b; } int main() int a=34, b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; Main() memory state a b 34 1 add_one memory state b 2

add_one – step by step int add_one(int b) Main() memory state { b=b+1; return b; } int main() int a=34, b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; Main() memory state a b 2 1

add_one – step by step int add_one(int b) Main() memory state { b=b+1; return b; } int main() int a=34, b=1; a=add_one(b); printf("a = %d, b = %d\n", a, b); return 0; Main() memory state a b 2 1

Example: Error in Scope int add_one(int b) { a=b+1; return a; } int main() int a=34, b=1; add_one(b); printf("a = %d, b = %d\n", a, b); return 0;

Example Write a function that approximates  using the formula : where n goes to infinity. The function accepts an argument n which determines the number of terms in the formula, and returns the approximation of . Write a program that gets an integer n from the user, and approximates  using n terms of the above formula.

pi - solution #include <math.h> /* Returns an approximation of pi using num terms */ double pi(int num) { int i; double result = 0.0; for (i = 1; i <= num; i++) result += 1.0 / (i * i); return sqrt(6*result); {

pi – solution cont. /*This program approximates pi*/ #include <stdio.h> int main() { int num; printf("enter number of terms\n"); scanf("%d",&num); printf("The calculated approximation of pi is: %g\n",pi(num)); return 0; {

Example Modify the previous function - now the function accepts an argument specifying the desired accuracy. It keeps adding terms until the contribution of the next term drops below this level. Write a program that gets a (small) double, epsilon, from the user and approximates  within this function.

pi (advanced )- solution #include <math.h> double pi(double epsilon) { double n=1, result = 0, term = 1; while(sqrt(term*6) >= epsilon) { result += term; n=n+1; term = 1.0/(n*n); } return sqrt(result*6); {

pi (advanced )- solution cont. /*This program approximates pi*/ #include <stdio.h> int main() { double epsilon; printf("enter approximation factor\n"); scanf("%lf",&epsilon); printf("The calculated approximation of pi is: %g\n",pi(epsilon)); return 0; }

Solution to class exercise #include <stdio.h> int fibonacci(int limit){ int fib1 = 0, fib2 = 1, fib_next = 0, counter; for(counter =1 ; counter < limit; counter++){ fib_next = fib1 + fib2; fib1 = fib2; fib2 = fib_next; { return fib1;} int main(){ int num, res; printf("enter an elemenet number\n"); scanf("%d",&num); res = fibonacci(num); printf("The %d elemenet in Fibonacci series is %d\n",num, res); return 0; {