Q2. What types of expressions can be formed in C++? Discuss each one of them with examples.
Ans. The expressions in C++ can be any type: arithmetic expression, relational (or logical) expression, compound expression etc.
- Arithmetic Expressions
Arithmetic expressions can either be integer expressions or real expressions. Sometimes a mixed expression can also be formed which is a mixture of real and integer expressions.
Integer expressions are formed by connecting integer constants and/or integer variables using integer arithmetic operators.
The following are valid integer expressions:
const count = 30;
int I, J, K, Y, Z;
- K –X
- K+X – Y + count
- –J +K *Y
- Z % X
Real expressions are formed by connecting real constants and/or real variables using real arithmetic operators (for example, % is not a real arithmetic operator).
The following are valid real expressions:
const bal = 250.53;
float qty, amount, value;
double fin, inter;
- qty * value
- (amount + qty * value) – bal
- fin + qty * inter
- inter – (qty * value) + fin
- Logical Expressions
The expressions that results into 0 (false) or 1 (true) are called logical expressions. The logical expressions are combination of constants, variables and logical and relational operators.
The rule for writing logical expressions states:
A logical expression may contain just one signed or unsigned variable or a constant, or it may have two or more variables or/and constants, or two or more expressions joined by valid relational and/or logical operators. Two or more variables or operators should not occur in continuation.
The following are examples of some valid logical expressions: