Quote:
Originally Posted by jamestl2
Alright, I still kinda have no idea what you just said there, John. What do you mean by "it increasing i by 1 each time"?
|
Sorry I didn't explain it enough
i is an assumed name of a variable. it can be anything though.
usually when you loop through elements of an array. assuming array name is arr
you need to access its elements like that
arr[0]
arr[1]
arr[2]
etc..
till arr[aSize-1]
where aSize is variable representing the max number can be in the array
say aSize=128 then array elements will be from 0 till 127
it is unreasonable to access it literally like typing
cin>>arr[0]
cin>>arr[1]
till
cin>>arr[127]
so you need to use a loop
with looping usually you loop whenever some condition is true and stop once it's false
you can implement that like the following example code
Code:
int i=0;//just a variable called i can be any thing but using i is common
while(i<5)
{
i++;//increase i by one. the same as i=i+1
cout<<i<<endl;
}
if you traced that code you will know it runs the command cout<<i
and if you run it it will print like
in another saying the code above do exactly the same if you used cout to output numbers from 0 to 4
Code:
cout<<0<<endl;
cout<<1<<endl;
cout<<2<<endl;
cout<<3<<endl;
cout<<4<<endl;
having that great feature of loop we can input the whole elements of the array from 0th till 127th element a simple loop instead of typing cin 128 times( from 0 till 127)
Code:
int i=0;//you need to declare and initialize the variable
while(i<aSize)//or i<128
{
cin>>arr[i];
i++;
}
simply that code will keep getting data from user for thoe whole 128 elements (from 0 till 127)
Quote:
|
128 is only suppose to be a potential for the array, I don't think you keep going regardless of what the user typed in, it's just a "validate the number" checker.
|
yes in the code above you keep going regardless of what the user typed in
however you need to check if the inputted value is -1 is so then you need to get out of the loop some how
to do that you can modify the code above to be like the following
Code:
int i=0,data;//we need another variable to check input data before assigning it to the array
while(i<aSize)//or i<128
{
data>>arr[i];
if(data==-1)//user typed -1 so get out of the loop using break statement
break;
else
{
arr[i]=data;//user didn't type -1 so assign input data to a new element in the array
i++;
}
}
I tried to write it simple as much as I could. I hope I could help
