Course outline
Course / The terminal and the language

Negate a value in place

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/13-04-negate-in-place
cd 13-04-negate-in-place
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Fill in NegateInPlace so it flips the sign of the int n points to, writing the result back through the pointer.

Example

x := 5
NegateInPlace(&x)
fmt.Println(x) // -5

NegateInPlace(&x)
fmt.Println(x) // 5

Rules

  • Edit negate.go. The function has a // TODO comment and currently does nothing.
  • Use *n to read and write the value n points to.
  • Flip the sign with subtraction: 0 minus the value gives you the opposite sign.
  • 0 negated is still 0.
  • Do not change the line func NegateInPlace(n *int) {. Do not add imports.

What you'll practice

Writing a new value back through a pointer parameter, and using subtraction to flip a number's sign.

Run it

gonomicon fetch week-1/13-04-negate-in-place
cd 13-04-negate-in-place
gonomicon test
gonomicon submit

Hints

  1. Negating a number means flipping its sign. Subtraction gets you there: 0 minus a number flips it to the opposite sign, since 0 - 5 = -5 and 0 - (-5) = 5.
  2. You don't need an if to flip a sign. Subtract *n from 0 and write the result back through n, the same way earlier pointer functions wrote back an updated value.
  3. *n = 0 - *n

Something wrong with this lesson? Report a problem