Professional Documents
Culture Documents
Language
-
Statements, Expressions,
and Operators
The Pieces of a C Program
Learning Outcome
What a statement is
What an expression is
What an operator is
Operator precedence
The if statement
Statements
-
Statements
A complete instruction that directs the computer to
carry out some task.
Usually written one per line, end with semicolon
(except for preprocessor directives: #define and
#include)
E.g.:
X = 2 + 3; is an assignment statement.
Instruct computer to add 3 to 2 and assign the result to
the variable X.
White Space on Statements
Refer to spaces, horizontal tabs, vertical tabs, and
blank line in C code.
C compiler is not sensitive to white space.
Statement X=2+3; is equivalent to X = 2 + 3;
White space is kept track in strong constant.
E.g.:
“How now brown cow” is different from “How now
brown cow”
Important to keep your statement readable.
Compound Statements
Also called a block.
A group of two or more C statements enclosed in braces.
E.g.:
{
printf (“Hello,”);
printf (“world!”);
}
Put braces on their own line to make it clear the start
and ending of a C program.
Expressions
Expressions
Anything that evaluates to a numeric value.
Simple Expression:
Consist of single item such as a simple variable, literal
constant, or symbolic constant.
Literal constant: evaluates to its own value.
Symbolic constant: evaluates to the value created using
the #define directive.
Variable: evaluates to the current value assigned to it by
the C program.
Expression Description
Rate A variable
Increments the
Increment ++ operand by one ++ X
5 == 1 Is 5 equal to 1? 0 (false)
!= = = Second
The if else Statement
Relational operator is usually used with the if else
statement to make C program control statement.
if else statement evaluates an expression and directs
program execution based on the result of that
evaluation.
Format:
If expression evaluates to true,
if (expression)
statement 1 is executed. If is
statement 1; false, control goes to else
else statement and execute
statement 2; statement 2.
/*Demonstrate the use of if statement with else clause*/
#include <stdio.h>
int x,y;
if (x == y)
printf("X is equal to Y\n");
else
printf("X is not equal to Y\n");
getch();
return 0;
}
/*Demonstrate the use of if statement with else clause*/
#include <stdio.h>
if (x + y == 10)
printf(”Welcome to C Language \n");
else
printf(”Hello C Language \n");
return 0;
}
Compound Assignment Operators
A shorthand method for combining a binary math
operation with an assignment operation.
E.g.:
Increase the value of X by 5.
Normal operator is X = X + 5;
Compound assignment operator is X += 5;
Compound Assignment Operators
Compound Normal
X *= Y X=X*Y
Y-=Z+1 Y=Y–Z+1
a/=b a = a / b
X+=Y/8 X=X+Y / 8
Y%=3 Y=Y%3
Exercise
-
Exercise
Write a C program that determines if someone is
legally an adult of not (age 21).
Write a C program that accept the price of two
products and calculate whether the total exceeds RM
100 budget. Display the output on screen.