C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C ExpressionsAn expression is a formula in which operands are linked to each other by the use of operators to compute a value. An operand can be a function reference, a variable, an array element or a constant. Let's see an example: a-b; In the above expression, minus character (-) is an operator, and a, and b are the two operands. There are four types of expressions exist in C:
Each type of expression takes certain types of operands and uses a specific set of operators. Evaluation of a particular expression produces a specific value. For example: x = 9/2 + a-b; The entire above line is a statement, not an expression. The portion after the equal is an expression.
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic operators. An arithmetic expression computes a value of type int, float or double. When an expression contains only integral operands, then it is known as pure integer expression when it contains only real operands, it is known as pure real expression, and when it contains both integral and real operands, it is known as mixed mode expression. Evaluation of Arithmetic Expressions The expressions are evaluated by performing one operation at a time. The precedence and associativity of operators decide the order of the evaluation of individual operations. When individual operations are performed, the following cases can be happened:
Let's understand through an example. 6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Relational Expressions
Let's see a simple example:
#include <stdio.h>
int main()
{
int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}
Output
Logical Expressions
Let's see some example of the logical expressions.
Let's see a simple program of "&&" operator.
#include <stdio.h>
int main()
{
int x = 4;
int y = 10;
if ( (x <10) && (y>5))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Output
Let's see a simple example of "| |" operator
#include <stdio.h>
int main()
{
int x = 4;
int y = 9;
if ( (x <6) || (y>10))
{
printf("Condition is true");
}
else
printf("Condition is false");
return 0;
}
Output
Conditional Expressions
The Syntax of Conditional operator Suppose exp1, exp2 and exp3 are three expressions. exp1 ? exp2 : exp3 The above expression is a conditional expression which is evaluated on the basis of the value of the exp1 expression. If the condition of the expression exp1 holds true, then the final conditional expression is represented by exp2 otherwise represented by exp3. Let's understand through a simple example.
#include<stdio.h>
#include<string.h>
int main()
{
int age = 25;
char status;
status = (age>22) ? 'M': 'U';
if(status == 'M')
printf("Married");
else
printf("Unmarried");
return 0;
}
Output
Next TopicData Segments
|