Program to print first 10 perfect squares

Last Updated : 9 Jan, 2024

Write a program to print the first 10 perfect squares. A perfect square is an integer which is the square of some other integer, or we can say that it is a second exponent of an integer

Output format:

1 4 9 16 25 ....

Approach:

We know that the first 10 perfect squares will be square of 1, square of 2, square of 3... till square of 10. So, iterate from 1 to 10 and print squares of each number.

Step-by-step algorithm:

  • Run a loop for i = 1 to 10:
    • For each iteration, calculate sq = i * i
    • Print the square as sq.
  • After 10 iterations, we will have the first 10 perfect squares.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

int main() {
    
    for(int i = 1; i <= 10; i++) {
        int sq = i * i;
        cout << sq << " ";
    }
    return 0;
}
Java
/*package whatever //do not write package name here */
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            int sq = i * i;
            System.out.print(sq + " ");
        }
    }
}
Python3
# code by flutterfly
for i in range(1, 11):
    sq = i * i
    print(sq, end=" ")
C#
//code by flutterfly
using System;

class Program {
    static void Main() {
        for (int i = 1; i <= 10; i++) {
            int sq = i * i;
            Console.Write(sq + " ");
        }
    }
}
JavaScript
//code by flutterfly
for (let i = 1; i <= 10; i++) {
    let sq = i * i;
    process.stdout.write(sq + " ");
}

Output
1 4 9 16 25 36 49 64 81 100 

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment