Ternary and Assignment Operators in C Language
Ternary and Assignment Operators in C Language
Ternary Operator (?:)
A conditional operator is a ternary operator, that is, it work on 3 operands.
Syntax
conditional Expression ? expression 1 : expression 2
Working of Conditional operator :-
- The first expression conditional Expression is evaluated first. This expression evaluates to 1 if it's true and evaluates to 0 if it's false.
- If conditional Expression is true, expression 1 is evaluated.
- If conditional Expression is false, expression 2 is evaluated.
Example :
#include <stdio.h>
int main ()
{
char february;
int days;
printf(" if this year is leap year, enter 1. if not enter any integer: ");
scanf(" %c", & february);
days = (february == '1') ? 29 : 28;
printf(" number of days in february = %d", days);
return 0;
}
Output
if this year is leap year, enter 1. if not enter any integer: 1
Number of days in february = 29
Assignment Operator
An assignment operator is used for assigning a value to a variable. The most common assignment operator is '='.
Operator
|
Example
|
Same
as
|
=
|
a = b
|
a = b
|
+=
|
a +=
b
|
a =
a+b
|
-=
|
a -=
b
|
a =
a-b
|
*=
|
a *=
b
|
a =
a*b
|
/=
|
a /=
b
|
a =
a/b
|
%=
|
a %=
b
|
a =
a%b
|
Example -
#include <stdio.h>
int main()
{
int a =5, c;
c=a;
printf(" c = %d \n", c);
c + = a; // c= c+a
printf(" c = %d \n", c);
int main()
{
int a =5, c;
c=a;
printf(" c = %d \n", c);
c + = a; // c= c+a
printf(" c = %d \n", c);
c - = a; // c= c-a
printf(" c = %d \n", c);
c *= a; // c= c*a
printf(" c = %d \n", c);
c /= a; // c= c/a
printf(" c = %d \n", c);
c % = a; // c= c%a
printf(" c = %d \n", c);
return 0;
}
c = 5
c = 10
return 0;
}
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
c = 0
Comments
Post a Comment