basics · beginner · ~15 min

Square a number

Use an arithmetic expression in a return.

Challenge

Return the square of an integer.

Task

Implement int square(int n) that returns n * n. No main — the grader calls it.

Input

A single int n.

Output

Returns n squared, as an int.

Example

square(4)    ->   16
square(-3)   ->   9
square(0)    ->   0

Edge cases

  • A negative input still produces a non-negative square.

Input format

A single int n.

Output format

n * n, as an int.

Constraints

n is an integer such that n * n does not overflow signed 32-bit int in tests.

Starter code

int square(int n) {
    /* TODO */
    return 0;
}

Common mistakes

Using the caret '^' operator, which in C is bitwise XOR rather than exponentiation.

Edge cases to handle

n = 0 (result 0), n = 1 (result 1), negative values (e.g. -5 -> 25).

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.