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

Size: px
Start display at page:

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

Transcription

1 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, / 29

2 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, / 29

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

4 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, / 29

5 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, / 29

6 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, / 29

7 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, / 29

8 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; } 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, / 29

9 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 } int main ( void ) 13 { factorial (4); } 0x1FDC: 0x1FE0: 0x1FE4: 0x1FE8: 0x1FEC: 0x1FF0: 0x1FF4: 0x1FF8: 0x1FFC: 0x2000: register: based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, / 29

10 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, / 29

11 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, / 29

12 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, / 29

13 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, / 29

14 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, / 29

15 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, / 29

16 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, / 29

17 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, / 29

18 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) { b( n); /* b can be called due to the forward decl. */ } 9 10 void b( int n) { a(n); } based on slides by Zsóka, Fiala, Vitéz Recursion. Enums 31 October, / 29

19 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, / 29

20 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, / 29

21 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, / 29

22 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, / 29

23 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, / 29

24 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, / 29

25 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, / 29

26 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, / 29

27 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, / 29

28 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 }; 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, / 29

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, / 29

Structures, Operators

Structures, Operators Structures Typedef Operators Type conversion Structures, Operators Basics of Programming 1 G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A. Vitéz 10 October, 2018 c based on slides by Zsóka, Fiala, Vitéz

More information

Programming for Engineers Structures, Unions

Programming for Engineers Structures, Unions Programming for Engineers Structures, Unions ICEN 200 Spring 2017 Prof. Dola Saha 1 Structure Ø Collections of related variables under one name. Ø Variables of may be of different data types. Ø struct

More information

High Performance Computing

High Performance Computing High Performance Computing MPI and C-Language Seminars 2009 Photo Credit: NOAA (IBM Hardware) High Performance Computing - Seminar Plan Seminar Plan for Weeks 1-5 Week 1 - Introduction, Data Types, Control

More information

C Structures, Unions, Bit Manipulations, and Enumerations

C Structures, Unions, Bit Manipulations, and Enumerations C Structures, Unions, Bit Manipulations, and Enumerations Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 10.2 Structure Definitions 10.4

More information

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

Type Definition. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18 Enum and Struct Type Definition C Types Derived Function Array Pointer Structure Union Enumerated 2 tj Type Definition Typedef Define a new Type Inherits members and operations from a standard or previously

More information

Compiling and Running a C Program in Unix

Compiling and Running a C Program in Unix CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name

More information

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

Introduction. Structures, Unions, Bit Manipulations, and Enumerations. Structure. Structure Definitions Introduction Structures, Unions, Bit Manipulations, and Enumerations In C, we can create our own data types If programmers do a good job of this, the end user does not even have to know what is in the

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1 Introduction 10.2 Structure Definitions 10.3 Initializing Structures 10.4 Accessing

More information

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

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation

More information

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

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information Laboratory 2: Programming Basics and Variables Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information 3. Comment: a. name your program with extension.c b. use o option to specify

More information

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

typedef int Array[10]; String name; Array ages; Morteza Noferesti The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; Length a, b, len ; Length

More information

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

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation CS113: Lecture 3 Topics: Variables Data types Arithmetic and Bitwise Operators Order of Evaluation 1 Variables Names of variables: Composed of letters, digits, and the underscore ( ) character. (NO spaces;

More information

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

CprE 288 Introduction to Embedded Systems Exam 1 Review.  1 CprE 288 Introduction to Embedded Systems Exam 1 Review http://class.ece.iastate.edu/cpre288 1 Overview of Today s Lecture Announcements Exam 1 Review http://class.ece.iastate.edu/cpre288 2 Announcements

More information

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

Tutorial 7. Number Colour Black Brown Red Orange Yellow Green Blue Violet Gray White Tutorial 7 Question 1. Write a C program which declares an array of 20 integers, and initialises them such that the first value is 1, the second 2, and so on, with the last value being 20. Use a loop to

More information

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

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 University of Illinois at Urbana-Champaign Dept. of Electrical and Computer Engineering ECE 120: Introduction to Computing Examples of C Programs with Loops Time for Some Detailed Examples Let s do some

More information

1.7 Recursion. Department of CSE

1.7 Recursion. Department of CSE 1.7 Recursion 1 Department of CSE Objectives To learn the concept and usage of Recursion in C Examples of Recursion in C 2 Department of CSE What is recursion? Sometimes, the best way to solve a problem

More information

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

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion School of Electrical and Computer Engineering Cornell University revision: 2018-09-13-21-07 1 Dictionary Analogy 2 2 Computing Factorial

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

CMIS 102 Hands-On Lab

CMIS 102 Hands-On Lab CMIS 10 Hands-On Lab Week 8 Overview This hands-on lab allows you to follow and experiment with the critical steps of developing a program including the program description, analysis, test plan, and implementation

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

Functions. Arash Rafiey. September 26, 2017

Functions. Arash Rafiey. September 26, 2017 September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic

More information

recursive algorithms 1

recursive algorithms 1 COMP 250 Lecture 11 recursive algorithms 1 Oct. 2, 2017 1 Example 1: Factorial (iterative)! = 1 2 3 1 factorial( n ){ // assume n >= 1 result = 1 for (k = 2; k

More information

Syntax and Variables

Syntax and Variables Syntax and Variables What the Compiler needs to understand your program, and managing data 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line

More information

Arrays III and Enumerated Types

Arrays III and Enumerated Types Lecture 15 Arrays III and Enumerated Types Multidimensional Arrays & enums CptS 121 Summer 2016 Armen Abnousi Multidimensional Arrays So far we have worked with arrays with one dimension. Single dimensional

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Functions BCA-105. Few Facts About Functions:

Functions BCA-105. Few Facts About Functions: Functions When programs become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult then C provides a most striking feature known as user defined function

More information

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

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

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

Data Types H&K Chapter 7. Instructor - Andrew S. O Fallon CptS 121 (October 17, 2018) Washington State University Data Types H&K Chapter 7 Instructor - Andrew S. O Fallon CptS 121 (October 17, 2018) Washington State University Data Types We already know that: Data type = set of values + set of operations on those

More information

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

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved Recursion Chapter 7 Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an Array Recursively Processing a Linked Chain The Time Efficiency

More information

AE52/AC52/AT52 C & Data Structures JUNE 2014

AE52/AC52/AT52 C & Data Structures JUNE 2014 Q.2 a. Write a program to add two numbers using a temporary variable. #include #include int main () int num1, num2; clrscr (); printf( \n Enter the first number : ); scanf ( %d, &num1);

More information

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

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values Data Types 1 data type: a collection of values and the definition of one or more operations that can be performed on those values C++ includes a variety of built-in or base data types: short, int, long,

More information

CS 3410 Ch 7 Recursion

CS 3410 Ch 7 Recursion CS 3410 Ch 7 Recursion Sections Pages 7.1-7.4, 7.7 93-319, 333-336 7.1 Introduction 1. A recursive method is a method that either directly or indirectly makes a call to itself. [Weiss]. It does this by

More information

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

File Handling in C. EECS 2031 Fall October 27, 2014 File Handling in C EECS 2031 Fall 2014 October 27, 2014 1 Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically

More information

Practice problems Set 2

Practice problems Set 2 Practice problems Set 2 1) Write a program to obtain transpose of a 4 x 4 matrix. The transpose of matrix is obtained by exchanging the elements of each row with the elements of the corresponding column.

More information

DC54 DATA STRUCTURES DEC 2014

DC54 DATA STRUCTURES DEC 2014 Q.2 a. Write a function that computes x^y using Recursion. The property that x^y is simply a product of x and x^(y-1 ). For example, 5^4= 5 * 5^3. The recursive definition of x^y can be represented as

More information

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

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:

More information

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

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Fundamental of C Programming Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Q2. Write down the C statement to calculate percentage where three subjects English, hindi, maths

More information

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

520 Principles of Programming Languages. Arithmetic. Variable Declarations. 19: Pascal Structure of a Pascal Program 520 Principles of Programming Languages 19: Pascal Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona PROGRAM Name (list of files);

More information

COMPUTER APPLICATION

COMPUTER APPLICATION Total No. of Printed Pages 16 HS/XII/A.Sc.Com/CAP/14 2 0 1 4 COMPUTER APPLICATION ( Science / Arts / Commerce ) ( Theory ) Full Marks : 70 Time : 3 hours The figures in the margin indicate full marks for

More information

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

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 Sample Test Paper-I Marks : 25 Time:1 Hrs. Q1. Attempt any THREE 09 Marks a) State four relational operators with meaning. b) State the use of break statement. c) What is constant? Give any two examples.

More information

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

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 13: Recursion Sandeep Manjanna, Summer 2015 Announcements Final exams : 26 th of June (2pm to 5pm) @ MAASS 112 Assignment 4 is posted and Due on 29 th of June

More information

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

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself

More information

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

8. Structures, File I/O, Recursion. 18 th October IIT Kanpur 8. Structures, File I/O, Recursion 18 th October IIT Kanpur C Course, Programming club, Fall 2008 1 Basic of Structures Definition: A collection of one or more different variables with the same handle

More information

Computer Organization & Systems Exam I Example Questions

Computer Organization & Systems Exam I Example Questions Computer Organization & Systems Exam I Example Questions 1. Pointer Question. Write a function char *circle(char *str) that receives a character pointer (which points to an array that is in standard C

More information

CS Programming I: Arrays

CS Programming I: Arrays CS 200 - Programming I: Arrays Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Array Basics

More information

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

Materials covered in this lecture are: A. Completing Ch. 2 Objectives: Example of 6 steps (RCMACT) for solving a problem. 60-140-1 Lecture for Thursday, Sept. 18, 2014. *** Dear 60-140-1 class, I am posting this lecture I would have given tomorrow, Thursday, Sept. 18, 2014 so you can read and continue with learning the course

More information

Reduction & Recursion Overview

Reduction & Recursion Overview Reduction & Recursion Overview Reduction definition Reduction techniques Recursion definition Recursive thinking (Many) recursion examples Indirect recursion Runtime stack Factorial isnumericstring add

More information

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

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions Announcements Thursday Extras: CS Commons on Thursdays @ 4:00 pm but none next week No office hours next week Monday or Tuesday Reflections: when to use if/switch statements for/while statements Floating-point

More information

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

Binary Search Tree 1.0. Generated by Doxygen Mon Jun :12:39 Binary Search Tree 1.0 Generated by Doxygen 1.7.1 Mon Jun 6 2011 16:12:39 Contents 1 Binary Search Tree Program 1 1.1 Introduction.......................................... 1 2 Data Structure Index 3

More information

IV Unit Second Part STRUCTURES

IV Unit Second Part STRUCTURES STRUCTURES IV Unit Second Part Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 10 Structures, Unions, Bit Manipulations and Enumerations Department of Computer Engineering

More information

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

Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1)))))) Tail Recursion 1 Tail Recursion In place of loops, in a functional language one employs recursive definitions of functions. It is often easy to write such definitions, given a problem statement. Unfortunately,

More information

CSCI 171 Chapter Outlines

CSCI 171 Chapter Outlines Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures

More information

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

For Solved Question Papers of UGC-NET/GATE/SET/PGCET in Computer Science, visit For Solved Question Papers of UGC-NET/GATE/SET/PGCET in Computer Science, visit http://victory4sure.weebly.com/ For Solved Question Papers of UGC-NET/GATE/SET/PGCET in Computer Science, visit http://victory4sure.weebly.com/

More information

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

CS10001: Programming & Data Structures. Dept. of Computer Science & Engineering CS10001: Programming & Data Structures Dept. of Computer Science & Engineering 1 Course Materials Books: 1. Programming with C (Second Edition) Byron Gottfried, Third Edition, Schaum s Outlines Series,

More information

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

First of all, it is a variable, just like other variables you studied Pointers: Basics 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 address (rather than the value)

More information

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

Instructor training course schedule v3 Confirmed courses due completion by 31 st July 2019 Confirmed courses due completion by 31 st July 2019 Courses: 2 Orientation 2 IoT Fundamentals 2 Networking Essentials 2 Cybersecurity Essentials 2 IT Essentials: PC Hardware and Software 2 CCNA Routing

More information

AMCAT Automata Coding Sample Questions And Answers

AMCAT Automata Coding Sample Questions And Answers 1) Find the syntax error in the below code without modifying the logic. #include int main() float x = 1.1; switch (x) case 1: printf( Choice is 1 ); default: printf( Invalid choice ); return

More information

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

Recursion, Trees and Tree Traversal. Module CE System Programming & Computer Control Systems Recursion, Trees and Tree Traversal Module CE00352-2 System Programming & Computer Control Systems Lists Data Pointer Data Pointer Can be used as queue or stack Data Pointer Data Pointer Tree Structure

More information

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

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

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

Lesson 5: Functions and Libraries. EE3490E: Programming S1 2018/2019 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lesson 5: Functions and Libraries 1 Functions 2 Overview Function is a block of statements which performs a specific task, and can be called by others Each function has a name (not identical to any other),

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

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

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself. Recursion What is recursion? Week 10 Generally, when something contains a reference to itself Gaddis:19.1-19.5 CS 5301 Spring 2014 Jill Seaman 1 Math: defining a function in terms of itself Computer science:

More information

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

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

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

More information

Chapter 5: Recursion

Chapter 5: Recursion Chapter 5: Recursion Objectives Looking ahead in this chapter, we ll consider Recursive Definitions Function Calls and Recursive Implementation Anatomy of a Recursive Call Tail Recursion Nontail Recursion

More information

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

Data Structures and Algorithms (DSA) Course 4. Iulian Năstac Data Structures and Algorithms (DSA) Course 4 Iulian Năstac 10. Functions for dynamic memory allocation (recapitulation) Dynamic allocation is a specific characteristic allowed by some computing languages,

More information

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

BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$ BBM#101# #Introduc/on#to# Programming#I# Fall$2013,$Lecture$12$ Instructors:!Aykut!Erdem,!Erkut!Erdem,!Fuat!Akal! Today#! Structures#! Structure#Defini/ons#! Ini/alizing#Structures#! Accessing#Members#of#Structures#!

More information

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

History. used in early Mac development notable systems in Pascal Skype TeX embedded systems Overview The Pascal Programming Language (with material from tutorialspoint.com) Background & History Features Hello, world! General Syntax Variables/Data Types Operators Conditional Statements Functions

More information

RECURSION. Many Slides from Ken Birman, Cornell University

RECURSION. Many Slides from Ken Birman, Cornell University RECURSION Many Slides from Ken Birman, Cornell University Iteration Computers are well-suited for executing the same task repeatedly Programs and algorithms use iteration to perform repetitive jobs Programming

More information

C: How to Program. Week /Apr/16

C: How to Program. Week /Apr/16 C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies

More information

EEE145 Computer Programming

EEE145 Computer Programming EEE145 Computer Programming Content of Topic 2 Extracted from cpp.gantep.edu.tr Topic 2 Dr. Ahmet BİNGÜL Department of Engineering Physics University of Gaziantep Modifications by Dr. Andrew BEDDALL Department

More information

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

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

cs109: Programming Paradigms C++ FS 2014

cs109: Programming Paradigms C++ FS 2014 UNIVERSITÄT BASEL Thorsten Möller Alexander Haesen Valentino Rugolo cs109: Programming Paradigms C++ FS 2014 Exercise 1 Deadline: 30.03.2014 23:59:59 Note: Please upload answers to the questions and source

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

MODULE 3: Arrays, Functions and Strings

MODULE 3: Arrays, Functions and Strings MODULE 3: Arrays, Functions and Strings Contents covered in this module I. Using an Array II. Functions in C III. Argument Passing IV. Functions and Program Structure, locations of functions V. Function

More information

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

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam Multimedia Programming 2004 Lecture 2 Erwin M. Bakker Joachim Rijsdam Recap Learning C++ by example No groups: everybody should experience developing and programming in C++! Assignments will determine

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 310 Advanced Data Structures and Algorithms Recursion June 27, 2017 Tong Wang UMass Boston CS 310 June 27, 2017 1 / 20 Recursion Recursion means defining something, such as a function, in terms of itself

More information

CS3157: Advanced Programming. Announcement

CS3157: Advanced Programming. Announcement CS3157: Advanced Programming Lecture #10 Mar 20 Shlomo Hershkop shlomo@cs.columbia.edu Announcement Welcome back from spring break Hope you ve caught up with your courses Have the exams back, will return

More information

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS Manish Dronacharya College Of Engineering, Maharishi Dayanand University, Gurgaon, Haryana, India III. Abstract- C Language History: The C programming language

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling Recursion Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling With reference to the call stack Compute the result of simple recursive algorithms Understand

More information

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

Q1: /20 Q2: /30 Q3: /24 Q4: /26. Total: /100 ECE 2035(B) Programming for Hardware/Software Systems Fall 2013 Exam Two October 22 nd 2013 Name: Q1: /20 Q2: /30 Q3: /24 Q4: /26 Total: /100 1/6 For functional call related questions, let s assume the

More information

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

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be

More information

ECE264 Spring 2013 Final Exam, April 30, 2013

ECE264 Spring 2013 Final Exam, April 30, 2013 ECE264 Spring 2013 Final Exam, April 30, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing

More information

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

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space

More information

Chapter 5: Recursion

Chapter 5: Recursion Chapter 5: Recursion Objectives Looking ahead in this chapter, we ll consider Recursive Definitions Function Calls and Recursive Implementation Anatomy of a Recursive Call Tail Recursion Nontail Recursion

More information

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

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Pointers and scanf() Steven R. Bagley

Pointers and scanf() Steven R. Bagley Pointers and scanf() Steven R. Bagley Recap Programs are a series of statements Defined in functions Can call functions to alter program flow if statement can determine whether code gets run Loops can

More information

Character Strings. String-copy Example

Character Strings. String-copy Example Character Strings No operations for string as a unit A string is just an array of char terminated by the null character \0 The null character makes it easy for programs to detect the end char s[] = "0123456789";

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

User Defined data Types

User Defined data Types User Defined data Types typedef datatype user_defined_data_type typedef int salary; salary emp1,emp2; salary x; typedef char sentence[50]; sentence header,footer; char header[50],footer[50]; 5/1/2006 Computer

More information

Dynamic Programming. An Introduction to DP

Dynamic Programming. An Introduction to DP Dynamic Programming An Introduction to DP Dynamic Programming? A programming technique Solve a problem by breaking into smaller subproblems Similar to recursion with memoisation Usefulness: Efficiency

More information

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

More Binary Search Trees AVL Trees. CS300 Data Structures (Fall 2013) More Binary Search Trees AVL Trees bstdelete if (key not found) return else if (either subtree is empty) { delete the node replacing the parents link with the ptr to the nonempty subtree or NULL if both

More information

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

Today s class. Finish review of C Process description and control. Informationsteknologi. Tuesday, September 18, 2007 Today s class Finish review of C Process description and control Computer Systems/Operating Systems - Class 6 1 Finish review of C Review in class exercise 3 #1: game cptr is 5004 #2: The value of c is

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information