How to input an unspecified number of values? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to input an unspecified number of values?

Say I wanted a program to add some numbers, but I didn't want to specify how many numbers, how would I store the input? I tried using an array and leaving the initialisation as a user input, but it didn't work. Anybody else know how to do this? Thanks! I've put my attempt at the code below. I'm a complete beginner so please let me know if there's any obvious oversights/flaws :) https://code.sololearn.com/cpLSeW75BNON/?ref=app

23rd Jun 2017, 3:43 AM
Jory Braun
Jory Braun - avatar
5 Answers
+ 3
You can use dynamic memory allocation with new/delete. For example: + Read the number of numbers that user wants to sum, save it to num variable. + Allocate an array that has a size of num: int[] arr = new int[num]; + Read the numbers and store in arr. + Do the sum. + Release the memory with: delete []arr; Hope that helps.
23rd Jun 2017, 4:42 AM
Thoong Lee
Thoong Lee - avatar
+ 1
You cannot use an array that way. Arrays reserve memory according to their size and do not change. You need a template class like list or vector. The differences between those are somewhat advanced, so just try either one.
23rd Jun 2017, 4:01 AM
1of3
1of3 - avatar
+ 1
you should try to see if it works. I'm pretty sure it'll work
23rd Jun 2017, 1:37 PM
Thoong Lee
Thoong Lee - avatar
0
Thanks for the tip! I haven't gotten to the tutorial on templates yet, so I was wondering if there's a simpler way to do it
23rd Jun 2017, 4:17 AM
Jory Braun
Jory Braun - avatar
0
@Thoong Lee wouldn't that work the same without the "new" and "delete" operators?
23rd Jun 2017, 8:28 AM
Jory Braun
Jory Braun - avatar