77 lines
1.5 KiB
C++
77 lines
1.5 KiB
C++
|
/**
|
|||
|
* File: iteration.cpp
|
|||
|
* Created Time: 2023-08-24
|
|||
|
* Author: krahets (krahets@163.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
/* for ѭ<><D1AD> */
|
|||
|
int forLoop(int n) {
|
|||
|
int res = 0;
|
|||
|
// ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1, 2, ..., n-1, n
|
|||
|
for (int i = 1; i <= n; ++i) {
|
|||
|
res += i;
|
|||
|
}
|
|||
|
return res;
|
|||
|
}
|
|||
|
|
|||
|
/* while ѭ<><D1AD> */
|
|||
|
int whileLoop(int n) {
|
|||
|
int res = 0;
|
|||
|
int i = 1; // <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
// ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1, 2, ..., n-1, n
|
|||
|
while (i <= n) {
|
|||
|
res += i;
|
|||
|
i++; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
}
|
|||
|
return res;
|
|||
|
}
|
|||
|
|
|||
|
/* while ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>θ<EFBFBD><CEB8>£<EFBFBD> */
|
|||
|
int whileLoopII(int n) {
|
|||
|
int res = 0;
|
|||
|
int i = 1; // <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
// ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1, 4, 10, ...
|
|||
|
while (i <= n) {
|
|||
|
res += i;
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
i++;
|
|||
|
i *= 2;
|
|||
|
}
|
|||
|
return res;
|
|||
|
}
|
|||
|
|
|||
|
/* ˫<><CBAB> for ѭ<><D1AD> */
|
|||
|
string nestedForLoop(int n) {
|
|||
|
ostringstream res;
|
|||
|
// ѭ<><D1AD> i = 1, 2, ..., n-1, n
|
|||
|
for (int i = 1; i <= n; ++i) {
|
|||
|
// ѭ<><D1AD> j = 1, 2, ..., n-1, n
|
|||
|
for (int j = 1; j <= n; ++j) {
|
|||
|
res << "(" << i << ", " << j << "), ";
|
|||
|
}
|
|||
|
}
|
|||
|
return res.str();
|
|||
|
}
|
|||
|
|
|||
|
/* Driver Code */
|
|||
|
int main() {
|
|||
|
int n = 5;
|
|||
|
int res;
|
|||
|
|
|||
|
res = forLoop(n);
|
|||
|
cout << "\nfor ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͽ<EFBFBD><CDBD><EFBFBD> res = " << res << endl;
|
|||
|
|
|||
|
res = whileLoop(n);
|
|||
|
cout << "\nwhile ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͽ<EFBFBD><CDBD><EFBFBD> res = " << res << endl;
|
|||
|
|
|||
|
res = whileLoopII(n);
|
|||
|
cout << "\nwhile ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>θ<EFBFBD><CEB8>£<EFBFBD><C2A3><EFBFBD><EFBFBD>ͽ<EFBFBD><CDBD><EFBFBD> res = " << res << endl;
|
|||
|
|
|||
|
string resStr = nestedForLoop(n);
|
|||
|
cout << "\n˫<EFBFBD><EFBFBD> for ѭ<><D1AD><EFBFBD>ı<EFBFBD><C4B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> " << resStr << endl;
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|