CMPT 125 Assignment 2 Solutions

Similar documents
1. (a) Write a C program to display the texts Hello, World! on the screen. (2 points)

CS 11 C track: lecture 1

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

High-Order Language APPLICATION LEVEL HIGH-ORDER LANGUAGE LEVEL ASSEMBLY LEVEL OPERATING SYSTEM LEVEL INSTRUCTION SET ARCHITECTURE LEVEL

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Examples and Applications of Binary Search

Homework 1 Solutions MA 522 Fall 2017

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Analysis of Algorithms

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Python Programming: An Introduction to Computer Science

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

. Written in factored form it is easy to see that the roots are 2, 2, i,

Python Programming: An Introduction to Computer Science

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

6.854J / J Advanced Algorithms Fall 2008

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Guide to Applying Online

Lecture 28: Data Link Layer

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Weston Anniversary Fund

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

How do we evaluate algorithms?

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

A graphical view of big-o notation. c*g(n) f(n) f(n) = O(g(n))

Big-O Analysis. Asymptotics

1.2 Binomial Coefficients and Subsets

Lecture 1: Introduction and Strassen s Algorithm

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

APPLICATION NOTE PACE1750AE BUILT-IN FUNCTIONS

The isoperimetric problem on the hypercube

Alpha Individual Solutions MAΘ National Convention 2013

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Ones Assignment Method for Solving Traveling Salesman Problem

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Arithmetic Sequences

Lecture 9: Exam I Review

Exceptions. Your computer takes exception. The Exception Class. Causes of Exceptions

ENGI 4421 Probability and Statistics Faculty of Engineering and Applied Science Problem Set 1 Descriptive Statistics

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a

Exercise 6 (Week 42) For the foreign students only.

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Behavioral Modeling in Verilog

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

Data Structures Week #5. Trees (Ağaçlar)

3. b. Present a combinatorial argument that for all positive integers n : : 2 n

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

WORKED EXAMPLE 7.1. Producing a Mass Mailing. We want to automate the process of producing mass mailings. A typical letter might look as follows:

Heaps. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015

IMP: Superposer Integrated Morphometrics Package Superposition Tool

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Data Structures Week #9. Sorting

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

Consider the following population data for the state of California. Year Population

End Semester Examination CSE, III Yr. (I Sem), 30002: Computer Organization

ENGR 132. Fall Exam 1

Polynomial Functions and Models. Learning Objectives. Polynomials. P (x) = a n x n + a n 1 x n a 1 x + a 0, a n 0

CS 111: Program Design I Lecture # 7: Web Crawler, Functions; Open Access

Big-O Analysis. Asymptotics

Sorting in Linear Time. Data Structures and Algorithms Andrei Bulatov

EE University of Minnesota. Midterm Exam #1. Prof. Matthew O'Keefe TA: Eric Seppanen. Department of Electrical and Computer Engineering

Array Applications. Sorting. Want to put the contents of an array in order. Selection Sort Bubble Sort Insertion Sort. Quicksort Quickersort

A Generalized Set Theoretic Approach for Time and Space Complexity Analysis of Algorithms and Functions

Pattern Recognition Systems Lab 1 Least Mean Squares

Numerical Methods Lecture 6 - Curve Fitting Techniques

Computers and Scientific Thinking

Major CSL Write your name and entry no on every sheet of the answer script. Time 2 Hrs Max Marks 70

One advantage that SONAR has over any other music-sequencing product I ve worked

CSE 417: Algorithms and Computational Complexity

Package RcppRoll. December 22, 2014

Recursive Procedures. How can you model the relationship between consecutive terms of a sequence?

NTH, GEOMETRIC, AND TELESCOPING TEST

CSE 111 Bio: Program Design I Class 11: loops

Chapter 4 The Datapath

ENGR Spring Exam 1

It just came to me that I 8.2 GRAPHS AND CONVERGENCE

Lecture 5. Counting Sort / Radix Sort

CS 111: Program Design I Lecture 15: Objects, Pandas, Modules. Robert H. Sloan & Richard Warner University of Illinois at Chicago October 13, 2016

Mathematical Stat I: solutions of homework 1

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

ENGR 132. Fall Exam 1 SOLUTIONS

Transcription:

CMPT 25 Assigmet 2 Solutios Questio (20 marks total) a) Let s cosider a iteger array of size 0. (0 marks, each part is 2 marks) it a[0]; I. How would you assig a poiter, called pa, to store the address of elemet 0 of this array? Write the C code for your aswer. it *pa = &a[0]; or it *pa = a; II. Usig pa, how would you obtai the value of the ext elemet (elemet ) of the array? pa poits to the first elemet of the array. So the ext elemet would be *(pa+) III. Explai i 2-3 seteces what the statemet pa = a[]; would do. The statemet would chage the address to which pa poits to the value stored i a[], which is meat to store a iteger, ot a address. While this code will compile, tryig to access the value of pa by usig *pa may cause a segmetatio fault (memory error). IV. Is the statemet a = pa; valid (would it cause compilatio errors)? How about a++;? Explai briefly i 3-4 seteces. No. There is oe key differece betwee a array ame ad poiter. A poiter is a variable, so pa=a ad pa++ are legal. But a array ame is ot a variable; costructios like a=pa ad a++ are thus illegal. V. Write C code to prit all the elemets from this array. Oe possible solutio: #iclude <stdio.h> it mai() { it a[0] = {0,,2,3,4,5,6,7,8,9; for (it *i = a; i <= a+9; i++) { pritf( %d\, *i); b) Cosider the two variables below. (5 marks) char amessage[] = "ow is the time"; char *pmessage = "ow is the time"; Page of 7

I. What is the differece betwee the two variables amessage ad pmessage? ( mark) char amessage[] is a array, whereas char *pmessage is a poiter iitialized to poit to a strig costat. II. Write a C code to chage the character t from time to uppercase T i the variable amessage. (5 marks) Oe possible solutio: #iclude <stdio.h> #iclude <strig.h> it mai() { char amessage[] = "ow is the time"; it c = 0; while (amessage[c]!= '\0') { if(amessage[c] == 't' && amessage[c+] == 'i') { amessage[c] = 'T'; pritf("letter: %c\", amessage[c]); c++; c) Cosider the followig code. (5 marks) void strcopy(char s[], char s2[]) { it le = strle(s2); for (it i = 0; i<=le; i++) { s[i] = s2[i]; it mai () { char s2[0] = "copy this"; char s[0]; strcopy(s, s2); The above code copies the character from s2 to s usig the cocept of array, i the strcopy fuctio. Implemet aother fuctio strcopy2 that achieves the same result, but that takes as iput poiters to character arrays that is, complete the strcopy2 fuctio i the followig code so that the code copies the cotet of s2 ito s. void strcopy2(char *s, char *s2) { Page 2 of 7

while (*s2!= '\0') { *s = *s2; s++; s2++; it mai () { char s2[0] = "copy this"; char s[0]; strcopy2(s, s2); Page 3 of 7

Questio 2 (0 marks, each part is 2 marks) Assume that each of the expressios below gives the processig time T() spet by a algorithm for solvig a problem of size. Fid the domiat term(s) havig the steepest icrease i ad specify the lowest Big-O complexity of each algorithm. Expressio Domiat term(s) O( ) 0.00 log 4 + log 2 (log 2 ) 0.00 log 4 O(log ) 3 log 2 + (log 2 ) 2 3 log 2 O( 3 log ) 0.0 + 00 3 00 3 O( 3 ) 0. + 4.5 + 2.5.5 4.5, 2.5.5 O(.5 ) 3 log 8 + log 2 (log 2 (log 2 )) 3 log 8 O(log ) Note that the base of log does t matter (by default, it s base 2 i this class). I additio, costats are dropped whe usig the Big-O otatio. To compare two terms to see which is domiat, oe ca take their ratio ad let. Example : Iitial evaluatio of gives, so we use L Hopital s rule ad take the derivative of the top ad bottom. log 2 (log 2 ) lim 0.00 log 4 = 000 lim l 2 log 2 l 2 l 4 log = costat lim 2 = costat lim log 2 = 0 This meas that the 0.00 log 4 term becomes much larger as. Note that the costat i frot, o matter how small, does ot make a differece as. Example 2: First we ca cacel a buch of thigs. (log 2 ) 2 lim 3 log 2 = lim log 2 2 Page 4 of 7

At this poit oe ca see that the 2 will is much bigger tha the log 2, so the domiat term is 3 log 2. However, to be completely pedatic, let s take. Iitial evaluatio of gives, so we use L Hopital s rule ad take the derivative of the top ad bottom. log 2 lim 2 = lim l 2 2 = l 2 lim 2 2 = 0 Questio 3 (8 marks, each part is 2 marks) For the followig parts, try to get the best Big-O estimate that you ca ad briefly justify your aswers. Part a) it i, j; it = 00; for (i = ; i <= ; i++) { for (j = 3*i; j <= ; j++) { pritf("programmig is fu\"); The ier loop goes from j = 3i to j =. This is 3i + times. Now, i goes from to, so the total umber of pritf calls is i= ( 3i + ). This is at most i= (), which is 2, so the total ruig time is O( 2 ). Part b) it i, j; it = 000000; for (i = ; i <= ; i++) { for (j = ; j <= 0000; j++) { pritf("%d %d\", i, j); Outer loop is executed O() times. For every executio of the outer loop, ier loop is executed 0000 times, which is a costat umber of times. So, total ruig time is 0000 = O(). Part c) Page 5 of 7

it i = 0; it = 0; it j; while (i < ) { j = i; while (i < ) { pritf("hello %d\", i); i = j; Outer loop executes times. For every executio of the outer loop, the ier loop is executed for j = i (the value of i i the outer loop) to, which is i + times. So the total executio cout of pritf is i= ( i + ), which is at most i= () = 2 = O( 2 ). Part d) it i = 0; it = 0; it j; while (i < ) { j = i; while (i < ) { pritf("hello %d\", i); break; i = j; Outer loop executes O() times. Ier loop has a break statemet so it becomes O(), costat. Total ruig time is O(). Questio 4 (5 marks) Write a program i C that prompts a user to select ay five beverages of your choice (e.g Coke, Lemo Tea, etc.). User should be able to select oe of these optios usig oly itegers from 0 to 4 as iputs. Oce a user has made the choice, prit the chose drik alog with its calorie iformatio. You may look up the calorie iformatio olie. Example iput: 3 Example output: Selected drik: Coca Cola Calorie cout: 40 Calories Page 6 of 7

Notes: You ca assume that the user will iput itegers. You do ot eed to hadle ivalid iputs of other types (such as strigs, floats, etc.). Your program should gracefully termiate if a user eters wrog iput three times. I additio, after every ivalid attempt, your program should tell the user how may tries he/she has remaiig. For example, the prompt should work somethig like this: o Prompt : User eters 6. Your program should tell that iput is ivalid ad eter agai. Also prit the remaiig tries (2). o Prompt 2: User eters -. Your program should tell that iput is ivalid ad eter agai. Also prit the remaiig tries (). o Prompt 3: User eters 200. Your program should tell that iput is ivalid ad termiate. Also prit the remaiig tries (0). o If the user eters a correct iput o or before the last try, the program should behave ormally, ad output should be like the provided example. #iclude <stdio.h> #iclude <strig.h> it beverages() { pritf("\please make a selectio of your favourite beverage by typig a umber\" "0 - Coca Cola\" " - Pepsi\" "2 - Lemo Tea\" "3 - Redbull\" "4 - Coffee\"); it tries = 3; it selectio; cost char *display[] = { "Selected drik: Coca Cola. Calorie cout: 40 Calories\", "Selected drik: Pepsi. Calorie cout: 50 Calories\", "Selected drik: Lemo Tea. Calorie cout: 90 Calories\", "Selected drik: Redbull. Calorie cout: 200 Calories\", "Selected drik: Coffee. Calorie cout: 60 Calories\", ; while(tries > 0) { tries--; pritf("eter a umber\"); scaf("%d", &selectio); if(selectio >= 0 && selectio <= 4) { pritf(display[selectio]); break; else { pritf("iput is ivalid. Remaiig tries (%d)\", tries); retur 0; Page 7 of 7