How to do algorithm type functions?

Ok, how would I get my MS-DOS prompt calculator to allow the user to inter multiple integers, and then add/multiply/etc them together? I've done this before, but I do not remember how, because it was SO long ago, and I forgot most of my C++.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
    int total = 0;
    const int MAX = 10;
    int numArray[ MAX ];

    for( int i = 0; i < MAX; i++ )
    {
        cout << "Enter integer: ";
        cin >> numArray[ i ];
        total += numArray[ i ];
    }

    cout << "\nThe total is " << total;

    return 0;
}


Here's a simple program that computes the sum of 10 integers, the integers entered by the user a stored in an array, every time the user enters an integer into the array, that number is added to total. You could replace "total += numArray[ i ]" with "total *= numArray[ i ]" to multiply the integers.
Ok, looks good except for one thing...copying your program directly results in the the program repeating the inquiry to enter an integer for the number of integers I enter. For example...if I did 2 integers it would return "Enter integer:" twice more but not give any results. If I enter 10 integers per MAX, it would return "Enter integer" 10 times, plus give the results.
You could use a sentinel controlled loop to add all the integers you enter until you type in the sentinel. For example...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int main()
{
    int total = 0;
    int num;

    cout << "Enter integer: ";
    cin >> num;

    while( num != -1 )
    {
            total += num;
            cout << "Enter integer: ";
            cin >> num;
    }

    cout << "\nThe total is " << total;

    return 0;
}


This program will keep prompting you for input until you enter "-1" (the sentinel) which causes the program to break out of the loop and display the total of the integers you've entered. This way you can add any number of integers.
Last edited on
A do while loop would be better for mike246's program ;)
Last edited on
Topic archived. No new replies allowed.