Question:
Is this the right way to create a 20 integer array in C++?
anonymous
2008-06-08 10:56:05 UTC
I need to make an array with at least 20 integers that will be searched with the linear and the binary search algorithms. Is this array right?

const int NUM_INTEGERS = 20;
int integer[NUM_INTEGERS];

integer[NUM_INTEGERS][0] = 45
integer[NUM_INTEGERS][1] = 63
integer[NUM_INTEGERS][2] = 12
integer[NUM_INTEGERS][3] = 21
integer[NUM_INTEGERS][4] = 90
integer[NUM_INTEGERS][5] = 79
integer[NUM_INTEGERS][6] = 43
integer[NUM_INTEGERS][7] = 56
integer[NUM_INTEGERS][8] = 29
integer[NUM_INTEGERS][9] = 44
integer[NUM_INTEGERS][10] = 52
integer[NUM_INTEGERS][11] = 37
integer[NUM_INTEGERS][12] = 109
integer[NUM_INTEGERS][13] = 9
integer[NUM_INTEGERS][14] = 85
integer[NUM_INTEGERS][15] = 123
integer[NUM_INTEGERS][16] = 14
integer[NUM_INTEGERS][17] = 60
integer[NUM_INTEGERS][18] = 99
integer[NUM_INTEGERS][19] = 101
Four answers:
Daniel B
2008-06-08 11:07:20 UTC
It's close, but these lines:



integer[NUM_INTEGERS][0] = 45



should look like this:



integer[0] = 45;



integer is a single dimension array, so you only need [0] to access an element. Also needed the ; at the end of the line.
anonymous
2008-06-08 19:24:41 UTC
You can also assign values to arrays this way



const int NUM_INTEGERS = 20;

int integer[NUM_INTEGERS] = {45, 63, 12, 21, 90, 79, 43, 56, 29 , 44, 52, 37, 109, 9 , 85, 123, 14, 60, 99, 101};



The above code is same as

integer[0] = 45;

integer[1] = 63;

integer = 12;

:

:

:

integer[17] = 60;

integer[18] = 99;

integer[19] = 101;



You made just 2 mistakes

1. forgetting ";" after initializing values (remember every statement in C or C++ needs semicolon at end, initializing a variable or array is also a statement of C/C++)

2. It's a one dimensional array so you need only one subscript not 2 like "integer[0]" and not this "integer[NUM_INTEGERS][0]"
jplatt39
2008-06-08 21:03:39 UTC
Kid, grab your textbook and read up about the preprocessor or look it up on line. The preprocessor will read you code snippet and replace all those array things with:



integer[20][1]=...integer[20][19]=101;



If it even COMPILES you are going to get a crash because there is NO integer[20] [ANY NUMBER]! Get that first set of brackets OUT of there. What has your computer done to you that you would torture it so? Never mind.
anonymous
2008-06-08 20:03:32 UTC
Not quite, you have declared a one-dimensional array

http://xoax.net/comp/cpp/console/Lesson10.php



not a two dimensional array:

http://xoax.net/comp/cpp/console/Lesson28.php



Here are some examples of array syntax:

http://xoax.net/comp/cpp/reference/arrays.php



Also, you need to sort the array before you can perform a binary search. This should help you:

http://xoax.net/comp/cpp/console/Lesson20.php


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...