Tutorial 2 Quick review of C syntax Implementing a few functions - - PowerPoint PPT Presentation

tutorial 2
SMART_READER_LITE
LIVE PREVIEW

Tutorial 2 Quick review of C syntax Implementing a few functions - - PowerPoint PPT Presentation

Tutorial 2 Quick review of C syntax Implementing a few functions Recursion in C 1 CS 136 Spring 2020 Tutorial 2 My first C programs All we have so far is: int types simple functions main with only trace_int Lets try


slide-1
SLIDE 1

Tutorial 2

  • Quick review of C syntax
  • Implementing a few functions
  • Recursion in C

CS 136 Spring 2020 Tutorial 2

1

slide-2
SLIDE 2

My first C programs

All we have so far is:

  • int types
  • simple functions
  • main with only trace_int

Let’s try using them in Seashell by implementing the factorial function:

// factorial(n) calculates the value of n! (n factorial) // requires: n >= 0

CS 136 Spring 2020 Tutorial 2

2

slide-3
SLIDE 3

Practice Problem 1:

Define, Document and Test Ceil Function

Define the following C function:

// ceiling(a, b) calculates the value of a / b // rounded up to the nearest integer // requires: a >= 0, b > 0

CS 136 Spring 2020 Tutorial 2

3

slide-4
SLIDE 4

Practice Problem 2

Translating Racket to C

Translate the following Racket function to C:

;; (sumpow n pow) sums up i^pow with i from 0 to n ;; sumpow: Nat Nat -> Nat (define (sumpow n pow) (cond [(zero? n) (expt 0 pow)] [else (+ (expt n pow) (sumpow (sub1 n) pow))]))

CS 136 Spring 2020 Tutorial 2

4

slide-5
SLIDE 5

Practice Problem 3

Printing a Rectangle

Write the following C function

// rectangle() asks the user for two integers, width and //

  • height. A rectangle with these dimensions is printed.

// requires: width, height >= 1.

Example:

// IN: width = 4, height = 3 // OUT: **** **** ****

CS 136 Spring 2020 Tutorial 2

5