2017資訊營
Array/Loop
We know how to use variables
but how about MANY variables?
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int num1, num2, num3;
cin >> num1 >> num2 >> num3;
return 0;
}
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int num1, num2, num3, num4, num5,
num6, num7, num8, num9, num10,
num11, num12, num13, num14, num15,
num16, num17, num18, num19, num20,
num21, num22, num23, num24, num25,
num26, num27, num28, num29, num30,
num31, num32, num33, num34, num35,
num36, num37, num38, num39, num40,
num41, num42, num43, num44, num45,
num46, num47, num48, num49, num50,
num51, num52, num53, num54, num55,
num56, num57, num58, num59, num60,
num61, num62, num63, num64, num65,
num66, num67, num68, num69, num70,
num71, num72, num73, num74, num75,
num76, num77, num78, num79, num80,
num81, num82, num83, num84, num85,
num86, num87, num88, num89, num90,
num91, num92, num93, num94, num95,
num96, num97, num98, num99;
return 0;
}
?????
Array
- Store many variables
- Must have same type ! (in C++)
- Use arr[index] to access
[ ]
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int arr[3];
cin >> arr[0] >> arr[1] >> arr[2];
return 0;
}
Only array can do nothing...
Loop
- continue running if condition is TRUE
- can use "break" or "continue" to control
- good for repeating the same job
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int arr[5];
for (int i = 0; i < 5; ++i) {
cin >> arr[i];
}
for (int i = 0; i < 5; ++i) {
cout << arr[i] << endl;
}
return 0;
}
while loop
while (/* condition */) {
/* do something */
}
int i = 0;
while (i < 5) {
cout << i << endl;
++i;:
}
for loop
for (initialize ; condition ; TODO after loop) {
/* do something */
}
for (int i = 0; i < 5; ++i) {
cout << arr[i] << endl;
}
do-while
do {
/* do something */
} while (condition);
int i;
do {
cin >> i
} while (i != 0);
break
- exit loop immediate
- often use with while(1)
continue
- skip this loop
while(1) {
if(finished) break;
}
for (int i = 0; i < count; ++i) {
if(arr[i] == 0) continue;
/* the code
won't run
when continue */
}
Infinity loop?
- Your program will not exit until crash
- In some case, this is a BUG
- But in some case, this is necessary
Array out of index?
(e.g. access arr[100] when you declare arr[5])
- Cause undefined behavior
- Your program may crash or run normally
- C++ will not check array index for you, handle it by yourself.
- but Java will throw an exception.
CSIE_CAMP_2017_CPP_3
By Liang Yu-Cheng
CSIE_CAMP_2017_CPP_3
- 751