C#編程基礎第四章:循環


一、為什么需要循環

假設現在我們要向屏幕輸出 1 到 8 之間的所有整數,可以一句一句實現,但這樣非常麻煩,有規律的工作可以使用循環完成。

二、循環語句

在 C#中提供了 4 種循環結構,它們都可以達到循環的目的。

  1. for 循環
  2. while 循環
  3. do…while 循環
  4. foreach 循環

本章只涉及前三種循環,foreach 循環將在以后學習中進行講解。

2.1、for

在講解 for 循環用法之前,我們首先分析一下輸出 1 到 8 之間整數的這個案例。我們知道,輸出
這個動作是重復執行的,需要通過循環解決。那么問題來了,循環從哪里開始,在哪里結束,每次輸
出的數據是不同的,如何去控制呢?數據從 1、2、3、…一直變化到 8,我們可以讓一個變量初始化為
1,然后每次輸出后變量累加 1,一直到變量的值大於 8,就可以結束輸出。這里的變量我們稱之為 循
環變量,它控制了循環的整個過程。它的初值為 1,就表示了循環從哪里開始;每次輸出后累加 1,就
表示了中間變化過程;直到大於 8,就表示了循環的結束。

2.1.1、概要

如何使用 for 循環來實現呢?先了解 for 循環的語法結構:

 
         

for( 表達式 1; 表達式 2; 表達式 3)

語句塊; 

在此語法中,各個部分的含義說明如下:
(1)表達式 1:通常是用來給循環變量賦初值,一般是賦值表達式;

(2)表達式 2:通常是循環進行的條件,一般是關系或邏輯表達式;

(3)表達式 3:通常用於修改循環變量的值,一般是復合賦值語句;

(4)語句塊:要重復執行的代碼,也稱之為循環體。

用 for 循環輸出 1-8 的整數。

為什么就能輸出 1 到 8 之間的整數呢?對此,我們要了解 for 循環的執行順序。for 循環的執行

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 8; i++)
            {
                Console.WriteLine(i+",你好");
            }
        }
    }
}

順序如下:

(1)執行表達式 1;

(2)判斷表達式 2 的真假;

(3)如果為真,則執行{}中的語句塊;然后執行表達式 3,回到第 2 步;

(4)如果為假,則結束 for 循環。

相應的流程圖如下所示:

對照這執行過程,我們很容易就能得到輸出的結果了。注意:此例的 i++也可以看做賦值表達
式,相當於 i+=1 或者 i=i+1。

小貼士:流程圖是用圖形的形式來描述算法的步驟,直觀形象,易於理解;一般用箭頭表示流程
線,矩形表示處理框,菱形表示判斷框等。

2.1.2、示例

用 for 循環實現計算 1+2+3+…+20 的和。

用 for 循環求出 1-30 之間 2 的倍數的所有整數,然后輸出。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //用 for 循環求出 1-30 之間 2 的倍數的所有整數,然后輸出。
            for (int i = 2; i <= 30; i=i+2)
            {
                Console.WriteLine(i);
            }

        }
    }
}

用 for 循環輸出 100 以內的偶數。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 0;
            //用 for 循環輸出 100 以內的偶數。
            for (int i = 1; i <=100; i++)
            {
                //如果一個數與2求余數結果為0則是偶數
                if (i % 2 == 0)
                {
                    Console.Write("{0}\t",i);
                    n=n+1;
                }
            }
            Console.WriteLine("偶數的個數是{0}",n);
        }
    }
}

 

2.2、while

while 循環語句根據循環條件執行一個語句塊零次或者多次,它的基本語法格式如下:

while( 布爾表達式) 
{ 
語句塊; 
} 

while 語句的執行順序如下:
1)計算布爾表達式;

2)如果布爾表達式的值為 true,則執行{}中的語句塊,執行完畢重新計算布爾表達式的值是
否為 true;

3)如果布爾表達式的值為 false,則結束整個循環。

下面我們看一些使用 while 循環實現的例子。
例 4.5 用 while 循環輸出 8 個的整數。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int i=1;
            while (i<=8)
            {
                Console.WriteLine("數字"+i);
                i++;
            }
        }
    }
}

從此例中可以看到,其實 while 循環語句就相當於把 for 循環的第一個表達式移到了循環的前面
賦值,而把 for 循環的第三個表達式移到了循環體的最后。所以掌握了一種循環,另外的循環就能觸
類旁通了。

另外 for 循環語句一般用於確定循環次數的情況,而 while 循環語句的特點是可以沒有循環變
量,可以不寫第一個表達式和第三個表達式,只寫一個條件表達式就夠了,循環的次數是不固定的。

1-100之和

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int i=1,sum=0;
            while (i<=100)
            {
                sum += i;  //sum=sum+i;
                i++;
            }
            Console.WriteLine("和是:"+sum);
        }
    }
}

 

1-100之積

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            double i = 1, sum = 1;
            while (i<=100)
            {
                sum *= i;
                i++;
            }
            Console.WriteLine("積是:"+sum);
        }
    }
}

例 4.6 老師很生氣后果很嚴重,老師心情不好就會罰同學們跑圈圈,跑多少圈不是固定的,要
跑到老師心情變好為止,用 while 循環實現模擬跑圈圈的功能,代碼如下:

分析:老師心情不好則進入循環跑圈圈,心情好則退出循環。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            //定義變量,用於記錄老師的心情好壞,yes表示好,no表示不好
            string feelGood;
            //提示輸入
            Console.Write("老師的心情好嗎?(yes/no):");
            //從鍵盤輸入老師現在的心情
            feelGood = Console.ReadLine();
            //如果心情為no,則循環繼續
            while (feelGood=="no")
            {
                Console.WriteLine("跑圈圈........");
                //再次提示輸入老師的心情狀態
                Console.Write("老師的心情好嗎?(yes/no):");
                feelGood = Console.ReadLine(); //從鍵盤輸入老師的心情 yes表示好,no表示不好
            }
        }
    }
}

輸出:

2.3、 do…while

do…while 循環和 while 循環是類似的,do…while 循環的基本語法格式如下:

do
{ 
語句塊; 
}while( 布爾表達式 );

while 語句的執行順序如下:

(1)首先執行語句塊;

(2)之后計算布爾表達式的值,如果為 true,則重新執行語句塊,然后繼續判斷布爾表達式;

(3)如果布爾表達式的值為 false,則結束整個循環。

相應的流程圖如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 1;
            do
            {
                Console.WriteLine(i);
                i++;
            } while (i<=10);
        }
    }
}

while 和 do…while 都用來控制代碼的循環,但 while 語句適用於先條件判斷,再執行循環結構
的場合;而 do…while 則適合於先執行循環結構,再進行條件判斷的場合。也就是說,使用 while
時,如果一開始條件表達式不成立,循環結構一次也不會執行;而使用 do…while 時,即使條件一開
始不成立,程序也至少執行一次循環結構。這是 while 和 do…while 的區別。

例 4.7 小明過兩天就要登台表演了,今天要再好好練習一下,如果排練的效果比較滿意就不用
再排練了,但是如果效果還不滿意則需一直排練下去,用 do…while 循環實現該功能。代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            String isOk;
            do
            {
                Console.WriteLine("小明排練一次");
                Console.WriteLine("是否滿意了(yes/no)");
                isOk=Console.ReadLine();
            } while (isOk.ToLower()=="no");
        }
    }
}

 

從此例中也可以看到排練無論如何都要先做一次,然后看情況是否還要繼續做。do…while 循環
語句的特點就是先執行后判斷。

例 4.8 編寫程序接收用戶輸入一個月份,如果月份輸入正確給出相應提示,如果不正確則讓用
戶重新輸入,用 do…while 循環語句實現功能。代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            //變量,月份
            int month;
            do
            {
                //提示
                Console.Write("請輸入月份(1-12):");
                //輸入
                month=Convert.ToInt32(Console.ReadLine());
            } while (month<1||month>12);  //如果月份小於1或月份大於12則重新輸入
            //輸出月份
            Console.WriteLine("您輸入的月份是:"+month);
        }
    }
}

 

課堂作業:使用 do…while 循環完成下列題目

(1) 輸出大寫字母 A-Z。

(2) 求 1-100 之間所有偶數的和。

三、break 和 continue

break 語句我們並不陌生,在之前的 switch 語句中就使用過,它的作用是結束 switch 語句,那
如果在循環語句中使用 break 語句,它的作用就是退出循環。

在上面的例子 4.8 中,如果月份輸入有誤,沒有錯誤提示就直接讓用戶再次輸入月份了,程序的
功能雖然實現了,但對用戶的操作並不友好,如果我們希望錯誤也有相應的提示,則可以將上面的例
子稍微改一下,加入錯誤提示,然后通過 break 語句來控制退出循環。代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            //變量,月份
            int month;
            do
            {
                //提示
                Console.Write("請輸入月份(1-12):");
                //輸入
                month = Convert.ToInt32(Console.ReadLine());
                //如果月份小於1或月份大於12則重新輸入
                if (month < 1 || month > 12)
                {
                    Console.WriteLine("輸入錯誤,請重新輸入");
                }
                else
                {
                    break;  //結束循環
                }
            } while (true);  
            //輸出月份
            Console.WriteLine("您輸入的月份是:"+month);
        }
    }
}

另外一個關鍵字 continue,也常用在循環當中,不過它的作用是用於終止本次循環,去執行下一
次循環。continue 通常跟 if 語句配合,用來加速循環過程。

例 4.10 在循環中使用 continue 語句求 1-100 之間所有奇數的和。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0, sum = 0;
            while (i<100)
            {
                i++;
                //如果是偶數當次循環結束
                if (i % 2 == 0)
                {
                    continue;  //結束當次循環,開始下一次循環,后面的語句將不會執行
                }
                sum = sum + i;
            }
            Console.WriteLine("和是:"+sum);
        }
    }
}

2500

四、嵌套循環結構

沒有進行嵌套的循環稱為一重循環結構。循環結構(for、while、do…while)可以進行相互嵌套,
構成二重、三重,甚至更多重的循環結構,如下列舉了一些二重循環的形式:

一般常用的是二重和三重循環。循環的層數越多,運行時間越長,程序越復雜。下面來使用循環
嵌套來解決問題

例 4.11 使用星號輸出矩形。

分析:要畫一個矩形就是要輸出很多行星星,我們可以使用循環來實現輸出很多行的功能,循環
一次則輸出一行星號,再循環一次則再輸出一行星號。

實現代碼如下:

static void Main()
{
for(int i=1;i<=5;i++)  //循環5次則輸出5行
{
Console.WriteLine("**********");  //輸出一行星星
}
}

上面代碼已經可以實現畫矩形的功能了,但是每行要輸出多少個星星不好控制,假如一行要輸出

20 的星星,則需要我們自己數 20 個,很麻煩,那么其實輸出一行星星也就是要重復的輸出很多個星

星,這個重復的工作同樣可以交給循環來完成,也就是在循環語句中再寫循環語句,就是嵌套的循環

語句了,我們將上面代碼修改成嵌套的循環看看。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <=10; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
        }
    }
}

 

例 4.12 通過嵌套 for 循環打印出一個九九乘法表。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            //控制行數
            for (int i = 1; i <= 9; i++)
            {
                //控制列數
                for (int j = 1; j <= i; j++)
                {
                    //輸出表達式,注意j與i的順序
                    Console.Write("{0}x{1}={2}\t",j,i,j*i);
                }
                //一行結束時,換行
                Console.WriteLine();
            }
        }
    }
}

 

五、作業

1、輸入十個數,輸出最大數。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication2
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             //認為第1個數是最大數
13             Console.Write("請輸入第1個數:");
14             int max = Convert.ToInt32(Console.ReadLine());
15 
16             //從第二個數開始與最大數比較
17             for (int i = 2; i <= 10; i++)
18             {
19                 Console.Write("請輸入第{0}個數:",i);
20                 int n = Convert.ToInt32(Console.ReadLine());
21                 //如果n比最大的數還大,最大數的數就是n
22                 if (n > max)
23                 {
24                     max = n;
25                 }
26             }
27             Console.WriteLine("最大數是:"+max);
28 
29         }
30     }
31 }
View Code

 

2、在屏幕上輸出一個三角形。

    *

   ***

  *****

 *******

*********

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication1
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             //外層循環控制行數 5
13             for (int i = 0; i < 5; i++)
14             {
15                 //控制每行前部的空格數  空格數=5-1-行數
16                 for (int k = 0; k < 5-1 - i; k++)
17                 {
18                     Console.Write(" ");
19                 }
20 
21                 //控制星號個數=行數*2+1
22                 for (int j = 0; j < i * 2 + 1; j++)
23                 {
24                     Console.Write("*");
25                 }
26 
27                 //換行
28                 Console.WriteLine();
29             }
30         }
31     }
32 }
View Code

 

3、完成第四章所有上機與理論作業,預習第五章

六、考試

1、使用for、while、do...while實現1-50間的數之和。

2、輸入年份與月份,輸出天數,要求考慮2月(潤年29,平年28),當用戶輸入錯誤時要求重新輸入。

3、輸出下面的形狀

A

BBB

CCCCC

DDDDDDD

EEEEEEEEE


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM