Loops
Loops in the three languages.
C++
Rust
Java
const int items_size = 3;
const int items[items_size] = {1, 2, 3};
for(int i=0; i<items_size; ++i)
cout << items[i] << endl;
for(int i:items)
cout << i << endl;
int i=0;
while(true) {
cout << items[i] << endl;
if(++i == items_size)
break;
}
i=0;
do {
cout << items[i] << endl;
++i;
} while(i<items_size);
let items = [1, 2, 3];
for i in 0..items.len() {
println!("{}", items[i]);
}
for i in &items {
println!("{}", i);
}
let mut i = 0;
loop {
println!("{}", items[i]);
i += 1;
if i == items.len() {
break;
}
}
// Rust does not have do-while loops
final int items[] = {1, 2, 3};
for(int i=0; i<items.length; ++i)
System.out.println(i);
for(int i:items)
System.out.println(i);
int i=0;
while(true) {
System.out.println(i);
++i;
if(i==items.length)
break;
}
i=0;
do {
System.out.println(i);
++i;
} while(i<items.length);
Loops in C++ and Java are essentially the same. Rust uses the keyword in
for use in
for
loops.
The keyword loop
is also introduced for occations where the
code will break inside of the loop after some condition is fulfilled.