56.0k views
0 votes
USING C++ write a program that prompts a user to enter a number n, then prints all even squares between 1 and n. see the sample ouput beneath as an example

enter n = 100
4
16
36
64
100

User Jwehrle
by
8.3k points

1 Answer

2 votes

Certainly! Here's an example of a C++ program that prompts the user to enter a number n and then prints all even squares between 1 and n:

cpp

Copy

#include <iostream>

int main() {

int n;

// Prompt the user to enter a number

std::cout << "Enter n: ";

std::cin >> n;

// Print all even squares between 1 and n

for (int i = 2; i * i <= n; i += 2) {

std::cout << (i * i) << std::endl;

}

return 0;

}

Explanation of the code:

The program starts by prompting the user to enter a number n.

The input is stored in the variable n.

The program then uses a for loop to iterate from 2 to the square root of n (inclusive) with an increment of 2 (to consider only even numbers).

Inside the loop, the program calculates the square of the current number i using i * i and prints it.

The loop continues until i * i is less than or equal to n.

After the loop finishes, the program ends.

When you run this program and enter a number, such as 100, it will print all the even squares between 1 and 100, which in this case are 4, 16, 36, 64, and 100.

User Anthorlop
by
8.9k points