Day15 (for loop, output 99 multiplication table, output the number within 1000 that can be divisible by 5)

for loop

  • All structures can be represented by while or do...while, but the for loop makes some loop structures easier.
  • The for loop statement is a general structure that supports iteration, and is the most effective and flexible loop structure.
  • The number of times the for loop is executed is determined before it is executed.
  • The syntax format is as follows:
for(初始值;布尔表达式;更新)//代码语句

Exercise 1:

Calculate odd and even sums between 0 and 100:

public static void main(String[] args) {
    
    
      int oddsum = 0;
      int evensum =0;
              //初始化值;条件判断;迭代
        for (int i = 0; i <= 100; i++) {
    
    if (i%2!=0) //i%2!=0  i除以2余0
        {
    
    oddsum=oddsum+i;}else {
    
    evensum=evensum+i;}

        }            System.out.println(oddsum);
        System.out.println(evensum);

Exercise 2:

Output the number from 1 to 1000 that is divisible by 5, and output 3 per line:

public static void main(String[] args) {
    
    
    int a=1;
    for (int i= 1;i<=1000;i++){
    
    if (i%5==0){
    
    
        System.out.print(i+"\t");}if(i%15==0){
    
    
        System.out.println();

(Wrong expression written by myself:)

//自己写的:输出1到1000能被5整除的数,每行输出3个;
int c=0;
for (int i = 1; i <= 1000; i++)
{
    
    int d=i; if (d%5==0){
    
    c=1;}
while(d%5==0 && c<=3){
    
    
    System.out.print(d+"   ");d=d+1;c=c+1;
    //存在换行错误;

Exercise 3:

Output 99 multiplication table:

//自己写的,一次写对~~~
public class A0118b {
    
    
    public static void main(String[] args) {
    
    
        int a =1;
        for (int i = 1; i <= 9; i++) {
    
    while (a<=i){
    
    
            System.out.print(a+"*"+i+"="+(a*i)+"\t");a=a+1;
        };a=1;
            System.out.println();
        }
    }
}
//另一种写法:
for (int c = 1; c <= 9; c++) {
    
    
    for (int d = 1; d <= c; d++) {
    
    
        System.out.print(c+"*"+d+"="+(c*d)+"\t");

    }
    System.out.println();

Guess you like

Origin blog.csdn.net/SuperrWatermelon/article/details/112760953