Basic for loop problem ):

Hey I'm doing an exercise and I was wondering if anyone can help me out?

The question : Write a program that requests the user to enter two integers. The program should then calculate and report the sum of all the integers between and including the two integers. At this point, assume that the smaller integer is entered first. For example, if the user enters 2 and 9, the program should report that the sum of all integers from 2 through 9 is 44.

=============

I have a code but when I enter 2 and 9 as the numbers, it comes out with a total of 32. Could someone please help me pinpoint where my error is? I have an idea but I'm not sure (something with my test expression?)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
int main()
{
    
    int iFirst;
    int iSecond;
    cout << "Please enter a digit: " << endl;
    cin >> iFirst;
    cout << "Please enter a second digit: " << endl;
    cin >> iSecond;
    
    int iTotalDisplay = 0;
    int iNewTotal;
    for (int counter = 0; counter < (iSecond-iFirst); ++counter, ++iFirst)
    {
        iNewTotal = iFirst + (iFirst + 1);
        iTotalDisplay = iTotalDisplay + iNewTotal;
    };
    cout << iTotalDisplay << endl;
    
    
    
        
        return 0; 
    
}
I don't understand your approach, but this can be written much simpler:
1
2
    int iTotalDisplay=0;
    for (int i=iFirst;i<=iSecond;i++)iTotalDisplay+=i;


As a note, i (j, k, l...) is the standard descriptor for a non-descriptive counter variable and is preferable to the lengthy "counter".
Also, the Hungarian notation is considered to be bad style by many people.
i'm not sure i understand my approach either.. i just kind of pulled it out of thin air.

Thank you for the simple method ~_~

and I only use hungarian notation cause of XoaX.net , guess I should stop?
Topic archived. No new replies allowed.