1.
You need to start at 1, so initialize a value, let's say i, to that value. Your while loop should go up to and including 104. After printing the first eight values, i will be eight. Increment it, and i = 9. At this point, we need to sum the last eight values and go to a new line. To sum of the first n integers is n*(n + 1)/2. If you don't know that formula, check out this link:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/runsums/triNbProof.html
However, in our case, i is 9 and we only want to sum the first 8 integers. So subtract 1 from each term in the numerator. Also, we don't want to sum all of the integers up to that point, just the last eight. So, subtract the sum of all integers before this point. You could probably simplify the expression I've used, but it's just the first one that came to mind.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i <= 104)
{
cout << i << " ";
i ++;
if ((i - 1) % 8 == 0)
{
cout << " a sum of " << (i*(i - 1)/2) - ((i - 8)*(i - 9)/2) << endl;
}
}
}
|
2.a) You'll need to use another while loop this time (or you could use a for loop). Initialize a result = 1 and a value i = n. Each time through the loop, multiply result*i, then decrement i until you get to one. Alternatively, you could start the while loop with i = 1 and go up to i = n.
2.b) Are you getting the hang of loops yet? For this one, your counter i should go from one to ten. Start with a result = 0. Each time through the loop, add 1/i to the result.
2.c) I'll leave this one completely up to you. It's basically just a combination of 2.a) and 2.b).