Ask a Teacher



Sir, I am making a c++ program to make a scientific calculator. For the basic addition I used an array b[80].So 80 values can be inputted and added.But the problem is that if I input 10 values only,the array is not complete and doesn't print the answer. For example, int b[80],s=0; for(i=0;i<80;i++) { cin>>b[i]; s=s+b[i]; } cout<<"sum="<

Hi Akash,

of course you can make a program that accepts an arbitrary number of inputs. But your program need to know how much number of inputs are there in advance. You can do it using any of the following methods -

Easy Way -
Ask the user to input the number of elements (or inputs) in advance and store the value in some variable. Then you can limit the loop to iterate till that variable. For example, suppose the number of elements is stored in max_inputs, then you can write something like -

for (i=0; i < max_inputs; i++) {
        // add elements here
}

Hard Way -
The above method is not so intuitive and user has to know number of inputs in advance.  The best way would be to add a "End of Input" at the end of input. For example, you can write a loop to input elements. Inside the loop, increment a counter each time an element is entered. When user inputs a special value, say -1 (or better, EOF if you know how end of file values work!), you can stop reading values into the array, use the counter as the length of the array and finally return the result. See the code below -

// Read input elements until -1 is entered

int no_of_elements;
int array[80];
int input;

no_of_elements = 0;

while (1) {
    cout << "Enter numbers. (-1 to stop)";
    cin >> input;

    if (input == -1)
        break;
    else
        array[no_of_elements] = input;

    no_of_elements += 1;
    if (no_of_elements >= 80)
        break;        // Inputs should not exceed the length of the array.
}

Then loop through a for loop with i < no_of_elements as the condition to find the sum.

Let us know if this works for you!


comments powered by Disqus