Loop Iteration Efficient
You have a loop that iterates over 1,000 i开发者_运维百科tems. You want to add a newline to every four items. The items are in an array structure that have numeric index starting at 0. How do you do it?
FWIW:
for (int i = 0; i < list.size(); ++i) {
// you want to 'do it' with list[i] here
if (0 == (i+1)%4))
{
// 'you want to add a new line' here
}
}
Just in case what you are really trying to ask is "How do I print these items, four to a line?" here's one way
int nOnLine = 0;
for (i = 0; i < 1000; i++){
// print item i
nOnLine++;
if (nOnLine >= 4){
// print newline
nOnLine = 0;
}
}
if (nOnLine > 0){
// print newline
nOnLine = 0;
}
for (int i = 0; i < list.size(); i += 4) {
// add to the item
}
The above iterates over every fourth item instead of every single item.
for(i=3;i<len;i=i+4) { // where len is the length of your array
ary[i]+='\n'; // use string append operator of your language.
}
which will add a newline to every fourth item, i.e. items 3, 7, 11, etc.
EDIT
Changed to fulfill the OP's criteria.
精彩评论