Change Contents of the Bubble
View this PageEdit this PageUploads to this PageHistory of this PageHomeRecent ChangesSearchHelp Guide

Matlab to Java quick tutorial: for and while loops

while loops

So let's write a while loop that'll go from 0 to 9 (for a total of 10 items) and print the current iteration to the console (Java)/main window(MATLAB)

MATLAB

%Ver 1.
i=0;
while(i ~=10)
  disp(i);
  i = i + 1;
end

%Ver 2.
i=0;
while(i < 10)
  disp(i);
  i = i + 1;
end

Java

int i = 0;
while(i != 10){
  System.out.println(i);
  i++;
}//Ver 1.

int i = 0;
while(i < 10){
  System.out.println(i);
  i++;
}//Ver 2. 


for loops

Let's write a for loop that work just like the while loop described above.

MATLAB

%Ver 1.
for i=0:1:9
  disp(i);
end

%Ver 2. You can also omit the 1
for i=0:9
  disp(i);
end 


Java

for (int i=0; i<10; i++){
  System.out.println(i);
}//Ver 1.

for (int i=0; i<=9; i++){
  System.out.println(i);
}//Ver 2.