C Programming Module3 Tenouk
C Programming Module3 Tenouk
STATEMENTS, EXPRESSIONS
AND OPERATORS
Abilities
▪ Statements.
▪ Expressions.
▪ Operators.
▪ The Unary Mathematical Operators.
▪ The Binary Mathematical Operators.
▪ Precedence and Parentheses.
▪ Relational Operator.
▪ Expression and if Statement.
▪ Relational Expressions.
▪ Precedence of Relational Operators.
▪ Logical Operators.
▪ True and False Values.
▪ Precedence of Logical Operators.
▪ Compound Assignment Operators.
▪ The Conditional Operator (Ternary).
▪ The Bitwise operators.
▪ The Comma Operator.
3.1 Statements
- A statement is a complete instruction asking the computer to carry out some tasks.
- Normally written one per line, although some statements span multiple lines.
- Always end with a semicolon ( ; ), except for preprocessor directive such as #define and #include.
- For example:
←←←
Evaluation direction
x = 2 + 3;
- This statement instructs the computer to add 2 to 3 and assign the result to the variable x.
- C/C++ compiler is not sensitive to white spaces such as spaces, tabs and blank lines in the source code,
within the statements.
- Compiler read a statement in the source code it looks for the characters and for the terminating semicolon
and ignores the white space. For example, three of the following examples are same.
x = 2 + 3; or
x=2+3; or
x =
2
+
3;
- You can try compiling the following program example; the ‘not so readable’ codes, then see whether it is
valid or not.
www.tenouk.com Page 1 of 28
printf("\npostfix mode, a-- = %d prefix mode, --b = %d", a--, --b);printf("\npostfix
mode, a-- = %d prefix mode, --b = %d", a--, --b);printf("\npostfix mode, a-- = %d
prefix mode, --b = %d", a--, --b);printf("\npostfix mode, a-- = %d prefix mode, --b =
%d", a--, --b);printf("\n");system("pause");return 0;}
Output:
- The most important thing here is the semicolon that defines a statement and codes such as preprocessor
directive and comments that cannot be in the same line with other codes. See also how the white spaces
have been ignored and how the compiler read the codes.
- But there is an exception: For Literal string constants, white space such as tabs and spaces are
considered part of the string.
- A string is a series of characters or combination of more than one character.
- Literal string constants are strings that are enclosed within double quotes and interpreted literally by the
compiler, space by space.
- Is legal but:
- To break a literal string constant line, use the backslash character ( \ ) just before the break, like this:
printf("Hello, \
World");
- For C++ you can use the double quotation pair, " " for each literal string for each line, so can break
more than one line easily.
- For example:
www.tenouk.com Page 2 of 28
cout<<"\nNow I'm in FunctTwo()!\nmay do some work here..."
<<"\nReceives nothing but return something"
<<"\nto the calling function..."<<endl;
- For a character, we use single quotation mark (''). So, you can see that for one character only, the using
"" and '' should provide the same result isn’t it? For example:
- Is a group of more than one C/C++ statements enclosed in curly braces. For example:
- Same as:
{printf("Hello, ");
printf("world! ");}
Note:
Bracket / square bracket - [ ]
Parentheses - ( )
Curly braces - { }
Angled brackets - < >
3.3 Expressions
x = 2 + 8;
x = a + 10;
- The last one evaluates the expression a + 10 and assigns the result to variable x.
- So, the general form of expression and variables, evaluated from the right to left, is:
variable = any_expression;
- E.g.
y = x = a + 10;
www.tenouk.com Page 3 of 28
x = 6 + (y = 4 + 5);
3.4 Operators
- Is a symbol that instructs C/C++ to perform some operation, or action, on one or more operands.
- Operand is something that an operator acts on.
- For example:
x = 2 + 3;
- In C/C++, all operands are expressions; and operators fall into several categories as follow:
x = y;
- Called unary because they take a single operand as shown in table 3.1.
Table 3.1
- These operators can be used only with variables not with constants.
- To add 1 or to subtract 1 from the operand.
++x same as x = x + 1
--y same as y = y + 1
- ++x and --y are called prefix mode, that means the increment or decrement operators modify their
operand before it is used.
- x++ and y-- are called postfix mode, the increment or decrement operators modify their operand after it
is used. Remember the before used and after used words.
- For example:
Postfix mode:
www.tenouk.com Page 4 of 28
x = 10;
y = x++;
After these statements are executed, x = 11, y has the value of 10, the value of x was assigned
to y, and then x was incremented.
Prefix mode:
y = 10;
y = ++x;
Both y and x having the value of 11, x is incremented, and then its value is assigned to y.
- Try the following program and study the output and the source code.
int main()
{
int a, b;
//set a and b both equal to 5
a = b = 5;
//print them, decrementing each time
//use prefix mode for b, postfix mode for a
Output:
- Change all the -- operator to ++ operator and re run the program, notice the different.
- Is used with printf() and scanf() function and other input/output functions to determine the
format of the standard output (screen) and standard input (keyboard).
- The frequently used format specifiers are listed in Table 3.2. Other format specifiers and their usage will
be discussed in formatted input/output Module in more detail.
www.tenouk.com Page 5 of 28
%f Is to print floating-point number.
%.2f Prints numbers with fractions with up to two decimal places.
%u Prints unsigned integer
Table 3.2
- Try the following program example and study the output and the source code.
int main()
{
printf("My name is %s and I am %d years old.\n", "John", 25);
printf("Examples of the decimal points %f\t%.3f\t%.2f\t\n",1.7885,1.7885,1.7885);
printf("Examples of characters\n");
printf(" %c \n %c \n %c\n", 'A', 'B', 'a');
system("pause");
return 0;
}
Output:
- C/C++ binary mathematical operators take two operands as listed in Table 3.3.
Table 3.3
- Modulus example:
www.tenouk.com Page 6 of 28
- Try the following program example and study the output and the source code.
int main()
{
unsigned seconds, minutes, hours, secs_left, mins_left;
Output:
#include <iostream.h>
www.tenouk.com Page 7 of 28
#include <stdlib.h>
//For VC++ .Net use the following processor directives
//comment out the previous #include…
//#include <iostream>
//#include <cstdlib>
//using namespace std;
//Define constants
#define SECS_PER_MIN 60
#define SECS_PER_HOUR 3600
void main()
{
unsigned int seconds, minutes, hours, secs_left, mins_left;
Output:
- Expression that contains more than one operator, the order in which operation are performed can be
confusing.
- For example:
x = 4 + 5 * 3;
x = 9 * 3;
x = 4 + 15;
- So, need some rules to define the order in which operations are performed. This is called operator
precedence.
- Operator with higher precedence is performed first.
- Precedence examples:
- If the operators are in the same level, then, the operators are performed from left to right order, referring
to table 3.4.
- For example:
www.tenouk.com Page 8 of 28
- But a sub expression enclosed in the parentheses, ( ), is evaluated first, without regard to the operator
precedence because parentheses have the highest precedence.
- For example:
x = (4 + 5) * 3
= 9 * 3
= 27
- For nested parentheses (more than one parentheses), evaluation proceeds from the innermost expression
outward.
- For example:
8 / 2 = 4
25 – (2 * (10 + 4))
2. Moving outward, 10 + 4 = 14
25 – (2 * 14)
25 – 28
25 – 28 = -3
- Use parentheses in expressions for clarity and readability, and must always be in pairs.
- Used to compare expressions, asking questions such as, “is x greater than 200?” or “is y equal to 10”.
- An expression containing a relational operator evaluates as either TRUE (1) or FALSE (0).
- C/C++ has six relational operators as shown in Table 3.5:
www.tenouk.com Page 9 of 28
to operand 2?
- Simple examples:
- Relational operators are used mainly to construct the relational expressions used in if and while
statements.
- This is the introduction of the basic if statement, used to create program control statements. Till now
we only deal with the top down approach or line by line code but that is not the limitation.
- We will learn more detail about program control in program control Module. Assume this part as an
introduction.
if ( expression )
statement(s);
next_statement;
1. Evaluate an expression and directs program execution depending on the result of that
evaluation.
2. If the expression evaluate as TRUE, statement(s) is executed, if FALSE,
statement(s) is not executed, execution then passed to the code follows the if
statement, that is the next_statement.
3. So, the execution of the statement(s) depends on the result of expression.
- if statement also can control the execution of multiple statements through the use of a compound
statement or a block of code. A block is a group of two or more statements enclosed in curly braces, { }.
- Typically, if statements are used with relational expressions, in other words, "execute the following
statement(s) only if a certain condition is true".
- For example:
if ( expression )
{
statement1;
statement2;
...
...
statement-n;
}
next_statement;
- Program example:
www.tenouk.com Page 10 of 28
//Demonstrate the use of the if statements
#include <stdio.h>
#include <stdlib.h>
int main ( )
{
int x, y;
//Input the two values to be tested
printf("\nInput an integer value for x: ");
scanf("%d", &x);
printf("Input an integer value for y: ");
scanf("%d", &y);
if (x > y)
{
printf("\nx is greater than y");
}
if (x < y)
{
printf("\nx is smaller than y");
}
printf("\n\n");
system("pause");
return 0;
}
Possible outputs:
- We can see that this procedure is not efficient. Better solution is to use if–else statement as shown
below:
www.tenouk.com Page 11 of 28
if ( expression )
statement1;
else
statement2;
next_statement;
- The expression can be evaluated to TRUE or FALSE. The statement1 and statement2 can be
compound or a block statement.
- This is called a nested if statement. Nesting means to place one or more C/C++ statements inside
another C/C++ statement.
- Program example:
int main()
{
int x, y;
Possible outputs:
www.tenouk.com Page 12 of 28
- Keep in mind that we will learn if–else statements more detail in program controls Module. As a pre
conclusion, there are 3 form of if statements.
Form 1:
if ( expression )
statement1;
next_statement;
Form 2:
if ( expression )
statement1;
else
statement2;
next_statement;
Form 3:
if ( expression )
statement1;
else if ( expression )
statement2;
else if ( … )
statement3;
…
…
…
else
statementN;
next_statement;
- Expression using relational operators evaluate, by definition, to a value of either FALSE (0) or TRUE
(1).
- Normally used in if statements and other conditional constructions.
- Also can be used to produce purely numeric values.
- Program example:
int main()
{
int a;
a = (5 == 5);
//Evaluates to 1, TRUE
printf ("\na = (5 == 5)\n Then a = %d\n", a);
a = (5 != 5);
//Evaluates to 0, FALSE
printf ("\na = (5 != 5)\n Then a = %d\n", a);
www.tenouk.com Page 13 of 28
//Evaluates to 1 + 1, TRUE
printf("\na = (12 == 12) + (5 != 1)\n Then a = %d\n", a);
system("pause");
return 0;
}
Output:
if(x = 5)
printf("x is equal to 5");
- The message always prints because the expression being tested by the if statement always evaluates as
TRUE, no matter what the original value of x happens to be.
- Referring to the above example, the value 5 does equal 5, and true (1) is assigned to 'a'. "5 does not
equal 5" is FALSE, so 0 is assigned to 'a'.
- As conclusion, relational operators are used to create relational expression that asked questions about
relationship between expressions. The answer returned by a relational expression is a numeric value 1 or
0.
(x + 2 > y)
((x + 2) > y)
- For example:
- Avoid using the “not equal to” operator ( != ) in an if statement containing an else, use “equal to” ( == )
for clarity.
- For example:
www.tenouk.com Page 14 of 28
if(x != 5)
statement1;
else
statement2;
if(x == 5)
statement1;
else
statement2;
- C/C++ logical operators enable the programmer to combine 2 or more relational expressions into a single
expression that evaluate as either TRUE (1) or FALSE (0).
Expression Evaluates As
(expression1
True (1) only if both expression1 and
&&
expression2 are true; false (0) otherwise.
expression2)
(expression1 || True (1) if either expression1 or expression2 is
expression2) true; false (0) only if both are FALSE.
False (0) if expression1 is true; true (1) if
(! expression1)
expression1 is true.
Table 3.8: Evaluation of the logical expressions
- These expressions use the logical operators to evaluate as either TRUE or FALSE depending on the
TRUE/FALSE value of their operand(s).
- For example:
Expressions Evaluates As
True (1) because both operands are
(5 == 5) && (6 != 2)
true
True (1) because one operand is
(5 > 1) || (6 < 1)
true
False (0) because one operand is
(2 == 1) && (5 == 5)
false
True (1) because the operand is
! (5 == 4)
false
NOT (FALSE) = TRUE
www.tenouk.com Page 15 of 28
Table 3.10: Logical AND Operation
- For example:
x = 125;
if(x)
printf("%d", x)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 5, b = 6, c = 5, d = 1;
int x;
www.tenouk.com Page 16 of 28
Output:
- Condition 1 logical expression that evaluate as true if condition 3 is true and if either condition 1 or
condition 2 is true. But this do not fulfill the specification because the && operator has higher
precedence than ||, the expression is equivalent to a < b || (a < c && c < d) and evaluates as true if (a < b)
is true, regardless of whether the relationships (a < c) and (c < d) are true.
x = x + 5;
⇒ x += 5;
- The examples:
Expression Equivalent
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
- Another example:
If x = 12;
Then,
z = x += 2;
z = x = x + 2
= 12 + 2
= 14
- Program example:
www.tenouk.com Page 17 of 28
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 3, b = 4;
printf("Initially: a = 3, b = 4\n");
printf("\na += b ---> a = a + b = %d\n", a+=b);
printf("a last value = %d\n", a);
printf("\na *= b ---> a = a * b = %d\n", a*=b);
printf("a last value = %d\n", a);
printf("\na -= b ---> a = a - b = %d\n", a-=b);
printf("a last value = %d\n", a);
printf("\na/=b ---> a = a / b = %d\n", a/=b);
printf("a last value = %d\n", a);
printf("\na-=(b+1)---> a = a - (b + 1) = %d\n", a-=(b+1));
printf("a last value = %d\n", a);
system("pause");
return 0;
}
Output:
- If expression1 evaluates as true (non zero), the entire expression evaluated to the value of
expression2. If expression1 evaluates as false (zero), the entire expression evaluated to the
value of expression3.
- For example:
x = y ? 1 : 100;
- It also can be used in places an if statement cannot be used, such as inside a single printf()
statement. For example:
z = (x > y)? x : y;
if(x > y)
www.tenouk.com Page 18 of 28
z = x;
else
z = y;
- Program example.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b = 4, c= 50;
Output:
- Change the (b>c) to (b<c), then recompile and rerun. Notice the output difference.
Operator Description
The bit in the result are set to 1 if the corresponding bits in the two
& (bitwise AND)
operands are both 1, otherwise it returns 0.
The bit in the result is set to 1 if at least one (either or both) of the
| (bitwise inclusive OR)
corresponding bits in the two operands is 1, otherwise it returns 0.
The bit in the result is set to 1 if exactly one of the corresponding bits in
^ (bitwise exclusive OR)
the two operands is 1.
~ (bitwise complement) Negation. 0 bit set to 1, and 1 bit set to 0. Also used to create destructors.
Moves the bit of the first operand to the left by the number of bits
<< (bitwise shift left) specified by the second operand; it discards the far left bit ; fill from the
right with 0 bits.
Moves the bit of the first operand to the right by the number of bits
>> (bitwise shift right) specified by the second operand; discards the far right bit; fill from the
right with 0 bits.
- Bitwise AND, bitwise inclusive OR, bitwise exclusive OR operators compare their two operands bit by
bit.
- &, >>, << are context sensitive. & can also be the pointer reference operator. >> can also be the input
operator in I/O expressions. << can also be the output operator in I/O expressions. You will learn this in
another Module.
www.tenouk.com Page 19 of 28
- Example of the &, | and ^ operators.
Operand1, OP1 Operand2, OP2 OP1 & OP2 OP1 | OP2 OP1 ^ OP2
0 0 0 0 0
1 0 0 1 1
0 1 0 1 1
1 1 1 1 0
- Program example:
//bitwise operators
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned p;
//function prototype…
void DisplayBits(unsigned);
//function definition…
void DisplayBits(unsigned number)
{
unsigned q;
//2 byte, 16 bits position
//operated bit by bit and hide/mask other bits
//using left shift operator
//start with 10000000 00000000
unsigned DisplayMask = 1<<15;
Output:
- Change DisplayMask = 0<<15 and & to | for inclusive OR operation and rerun the program.
- The shift general syntax:
- The shift count must be non-negative and less than the number of bits required to represent the data type
of the left operand.
- For example, let say the variable declaration is:
www.tenouk.com Page 20 of 28
unsigned int p = 5
- For right shift, while bits are shifted toward low-order position, 0 bits enter the high-order positions, if
the data is unsigned. If the data is signed and the sign bit is 0, then 0 bits also enter the high-order
positions.
- If the sign bit is 1, the bits entering high-order positions are implementation dependent, on some
machines (processor architecture) 1s, and on others 0s, are shifted in.
- The former type of operation is known as the arithmetic right shift, and the latter type is the logical
right shift. So, for portability issue, these operators should only be used on unsigned operands.
- For example:
- Program example:
//bitwise operators
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned int num1, num2, num3, mask, SetBit;
num1 = 7535;
mask = 1;
num1 = 15;
SetBit = 241;
printf("\nThe result of inclusive ORing the following numbers\n");
printf("using the bitwise inclusive OR, | is\n");
BitwiseOp(num1);
BitwiseOp(SetBit);
printf(" ------------------------\n");
//Bitwise inclusive OR operation
BitwiseOp(num1 | SetBit);
www.tenouk.com Page 21 of 28
num1 = 249;
num2 = 299;
printf("\nThe result of exclusive ORing the following numbers\n");
printf("using the bitwise exclusive OR, ^ is\n");
BitwiseOp(num1);
BitwiseOp(num2);
//Bitwise exclusive OR operation
printf(" ------------------------\n");
BitwiseOp(num1 ^ num2);
num3 = 21321;
printf("\nThe One's complement of\n");
BitwiseOp(num3);
printf(" |||||||| ||||||||\n");
//One's complement operation
BitwiseOp(~num3);
system("pause");
return 0;
}
//function definition…
void BitwiseOp(unsigned int value)
{
unsigned int p;
//Two 8 bits, 16 position, shift to left
unsigned int DisplayMask = 1 << 15;
Output:
- For C++, the following is a list of the binary operators’ categories that can be used in C++ expressions.
www.tenouk.com Page 22 of 28
Assignment (=)
Addition assignment (+=)
Subtraction assignment (–=)
Multiplication assignment (*=)
Division assignment (/=)
Modulus assignment (%=)
Left shift assignment (<<=)
Right shift assignment (>>=)
Bitwise AND assignment (&=)
Bitwise exclusive OR assignment (^=)
Bitwise inclusive OR assignment (|=)
2 Additive operators:
Addition (+)
Subtraction (–)
3 Multiplicative operators:
Multiplication (*)
Division (/)
Modulus (%)
4 Shift operators:
Right shift (>>)
Left shift (<<)
6 Bitwise operators:
Bitwise AND (&)
Bitwise exclusive OR (^)
Bitwise inclusive OR (|)
7 Logical operators:
Logical AND (&&)
Logical OR (||)
- Furthermore in C++ the <bitset> header defines the template class bitset and two supporting template
functions for representing and manipulating fixed-size sequences of bits.
x = (a ++, b++);
Operators Associativity
( ) [ ] → . Left to right
! ~ ++ -- + - * & (type)
Right to left
sizeof()
www.tenouk.com Page 23 of 28
* / % Left to right
+ - Left to right
<< >> Left to right
< <= > >= Left to right
== != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= %= &=
Right to left
^= |= <<= >>= ,
Left to right
The operators are shown in decreasing order of precedence from
top to bottom
- For this Table it is read from top (the highest) to bottom (the lowest). Then if they are at the same level,
we read it from left (the highest) to right (the lowest).
int main()
{
int count;
Output:
www.tenouk.com Page 24 of 28
//using pre defined functions
//getchar() and putchar() with End Of File, EOF
//EOF is system dependent
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count;
Output:
int main()
{
//printf("Some prompt here...\n");
Output:
www.tenouk.com Page 25 of 28
//simple steps in program development…
#include <stdio.h>
#include <stdlib.h>
int main()
{
//printf("Some prompt here...\n");
Output:
int main()
{
//printf("Some prompt here...\n");
www.tenouk.com Page 26 of 28
//-------------First: build the loop-----------
//while storing the character process
//not equal to the End Of File...
while((count = getchar()) != EOF)
{
//do the character count
if(count != ' ')
++charnum;
//and the line count...
if(count == '\n')
{
++linenum;
charnum = charnum -1;
}
}
//----------Second: test the output---------------
printf("The number of line = %d\n", linenum);
printf("The number of char = %d\n", charnum);
return 0;
}
Output:
/******-cpoundassig.c-*******/
#include <stdio.h>
int main()
{
int a = 10, b = 20;
printf("Initially: a = 3, b = 4\n");
printf("\na += b ---> a = a + b = %d\n", a+=b);
printf("a last value = %d\n", a);
printf("\na *= b ---> a = a * b = %d\n", a*=b);
printf("a last value = %d\n", a);
printf("\na -= b ---> a = a - b = %d\n", a-=b);
printf("a last value = %d\n", a);
printf("\na/=b ---> a = a / b = %d\n", a/=b);
printf("a last value = %d\n", a);
printf("\na-=(b+1)---> a = a - (b + 1) = %d\n", a-=(b+1));
printf("a last value = %d\n", a);
return 0;
}
a += b ---> a = a + b = 30
a last value = 30
a *= b ---> a = a * b = 600
a last value = 600
a -= b ---> a = a - b = 580
a last value = 580
a/=b ---> a = a / b = 29
www.tenouk.com Page 27 of 28
a last value = 29
a-=(b+1)---> a = a - (b + 1) = 8
a last value = 8
- Another example.
/*bitwise operators*/
/******--bitwise.c--******/
#include <stdio.h>
int main()
{
unsigned p;
/*function prototype.*/
void DisplayBits(unsigned);
/*function definition.*/
void DisplayBits(unsigned number)
{
unsigned q;
/*2 byte, 16 bits position*/
/*operated bit by bit and hide/mask other bits*/
/*using left shift operator*/
/*start with 10000000 00000000*/
unsigned DisplayMask = 1<<15;
------------------------------------------------o0o------------------------------------------------
www.tenouk.com Page 28 of 28