Control Flow Statement
The C Program is consisted of prodecural program and imperative programs. There are many control flow statements, which allow us to control the flow of the code, since it always run downwards fron the very top. There are conditional statements and loops, as examples of control flow statements. They are covered by {}, which we call them as "block".
Conditional statements: If, If/else, If/else if/else, and switch.
- If statement: They are the most common conditional, and if the conditional statement is true, it runs the command, and not if the conditional statement is false.
- If/else statement: Same thing as if, except for that if the conditional statement is false, it runs another command rather than just not running the first command.
-If/else if/else statement: Same thing as if/else, except for that if the conditional statement is false, it goes to another conditional statement, then if all statements are wrong, it goes to else statement. *Else if can be used multiple times.
- Switch statement: Compiler is easily able to understand, so it is faster, but we usually use less than if/else, because this statement can only be given interger promotion (int) as the conditional value. We use "break" to finish the code for the switch statement. For example, the image below will give the answer in case 2, as the conditional value, the "num", it 2.
Iteration statements (loops): while, do/while, and for.
- While loop: This is simple; while the conditional is met, it will run the command. The basic format is consisted of
while( i < 6) {
printf("Number IDK);
i++
}.
The i++, or the increment is very important, because without it, there will be infintely many runs, causing an infinite loop.
- Do/while loop: Same thing with while, but it would run the loop at least once, then check fo the conditionals are met. So even though the conditional is false, it runs the command at least once.
- For loop: Many people uses for loops, it is very common. It consists of all initial, conditional, and increments in one statement, in format of (initial;conditional;increment). The running process is same with while loop.
Other Control Flow Statements: Continue, Break, and goto.
- Continue: Continue is used in the loop, to make a part of loop get skipped. Then it would go to the next rotation of the loop. For example, this would print from 1~100 except for multiple of 3s because it has continue when there is a multiple of 3.
- Break: Break is also used in the loop, to actually stop the loop and become free of it instantly. For example, this would break out of the loop instantly as soon as starting number equals the ending number.
- Goto: Makes the flow of the program to the label that the programmer wants. However, sinnce it can ironically disturb the flow, it is not used commonly except for debugging.