IF Structure

Credits for Lecturing and Authoring
IF Statement
Execution Sequence
IF Example
Logical Expressions and Relational Operators
Relational Operators
Logical Expressions
Logical Operators
IF Then ELSE Structure
Ex: Flow Chart
Flow Chart ELSE IF
Nested IF Statements

IF Structure

Authored by: John Even (edited by Lex Jacobson)

Faculty Supervisor: Al Day

Some material derived from lessons authored by Dr. James Hilliard

HTML Documentation by Larry Genalo Jr.

Date Last Updated: 8/7/95


IF Statement

Form: if (logic) statement

logic is a logical expression

statement is any executable C statement

Execution Sequence for the IF Statement

  1. The logical expression is evaluated as True or False.

  2. If the expression is true, statement is executed. Then the next C statement in the program sequence is executed.

  3. If the expression is false, statement is not executed. The next statement in the program sequence is executed.

Example of IF

if (a==b) printf("a is equal to b.\n");

If a is equal to b, the string is output to the screen. If a is not equal to b, execution continues with the next C statement.

Note: == is the relational operator to test for equality.

Logical Expressions and Relational Operators

Logical expression: Asks a question about two or more variables or arithmetic expressions.

Examples:
Is x less than y?
Is pow(a,2) equal to pow(b,2)?
Is pow(x*x+y*y, 0.5) greater than 10?

Logical Expressions:


Logical Operators

Logical   "AND"

Form:              &&

Examples:  x<y&&a>b
     Interpretation: Is x&lty and a&gtb?

             x&lty&&a*a==b*b
Interpretation: Is x&lty AND a squared = b squared?

Logical   "OR"

Form:         ||

Example:   a>=b||a*a<=y Interpretation: Is a>=b or a*a>=y


Block IF Structure

Form:
	  if (logical condition){
	      ___________________________
	      ___________________________
              ___________________________
	     } else {
	      ___________________________
	      ___________________________
	     }