Course / The terminal and the language
Negate a value in place
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach 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 submitGoal
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// TODOcomment and currently does nothing. - Use
*nto read and write the valuenpoints to. - Flip the sign with subtraction:
0minus the value gives you the opposite sign. 0negated is still0.- 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
- 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.
- 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.
- *n = 0 - *n