Loop structure:
Cyclic structure may reduce the workload of the source code written in duplicate, to describe the implementation of certain repeat algorithm, a program loop structure Structured Programming a computer to play the most expertise.
Loop structure can be seen as a combination of a conditional statement and the statement of the steering back.
Loop structure of the four elements:
1. loop variable
2. loop
3. cycling conditions
4. iterator
while loop:
while loop is the most basic cycle, while the statement before the start of first determines the result of a Boolean expression, if it is true (true), the loop body is executed, otherwise, out of the loop.
expression:
the while (Boolean expressions) { // the while the first determination of the Boolean expressions, the true start of the loop is the loop body // iteration of the loop iterator // iterations (typically from unary plus (++), or from minus (-)), the iteration is finished after the return to continue the next cycle is determined whether }
Example:
① while loop and the calculated 0-100:
package exercise; / ** * @author Liu will * While loop * (Cycle four conditions must be met: 1, initialization; 2, condition judgment; 3, loop; 4, iteration) * While loop: 0 to 100 and calculates how much */ public class TestWhile { public static void main(String[] args) { int a = 0; int sum = 0; while(a<=100) { sum += a; a++; } System.out.println("0~100的和为:"+sum); } }
②使用while循环计算0-100间的所有偶数和与基数和:
package com.lxj.cnblogs; /** * @author 刘小将 * while循环 * 计算0-100间的所有偶数和与基数和 */ public class TestWhile{ public static void main(String[] args){ int oddSum = 0; //奇数 int evenSum = 0; //偶数 int i = 0; //声明循环变量 while(i <=100){ if(i % 2 !=0){ oddSum += i; i++; }else{ evenSum += i; i++; } } System.out.println("oddSum is:"+oddSum); System.out.println("evenSum is:"+evenSum); } }