Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

CS1PR16 CONDITIONAL STATEMENTS

IF evaluates a condition and returns either true or false:


IF (condition)
{ statement …} - this statement is executed if the condition is true. Then the program goes on
to the next statement. If the condition is false, this statement is skipped.
Example:

This would be coded as:


if (grade >=60)
{printf("Passed.");}
Note: 5 – 7 would be evaluated as true – the result is non-zero. A decision can be made on any
expression.

IF … ELSE
If may be supplemented by an else statement – the else part will be executed if the condition is false.
Example:

if (grade>=60)
{printf("Passed");}
else
{printf("Failed");}
If the block of code to be executed consists of only one line, the braces may be skipped. The
ternary operator may also be used in this case:
Grade >= 60 ? printf("passed") : printf("failed");
However, this is not generally recommended as it decreases clarity.

You can nest if...else statements inside each other but you shouldn't have too many of them.

SWITCH statement is an alternative to using many if...else statements.

It is faster than using if statements as it


allows the CPU to jump to the selected case with only 1 comparison.
Example:
switch(number)
{
case 1: printf(“Special case, 1\n”); break;
case 2: printf(“prime\n”); break;
case 3: printf(“prime\n”); break;
case 4: printf(“even\n”); break;
case 5: printf(“prime\n”); break;
default : printf(“out of range\n”); break;
}
Default catches all other values not listed.
Break exits the statement once the chosen case has been executed. Without the break
statements, the program would carry on through all remaining cases.

Confusing equality (==) and assignment (=) operators is a common mistake. It doesn't usually cause a
syntax error and still compiles but leads to incorrect results.

You might also like