सी, पायथन, जावास्क्रिप्ट, गो, रस्ट, सॉलिडिटी जैसी भाषाओं और कंप्यूटर साइंस के बुनियादी और गणित के उन्नत सिद्धांतों को हिंदी में पढ़ने के लिए संपर्क करें। हम वेबसाइट और सॉफ्टवेयर भी बनाते हैं।
An operator is a symbol that specifies the mathematical, logical, or relational operation to be performed. C language supports different types of operators, which can be used with variables and constants to form expressions. These operators can be categorized into the following major groups:
Arithmetic operators
Relational operators
Equality operators
Logical operators
Unary operators
Conditional operators
Bitwise operators
Assignment operators
Comma operator
Sizeof operator
In this section, we will discuss all these operators.
2.15.1 Arithmetic Operators
Consider three variables declared as,
int a=9, b=3, result;
We will use these variables to explain arithmetic operators. Table 2.8 shows the arithmetic operators, their syntax, and usage in C language.
In Table 2.8, a and b (on which the operator is applied) are called operands. Arithmetic operators can be applied to any integer or floating-point number. The addition, subtraction, multiplication, and division (+, -, *, /) operators perform the usual arithmetic operations in C programs, so you are already familiar with these operators.
Introduction to C — पेज 41
Table 2.8 Arithmetic operators
Operation
Operator
Syntax
Comment
Result
Multiply
*
a*b
result = a*b
27
Divide
/
a/b
result = a/b
3
Addition
+
a+b
result = a+b
12
Subtraction
-
a-b
result = a-b
6
Modulus
%
a%b
result = a%b
0
However, the operator % must be new to you. The modulus operator (%) finds the remainder of an integer division. This operator can be applied only to integer operands and cannot be used on float or double operands. Therefore, the code given below generates a compiler error.
#include <stdio.h>
int main()
{
float c = 20.0;
printf("\n Result = %f", c % 5);
// WRONG. Modulus operator is being applied
// to a float operand
return 0;
}
While performing modulo division, the sign of the result is always the sign of the first operand (the dividend). Therefore,
16 % 3 = 1 -16 % 3 = -1
16 % -3 = 1 -16 % -3 = -1
When both operands of the division operator (/) are integers, the division is performed as an integer division. Integer division always results in an integer result. So, the result is always rounded-off by ignoring the remainder. Therefore,
9/4 = 2 and -9/4 = -3
From the above observation, we can conclude two things. If op1 and op2 are integers and the quotient is not an integer, then we have two cases:
If op1 and op2 have the same sign, then op1/op2 is the largest integer less than the true quotient.
If op1 and op2 have opposite signs, then op1/op2 is the smallest integer greater than the true quotient.
Note that it is not possible to divide any number by zero. This is an illegal operation that results in a run-time division-by-zero exception, thereby terminating the program.
Except for modulus operator, all other arithmetic operators can accept a mix of integer and floating point numbers. If both operands are integers, the result will be an integer. If one or both operands are floating point numbers, then the result would be a floating point number.
All the arithmetic operators bind from left to right. As in mathematics the multiplication, division, and modulus operators have higher precedence over the addition and subtraction operators, i.e., if an arithmetic expression consists of a mix of operators, then multiplication, division, and modulus will be carried out first in a left to right order, before any addition and subtraction could be performed. For example,
3 + 4 * 7
= 3 + 28
= 31
6. Write a program to perform addition, subtraction, division, integer division, multiplication, and modulo division on two integer numbers.
#include <stdio.h>
int main()
{
int num1, num2;
int add_res=0, sub_res=0, mul_res=0,
idiv_res=0, modiv_res=0;
float fdiv_res=0.0;
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
add_res= num1 + num2;
sub_res=num1 - num2;
mul_res = num1 * num2;
idiv_res = num1/num2;
modiv_res = num1%num2;
fdiv_res = (float)num1/num2;
printf("\n %d + %d = %d", num1, num2, add_res);
printf("\n %d - %d = %d", num1, num2, sub_res);
printf("\n %d x %d = %d", num1, num2, mul_res);
printf("\n %d / %d = %d (Integer Division)", num1, num2, idiv_res);
printf("\n %d %% %d = %d (Moduluo Division)", num1, num2, modiv_res);
printf("\n %d / %d = %.2f (Normal Division)", num1, num2, fdiv_res);
return 0;
}
Output
Enter the first number : 9
Enter the second number : 7
9 + 7 = 16
9 - 7 = 2
9 x 7 = 63
9 / 7 = 1 (Integer Division)
9 % 7 = 2 (Moduluo Division)
9 / 7 = 1.29 (Normal Division)
Programming in C — पेज 42
7. Write a program to subtract two long integers.
#include <stdio.h>
int main()
{
long int num1= 1234567, num2, diff=0;
printf("\n Enter the number: ");
scanf("%ld", &num2);
diff = num1 - num2;
printf("\n Difference = %ld", diff);
return 0;
}
Output
Enter the number: 1234
Difference = 1233333
2.15.2 Relational Operators
A relational operator, also known as a comparison operator, is an operator that compares two values. Expressions that contain relational operators are called relational expressions. Relational operators return true or false value, depending on whether the conditional relationship between the two operands holds or not.
For example, to test if x is less than y, relational operator < is used as x < y. This expression will return TRUE if x is less than y; otherwise the value of the expression will be FALSE.
Relational operators can be used to determine the relationships between the operands. These relationships are illustrated in Table 2.9.
Table 2.9 Relational operators
Operator
Meaning
Example
<
Less than
3<5 gives 1
>
Greater than
7>9 gives 0
<=
Less than or equal to
100 <= 100 gives 1
>=
Greater than equal to
50 >= 100 gives 0
The relational operators are evaluated from left to right. The operands of a relational operator must evaluate to a number. Characters are considered valid operands since they are represented by numeric values in the computer system. So, if we say, 'A' < 'B', where A is 65 and B is 66, then the result would be 1 as 65 < 66.
When arithmetic expressions are used on either side of a relational operator, then first the arithmetic expression will be evaluated and then the result will be compared. This is because arithmetic operators have a higher priority over relational operators.
However, relational operators should not be used for comparing strings as this will result in comparing the address of the string and not their contents. You must be wondering why so? The answer to this question will be clear to you in the later chapters. A few examples of relational operators are given below.
If x=1, y=2, and z=3, then
Expressions that evaluate to TRUE
Expressions that evaluate to FALSE
Note that these expressions are true because their value is not zero.
Note that these expressions are false because their value is zero.
(x)
(x - 1)
(x + y)
(!(z))
(z * 9)
(0 * y)
(z + 10 - 5 * x)
(y == 1)
(z - x + y)
(y % 2)
Note
Although blank spaces are allowed between an operand and an operator, no space is permitted between the components of an operator (like > = is not allowed, it should be >=). Therefore, writing x==y is correct but writing x = = y is not acceptable in C language.
8. Write a program to show the use of relational operators
#include <stdio.h>
int main()
{
int x=10, y=20;
printf("\n %d < %d = %d", x, y, x<y);
printf("\n %d == %d = %d", x, y, x==y);
printf("\n %d != %d = %d", x, y, x!=y);
printf("\n %d > %d = %d", x, y, x>y);
printf("\n %d >= %d = %d", x, y, x>=y);
printf("\n %d <= %d = %d", x, y, x<=y);
return 0;
}
C language supports two kinds of equality operators to compare their operands for strict equality or inequality. They are equal to (==) and not equal to (!=) operators. The equality operators have lower precedence than the relational operators.
The equal-to operator (==) returns true (1) if operands on both the sides of the operator have the same value; otherwise, it returns false (0). On the contrary, the not-equal-to operator (!=) returns true (1) if the operands do not have the same value; else it returns false (0). Table 2.10 summarizes equality operators.
Table 2.10 Equality operators
Operator
Meaning
==
Returns 1 if both operands are equal, 0 otherwise
!=
Returns 1 if operands do not have the same value, 0 otherwise
2.15.4 Logical Operators
C language supports three logical operators—logical AND (&&), logical OR (||), and logical NOT (!). As in case of arithmetic expressions, the logical expressions are evaluated from left to right.
Logical AND
Logical AND operator is a binary operator, which simultaneously evaluates two values or relational expressions. If both the operands are true, then the whole expression evaluates to true. If both or one of the operands is false, then the whole expression evaluates to false. The truth table of logical AND operator is given in Table 2.11.
Table 2.11 Truth table of logical AND
A
B
A && B
0
0
0
0
1
0
1
0
0
1
1
1
For example,
(a < b) && (b > c)
The expression to the left is (a < b) and that on the right is (b > c). The whole expression is true only if both expressions are true, i.e., if b is greater than both a and c.
Logical OR
Logical OR returns a false value if both the operands are false. Otherwise it returns a true value. The truth table of logical OR operator is given in Table 2.12.
Table 2.12 Truth table of logical OR
A
B
A || B
0
0
0
0
1
1
1
0
1
1
1
1
For example,
(a < b) || (b > c)
The expression to the left is (a < b) and that on the right is (b > c). The whole expression is true if either b is greater than a or b is greater than c or b is greater than both a and c.
Logical NOT
The logical NOT operator takes a single expression and negates the value of the expression. That is, logical NOT produces a zero if the expression evaluates to a non-zero value and produces a 1 if the expression produces a zero. In other words, it just reverses the value of the expression. The truth table of logical NOT operator is given in Table 2.13.
Programming in C — पेज 44
Table 2.13 Truth table of Logical NOT
A
!A
0
1
1
0
For example,
int a = 10, b;
b = !a;
Now the value of b = 0. This is because value of a = 10. !a = 0. The value of !a is assigned to b, hence, the result.
Logical expressions operate in a short cut fashion and stop the evaluation when it knows for sure what the final outcome would be. For example, in a logical expression involving logical AND, if the first operand is false, then the second operand is not evaluated as it is for sure that the result will be false. Similarly, for a logical expression involving logical OR, if the first operand is true, then the second operand is not evaluated as it is for sure that the result will be true.
But this approach has a side effect. For example, consider the following expression:
(x > 9) && (y++ > 0)
OR
(x > 9) || (y++ > 0)
In the above logical AND expression if the first operand is false then the entire expression will not be evaluated and thus the value of y will never be incremented. Same is the case with the logical OR expression. If the first expression is true then the second will never be evaluated and value of y will never be incremented.
2.15.5 Unary Operators
Unary operators act on single operands. C language supports three unary operators: unary minus, increment, and decrement operators.
Unary Minus
Unary minus (-) operator is strikingly different from the binary arithmetic operator that operates on two operands and subtracts the second operand from the first operand. When an operand is preceded by a minus sign, the unary operator negates its value. For example, if a number is positive then it becomes negative when preceded with a unary minus operator. Similarly, if the number is negative, it becomes positive after applying the unary minus operator. For example,
int a, b = 10;
a = -(b);
The result of this expression is a = -10, because variable b has a positive value. After applying unary minus operator (-) on the operand b, the value becomes -10, which indicates it as a negative value.
Increment Operator (++) and Decrement Operator (--)
The increment operator is a unary operator that increases the value of its operand by 1. Similarly, the decrement operator decreases the value of its operand by 1. For example, --x is equivalent to writing x = x - 1.
The increment/decrement operators have two variants—prefix and postfix. In a prefix expression (++x or --x), the operator is applied before an operand is fetched for computation and, thus, the altered value is used for the computation of the expression in which it occurs. On the contrary, in a postfix expression (x++ or x--) an operator is applied after an operand is fetched for computation. Therefore, the unaltered value is used for the computation of the expression in which it occurs.
Therefore, an important point to note about unary increment and decrement operators is that x++ is not same as ++x. Similarly, x-- is not same as --x. Both x++ and ++x increment the value of x by 1. In the former case, the value of x is returned before it is incremented, whereas, in the latter case, the value of x is returned after it is incremented. For example,
int x = 10, y;
y = x++;
is equivalent to writing
y = x;
x = x + 1;
whereas,
y = ++x;
is equivalent to writing
x = x + 1;
y = x;
Introduction to C — पेज 45
The same principle applies to unary decrement operators. The unary operators have a higher precedence than the binary operators. If in an expression we have more than one unary operator then unlike arithmetic operators, they are evaluated from right to left.
When applying the increment or decrement operator, the operand must be a variable. This operator can never be applied to a constant or an expression.
Note
When postfix ++ or -- is used with a variable in an expression, then the expression is evaluated first using the original value of the variable and then the variable is incremented or decremented by one.
Similarly, when prefix ++ or -- is used with a variable in an expression, then the variable is first incremented or decremented and then the expression is evaluated using the new value of the variable.
9. Write a program to illustrate the use of unary prefix increment and decrement operators.
#include <stdio.h>
int main()
{
int num = 3;
// Using unary prefix increment operator
printf("\n The value of num = %d", num);
printf("\n The value of ++num = %d", ++num);
printf("\n The new value of num = %d", num);
// Using unary prefix decrement operator
printf("\n\n The value of num = %d", num);
printf("\n The value of --num = %d", --num);
printf("\n The new value of num = %d", num);
return 0;
}
Output
The value of num = 3
The value of ++num = 4
The new value of num = 4
The value of num = 4
The value of --num = 3
The new value of num = 3
10. Write a program to illustrate the use of unary postfix increment and decrement operators.
#include <stdio.h>
int main()
{
int num = 3;
// Using unary postfix increment operator
printf("\n The value of num = %d", num);
printf("\n The value of num++ = %d", num++);
printf("\n The new value of num = %d", num);
// Using unary postfix decrement operator
printf("\n\n The value of num = %d", num);
printf("\n The value of num-- = %d", num--);
printf("\n The new value of num = %d", num);
return 0;
}
Output
The value of num = 3
The value of num++ = 3
The new value of num = 4
The value of num = 4
The value of num-- = 4
The new value of num = 3
2.15.6 Conditional Operator
The conditional operator or the ternary (?:) is just like an if-else statement that can be used within expressions. Such an operator is useful in situations in which there are two or more alternatives for an expression. The syntax of the conditional operator is
exp1 ? exp2 : exp3
exp1 is evaluated first. If it is true, then exp2 is evaluated and becomes the result of the expression, otherwise exp3 is evaluated and becomes the result of the expression. For example,
large = (a > b) ? a : b
The conditional operator is used to find the larger of two given numbers. First exp1, that is (a > b) is evaluated. If a is greater than b, then large = a, else large = b. Hence, large is equal to either a or b but not both.
Hence, conditional operator is used in certain situations, replacing if-else condition phrases. Conditional
Programming in C — पेज 46
operator makes the program code more compact, more readable, and safer to use, as it is easier to check any error (if present) in one single line itself. Conditional operator is also known as ternary operator as it is neither a unary nor a binary operator; it takes three operands.
An expression using conditional operator can be used as an operand of another conditional operation. That means C allows you to have nested conditional operators. Consider the expression given below which illustrates this concept.
int a = 5, b = 3, c= 7, small;
small = (a<b? (a<c?a:c) : (b<c?b:c));
11. Write a program to find the largest of three numbers using ternary operator.
#include <stdio.h>
int main()
{
int num1, num2, num3, large;
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
large = num1>num2? (num1>num3?num1:num3) :
(num2>num3?num2:num3);
printf("\n The largest number is: %d", large);
return 0;
}
Output
Enter the first number: 12
Enter the second number: 34
Enter the third number: 23
The largest number is: 34
2.15.7 Bitwise Operators
As the name suggests, bitwise operators are those operators that perform operations at bit level. These operators include: bitwise AND, bitwise OR, bitwise XOR, and shift operators. The bitwise operators expect their operands to be integers and treat them as a sequence of bits.
Bitwise AND
Like boolean AND (&&) bitwise AND operator (&) performs operation on bits instead of bytes, chars, integers, etc. When we use the bitwise AND operator, the bit in the first operand is ANDed with the corresponding bit in the second operand. The truth table is same as we had seen in logical AND operation, i.e., the bitwise AND operator compares each bit of its first operand with the corresponding bit of its second operand. If both bits are 1, the corresponding bit in the result is 1 and 0 otherwise. For example,
10101010 & 01010101 = 00000000
In a C program, the & operator is used as follows
int a = 10, b = 20, c=0;
c= a&b;
Bitwise OR
When we use the bitwise OR operator (|), the bit in the first operand is ORed with the corresponding bit in the second operand. The truth table is same as we had seen in logical OR operation, i.e., the bitwise-OR operator compares each bit of its first operand with the corresponding bit of its second operand. If one or both bits are 1, the corresponding bit in the result is 1 and 0 otherwise. For example,
10101010 | 01010101 = 11111111
In a C program, the | operator is used as follows.
int a = 10, b = 20, c=0;
c= a|b;
Bitwise XOR
The bitwise XOR operator (^) performs operation on individual bits of the operands. When we use the bitwise XOR operator, the bit in the first operand is XORed with the corresponding bit in the second operand. The truth table of bitwise XOR operator is shown in Table 2.14.
The bitwise XOR operator compares each of its first operand with the corresponding bit of its second operand. If one of the bits is 1, the corresponding bit in the result is 1 and 0 otherwise. For example,
10101010 ^ 01010101 = 11111111
Table 2.14 Truth table of bitwise XOR
A
B
A ^ B
0
0
0
0
1
1
1
0
1
1
1
0
Introduction to C — पेज 47
In a C program, the ^ operator is used as follows:
int a = 10, b = 20, c=0;
c= a^b
Bitwise NOT
The bitwise NOT, or complement, is a unary operator that performs logical negation on each bit of the operand. By performing negation of each bit, it actually produces the 1s complement of the given binary value. Bitwise NOT operator sets the bit to 1 if it was initially 0 and sets it to 0 if it was initially 1. For example,
~10101011 = 01010100
Note
Bitwise operators are used for testing the bits or shifting them left or right. Always remember that bitwise operators cannot be applied to float or double variables.
Shift Operator
C supports two bitwise shift operators. They are shift-left (<<) and shift-right (>>). These operations are simple and are responsible for shifting bits either to the left or to the right. The syntax for a shift operation can be given as
operand op num
where the bits in operand are shifted left or right depending on the operator (left if the operator is << and right if the operator is >>) by the number of places denoted by num.
For example, if we have x = 0001 1101, then
x << 1 produces 0011 1010
When we apply a left-shift, every bit in x is shifted to the left by one place. So, the MSB (most significant bit) of x is lost, and the LSB of x is set to 0.
Therefore, if we have x = 0001 1101, then
x << 4 produces 1101 0000.
If you observe carefully, you will notice that shifting once to the left multiplies the number by 2. Hence, multiple shifts of 1 to the left, results in multiplying the number by 2 over and over again.
On the contrary, when we apply a shift-right operator, every bit in x is shifted to the right by one place. So, the LSB (least significant bit) of x is lost, and the MSB of x is set to 0. For example, if we have x = 0001 1101, then
x >> 1 produces = 0000 1110
Similarly, if we have x = 0001 1101, then
x >> 4 produces 0000 0001.
If you observe carefully, you will notice that shifting once to the right divides the number by 2. Hence, multiple shifts of 1 to the right, results in dividing the number by 2 over and over again.
12. Write a program to show use of bitwise operators.
#include <stdio.h>
void main()
{
int a=27, b= 39;
printf("\n a & b = %d", a&b);
printf("\n a | b = %d", a|b);
printf("\n ~a = %d", ~a);
printf("\n ~b = %d", ~b);
printf("\n a ^ b = %d", a^b);
printf("\n a << 1 = %d", a<<1);
printf("\n b >> 1 = %d", b>>1);
}
Output
a & b = 3
a | b = 63
~a = -28
~b = -40
a ^ b = 60
a << 1 = 54
b >> 1 = 19
2.15.8 Assignment Operators
In C, the assignment operator is responsible for assigning values to the variables. While the equal sign (=) is the fundamental assignment operator, C language also supports other assignment operators that provide shorthand ways to represent common variable assignments.
When an equal sign is encountered in an expression, the compiler processes the statement on the right side of the sign and assigns the result to the variable on the left side. For example,
int x;
x = 10;
assigns the value 10 to variable x. If we have,
int x = 2, y = 3, sum = 0;
sum = x + y;
then sum = 5.
The assignment operator has right-to-left associativity, so the expression
a = b = c = 10;
Programming in C — पेज 48
is evaluated as
(a = (b = (c = 10)));
First 10 is assigned to c, then the value of c is assigned to b. Finally, the value of b is assigned to a.
The operand to the left of the assignment operator must always be a variable name. C does not allow any expression, constant, or function to be placed to the left of the assignment operator. Therefore, the statement a + b = 0, is invalid in C language.
To the right of the assignment operator you may have an arbitrary expression. In that case, the expression would be evaluated and the result would be stored in the location denoted by the variable name.
Other Assignment Operators
C language supports a set of shorthand assignment operators of the form
variable op = expression
where op is a binary arithmetic operator. Table 2.15 shows the list of other assignment operators that are supported by C.
The advantage of using shorthand assignment operators are as follows:
Shorthand expressions are easier to write as the expression on the left side need not be repeated.
The statements involving shorthand operators are easier to read as they are more concise.
The statements involving shorthand operators are more efficient and easy to understand.
13. Write a program to demonstrate the use of assignment operators.
#include <stdio.h>
int main()
{
int num1 = 3, num2 = 5;
printf("\n Initial value of num1 = %d and
num2 = %d", num1, num2);
num1 += num2 * 4 - 7;
printf("\n After the evaluation of the
expression num1 = %d and num2 = %d",
num1, num2);
return 0;
}
Output
Initial value of num1 = 3 and num2 = 5
After the evaluation of the expression num1 = 16 and num2 = 5
2.15.9 Comma Operator
The comma operator in C takes two operands. It works by evaluating the first and discarding its value, and then evaluates the second and returns the value as the result of the expression. Comma separated operands when chained together are evaluated in left-to-right sequence with the right most value yielding the result of the expression. Among all the operators, the comma operator has the lowest precedence.
Therefore, when a comma operator is used, the entire expression evaluates to the value of the right expression. For example, the following statement first increments a, then increments b and then assigns the value of b to x.
int a=2, b=3, x=0;
x = (++a, b+=a);
Now, the value of x = 6.
2.15.10 Sizeof Operator
The sizeof operator is a unary operator used to calculate the size of data types. This operator can be applied to all data types. When using this operator, the keyword sizeof is followed by a type name, variable, or expression. The operator returns the size of the variable, data type, or expression, in bytes, i.e., the sizeof operator is used to determine the amount of memory space that the variable/expression/data type will take.
When a type name is used, it is enclosed in parentheses, but in case of variable names and expressions they can be specified with or without parentheses. A sizeof expression returns an unsigned value that specifies the space in bytes required by the data type, variable, or expression. For example, sizeof(char) returns 1, i.e., the size of a character data type. If we have,
int a = 10;
unsigned int result;
result = sizeof(a);
Then result = 2, which is the space required to store the variable a in memory. Since a is an integer, it requires 2 bytes of storage space.
2.15.11 Operator Precedence Chart
C operators have two properties: priority and associativity. When an expression has more than one operator then it is the relative priorities of the operators with respect to each other that determine the order in which the expression will be evaluated. Associativity defines the direction in
Introduction to C — पेज 49
Table 2.15 Assignment Operators
Operator
Syntax
Equivalent to
Meaning
Example
/=
variable /= expression
variable = variable / expression
Divides the value of a variable by the value of an expression and assigns the result to the variable.
float a= 9.0;float b = 3.0;a /= b;
\=
variable \= expression
variable = variable \ expression
Divides the value of a variable by the value of an expression and assigns the integer result to the variable.
int a= 9;int b = 3;a \= b;
*=
variable *= expression
variable = variable * expression
Multiplies the value of a variable by the value of an expression and assigns the result to the variable.
int a= 9;int b = 3;a *= b;
+=
variable += expression
variable = variable + expression
Adds the value of a variable to the value of an expression and assigns the result to the variable.
int a= 9;int b = 3;a += b;
-=
variable -= expression
variable = variable - expression
Subtracts the value of the expression from the value of the variable and assigns the result to the variable.
int a= 9;int b = 3;a -= b;
&=
variable &= expression
variable = variable & expression
Performs the bitwise AND between the value of variable and value of the expression and assigns the result to the variable.
int a = 10;int b = 20;a &= b;
^=
variable ^= expression
variable = variable ^ expression
Performs the bitwise XOR between the value of variable and value of the expression and assigns the result to the variable.
int a = 10;int b = 20;a ^= b;
<<=
variable <<= amount
variable = variable << amount
Performs an arithmetic left shift (amount times) on the value of a variable and assigns the result back to the variable.
int a= 9;int b = 3;a <<= b;
>>=
variable >>= amount
variable = variable >> amount
Performs an arithmetic right shift (amount times) on the value of a variable and assigns the result back to the variable.
int a= 9;int b = 3;a >>= b;
Programming in C — पेज 50
which the operator having the same precedence acts on the operands. It can be either left-to-right or right-to-left. Priority is given over associativity to determine the order in which the expressions are evaluated. Associativity is then applied, if the need arises.
Table 2.16 lists the operators that C language supports in the order of their precedence (highest to lowest). The associativity indicates the order in which the operators of equal precedence in an expression are evaluated.
You must be wondering why the priority of the assignment operator is so low. This is because the action of assignment is performed only when the entire computation is done. It is not uncommon for a programmer to forget the priority of the operators while writing any program. So it is recommended that you use the parentheses operator to override default priorities. From Table 2.16 you can see that the parenthesis operator has the highest priority. So any operator placed within the parentheses will be evaluated before any other operator.
14. Write a program to calculate the area of a circle.
#include <stdio.h>
int main()
{
float radius;
double area, circumference;
printf("\n Enter the radius of the circle: ");
scanf("%f", &radius);
area = 3.14 * radius * radius;
circumference = 2 * 3.14 * radius;
printf(" Area = %.2lf", area);
printf("\n CIRCUMFERENCE = %.2e", circumference);
return 0;
}
Output
Enter the radius of the circle: 7
Area = 153.86
CIRCUMFERENCE = 4.40e+01
15. Write a program to print the ASCII value of a character.
#include <stdio.h>
int main()
{
char ch;
printf("\n Enter any character: ");
scanf("%c", &ch);
printf("\n The ASCII value of %c is:
%d",ch,ch);
return 0;
}
Output
Enter any character: A
The ASCII value of A is: 65
16. Write a program to read a character in upper case and then print it in lower case.
#include <stdio.h>
int main()
{
char ch;
printf("\n Enter any character in upper
case: ");
scanf("%c", &ch);
printf("\n The character in lower case
is: %c", ch+32);
return 0;
}
Output
Enter any character: A
The character in lower case is: a
17. Write a program to print the digit at ones place of a number.
#include <stdio.h>
int main()
{
int num, digit_at_ones_place;
printf("\n Enter any number: ");
scanf("%d", &num);
digit_at_ones_place = num % 10;
printf("\n The digit at ones place of %d
is %d", num, digit_at_ones_place);
return 0;
}
Programming in C — पेज 52
Output
Enter any number: 123
The digit at ones place of 123 is 3
18. Write a program to swap two numbers using a temporary variable.
#include <stdio.h>
int main()
{
int num1, num2, temp;
printf("\n Enter the first number: ");
scanf("%d",&num1);
printf("\n Enter the second number: ");
scanf("%d",&num2);
temp = num1;
num1 = num2;
num2=temp;
printf("\n The first number is %d", num1);
printf("\n The second number is %d", num2);
return 0;
}
Output
Enter the first number : 3
Enter the second number : 5
The first number is 5
The second number is 3
19. Write a program to swap two numbers without using a temporary variable.
#include <stdio.h>
int main()
{
int num1, num2;
printf("\n Enter the first number: ");
scanf("%d",&num1);
printf("\n Enter the second number: ");
scanf("%d",&num2);
num1 = num1 + num2;
num2= num1 - num2;
num1 = num1 - num2;
printf("\n The first number is %d", num1);
printf("\n The second number is %d", num2);
return 0;
}
Output
Enter the first number: 3
Enter the second number: 5
The first number is 5
The second number is 3
20. Write a program to convert degrees Fahrenheit into degrees celsius.
#include <stdio.h>
int main()
{
float fahrenheit, celsius;
printf("\n Enter the temperature in
fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (0.56) * (fahrenheit - 32);
printf("\n Temperature in degrees celsius
= %f", celsius);
return 0;
}
Output
Enter the temperature in fahrenheit: 32
Temperature in degree celsius = 0
21. Write a program that displays the size of every data type.
#include <stdio.h>
int main()
{
printf("\n The size of short integer is:
%d", sizeof(short int));
printf("\n The size of unsigned integer
is: %d", sizeof(unsigned int));
printf("\n The size of signed integer is:
%d", sizeof(signed int));
printf("\n The size of integer is: %d",
sizeof(int));
printf("\n The size of long integer is:
%d", sizeof(long int));
printf("\n The size of character is: %d",
sizeof(char));
printf("\n The size of unsigned character
is: %d", sizeof(unsigned char));
printf("\n The size of signed character
is: %d", sizeof(signed char));
Introduction to C — पेज 53
printf("\n The size of floating point
number is: %d", sizeof(float));
printf("\n The size of double number is:
%d", sizeof(double));
return 0;
}
Output
The size of short integer is: 2
The size of unsigned integer is: 2
The size of signed integer is: 2
The size of integer is: 2
The size of long integer is: 2
The size of character is: 1
The size of unsigned character is: 1
The size of signed character is: 1
The size of floating point number is: 4
The size of double number is: 8
22. Write a program to calculate the total amount of money in the piggybank, given the coins of Rs 10, Rs 5, Rs 2, and Re 1.
#include <stdio.h>
int main()
{
int num_of_10_coins, num_of_5_coins, num_
of_2_coins, num_of_1_coins;
float total_amt = 0.0;
printf("\n Enter the number of Rs10 coins
in the piggybank: ");
scanf("%d", &num_of_10_coins);
printf("\n Enter the number of Rs5 coins
in the piggybank: ");
scanf("%d", &num_of_5_coins);
printf("\n Enter the number of Rs2 coins
in the piggybank: ");
scanf("%d", &num_of_2_coins);
printf("\n Enter the number of Re1 coins
in the piggybank: ");
scanf("%d", &num_of_1_coins);
total_amt = num_of_10_coins * 10 + num_
of_5_coins * 5 + num_of_2_coins * 2 +
num_of_1_coins;
printf("\n Total amount in the piggybank
= %f", total_amt);
return 0;
}
Output
Enter the number of Rs10 coins in the piggybank: 10
Enter the number of Rs5 coins in the piggybank: 23
Enter the number of Rs2 coins in the piggybank: 43
Enter the number of Re1 coins in the piggybank: 6
Total amount in the piggybank = 307
23. Write a program to calculate the bill amount for an item given its quantity sold, value, discount, and tax.
#include <stdio.h>
int main()
{
float total_amt, amt, sub_total,
discount_amt, tax_amt, qty, val,
discount, tax;
printf("\n Enter the quantity of item
sold: ");
scanf("%f", &qty);
printf("\n Enter the value of item: ");
scanf("%f", &val);
printf("\n Enter the discount percentage: ");
scanf("%f", &discount);
printf("\n Enter the tax: ");
scanf("%f", &tax);
amt = qty * val;
discount_amt = (amt * discount)/100.0;
sub_total = amt - discount_amt;
tax_amt = (sub_total * tax) /100.0;
total_amt = sub_total + tax_amt;
printf("\n\n\n ************** BILL
**************");
printf("\n Quantity Sold: %f", qty);
printf("\n Price per item: %f", val);
printf("\n ---------------");
printf("\n Amount: %f", amt);
printf("\n Discount: - %f", discount_amt);
Enter the quantity of item sold: 20
Enter the value of item: 300
Enter the discount percentage: 10
Enter the tax: 12
************** BILL **************
Quantity Sold : 20
Price per item : 300
-----------------------------
Amount : 6000
Discount : - 600
Discounted Total : 5400
Tax : + 648
-----------------------------
Total Amount 6048
2.16 TYPE CONVERSION AND TYPECASTING
Till now we have assumed that all the expressions involved data of the same type. But what happens when expressions involve two different data types, like multiplying a floating point number and an integer. Such type of situations are handled either through type conversion or typecasting.
Type conversion or typecasting of variables refers to changing a variable of one data type into another. Type conversion is done implicitly, whereas typecasting has to be done explicitly by the programmer. We will discuss both of them here.
2.16.1 Type Conversion
Type conversion is done when the expression has variables of different data types. To evaluate the expression, the data type is promoted from lower to higher level where the hierarchy of data types (from higher to lower) can be given as: double, float, long, int, short, and char. Figure 2.14 shows the conversion hierarchy of data types.
Figure 2.14 Conversion hierarchy of data types
Higher level
long double
double
float
unsigned long int
long int
unsigned int
int
short, char
Lower level
Type conversion is automatically done when we assign an integer value to a floating point variable. Consider the code given below in which an integer data type is promoted to float. This is known as promotion (when a lower level data type is promoted to a higher type).
float x;
int y = 3;
x = y;
Now, x = 3.0, as automatically integer value is converted into its equivalent floating point representation. In some cases, when an integer is converted into a floating point number, the resulting floating point number may not exactly match the integer value. This is because the floating point format used internally by the computer cannot accurately represent every possible integer number. So even if the value of x = 2.99999995, you must not worry. The loss of accuracy because of this feature would be always insignificant for the final result.
Let us summarize how promotion is done:
float operands are converted to double.
char or short operands whether signed or unsigned are converted to int.
If any one operand is double, the other operand is also converted to double. Hence, the result is also of type double.
If any one operand is long, the other operand is also converted to long. Hence, the result is also of type long.
Figure 2.15 exhibits type conversions in an expression.
(ch + i) (f / i) (d - f)
int + int float / int double - float
int float double
(int promoted (float promoted
to float) to double)
int * float -> float
float + double -> double
double
When a char type is operated with an int type data, char is promoted to int.
When a float type data is operated with an int, then int is promoted to float.
When a float type data is subtracted from a double type data, then float is promoted to double.
Consider the following group of statements:
float f = 3.5;
int i;
i = f;
The statement i = f results in f to be demoted to type int, i.e., the fractional part of f will be lost and i will contain 3 (not 3.5). In this case demotion takes place, i.e., a higher level data type is converted into a lower type. Whenever demotion occurs, some information is lost. For example, in this case the fractional part of the floating point number is lost.
Similarly, if we convert an int to a short int or a long int to int, or int to char, the compiler just drops the extra bits (Figure 2.16).
Note
No compile time warning message is generated when information is lost while demoting the type of data.
Figure 2.16 Implicit conversion example
char ch;
int i;
i = 1234;
ch = i;
Contents of i (binary equivalent of 1234): 0000 0100 1101 0010
Contents of ch: 1101 0010
Thus we can observe the following changes are unavoidable when performing type conversions.
When a float value is converted to an int value, the fractional part is truncated.
When a double value is converted to a float value, rounding of digits is done.
When a long int is converted into int, the excess higher order bits are dropped.
These changes may cause incorrect results.
2.16.2 Typecasting
Typecasting is also known as forced conversion. Typecasting an arithmetic expression tells the compiler to represent the value of the expression in a certain way. It is done when the value of a higher data type has to be converted into the value of a lower data type. But this casting is under the programmer's control and not under compiler's control. For example, if we need to explicitly typecast an integer variable into a floating point variable, then the code to perform typecasting can be given as:
float salary = 10000.00;
int sal;
sal = (int) salary;
When floating point numbers are converted to integers (as in type conversion), the digits after the decimal are truncated. Therefore, data is lost when floating-point numbers are converted to integral representations. So in order to avoid such type of inaccuracies, int type variables must be typecast to float type.
As we see in the code, typecasting can be done by placing the destination data type in parentheses followed by the variable name that has to be converted. Hence, we conclude that typecasting is done to make a variable of one data type to act like a variable of another data type.
We can also typecast integer values to its character equivalent (as per ASCII code) and vice versa. Typecasting is also done in arithmetic operations to get correct result. For example, when dividing two integers, the result can be of floating type. Also when multiplying two integers the result can be of long int. So to get correct precision value, typecasting can be done. For instance:
int a = 500, b = 70 ;
float res;
res = (float) a/b;
Let us look at some more examples of typecasting.
res = (int) 9.5;
9.5 is converted to 9 by truncation and then assigned to res.
Programming in C — पेज 56
res = (int)12.3 / (int)4.2;
It is evaluated as 12/4 and the value 3 is assigned to res.
res = (double) total/n;total is converted to double and then division is done in floating point mode.
res = (int) (a+b);
The value of a+b is converted to integer and then assigned to res.
res = (int)a + b;a is converted to int and then added with b.
res = cos((double)x);
It converts x to double before finding its cosine value.
24. Write a program to convert a floating point number into the corresponding integer.
#include <stdio.h>
int main()
{
float f_num;
int i_num;
printf("\n Enter any floating point number: ");
scanf("%f", &f_num);
i_num = (int)f_num;
printf("\n The integer variant of %f is =
%d", f_num, i_num);
return 0;
}
Output
Enter any floating point number: 23.45
The integer variant of 23.45 is = 23
25. Write a program to convert an integer into the corresponding floating point number.
#include <stdio.h>
int main()
{
float f_num;
int i_num;
printf("\n Enter any integer: ");
scanf("%d", &i_num);
f_num = (float)i_num;
printf("\n The floating point variant of
%d is = %f", i_num, f_num);
return 0;
}
Output
Enter any integer: 12
The floating point variant of 12 is = 12.00000
26. Write a program to calculate a student's result based on two examinations, one sports event, and three activities conducted. The weightage of activities = 30%, sports = 20%, and examination = 50%.
#include <stdio.h>
#define ACTIVITIES_WEIGHTAGE 30
#define SPORTS_WEIGHTAGE 20
#define EXAMS_WEIGHTAGE 50
#define EXAMS_TOTAL 200
#define ACTIVITIES_TOTAL 60
#define SPORTS_TOTAL 50
int main()
{
int exam_score1, activities_score1,
sports_score;
int exam_score2, activities_score2,
activities_score3;
float exam_total, activities_total;
float total_percent, exam_percent,
sports_percent, activities_percent;
printf("\n Enter the score obtained in
two examinations (out of 100) : ");
scanf("%d %d", &exam_score1, &exam_
score2);
printf("\n Enter the score obtained in
sports events (out of 50) : ");
scanf("%d", &sports_score);
printf("\n Enter the score obtained in
three activities (out of 20) : ");
scanf("%d %d %d", &activities_score1,
&activities_score2, &activities_
score3);
exam_total = exam_score1 + exam_score2;
activities_total = activities_score1 +
activities_score2 + activities_score3;
exam_percent = (float)exam_total * EXAMS_
WEIGHTAGE / EXAMS_TOTAL;
sports_percent = (float)sports_score *
SPORTS_WEIGHTAGE / SPORTS_TOTAL;
activities_percent = (float)activities_
total * ACTIVITIES_WEIGHTAGE /
ACTIVITIES_TOTAL;
total_percent = exam_percent + sports_
percent + activities_percent;
printf("\n\n *************************
RESULT *************************");
printf("\n Total percent in examintaion :
%f", exam_percent);
printf("\n Total percent in activities :
%f", activities_percent);
printf("\n Total percent in sports :
%f", sports_percent);
printf("\n ---------------------------------------------
--");
printf("\n Total percentage : %f", total_
percent);
return 0;
}
printf("\n Total percent in examintaion :
%f", exam_percent);
printf("\n Total percent in activities :
%f", activities_percent);
printf("\n Total percent in sports :
%f", sports_percent);
printf("\n ---------------------------------------------
--");
printf("\n Total percentage : %f", total_
percent);
return 0;
}