Recursion Enums. Basics of Programming 1. Department of Networked Systems and Services G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A.

Similar documents
Structures, Operators

Programming for Engineers Structures, Unions

High Performance Computing

C Structures, Unions, Bit Manipulations, and Enumerations

Type Definition. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18

Compiling and Running a C Program in Unix

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions

OBJECT ORIENTED PROGRAMMING USING C++

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

typedef int Array[10]; String name; Array ages;

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Tutorial 7. Number Colour Black Brown Red Orange Yellow Green Blue Violet Gray White

9/10/2016. Time for Some Detailed Examples. ECE 120: Introduction to Computing. Let s See How This Loop Works. One Statement/Step at a Time

1.7 Recursion. Department of CSE

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

A Fast Review of C Essentials Part I

CMIS 102 Hands-On Lab

BLM2031 Structured Programming. Zeyneb KURT

Functions. Arash Rafiey. September 26, 2017

recursive algorithms 1

Syntax and Variables

Arrays III and Enumerated Types

CS 61c: Great Ideas in Computer Architecture

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Functions BCA-105. Few Facts About Functions:

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Data Types H&K Chapter 7. Instructor - Andrew S. O Fallon CptS 121 (October 17, 2018) Washington State University

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

AE52/AC52/AT52 C & Data Structures JUNE 2014

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

CS 3410 Ch 7 Recursion

File Handling in C. EECS 2031 Fall October 27, 2014

Practice problems Set 2

DC54 DATA STRUCTURES DEC 2014

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Data Structures And Algorithms

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

520 Principles of Programming Languages. Arithmetic. Variable Declarations. 19: Pascal

COMPUTER APPLICATION

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur

Computer Organization & Systems Exam I Example Questions

CS Programming I: Arrays

Materials covered in this lecture are: A. Completing Ch. 2 Objectives: Example of 6 steps (RCMACT) for solving a problem.

Reduction & Recursion Overview

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Binary Search Tree 1.0. Generated by Doxygen Mon Jun :12:39

IV Unit Second Part STRUCTURES

Fundamental of Programming (C)

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))

CSCI 171 Chapter Outlines

For Solved Question Papers of UGC-NET/GATE/SET/PGCET in Computer Science, visit

CS10001: Programming & Data Structures. Dept. of Computer Science & Engineering

First of all, it is a variable, just like other variables you studied

Instructor training course schedule v3 Confirmed courses due completion by 31 st July 2019

AMCAT Automata Coding Sample Questions And Answers

Recursion, Trees and Tree Traversal. Module CE System Programming & Computer Control Systems

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Lesson 5: Functions and Libraries. EE3490E: Programming S1 2018/2019 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

C: How to Program. Week /Mar/05

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Chapter 5: Recursion

Data Structures and Algorithms (DSA) Course 4. Iulian Năstac

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$

History. used in early Mac development notable systems in Pascal Skype TeX embedded systems

RECURSION. Many Slides from Ken Birman, Cornell University

C: How to Program. Week /Apr/16

EEE145 Computer Programming

Procedures, Parameters, Values and Variables. Steven R. Bagley

cs109: Programming Paradigms C++ FS 2014

Scheme as implemented by Racket

Chapter 2 - Introduction to C Programming

MODULE 3: Arrays, Functions and Strings

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

CS 310 Advanced Data Structures and Algorithms

CS3157: Advanced Programming. Announcement

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

CSE123. Program Design and Modular Programming Functions 1-1

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Q1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

ECE264 Spring 2013 Final Exam, April 30, 2013

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Chapter 5: Recursion

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Pointers and scanf() Steven R. Bagley

Character Strings. String-copy Example

Functions and Recursion

User Defined data Types

Dynamic Programming. An Introduction to DP

More Binary Search Trees AVL Trees. CS300 Data Structures (Fall 2013)

Today s class. Finish review of C Process description and control. Informationsteknologi. Tuesday, September 18, 2007

Dynamic memory allocation

Transcription:

Recursion The enumerated type Recursion Enums Basics of Programming 1 Department of Networked Systems and Services G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A. Vitéz 31 October, 2018 based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 1 / 29

Recursion The enumerated type Content 1 Recursion Definition Writing recursive programs Recursion or iteration Applications Indirect recursion 2 The enumerated type Motivation Syntax Examples based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 2 / 29

Chapter 1 Recursion based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 3 / 29

Recursion definition Many mathematical problems can be formulated recursively Sum of sequence a n { S n 1 + a n n > 0 S n = a 0 n = 0 Factorial n! = { (n 1)! n n > 0 1 n = 0 Fibonacci numbers F n 2 + F n 1 n > 1 F n = 1 n = 1 0 n = 0 based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 4 / 29

Recursion definition Several everyday problems can be formulated recursively Is Albert Einstein my ancestor? Ancestor of my father/mother? My ancestor? = Is he my father? Is she my mother? In general Problem = { Simpler, similar problem(s) Trivial case(es) based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 5 / 29

Recursion outlook Recursion is useful in many areas Mathematical proof e.g., proof by induction Definition e.g., Fibonacci numbers Algorithm e.g., path finding algorithms Data structure e.g., linked list, folders of the op. system Geometric constructions e.g., fractals We are going to study recursive data structures and recursive algorithms based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 6 / 29

Recursive algorithms in C Factorial n! = { (n 1)! n n > 0 1 n = 0 Let us implement it to C! 1 unsigned factorial ( unsigned n) 2 { 3 if (n > 0) 4 return factorial (n -1) * n; 5 else 6 return 1; 7 } Calling the function 1 unsigned f = factorial (5); /* it works! */ 2 printf ("%u\n", f); based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 7 / 29

Some considerations How to imagine recursive functions? 1 unsigned f0( void ) { return 1; } 2 unsigned f1( void ) { return f0 () * 1; } 3 unsigned f2( void ) { return f1 () * 2; } 4 unsigned f3( void ) { return f2 () * 3; } 5 unsigned f4( void ) { return f3 () * 4; } 6 unsigned f5( void ) { return f4 () * 5; } 7... 8 unsigned f = f5 (); Many different instances of the same function coexist simultaneously The instances were called with different parameters based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 8 / 29

Implementing recursion How can multiple instances of the same function coexist? 1 /* 2 recursive factorial function 3 */ 4 unsigned factorial ( unsigned n) 5 { 6 if (n > 0) 7 return factorial (n -1) * n; 8 else 9 return 1; 10 } 11 12 int main ( void ) 13 { 14... 15 factorial (4); 16... 17 } 0x1FDC: 0x1FE0: 0x1FE4: 0x1FE8: 0x1FEC: 0x1FF0: 0x1FF4: 0x1FF8: 0x1FFC: 0x2000: register: 7 0 7 1 7 2 7 3 15 4 24 based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 9 / 29

Implementing recursion The mechanism of the function calls in C is capable of writing recursive functions All the data (local variables, return addresses) of the calling functions are stored in the stack Whether the function calls itself or an other function makes no difference The maximal depth of recursive calls: given by the stack size based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 10 / 29

Recursion or iteration factorial Calculating n! recursively elegant, but inefficient 1 unsigned fact_ rec ( unsigned n) 2 { 3 if (n == 0) 4 return 1; 5 return fact_ rec (n -1) * n; 6 } link and iteratively boring, but efficient 1 unsigned fact_ iter ( unsigned n) 2 { 3 unsigned f = 1, i; 4 for ( i = 2; i <= n; ++ i) 5 f *= i; 6 return f; 7 } link based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 11 / 29

Recursion or iteration Fibonacci Calculating F n recursively elegant, but way too slow! 1 unsigned fib_rec ( unsigned n) 2 { 3 if (n <= 1) 4 return n; 5 return fib_rec (n -1) + fib_rec (n -2); 6 } link and iteratively boring, but efficient 1 unsigned fib_ iter ( unsigned n) 2 { 3 unsigned f1 = 0, f2 = 1, f3, i; 4 for ( i = 2; i <= n; ++ i) { 5 f3 = f1 + f2; 6 f1 = f2; 7 f2 = f3; 8 } 9 return f2; 10 } link based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 12 / 29

Recursion or iteration 1 Every recursive algorithm can be transformed to an iterative one (loops) There is no general method for this transformation 2 Every iterative algorithm can be transformed to a recursive one Easy to do systematically, but usually not efficient There is no universal truth: the choice between recursive and iterative algorithms depends on the problem based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 13 / 29

Iterative algorithms recursively Traversing arrays recursively (without loops) 1 void print_ array ( int * array, int n) 2 { 3 if (n == 0) 4 return ; 5 printf ("%d ", array [0]); 6 print_ array ( array +1, n -1); /* recursive call */ 7 } Traversing strings recursively 1 void print_ string ( char * str ) 2 { 3 if ( str [0] == \0 ) 4 return ; 5 printf ("%c", str [0]); 6 print_ string ( str +1); /* recursive call */ 7 } based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 14 / 29

Printing number in a given numeral system recursively 1 void print_ base_ rec ( unsigned n, unsigned base ) 2 { 3 if ( n >= base ) 4 print_base_rec (n/base, base ); 5 printf ("%d", n% base ); 6 } link iteratively 1 void print_ base_ iter ( unsigned n, unsigned base ) 2 { 3 unsigned d; /* power of base not greater than n */ 4 for ( d = 1; d* base <= n; d*= base ); 5 while ( d > 0) 6 { 7 printf ("%d", (n/d)% base ); 8 d /= base ; 9 } 10 } link based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 15 / 29

When the recursive algorithm is definitely better The array below stores a labyrinth 1 char lab [9][9+1] = { 2 "+-------+", 3 " ", 4 "+-+ ++ ++", 5 " ", 6 " + + -+ ", 7 " ", 8 "+-+ + -+ ", 9 " ", 10 "+-----+-+" 11 }; link Let us visit the entire labyrinth from start position (x,y) 1 traverse ( lab, 1, 1); We go in every possible direction and visit the yet unvisited parts of the labyrinth based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 16 / 29

When the recursive algorithm is definitely better The simplicity of the recursive solution is striking 1 void traverse ( char lab [][9+1], int x, int y) 2 { 3 lab [x][y] =. ; /* mark that we were here */ 4 if ( lab [x -1][ y] == ) /* go upwards, if needed */ 5 traverse (lab, x -1, y); 6 if ( lab [x +1][ y] == ) /* go downwards, if needed */ 7 traverse (lab, x+1, y); 8 if ( lab [x][y -1] == ) /* go left, if needed */ 9 traverse (lab, x, y -1); 10 if ( lab [x][y+1] == ) /* go right, if needed */ 11 traverse (lab, x, y +1); 12 } link It is also possible to do with an iterative algorithm but it is much more complex based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 17 / 29

Indirect recursion Indirect recursion: Functions mutually call each other function a function b 1 /* forward declaration */ 2 void b( int ); /* name, return type, parameter types */ 3 4 void a( int n) { 5... 6 b( n); /* b can be called due to the forward decl. */ 7... 8 } 9 10 void b( int n) { 11... 12 a(n); 13... 14 } based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 18 / 29

Forward declaration Forward declaration will be necessary for recursive data structures 1 /* forward declaration */ 2 struct child_s ; 3 4 struct mother_ s { /* mother type */ 5 char name [50]; 6 struct child_s * children [20]; /* pntr. arr. of children */ 7 }; 8 9 struct child_s { /* child type */ 10 char name [50]; 11 struct mother_ s * mother ; /* pointer to the mother */ 12 }; based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 19 / 29

Recursion The enumerated type Motivation Syntax Examples Chapter 2 The enumerated type based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 20 / 29

Recursion The enumerated type Motivation Syntax Examples The enumerated type Motivation We are writing a game, in which the user can control direction of the player with 4 keys. W A S D As the input from user needs to be read (checked) frequently, we create a read_direction() function for this task. This function reads from the keyboard and returns the direction to the calling program segment. What type should the function return with? based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 21 / 29

Recursion The enumerated type Motivation Syntax Examples The enumerated type Motivation Idea Nr. 1: Let s return with the key pressed. ( a, s, w, d ): 1 char read_ direction ( void ) 2 { 3 char ch; 4 scanf ("%c", &ch ); 5 return ch; 6 } link Problems: We have to decode characters into directions many times at different parts of the source code. If we change to use the arrow keys for control, we have to modify the source code a thousand time and place. Solution: We have to decode in place (inside the function), and should return with direction. But how can we do that? based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 22 / 29

Recursion The enumerated type Motivation Syntax Examples The enumerated type Motivation Idea Nr. 2: Let s return with int values 0,1,2,3: a 0 1 int read_ direction ( void ) { w 1 2 char ch; d 2 3 scanf ("%c", &ch ); 4 s 3 switch (ch) { 5 case a : return 0; /* left */ 6 case w : return 1; /* up */ 7 case d : return 2; /* right */ 8 case s : return 3; /* down */ 9 } 10 return 0; /* default is left :) */ 11 } Problem: In other parts of the program we have to use numbers 0-3 for the directions, so the programmer must remember the number-direction assignments. based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 23 / 29

Recursion The enumerated type Motivation Syntax Examples The enumerated type Motivation We need a type named direction, that can store LEFT, RIGHT, UP, DOWN values. We can do such thing in C! Declaration of the appropriate enumerated type (enum): 1 enum direction { LEFT, RIGHT, UP, DOWN }; How to use the type: 1 enum direction d; 2 d = LEFT ; based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 24 / 29

Recursion The enumerated type Motivation Syntax Examples The enumerated type Motivation The final solution with the new type 1 enum direction { LEFT, RIGHT, UP, DOWN }; 2 typedef enum direction direction ; /* simplification */ 3 4 direction read_ direction ( void ) 5 { 6 char ch; 7 scanf ("%c", &ch ); 8 switch ( ch) 9 { 10 case a : return LEFT ; 11 case w : return UP; 12 case d : return RIGHT ; 13 case s : return DOWN ; 14 } 15 return LEFT ; 16 } link based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 25 / 29

Recursion The enumerated type Motivation Syntax Examples The enumerated type Motivation Usage of the function: 1 direction d = read_ direction (); 2 if ( d == RIGHT ) 3 printf (" You were eaten by a tiger \ n"); link Without the enumerated type, it would look like this: 1 int d = read_ direction (); 2 if ( d == 2) /* " magic " constant, what does it mean? */ 3 printf (" You were eaten by a tiger \ n"); link The enumerated type... replaces magic constants with informative code, focuses on content instead of representation, allows a higher level programming. based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 26 / 29

Recursion The enumerated type Motivation Syntax Examples The enumerated type Definition The enumerated (enum) type Joins into one type integer type constants referenced by symbolic names. enum [<enumeration label>] opt { <enumeration list> } [<variable identifiers>] opt ; 1 enum direction { LEFT, RIGHT, UP, DOWN } dir1, dir2 ; based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 27 / 29

Recursion The enumerated type Motivation Syntax Examples enum examples 1 enum month { 2 JAN, /* 0 */ 3 FEB, /* 1 */ 4 MAR, /* 2 */ 5 APR, /* 3 */ 6 MAY, /* 4 */ 7 JUNE, /* 5 */ 8 JULY, /* 6 */ 9 AUG, /* 7 */ 10 SEPT, /* 8 */ 11 OCT, /* 9 */ 12 NOV, /* 10 */ 13 DEC /* 11 */ 14 }; 15 16 enum month m= OCT ; /*9*/ 1 enum { 2 RED, /* 0 */ 3 BLUE = 3, /* 3 */ 4 GREEN, /* 4 */ 5 YELLOW, /* 5 */ 6 GRAY = 10 /* 10 */ 7 } c; 8 9 c = GREEN ; 10 printf ("c: %d\n", c); c: 4 based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 28 / 29

Recursion The enumerated type Motivation Syntax Examples Thank you for your attention. based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, 2018 29 / 29