understanding use of arrays | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

understanding use of arrays

what is the purpose of an array? when it is good to use? why is the for loop recommended over other loops for … a. locating (indexing) the position of values inside an array.? b. inputting values in an array can you do a and b in other loops: the while loop, the do loop? if statements? is there a way to get the user to input his/her own values and to locate the position of user-inputted values?

27th Jan 2017, 7:49 PM
Mich
Mich - avatar
2 Answers
+ 2
1. What is an array used for: For example you need to count 100 smallest prime numbers. You will need to store them somewhere. Declaring 100 variables is not a way to do it. But you can declare a space for 100 in one line just declaring an array. The other thing that you can easily reach any value of an array, I mean instead of int i; switch(i) { case 0; a0; case 1: a1; case 2: a2; etc. you can just write a[i]; Also, if you do not know in advance how much value will be needed to store, you can use a list. Once an array is declared, its size can not be changed, unlike a list. 2. For loop is recommended to be used when you know in advance how many iterations will be needed to do. In case of an array you do - the number of iterations will be the same as the size of array. In such cases for is recommended over while because for is more clear or readable. You can easily see the initialization of iterator, condition and changing the iterator in one place, but in while it all would be in different places and thats why harder to read. 3. In C++ you can get a user input by cin or cin.getline. cin.getline is used for strings and cin for other types. For example: //input of number using namespace std; int x; cout << "Please, enter a number: "; cin << x; //input of string using namespace std; char[100] x; cout << "Please, enter a string: "; cin.getline(x, 100); When a programm reaches cin or cin.getline, it stops and waits till the user will type a value from keabord and press "Enter". After pressing "Enter" programm will continue to run and a user inputed value will be stored in variable x.
27th Jan 2017, 9:55 PM
Антон Обожин
Антон Обожин - avatar
0
wow very helpful. thank you very much
27th Jan 2017, 11:04 PM
Mich
Mich - avatar