for, while do_while.
for ();
while ( );
do_while , ( ).
1. for ()
for :
for(; ; )
, , . ( ). , , .
, .
, FALSE .
, .
, , . , .
1. , 1 10 :
for (int i = 1; i <= 10; i++)
Console.Write("{0} ",i);
( 1.) , , , .
1A. :
1 2 1 2 3 1 2 3 4 1 2 3 4 5 | for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) Console.Write(" {0}", j); Console.WriteLine(); } |
5 5 5 5 5 6 6 6 6 7 7 7 8 8 | for (int i = 5; i <= 9; i++) { for (int j = 1; j <= 10-i; j++) Console.Write(" {0}", i); Console.WriteLine(); } |
2. 1 100.
int s = 0;
for (int i = 1; i <= 100; i++)
s += i;
Console.WriteLine(s);
i 1. 1 i, s i.
, i 101. , , s, 100.
for s 5050 1 100.
:
int s = 0;
for (int i = 1; i >= 100; i++) s += i;
.
3. n
.
, .
, .. ( , , 1), for.
|
|
Console.Write("n=");
string w = Console.ReadLine();
int n = Convert.ToInt32(w);
double s = 0;
for (i = 1; i <= n; i++)
s = s + 1.0 / i / (i + 1); // s += 1.0 / i / (i + 1)
Console.WriteLine("s={0}",s);
, , 1.0.
:
1. , ( ) .
4. y=y(x), , ( -3 14) (1,8). , 100, .
double Xn=-3, Xk=14, dX=1.8, y;
Console.WriteLine("------------------------------");
Console.WriteLine("| X | Y |");
Console.WriteLine("------------------------------");
for (double x = Xn; x <= Xk; x += dX)
{
if (x < 0) y = 0;
else if (x < 10) y = x;
else y = x * x;
if (y>100) Console.WriteLine("| {0,9:F2} | {1,9:F0} |", x, y);
else Console.WriteLine("| {0,9:F2} | {1,9:F2} |", x, y);
}
Console.WriteLine("------------------------------");
:
.
2. while ( )
while , :
while (<>) < >;
while . true, . , false, . , , .
5. 1 100.
1 | 2 |
int s = 0, i = 1; while(i <= 100) { s = s + i; i++; } | int s = 0; i = 100; while(i > 0) { s = s + i; i--; } |
s ( = 0) i ( = 1) 1. , i 101 i<= 100. | s ( = 0) i ( = 100) 1. , i i > 0. |
, , :
3 | 4 | 5 |
int s = 0, i = 1; while(i <= 100) s += i++; | int s = 0; i = 100; while(i > 0) s += i--; | int s = 0, i = 0; while(i < 100) s += i++; |
5 3. . , .
|
|
6. () p q.
. Ļ, , . for , .. . p q :
Console.Write("p=");
int p = int.Parse(Console.ReadLine());
Console.Write("q=");
int q = int.Parse(Console.ReadLine());
int pp = p, qq = q;
while (p!= q)
if (p > q) p -= q;
else q -= p;
Console.WriteLine("({0},{1})={2}", pp,qq,p);
7. n.
. , 10, . , , 0.
Console.Write("n=");
int n = int.Parse(Console.ReadLine());
int s=0;
while (n > 0)
{ s += n % 10;
n /= 10;
}
Console.WriteLine(" {0}", s);
3. do_while ( )
do_while , .
do < > while (<>);
do_while , < > . < >, <>.
, do_while .
, .
8. n.
7, ,
int s=0;
while (n > 0)
{ s++;
n /= 10;
}
n=0 (s=0), .. 0. , :
Console.Write("n=");
int n = int.Parse(Console.ReadLine());
int s = 0;
do
{ s++;
n /= 10;
}
while (n > 0);
Console.WriteLine(" {0}", s);