This is the solution in c++, using a user-defined function. Now, it's really much simpler, and you don't need the function at all. All of the stuff inside of the function can just be put into main, but I did it to show off how user-defined functions work.
// We'll be using a user defined function.
int nat_addition(int);
// This function accepts an integer as a parameter.
// The function defintion is found below main.
int main()
{
int up_to;
// Prints out a bit of a menu
cout << "Project Euler, problem 1:";
cout << "\nIf we list all the natural numbers below 10 that are multiples of";
cout << "\n3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.";
cout << "\nFind the sum of all the multiples of 3 or 5 below 1000.";
// Asks for and accepts the upper limit of the number you want
cout << "\n\nEnter the number up to which you would like to find";
cout << "\nthe sum of the multiples of 3 or 5: ";
cin >> up_to;
cout << "\n" << nat_addition(up_to);
system("PAUSE");
return 0;
}
// nat_addition finds the sum of all of the multiples of 3 or 5
// below a specified number.
int nat_addition(int Below)
{
int sum = 0; // Note that sum is initalized to 0
// This is to prevent sum from having a value
// already stored in it that we don't want.
for (int i = 1; i <= Below; i++) { // This for loop
if (i%3 == 0 || i%5 == 0) { // is designed to loop
sum += i; // through every number between
} // one and the integer specified. If the
} // number is divisible by 3 or 5, it is added
// to sum, which is then returned.
return sum;
};
No comments:
Post a Comment