Simple Control Structures IF IFELSE statements in C

  • Slides: 10
Download presentation
Simple Control Structures IF, IF-ELSE statements in C

Simple Control Structures IF, IF-ELSE statements in C

The if statement: if (expression){ statement; } n How it works: n The expression

The if statement: if (expression){ statement; } n How it works: n The expression is evaluated n If the expression is TRUE the statement are executed and program continues to the next statement after IF n If the expression is FALSE, program continues to the next statement after IF n

Flowchart for the if statement expr false true statement

Flowchart for the if statement expr false true statement

The if-else statement n The if-else statement: if (expression) { statement 1; } else

The if-else statement n The if-else statement: if (expression) { statement 1; } else { statement 2; }

IF-ELSE works as follows Expression is evaluated n If the expression is TRUE, statement

IF-ELSE works as follows Expression is evaluated n If the expression is TRUE, statement 1 is executed and program continues to the next statement after if-else n If the expression is FALSE, statement 2 is executes and program continues to the next statement after if-else n

Flowchart for the if-else statement true statement 1 expr false statement 2

Flowchart for the if-else statement true statement 1 expr false statement 2

SYNTAX ROOLES and INDENTATION If the statement in IF statement is a single statement,

SYNTAX ROOLES and INDENTATION If the statement in IF statement is a single statement, the curly braces could be omitted n If the statement 1 or/and statement 2 is/are singe statements, the curly braces could be omitted INDENTATION n The statement part of the if, if-else statement should be shifted n

EXAMPLES n What would be the output of the following programming fragment? int a

EXAMPLES n What would be the output of the following programming fragment? int a = 10; if (a >= 10){ a = a + 1; printf(“%dn”, a); } a = 0; printf(“%dn”, a);

EXAMPLES n What would be the output of the following programming fragment? int a

EXAMPLES n What would be the output of the following programming fragment? int a = 9; if (a >= 10){ a = a + 1; printf(“%dn”, a); } a = 0; printf(“%dn”, a);

EXAMPLES n What would be the output of the following programming fragment? int a

EXAMPLES n What would be the output of the following programming fragment? int a = 10; if (a >= 10) a = a + 1; else a = 0; printf(“%dn”, a);