Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Generate an even squares between 1 to n using for loop in C Programming
Even square numbers are the squares of even integers like 22, 42, 62, 82, which result in 4, 16, 36, 64, 100, and so on. In this tutorial, we will generate even squares between 1 to n using a for loop in C programming.
Syntax
for (initialization; condition; increment) {
// Loop body
}
Algorithm
START
Step 1: Declare variables a and n
Step 2: Read number n from user
Step 3: Use for loop to generate even squares
For a = 2; a*a <= n; a += 2
Print a*a (square of even numbers)
STOP
Example 1: Generate Even Squares Between 1 to n
This program generates all even squares from 1 to a given number n −
#include <stdio.h>
int main() {
int a, n;
printf("Enter a number for n: ");
scanf("%d", &n);
printf("Even squares between 1 and %d are:
", n);
for (a = 2; a * a <= n; a += 2) {
printf("%d
", a * a);
}
return 0;
}
Enter a number for n: 200 Even squares between 1 and 200 are: 4 16 36 64 100 144 196
Example 2: Generate Even Cubes Between 1 to n
Similarly, we can generate even cubes by calculating a3 for even values of a −
#include <stdio.h>
int main() {
int a, n;
printf("Enter a number for n: ");
scanf("%d", &n);
printf("Even cubes between 1 and %d are:
", n);
for (a = 2; a * a * a <= n; a += 2) {
printf("%d
", a * a * a);
}
return 0;
}
Enter a number for n: 300 Even cubes between 1 and 300 are: 8 64 216
How It Works
- The for loop starts with
a = 2(first even number) - The condition
a * a <= nensures we only generate squares within the given range - The increment
a += 2moves to the next even number - Inside the loop,
a * acalculates the square of the current even number
Conclusion
Generating even squares using a for loop is efficient and straightforward. By incrementing the loop variable by 2 and starting from 2, we ensure only even numbers are squared within the specified range.
Advertisements
