#include <iostream>
usingnamespace std ;
int main()
{
int first;
int second;
int n=1;
//maybe i hav to declare array variable here
int allFirst;
int allSeconds;
do
{
cout << "enter first number: ";
cin >> first;
allFirst[n] = first;
cout << "enter second number: ";
cin >> second;
allSecond[n] = second;
n++;
}while(first > second);
}
so, its unknown how many loops...so whts arrays lengths. its varies
i hav to store all the inputs using Array. cant use another method
& although in example i used only int, i might have to add char, unsigned etc also
first & second are not arrays, but single objects. You have to ways to go:
1) Use the std::vector (based on what you've written, I recommend option #2)
2) Declare first & second as arrays, like so: int Array[N] (N is a constant integer)
Finally, the offset (index) range of an array starts at 0 (zero) and ends at N - 1 (N is the number of elements the array has).
#include <iostream>
usingnamespace std ;
int main()
{
int first;
int second;
constint n=0;
int m=1;
//maybe i hav to declare array variable here
int allFirst[n];
int allSecond[n];
do
{
cout << "enter first number: ";
cin >> first;
allFirst[m] = first;
cout << "enter second number: ";
cin >> second;
allSecond[m] = second;
m++;
}while(first > second);
for(int x=1; x <= m; x++)
{
cout << allFirst[x] << "\t" << allSecond[x] << endl;
}
system("pause");
}
& the output
enter first number: 9
enter second number: 8
enter first number: 6
enter second number: 5
enter first number: 3
enter second number: 2
enter first number: 5
enter second number: 4
enter first number: 1
enter second number: 2
4 8
2 5
3 2
7 0
0 4
2 2
1 3
Press any key to continue . . .
This is dangerous. Here, you're creating an array of zero elements. Any form of access to the array will cause a segmentation fault (accessing memory that your program doesn't own). When I said create an array, I was expecting something like this:
1 2 3 4 5 6 7 8 9 10 11
int main()
{
constint ARRAY_LENGTH(10); // Same as ARRAY_LENGTH = 10;
int MyArray[ARRAY_LENGTH]; // Creates an array of 10 elements.
// Access the last element:
MyArray[(ARRAY_LENGTH - 1)];
// Access the first element:
MyArray[0];
}
As the length of the arrays is not know, it is a poor choice to use fixed length arrays.
Use a dynamic container (vector, list, deque, queue, stack, valarray, etc)
About your code
You are declaring your arrays of size 0.
Accessing out of bounds is an error, it would not resize the array (it has fixed length) Framework already pointed that you can access from 0 to n-1, ¿/why then are you looping from 1 to n?
tnx again Framework. but again, array length will be UNKNOWN. i cant declare that like u did 10 !
ne555,
u are right. i googled a lot & learn something abt vector & list
i tried a lot but cannot use any of those in my code. As im a very NOVICE at c++
i'll be very grateful if u kindly show me an example of those (lets say List) with my given code :)