Hi all!
First, I am new here, but I have read the forum as a guest from time to time.
I am also quite new to C++, but have learnt a little, and solved a couple of obstacles in the way. Until now. At this point I am completely stuck, hence my appearance at this forum.
I am certain my question is ”simple” for those of you who are well versed in C++, please bear in mind that I am (as stated above), pretty new to this language.
Anyway, the problem I have is as follows:
A user is asked to input two integers, the function I want to write is supposed to add the numbers, and the ones in between, together, as follows:
1 2
|
cout << "Please enter two numbers: ";
cin >> no1 >> no2;
|
Now, let's say the user input is 2 and 4. The function should then add 2+3+4. If the user enters 1 and 6, the function should do 1+2+3+4+5+6, and so on.
(Even when I look at it now, I go ”this should be EASY!!!”).
In other words, the first number, and all the numbers in between and up until the last number.
I have tried various (all!?!) types of loops (because I'm guessing a loop must be used in order to find out how many times the function should add). One example looks as follows:
1 2 3 4 5 6
|
for ( no1; no1 <= no2; no1++)
{
result = no1 + no1+1;
}
cout << result;
|
...it doesn't work.
I tried the while variant:
1 2 3 4
|
while (no1 <= no2)
{
result = no1 + ++no1;
}
|
...doesn't work either. I also tried with a do-while loop, but I'll spare you from that.
Now, my guess is that it might not be the loops themselves, rather my logical thinking that is at fault. Furthermore, I am not ”allowed” to use arrays or any fancy stuff in order to solve this dilemma.
Yes folks, I have searched the mighty Google for answers - the closest I came was something called a ”factorial”, but it did not seem to work - mainly because factorials seem to always go from whatever value down to 1. Whereas I need to go from ”point a to b” so to speak.
Ok, this turned into quite a long first post. To sum it up and repeat;
I need a function that adds x+x+x+x dependeding on user input.
I hope I can give back to the community here once I learn a little more.
Thanks for reading this,
HMW