C++ Program: Summing Even Numbers Within a User-Defined Limit
Introduction
Welcome to the exciting world of C++ programming! Today, we'll embark on a journey into the heart of coding by exploring a simple yet powerful program that captures the essence of logic and iteration. Our quest: to sum even numbers up to a user-specified limit.
This program prompts the user to enter a positive integer. It then validates the input and calculates the sum of all even numbers from 2 up to the entered value using a for
loop. The result is displayed to the user.
#include <iostream>
int main() {
// Declare variables
int userInput, sum = 0;
// Get user input
std::cout << "Enter a positive integer: ";
std::cin >> userInput;
// Validate input
if (userInput <= 0) {
std::cout << "Please enter a positive integer.\n";
return 1; // Exit the program with an error code
}
// Add even numbers up to the user input
for (int i = 2; i <= userInput; i += 2) {
sum += i;
}
// Display the result
std::cout << "The sum of even numbers up to " << userInput << " is: " << sum << std::endl;
return 0; // Exit the program successfully
}
Let's break down the C++ code step by step:
#include <iostream>
This line includes the iostream library, which is necessary for performing input and output operations.
int main() {
This is the beginning of the main function, which is the entry point of any C++ program.
// Declare variables
int userInput, sum = 0;
Here, we declare two variables: userInput
to store the user's input, and sum
to store the sum of even numbers.
// Get user input
std::cout << "Enter a positive integer: ";
std::cin >> userInput;
This prints a message asking the user to enter a positive integer and then reads the user's input from the console into the userInput
variable.
// Validate input
if (userInput <= 0) {
std::cout << "Please enter a positive integer.\n";
return 1; // Exit the program with an error code
}
This block checks if the entered value is less than or equal to 0. If it is, it prints an error message and exits the program with a return code of 1, indicating an error.
// Add even numbers up to the user input
for (int i = 2; i <= userInput; i += 2) {
sum += i;
}
This for
loop iterates over even numbers from 2 up to the entered userInput
, incrementing by 2 in each iteration, and adds them to the sum
variable.
// Display the result
std::cout << "The sum of even numbers up to " << userInput << " is: " << sum << std::endl;
Finally, this line prints the result, showing the sum of even numbers up to the entered value.
return 0; // Exit the program successfully
}
This line indicates that the program has run successfully, and the main function is returning 0, which conventionally indicates a successful execution.