Add two numbers

Easy
The course
Number Input and output
1

Understand

Before writing anything, get clear on what is being asked.

Think of it like this

A function is a vending machine. The parameters are what you put in — here, two numbers. The return value is what drops out. Your job is to wire up what happens in between.

Write a function that takes two whole numbers and gives back their total.

Example 1

Given a = 2, b = 3

Answer 5

Example 2

Given a = 10, b = 0

Answer 10

What you can rely on

  • Both numbers are whole numbers
  • They may be negative
2

Write it

Write the function in the editor, then run it against the examples.

The editor on the right already has the function signature filled in for you. Write your answer inside it and press Run — that checks your code against the examples above only, so you can experiment freely.

Run your code to tick this step off.

Stuck? Take one hint at a time

Each one nudges you a little further. There is no reveal-the-answer button — working it out is the part that actually teaches you.

3

Own it

Submit against every test, then check you can explain why it works.

Add them and return

O(1) time · O(1) space

This one really is as short as it looks. What matters is noticing the shape: values come in as parameters, one value goes out as the return. Every exercise on this site has that shape, including the hard ones.

return a + b

O(1) means the work does not grow with the input. Adding 2 and 3 takes the same time as adding two million-digit numbers’ worth of machine words. You will meet this idea properly in week 2.

Press Submit to run every test, including the hidden ones.