From the course: Complete Guide to C Programming Foundations

Making a decision

- [Instructor] C programs run top-down as written in the source code file. Each statement runs after the other, until the final statement in the main function. You can alter program flow by calling a function, in which case the functions statements interrupt the flow of execution. The main function always runs first no matter where it appears in the source code file. Here at line 32, the get_value function is called, execution jumps to this function up here, then returns to the following statement in the main function once it's done at line 33. Within a function, an IF decision statement can alter program flow. When the IF statement's condition is true, the statements belonging to the decision, one here at line 34, are executed. Otherwise, its statements are skipped. You can also alter program flow by repeating one or more statements in a loop. The FOR statements at line 37 repeats a group of statements based on its condition. The loop's statements are skipped when the condition isn't true. The flow in this code is altered by the IF statement at line nine. The IF keyword is followed by a set of parentheses in which an expression is evaluated, a condition. When the expression is true or equals a non-zero value, the statements in the block are executed. When the expression is false or zero, the statements are skipped. Here when the value of variable A is less than 10, the statement block belonging to IF is executed. Otherwise, it's skipped. And I'll try 4 and the statements are executed. Try again with 100. The statements are skipped. Because only one statement is included in this IF construction, you can remove the braces. In fact, both lines act as a single statement, though it's traditional to format it on two lines as shown here. Oh, and don't put a semicolon here. This is a common mistake and it happens due to habit, but it's wrong. When multiple statements belong to the code's IF decision, they must be enclosed in braces. I'll add a few lines. Run. The extra statements are executed. You can nest IF statements as shown in this code. Two statements work like a filter, ensuring that all values of variable A greater than six, but also less than 15 are prefixed with an asterisk. This code can be written in a better way. The condition is really, if A is less than six and A is less than 15. Only when both conditions logical and are met is the putchar statement executed. The output doesn't change, but the code presents a better construction of how program flow is altered.

Contents