#include <iostream>
using namespace std;
int main ()
{
int num1 = 1; //initialize the first term
int num2 = 2; //initialize the second term
int num3 = 0; //initialize the container
int sum = 0; //initialize the sum
//iterate as long as the largest term is less than 4000000
while (num2 <= 4000000)
{
//check for divisibility by 2
if (num2%2 == 0)
{
sum = sum + num2; //add even terms to sum
}
num3 = num2; //store num2 in the container
num2 = num1 + num2; //add num1 and num2 for the next term in the sequence
num1 = num3; //move the number stored in the container to num1
}
cout << sum; //output the sum
}
Add all multiples of 3 or 5 between 1 and 1000
#include <iostream>
using namespace std;
int main()
{
//initialize a variable to store the sum
int sum = 0;
//check each integer between 1 and 1000 for divisibility by 3 or 5 and add them to the sum
for (int i = 0; i < 1000; i++)
{
if (i%3 == 0 || i%5 == 0)
{
sum = sum + i;
}
}
//output the sum
cout << sum;
}
Programming Exercises
I am always looking for new problems to solve in programming. Here are a few of my favorite resources. I will try to keep this up to date as I find more exercise repositories.
Computational and mathematical problems.
General programming problems maintained by the /r/learnprogramming community.