How to Square a Number

beginner c++11 math

Related: Pow Functon

The easiest way to square a number is to multiply it by itself.

#include <iostream>

int square(int x) {
  return x * x;
}

int main() {
  int x = 7;
  std::cout << square(x) << "\n";
}
49

If we want to square any type that can be multiplied by itself then we want to use a template. Templates let us define a function with a placeholder for the type (a parameter that we’ll call “T” in this example) that the compiler then implements for us at compile time based on how the function is used. You’ve used templates before when you created a std::array or a std::vector. Here’s how to write a template function that squares anything that can be multiplied by itself.

#include <iostream>

template <typename T>
T square(T x) {
  return x * x;
}

int main() {
  int x = 7;
  std::cout << square(x) << "\n";

  float pi = 3.14159f;
  std::cout << square(pi) << "\n";
}
49
9.86959

For more C++ By Example, click here.