By default, C executes statements one after another in the order they are written. Control statements change that order. This section introduces the three kinds of control and the most basic decision statement, if, with its partner else.
Three kinds of control
Every program is built from three control structures (the same ones met in the flowcharts of Unit 1):
Structure
Meaning
C statements
Sequence
Statements run one after another
Default behaviour
Selection (decision)
Choose which statements run, based on a condition
if, if–else, switch
Iteration (loop)
Repeat statements
while, do–while, for
A control statement is a statement that changes the order in which other statements are executed.
The simple if statement
Syntax
if (condition) statement;if (condition) { statement1; statement2;}
The condition is evaluated. If it is non-zero (true), the statement or block runs; if it is zero (false), it is skipped. Either way, execution continues with the statement after the if. Braces { } group several statements into one block; without braces, only the first statement belongs to the if.
The if–else statement
Syntax
if (condition) { statements executed when the condition is true} else { statements executed when the condition is false}
Exactly one of the two blocks runs, never both and never neither.
For a choice between two values, the conditional operator from Unit 2 is a compact alternative: y = (x >= 6) ? 6 : x;. Use if–else when each branch has to do something.
Key takeaways
Control statements change the default top-to-bottom order: selection and iteration.
if (condition) runs its statement only when the condition is non-zero.
if–else runs exactly one of two blocks.
Use braces for blocks of more than one statement.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write an if–else statement that prints “Pass” when marks is at least 40 and “Fail” otherwise, and trace it for marks = 40.
Show worked answer
if (marks >= 40) printf("Pass\n"); else printf("Fail\n");. For marks = 40, the condition 40 >= 40 is true (1), so the first branch runs and “Pass” is printed; the else branch is skipped.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/decision-and-loop-control-statements/control-statements-and-the-if-statement/ to read this page.