Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions.

Slides:



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

Spring Semester 2013 Lecture 5
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
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.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
CS 201 Functions Debzani Deb.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Algorithms. Introduction Before writing a program: –Have a thorough understanding of the problem –Carefully plan an approach for solving it While writing.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Introduction to Computer Algorithmics and Programming Ceng 113 Variables and Operators in C.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Ceng-112 Data Structures I Chapter 6 Recursion.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
© 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.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Variable Scope Storage Class Recursion
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
CPS120: Introduction to Computer Science Decision Making in Programs.
 Building blocks of a C++ program  Each function has a name, which is used to call the function; functions call each other  You will write your own.
UniMAP SemI-09/10EKT120: Computer Programming1 Week 5 – Functions (1)
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Pointers *, &, array similarities, functions, sizeof.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
1 ICS103 Programming in C Lecture 8: Functions I.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
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 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Computer Programming for Engineers
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
A First Book of ANSI C Fourth Edition
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.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
User-Written Functions
Chapter 7: User-Defined Functions II
Lecture 7: Repeating a Known Number of Times
Functions and Structured Programming
Programmazione I a.a. 2017/2018.
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Arrays, For loop While loop Do while loop
Structured Program
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Chapter 7: User-Defined Functions II
1-6 Midterm Review.
ECE 103 Engineering Programming Chapter 18 Iteration
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
Presentation transcript:

Introduction to Computer Algorithmics and Programming Ceng 113 Functions and Recursive Functions

Functions The general form of a function is; type_specifier function_name(parameter list) { body of the function } The type_specifier specifies the type of value that the return statement of the function returns. If no type is specified, the compiler assumes that the function returns an integer result.

Functions type_specifier function_name(type var_name1,..., type var_nameN) { body of the function } The parameter list is a comma sperated list of variable names and types that receive the values of the arguments when the function called.

Scope Rules of Functions 1.Each function is discrete block of code (for instance, you cannot use goto to jump into middle of another function). 2.Variables that are defined within a function are called local variables. Local variables cannot hold their value between function calls. The only exception to this rule is when the variable is declared with static storage class specifier. 3.You cannot define a function within a function. 4.If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. They behave like other local variables.

Example /* return 1 if c is part of string s; 0 otherwise */ is_in(char *s, char c) { while(*s) if (*s==c) return 1; else s++; return 0; }

call by value / call by reference Subroutines can be passed arguments in one of two ways; 1.Call by value; This method copies the value of an argument into the formal parameter of the subroutine. 2.Call by reference; In this method, the address is used to access the actual argument used in the call. #include int sqr(int x); void main(void) { int t=10; printf(“%d %d”, sqr(t), t); } sqr(int x) { x= x*x; return x; } #include void swap(int *a, int *b); void main(void) { int x, y; x=10; y = 20; swap(&x, &y); } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; }

Calling Functions with Arrays In C, an array name without any index is a pointer to the first element in the array. There are three ways to declare a parameter to receive an array pointer: 1.It may be declare as an array; #include void main(void) { int t[10], i; for(i=0; i<10; ++i) t[i]=i; display(t); } void display(int num[10]) { int i; for(i=0; i<10;i++) printf(“%d”, num[i]); } 2. It may be declare as an unsized array; #include void main(void) { int t[10], i; for(i=0; i<10; ++i) t[i]=i; display(t); } void display(int num[ ]) { int i; for(i=0; i<10;i++) printf(“%d”, num[i]); } 3. It may be declare as a pointer of array; #include void main(void) { int t[10], i; for(i=0; i<10; ++i) t[i]=i; display(t); } void display(int *num) { int i; for(i=0; i<10;i++) printf(“%d”, num[i]); }

Example #include void print_upper(char *string); void main(void) { char s[80]; gets(s); print_upper(s); } /*print a string in uppercase. */ void print_upper(char string[ ]) { int t; for(t=0; string[t]; ++t) { string[t] = toupper(string[t]); putchar(string[t]); } printf("\n"); }

argc and argv – Arguments to main( ) Generally, we pass information into main() function via command line arguments. argc; holds the number of arguments on the command line. argv; is a pointer to an array of character pointers. #include void main(int argc, char *argv[ ]) { if(argc != 2) { printf("you forgot to type your name \n"); exit(1); } printf("Hello %s\n ", argv[1]); printf("Program name is %s\n", argv[0]); printf("The count of the input word %d \n", argc); }

#include void main(int argc, char *argv[ ]) { int disp, count; if (argc < 2 ){ printf("You must enter the length of the count \n"); printf("on the commant line. Try again. \n"); exit(1); } if (argc == 3 && !strcmp(argv[2], "display")) disp = 1; else disp = 0; for(count=atoi(argv[1]); count; - - count) if (disp) printf("%d \n", count); printf("done \n"); }

The return Statement The return statement has two important usage; 1.It couses an immediate exit from the function and the program execution pass to the calling code. 2.It may be used to return a value to the calling procedure.

/* Return index of first match of s2 in s1. */ find_substr(char *s1, char *s2) { int t; char *p, *p2; for (t=0; s1[t]; t++) { p= &s1[t]; p2=s2; while(*p2 && *p2==*p) { p++; p2++; } if (!*p2) return t; } return -1; }

Returning The Values All functions, except those of type void, return a value. This value is specified by the return statement. The functions can be three types; –Simply computational; these functions are specifically designed to perform operations on their arguments and return a value based on that operation. ( Exmp: sqrt( ) or sin( ) ). –The second type of functions; manipulates information and returns a value that simply indicates the success or failure of that manipultion. (Examp: fclose( )..). –The last typeof function has no explicit return value. (Examp: exit( ) ).

#include int mul(int a, int b); void main(void) {int x, y, z; x=10; y=20; z=mul(x,y); /* return value assign to z. */ printf("%d \n", mul(x,y)); /* return value is used by the printf( ) function. */ mul(x,y); /* return value is lost. */ } mul(int a, int b) { return a*b; }

Function Prototype When you use prototypes, C can find and report any illegal type convertions between the type of arguments used to call a function and the type definition of its parameters. The general form of a function prototype definition is; type func_name(type parm_name1,..., type parm_nameN); #include void sqr_it(int i); /* prototype */ void main(void) {int x; x=10; sqr_it(x); /* ?? */ printf("%d \n", x); } void sqr_it(int *i) { *i = *i * *i; }

Return Non-integer Values When the type of function is not declared, it automatically defaults to integer. For the non-integer values; the function must be given an explicit type specifier and type of function must be identified before the first call made to it. #include float sum(); /* identify the function */ void main(void) {float first, second ; first = ; second = 99.09; printf("%f \n", sum(first, second)); } float sum(float f, float s) { return (f + s); }

Returning Pointers #include char *match(char c, char *s); /* prototype */ void main(void) {char s[80], *p, ch; gets(s); ch = getchar(); p=match(ch, s); if(*p) /* there is a match */ printf("%s \n", p); else printf("no match found \n"); } char *match(char c, char *s) {while(c != *s && *s) s++; return s; }

Lab. Exercise #1 Write a program to find the number of times that a given word (i.e. a short string) occurs in a sentence (i.e. a long string!). Read data from standard input. The first line is a single word, which is followed by general text on the second line. Typical output should be: The word is "the". The sentence is "the cat sat on the mat". The word occurs 2 times.

Recursion There are two approaches to writing repititive algorithms: 1.Iteration 2.Recursion; is a repititive process in which an algorithm call itself. Definition: The recursive solution for a problem involves a two-way journey: 1. Decompose the problem from the top to the bottom. 2. Solve the problem from the bottom to the top.

Recursive Functions The general form of a function is; void recurse() { recurse(); //Function calls itself } int main() { recurse(); //Sets off the recursion return 0; //Rather pitiful, it will never be reached } Recursion is defined as a function calling itself. It is in some ways similar to a loop because it repeats the same code, but it requires passing in the looping variable and being more careful.

Recursive Functions Recursive program will not continue forever. The computer keeps function calls on a stack and once too many are called without ending, the program will terminate. Let write a program to see how many times the function is called before the program terminates? #include void recurse(int count) /*The count variable is initalized by each function call */ { printf(“%d”, count); recurse(count+1); /* It is not necessary to increment count each */ /* function's variables */ } /*are separate (so each count will be initialized one greater) */ int main() { recurse(1); /*First function call, so it starts at one return 0; */ }

Recursive Functions Recursive functions can be thought of like the Russian dolls that always have a smaller doll inside. Each doll calls another doll, and we can think of the size being a counter variable that is being decremented by one. Think of a really tiny doll, the size of a few atoms. We can't get any smaller than that, so there are no more dolls. Normally, a recursive function will have a variable that performs a similar action; one that controls when the function will finally exit. The condition where the function will not call itself is termed the base case of the function. Basically, it is an if-statement that checks some variable for a condition (such as a number being less than zero, or greater than some other number) and if that condition is true, it will not allow the function to call itself again. (Or, it could check if a certain condition is true and only then allow the function to call itself).

Example void doll(int size) { if(size==0) /* No doll can be smaller than 1 atom (10^0==1) so doesn't call /* itself return; /* Return does not have to return something, it can be used /* to exit a function doll(size-1); /* Decrements the size variable so the next doll will be smaller. } int main() { doll(10); /*Starts off with a large doll (its a logarithmic scale) return 0; /*Finally, it will be used }

Sample Algorithm /*The power algorithm */ program TestPower 1. read base, exp 2. result = power(base, exp) 3. print result end TestPower algorithm Power(base, exp) 1.num=1 2.loop(exp > 0) 1.num=num*base 2.exp=exp-1 3.return num

Sample Algorithm /*The recursive power algorithm */ program Power(int base, int exp) Pre base is the number to be raised exp is the exponent Post value of base **exp computed Return value of base**exp returned if (exp equal 0) return(1) else return (base*power(base, exp-1)) endpower Power(5,2) Power(5,1) Power(5,2) Power(5,1) Power(5,0) base=5 exp=2 return 1 return 5 return 25

Recursive Functions Once a function has called itself, it will be ready to go to the next line after the call. It can still perform operations. One function we could print out the numbers How can we use recursion to write a function to do this? Simply have it keep incrementing a variable passed in, and then output the variable...twice, once before the function recurses, and once after...

Example void printnum(int begin) { printf(“%d”, begin); if(begin<9) /*The base case is when begin is greater than 9 printnum(begin+1); /*for it will not recurse after the if-statement printf(“%d”, begin); /*Outputs the second begin, after the program has /*gone through and output } /*the numbers from begin to 9. void main( ) { printnum(1); } The output is;

Lab. Exercise #2 Use recursion to write a program that returns the factorial of any number greater than 0. Factorial is number*(number-1)*(number-2)...*(1)

Homework Write a C code to tell the user whether a number is polindrome. (A polindrome is a number that is the same written both forward and backward, such as 81318). Create two solutions: 1. use recursion function structure and call by reference technique, and 2. use not recursion function structure and call by value technique. Upload to FTP until December 21th at 17:00

Next Course Structures, Unions, Enumarations and User-Defined Types...