if(Letter == 'A'){
// Do something
}
elseif(Letter == 'B'){
// Do something
}
elseif(Letter == 'C'){
// Do something
}
else{
// Do something
}
decision-making in C
"switch" on
switch between cases
break; each cases
Use default as the last else
decision-making in C
examples:
switch(Letter){
case'A':
// Do somethingbreak;
case'B':
// Do somethingbreak;
case'C':
// Do somethingbreak;
default:
// Do somethingbreak;
}
decision-making in C
"switch" Tips:
Don't forget to break.
example:
switch(Letter){
case'A':
printf("The letter is A.\n");
case'B':
printf("The letter is B.\n");
case'C':
printf("The letter is C.\n");
default:
printf("None of them above.\n");
}
results:
darkknive@1091cp1:~$ ./a.out B
The letter is B.
The letter is C.
None of them above.
darkknive@1091cp1:~$
repetition statements
repetition statements
Introducing "for"
Usage: for(init; condition; increment){}
init part will be executed before for loop start.
condition part will be executed before each looped. Only when return value is true will the next loop be triggered.
Declear an int and start with 0, set condition as index < N; and increment as index++. This for loop will run N times with index = 0, 1, 2, 3......N-2, N-1.
If you get a segmentation fault during runtime, it may because your for loop messed up. For example, for(int index = N-1; index >= 0; index++).
You may declare multiple variables in init part by using int a = 0, b = 0, ...;. Please note that they should be the same data type.
repetition statements
do "while"
Usage: while(condition){statement(s)}.
While (condition == true), do statement(s), then do the whole loop again.
If your runtime is stucked, it is very possible that you have an infinite while loop. For example, while(a > 1){printf("%d ", a);}. The value of a won't be changed in the loop, so if you enters this while loop, it's gonna run FOREVER.