ALGORITHM 2-1 Solution for Exercise 4

Similar documents
Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

Technical Questions. Q 1) What are the key features in C programming language?

ME 172. Lecture 2. Data Types and Modifier 3/7/2011. variables scanf() printf() Basic data types are. Modifiers. char int float double

M1-R4: Programing and Problem Solving using C (JAN 2019)

Tribhuvan University Institute of Science and Technology 2065

Solution for Data Structure

Subject: Fundamental of Computer Programming 2068

Pointers and scanf() Steven R. Bagley

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Functions. Systems Programming Concepts

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Solutions to Assessment

BİL200 TUTORIAL-EXERCISES Objective:

SAMPLE MIDTERM SOLUTION

Fundamentals of Programming & Procedural Programming

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

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

ESC101N: Fundamentals of Computing End-sem st semester

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

School of Computer Science Introduction to Algorithms and Programming Winter Midterm Examination # 1 Wednesday, February 11, 2015

AROUND THE WORLD OF C

JTSK Programming in C II C-Lab II. Lecture 3 & 4

Multiple Choice Questions ( 1 mark)

ECE264 Fall 2013 Exam 1, September 24, 2013

Strings and Library Functions

Introduction to C Language (M3-R )

Flow Chart. The diagrammatic representation shows a solution to a given problem.

Functions. Arash Rafiey. September 26, 2017

COMS Spring Homework 3

Chapter 7 Functions. Now consider a more advanced example:

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Solutions to Assessment

Control Structure: Loop

C Functions. 5.2 Program Modules in C

Computer Programming. Decision Making (2) Loops

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

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

C: How to Program. Week /Apr/16

ECE264 Spring 2013 Final Exam, April 30, 2013

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Assoc. Prof. Dr. Tansu FİLİK

Midterm Examination # 2 Wednesday, March 19, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

ECE264 Spring 2013 Exam 1, February 14, 2013

Chapter 5 C Functions

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

2) Some coders debug their programs by placing comment symbols on some codes instead of deleting it. How does this aid in debugging?

Solutions to Chapter 8

Unit 7. Functions. Need of User Defined Functions

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Fundamentals of Programming & Procedural Programming

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

MARKS: Q1 /20 /15 /15 /15 / 5 /30 TOTAL: /100

Practice problems Set 2

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

Basics of Programming

CSI 402 Lecture 2 Working with Files (Text and Binary)

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

Function I/O. Last Updated 10/30/18

PESIT Bangalore South Campus Hosur Road (1km before Electronic City), Bengaluru Department of Basic Science and Humanities

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

CSCE 2014 Final Exam Spring Version A

Chapter 4 Homework Individual/Team (1-2 Persons) Assignment 15 Points

Lecture 04 FUNCTIONS AND ARRAYS

CSL 201 Data Structures Mid-Semester Exam minutes

Chapter 4 Functions By C.K. Liang

Operators and Expressions:

Tutorial No. 2 - Solution (Overview of C)

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #10

Exercises C-Programming

Question Bank (SPA SEM II)

Procedural Programming

Programming in C Quick Start! Biostatistics 615 Lecture 4

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.

Example: Pointer Basics

CSE 2123 Recursion. Jeremy Morris

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Preview from Notesale.co.uk Page 2 of 79

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Question 2. [5 points] Given the following symbolic constant definition

Precedence and Associativity Table. % specifiers in ANSI C: String Control Codes:

printf( Please enter another number: ); scanf( %d, &num2);

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

C introduction: part 1

Procedural programming with C

Duration: 110 minutes

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Chapter 8: Character & String. In this chapter, you ll learn about;

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

Pointers, Arrays, and Strings. CS449 Spring 2016

'C' Programming Language

UNIT-I Input/ Output functions and other library functions

CSE123. Program Design and Modular Programming Functions 1-1

Engineering program development 6. Edited by Péter Vass

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Transcription:

Chapter 2 Recursion Exercises 1. a. 3 * 4 = 12 b. (2 * (2 * fun1(0) + 7) + 7) = (2 * (2 * (3 * 0) + 7) + 7) = 21 c. (2 * (2 * fun1(2) + 7) + 7) = (2 * (2 * (3 * 2) + 7) + 7) = 45 2. a. 3 b. (fun2(2, 6) + 3) = ( 3 + 3) = 0 c. fun2(12, 6) + 3) = ((fun2(6, 9) + 6) + 3) = ( 3 + 6 + 3) = 6 3. a. 1 b. 1 c. (4 * fun3(5, 7)) = (4 * (5 * fun3(6, 7))) = 4 * (5 * (6 * fun3 (7, 7))) = 120 d. 1 4. See Algorithm 2.1. ALGORITHM 2-1 Solution for Exercise 4 algorithm squareroot (num, ans, tol) This algorithm computes the square root of a number using Newton's method and returns the computed square root. Pre num is number for square root ans is estimate of the square root initially the same as num tol is the tolerance (accuracy) desired Post square root calculated and returned Return square root 1 if (absolute value of (ans * ans num) <= tol) 1 return ans 2 else 1 return (squareroot (num, (ans * ans + num) / (2 * ans), tol) end squareroot 5. See Algorithm 2.2. ALGORITHM 2-2 Solution for Exercise 5 algorithm Combination (n, k) This algorithm calculates the combination of n objects taken k at a time 7

8 Chapter 2 Recursion ALGORITHM 2-2 Solution for Exercise 5 (continued) Pre n and k are positive integers and n >= k Post number of combination calculated and returned 1 if ((k is 0) OR (n equals k)) 1 return 1 2 else if (n > k AND k > 0) 1 return (C (n 1, k) + C (n 1, k 1)) end Combination 6. See Algorithm 2.3. ALGORITHM 2-3 Solution to Exercise 6 algorithm Ackerman (M, N) This algorithm calculates the Ackerman number Pre M an N are integers Post Ackerman number calculated and returned 1 if (M equal 0) 1 return (N + 1) 2 else if ((N equal 0) and (M > 0)) 1 return (Ackerman (M 1, 1)) 3 else 1 return (Ackerman (M 1, Ackerman (M, N 1))) end Ackerman Problems 7. See Algorithm 2.4. ALGORITHM 2-4 Solution for Problem 7 algorithm lengthoflist (list) This algorithm calculates and returns the length of a list Pre list is a valid list Post length is returned 1 if (empty list) 1 return 0 2 else 1 return (1 + lengthoflist (list minus first element)) end lengthoflist 8. See Algorithm 2.5. ALGORITHM 2-5 Solution for Problem 8 algorithm strtoint (string, num) This algorithm converts a number string to an integer. Pre string is an array of characters (all digits) num is address for converted number (initial call uses num of 0) Post the converted integer value in num

Problems 9 ALGORITHM 2-5 Solution for Problem 8 (continued) 1 return 0 3 set num to ((num * 10) + value of right character) 4 strtoint (string minus right character, num) end strtoint 9. See Algorithm 2.6. ALGORITHM 2-6 Solution to Problem 9 algorithm addn (n) This algorithm adds the first n elements of the series 1 + 1/2 + 1/3 + 1/4 + 1/5 +... + 1/n Pre n is an integer Post the sum is returned 1 if (n is 1) 1 return 1 2 else 1 return (1 / n + addn (n 1)) end addn 10. See ALGORITHM 2.7. ALGORITHM 2-7 Solution to Problem 10 algorithm palindrome (string) This algorithm will determine if a string is a palindrome Pre string is the string to be checked Post string has been checked Return true if palindrome false if not palindrome 1 return true 3 if (string only one character) 2 return true 5 if (first character not alphabetic) 1 return palindrom (string minus first character) 6 end if 7 if (last character not alphabetic) 1 return palindrom (string minus last character) 8 end if 9 if (lowercase first equals lowercase last) 1 return palindrom(string minus first and last characters) 10 end if 11 return false end palindrome

10 Chapter 2 Recursion 11. See Algorithm 2.8. ALGORITHM 2-8 Solution to Problem 11 algorithm checkcharacter (string, c) This algorithm checks if a character is in a string. Pre string is the string to search c is the character to look for Post returns true if found, false if not return false 3 if (first character equals c) 1 return true 5 return checkcharacter (string minus first character, c) end checkcharacter 12. See Algorithm 2.9. ALGORITHM 2-9 Solution to Problem 12 algorithm countchar (string, c) This algorithm counts all occurrences of a specified character in a string. Pre string is the string to search c is the character to count Post character count returned 1 return 0 3 if (first character equals c) 1 return (1 + countchar (string minus first character, c)) 5 return (countchar (string minus first character, c)) end countchar 13. See Algorithm 2.10. ALGORITHM 2-10 Solution for Problem 13 algorithm removecharacter (string, newstring, c) This algorithm removes all occurrences of a specified character in a string and returns new string. Pre string is the string to searched newstring is empty string c is character to be deleted Post return new string with c-characters deleted 1 return newstring 3 if (first character in string not equal c) 1 append first character to newstring

Problems 11 ALGORITHM 2-10 Solution for Problem 13 (continued) 5 return removechar(string minus first character, newstring, c) 6 end if end removecharacter 14. See Algorithm 2.11. ALGORITHM 2-11 Solution to Problem 14 algorithm findsubstring (string, substr, loclist) Find location of all occurrences of a specified substring in a string. Pre string is the string to search substr is substring to be located loclist is list to hold matching positions Post returns the count 1 return 3 if (substring matches beginning of string) 1 append location to loclist 2 findsubstring (string minus substring, substr, loclist) 4 else 1 findsubstring (string minus first character, substr, loclist) 5 end if end findsubstring 15. See Algorithm 2.12. ALGORITHM 2-12 Solution to Problem 15 algorithm integertobinary (num, binary) This algorithm changes an integer to a binary number stored in a string. Pre num is an integer binary is a null string large enough to hold (size of integer * 8 + 1) characters must be zero on initial call Post binary number is stored in binary 1 if (num equals 0) 1 return 3 integertobinary(num / 2, binary) 4 if (num modulo 2 equals 0) 1 append (binary, "0") 5 else 1 append (binary, "1") 6 end if 7 return end integertobinary

12 Chapter 2 Recursion 16. See Program 2-1. PROGRAM 2-1 Solution to Problem 16 /* This program tests the calculation of a square root using Newton's method. Written by: Date: #include <stdio.h> #include <stdlib.h> #include <math.h> // Prototype Declarations float squareroot (float num, float ans, float tol); int main (void) // Local Definitions float result; result = squareroot (125, 11, 0.01); printf ("The square root of 125 is %f\n", result); result = squareroot (763, 27, 0.01); printf ("The square root of 763 is %f\n", result); result = squareroot (997, 31, 0.01); printf ("The square root of 997 is %f\n", result); return 0; } // main /* ==================== squareroot ==================== This function calculates the squareroot of a number using Newton's method Pre num is the number whose root is desired ans is an estimate of the square root tol is the tolerance desired Post the squareroot is returned float squareroot (float num, float ans, float tol) if (fabs (ans * ans - num) <= tol) return (ans); else return (squareroot (num, (num + ans * ans) / (2 * ans), tol)); } // squareroot 17. See Algorithm 2.13. ALGORITHM 2-13 Solution to Problem 17 algorithm stringreverse This is a recursive algorithm that reads a string of characters from the keyboard and prints them reversed. Pre nothing

Problems 13 ALGORITHM 2-13 Solution to Problem 17 (continued) Post string is printed reversed 1 read (character) 2 if (end of input) 1 return 4 stringreverse 5 print (character) 6 return end stringreverse 18. See Program 2-2 PROGRAM 2-2 Solution to Problem 18 /* This program tests the combination function. Written by: Date: #include<stdio.h> #include<math.h> // Prototype Statements int combo (int n, int k); int main (void) printf ("The combination of 10 objects taken 3 " "at a time is: %d\n", combo(10, 3)); return 0; } // main /* ==================== combo ==================== This function calculates the combination of n objects taken k at a time Pre n and k are positive integers and n >= k Post the number of combination is returned int combo (int n, int k) if ((k == 0) (n == k)) return 1; else return (combo (n - 1, k) + combo (n - 1, k - 1)); } // combo 19. See Program 2-3. PROGRAM 2-3 Solution to Problem 19 /* This program tests the Ackerman number function. Written by: Date: #include <stdio.h> #include <math.h> // Prototype Statements int Ackerman (int M, int N);

14 Chapter 2 Recursion PROGRAM 2-3 Solution to Problem 19 (continued) int main (void) printf ("The Ackerman number for 2, 3 is %d\n", Ackerman (2, 3)); printf ("The Ackerman number for 2, 5 is %d\n", Ackerman (2, 5)); printf ("The Ackerman number for 0, 3 is %d\n", Ackerman (0, 3)); printf ("The Ackerman number for 3, 0 is %d\n", Ackerman (3, 0)); return 0; } // main /* ==================== Ackerman ==================== This function calculates Ackerman s number. Pre M and N are integers Post Ackerman's number is returned int Ackerman (int M, int N) if (M == 0) return (N + 1); else if ((N == 0) && (M > 0)) return (Ackerman (M - 1, 1)); else return (Ackerman (M - 1, Ackerman (M, N - 1))); } // Ackerman 20. See Program 2-4. PROGRAM 2-4 Solution to Problem 20 /* =================== printreverse =================== This algorithm prints the elements of a linked list in reverse order Pre plist is a node pointer Post list is printed in reverse order void printreverse (NODE *plist) if (plist == NULL) return; printreverse (plist >next); printf ("%d\n", plist >data); return; } // printreverse