13
12 3. OPERATORS & EXPRESSIONS EXERCISES A] Answer the following questions. 1) Explain different types of operators available in C. Following types, operators are available in C. Type of Operator Symbolic Representation Arithmetic Operators +, - , *, / and % Relational Operators >,<,= =,>=.<= and != Logical Operators &&,|| and ! Increment and Decrement operator ++ and -- Assignment Operator = Bit wise Operators &,|,^,>>,<< and ~ Comma Operator , Conditional Operator ? : 2) What are the uses of comma (,) and conditional (?) operators? 1) Comma Operator (,): The comma operator is used to separate two or more expressions. The comma operator has the lowest priority among all the operators. It is not essential to enclose the expressions with comma operators within the parenthesis. For example the below given statements are valid. Example: a=2,b=4,c=a+b; (a=2,b=4,c=a+b;) 2) Conditional Operator (?): The conditional operator contains condition followed by two statements or values. If the condition is true the first statement is executed otherwise the second statement. The conditional operator (?) and (:) are sometimes called ternary operators because they take three arguments. The syntax of conditional operator is as given below. Syntax: Condition ? (expression1) : (expression2); 3) What are Unary operators and their uses? Unary Operators Unary operators are increment operator (++), decrement (--) and minus (-). These operators and their descriptions are given in the table 3.3. Operator Description or Action - Minus ++ Increment -- Decrement & Address Operator Size of Gives the size of operator Table 3.3 Unary Arithmetic Operators a ) Minus (-) : Unary minus is used for indicating or changing the algebraic sign of a value. For Example int x= -50; int y= -x;

Chapter 3 Operators

Embed Size (px)

Citation preview

Page 1: Chapter 3 Operators

12

3. OPERATORS & EXPRESSIONS

EXERCISES

A] Answer the following questions. 1) Explain different types of operators available in C. Following types, operators are available in C.

Type of Operator Symbolic Representation Arithmetic Operators +, - , *, / and % Relational Operators >,<,= =,>=.<= and != Logical Operators &&,|| and ! Increment and Decrement operator ++ and -- Assignment Operator = Bit wise Operators &,|,^,>>,<< and ~ Comma Operator , Conditional Operator ? : 2) What are the uses of comma (,) and conditional (?) operators? 1) Comma Operator (,): The comma operator is used to separate two or more expressions. The comma operator

has the lowest priority among all the operators. It is not essential to enclose the expressions with comma operators within the parenthesis. For example the below given statements are valid.

Example: a=2,b=4,c=a+b; (a=2,b=4,c=a+b;)

2) Conditional Operator (?): The conditional operator contains condition followed by two statements or values.

If the condition is true the first statement is executed otherwise the second statement. The conditional operator (?) and (:) are sometimes called ternary operators because they take three arguments.

The syntax of conditional operator is as given below.

Syntax: Condition ? (expression1) : (expression2);

3) What are Unary operators and their uses? Unary Operators Unary operators are increment operator (++), decrement (--) and minus (-). These operators and their descriptions are given in the table 3.3.

Operator Description or Action - Minus ++ Increment -- Decrement & Address Operator Size of Gives the size of operator

Table 3.3 Unary Arithmetic Operators a ) Minus (-) : Unary minus is used for indicating or changing the algebraic sign of a value. For Example int x= -50; int y= -x;

Page 2: Chapter 3 Operators

13

Assigns the value of -50 to x and the value of -50 to y through x. The - sign used in this way is called the unary operator because it takes just one operand. There is no unary plus (+) in C. Even though, a value assigned with plus sign is valid. For example int x=+50; here + is valid but in practice this sign should not be attached in ‘C’. b) Increment (++) & Decrement (--) Operators The C compilers produce very fast, efficient object codes for increment and decrement operations. This code is better than the one generated by using the equivalent assignment statement. So, increment and decrement operators should be used whenever possible.

The operator ++ adds one to its operand. Where as the operator -- subtracts one from its operand. For justification x=x+1 can be written as x++; and x=x-1; can be written as x--;. Both these operators may either follow or precede the operand. I.e. x=x+1; can be represented as x++; or ++x;

If “++” or “—“ are used as a suffix to the variable name then post increment / decrement operations take place. Consider an example for understanding “++” operator as a suffix to the variable. x=20; y=10; z=x*y++;

In the above equation the current value of y is used for the product. The result is 200, which is assigned to ‘z’. After multiplication the value of y is incremented by one.

If “++” or “—“ are used as a prefix to the variable name then pre increment / decrement operations take place. Consider an example for understanding “++” operator as a prefix to the variable. x=20; y=10; z=x*++y; In the above equation the value of y is incremented and then used for multiplication. The result is 220, which is assigned to ‘z’. 4) Describe logical operators with their return values.

The logical relationships between the two expressions are checked with logical operators. Using these operators’ two expressions can be joined. After checking the conditions, it provides logical true (1) or false (0) status. The operands could be constants, variables, and expressions. The following table describes the three logical operators together with examples and their return values. Operator Description or Action Example Return Value && Logical AND 5>3 && 5<10 1 || Logical OR 8>5 || 8<2 1 ! Logical NOT 8!=8 0 From the above table following rules can be followed for logical operators. 1) The logical AND (&& ) operator provides true result when both expressions are true otherwise 0. 2) The logical OR (||) operator provides true result when one of the expressions is true otherwise 0. 3) The logical NOT operator (!) provides 0 if the condition is true otherwise 1. 5) Distinguish between logical and bitwise operators. Logical operators are used with conditional statement to test one or more expression whereas bitwise operator are used to change bit status of the number to produce a new number. 6) What are the relational operators? These operators are used to distinguish between two values depending on their relations. These operators provide relationship between two expressions. If the relation is true then it returns a value 1 otherwise 0 for false. The relational operators together with their descriptions, example, and return value are described in following table. Operator Description or Action Example Return Value > Greater than 5>4 1 < Less than 10<9 0 <= Less than or equal to 10<=10 1 >= Greater than equal to 11>=5 1

Page 3: Chapter 3 Operators

14

= = Equal to 2==3 0 != Not equal to 3!=3 0

Table Relational Operators The relational operator’s symbols are easy for understanding. They are self-explanatory. 7) What is the difference between ‘=’ and ‘= =‘? The ‘=’ assignment operator is used to assign a value to variable whereas ‘= =’ is used with conditional statement to test number for equality condition. 8) What are the symbols used for a) OR b) AND c) XOR d) NOT operations? List of the symbols are gives the following table Operation Symbol OR | AND & XOR ^ NOT ~ 9) Explain the precedence of operators in arithmetic operations. The precedence of arithmetic operator is described in the following table.

Operators Operation Clubbing Priority + - ++ --

Unary plus Unary minus Increment Decrement

Right to left 2nd

* / %

Multiplication Division Modular division

Left to right 3rd

+ -

Addition Subtraction

Left to right 4th

10) List the operators from higher priority to least priority. The following table describes the various operators with their priorities.

Operators Operation Clubbing Priority () [] -> .

Function call Array expression or square bracket Structure Operator Structure Operator

Left to right 1st

+ - ++ -- ! ~ * & sizeof type

Unary plus Unary minus Increment Decrement Not operator Ones complement Pointer Operator Address Operator Size of an object Type cast

Right to left 2nd

* / %

Multiplication Division Modular division

Left to right 3rd

+ -

Addition Subtraction

Left to right 4th

<< Left shift Left to right 5th

Page 4: Chapter 3 Operators

15

>> Right shift < <= > >=

Less than Less than or equal to Greater than Greater than or equal to

Left to right 6th

== ! =

Equality Inequality

Left to right 7th

& Bitwise AND Left to right 8th ^ Bitwise XOR Left to right 9th | Bitwise OR Left to right 10th && Logical AND Left to right 11th || Logical OR Left to right 12th ?: Conditional operator Right to left 13th =, *=,- =, &=,+= ^= , |=, <<=,>>=

Assignment Operators Right to left 14th

, Comma operator Left to right 15th 11) What is the difference between %f and %g? Both %f and %g are used as format string for float data. The %f displays leading zeros whereas %g omits the leading zeros. 12) What is the difference between division and modular division operations? The division operation returns quotients and the modular division operation returns remainder. 13) What is the ASCII codes? List the codes for digits 1 to 9, A to Z and a to z. ASCII codes are American standard code for information interchange. The ASCII values of numerical numbers and Characters are given below. Range ASCII range 1 to 9 49 to 57 A to Z 65 to 90 a to z 97 to 122 B] Answer the following by selecting the appropriate option. (Answers are in bold) 1) What will be the output of the following program?

# include <stdio.h> # include <conio.h>

void main() {

int ans=2; int m=10; int k; k=!((ans<2) && (m>2));

printf ("\n %d",k); }

a) 1 b) 0 c) –1 d) 2 2) What will be the output of the following program?

# include <stdio.h> # include <conio.h>

void main() {

int m,j=3,k; m=2*j/2; k=2*(j/2); clrscr();

Page 5: Chapter 3 Operators

16

printf ("\n m=%d k=%d",m,k); } a) m=3 k=2 b) m=3 k=3 c) m=2 k=3 d) m=2 k=2 3) What will be the value of x,y and z after execution of the following program?

# include <stdio.h> # include <conio.h> void main()

{ int x,y,z; y=2; x=2; x=2*(y++); z=2*(++y); printf ("\n x=%d y=%d z=%d",x,y,z);

} a) x=4 y=4 z=8 b) x=6 y=4 z=8 c) x=2 y=4 z=8 d) x=4 y=4 z=4 4) What will be the value of ‘x’ after execution of the following program?

# include <stdio.h> # include <conio.h>

void main() {

int x=!0*10; }

a) 10 b) 1

c) 0 d) None of the above.

5) What is the value of !0? a) 1 b) 0

c) –1 d) None of the above.

6) Hierarchy decides which operator a) is used first b) is most important

c) operates on large numbers d) None of the above.

7) What will be the value of k after execution of the following program?

# include <stdio.h> # include <conio.h>

void main() { int k=8; (k++-k++); }

a) k=10; b) k=0; c) k=8; d) k=9;

8) What will be the value of b after execution of the following program?

void main() { int b,k=8; b=(k++-k++-k++,k++);

Page 6: Chapter 3 Operators

17

} e) b=11; f) b=12; g) b=7; h) b=9;

9) The ‘&’ operator displays a) address of the variable b) value of the variable

c) both (a) and (b) d) none of the above.

10) Addition of two numbers is performed using a) arithmetic operator b) logical operator

c) unary operator d) comma operator

11) What is the remainder of 8% 10? a) 8 b) 2 c) 1 d) 0 12) What is the result of the expression (10/3)*3+5%3? a) 11 b) 10 c) 8 d) 1 13) What is the result of expression (23*2) % (int) 5. 5? a) 2 b) 1 c) 3 d) 0 14) What is the result of 16>>2? a) 4 b) 8 c) 2 d) 5

15) What is the result of 5&&2? a) 0 b) 1 c) 2 d) 5 16) What will be the value of c after execution of the program?

# include <stdio.h> # include <conio.h>

void main() { int a,b,c; a=9; b=10; c=(b<a || b>a); clrscr(); printf ("\n c=%d",c); } OUTPUT: a) c=1 b) c=0

c) c=-1 d) none of the above

C] Attempt the following programs. 1) Write a program to shift the entered number by three bits left and display the result.

Page 7: Chapter 3 Operators

18

#include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf("Enter the number:-"); scanf("%d",&b); a=b<<3; printf ("\n a=%d",a); } OUTPUT Enter the number:-8 a=64 Explanation In the above program an integer is entered. Using left shift operator bits are shifted and obtained number is displayed. 2) Write a program to shift the entered number by five bits right and display the result. #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf("Enter the number:-"); scanf("%d",&b); a=b>>5; printf ("\n a=%d",a); } OUTPUT Enter the number:-64 a=2 Explanation The above program is same as last one. Here, right shift operator is used. 3) Write a program to mask the most significant digit of the entered number. Use AND operator. #include <stdio.h> #include <conio.h> void main () { int x,n; clrscr(); printf ("\n Enter numbers : "); scanf ("%x",&n); x=n&0xf; printf ("x=%d",x); } OUTPUT Enter numbers: 89 x=9 Explanation In the above program a decimal number is entered. The decimal number is converted to hexa-decimal equivalent using %x format string in the scanf () statement. Using & operator with 0xf number the most significant digit of enter number is masked. 4) Write a program to enter two numbers and find the smallest out of them. Use conditional operator. # include <stdio.h> # include <conio.h>

Page 8: Chapter 3 Operators

19

main() { int a,b; clrscr(); printf("Enter 1st integer:"); scanf("%d",&a); printf("Enter 2nd integer:"); scanf("%d",&b); printf("The smallest number =%d",(a<b?a:b)); getche(); } OUTPUT Enter 1st integer:35 Enter 2nd integer:18 The smallest number =18 OR Enter 1st integer:14 Enter 2nd integer:82 The smallest number =14 Explanation In the above program two integers are entered. Using conditional operator their comparison is done. The conditional operator also contains two statements, which are executed after the expression is solved. Thus, the smallest number is tested and displayed. 4) Write a program to enter a number, carry out modular division operation by 2,3 and 4, and display the

remainders. #include<stdio.h> #include<conio.h> void main() { int a; clrscr(); printf("Enter a number:-"); scanf("%d",&a); printf ("Modular Division by 2: %d",a%2); printf ("\nModular Division by 3: %d",a%3); printf ("\nModular Division by 4: %d",a%4); getch(); } OUTPUT Enter a number:-23 Modular Division by 2: 1 Modular Division by 3: 2 Modular Division by 4: 3 Explanation In the above program an integer number is entered. Modular division by 2,4 and 4 is performed and result is displayed. 5) Attempt the program (5) with division operation and find the quotients. #include<stdio.h> #include<conio.h> void main() { float a; clrscr(); printf("Enter a number:-"); scanf("%f",&a); printf ("Division by 2: %.2g",a/2); printf ("\nDivision by 3: %.2g",a/3); printf ("\nDivision by 4: %.2g",a/4); getch();

Page 9: Chapter 3 Operators

20

} OUTPUT Enter a number:-24 Division by 2: 12 Division by 3: 8 Division by 4: 6 Explanation The above program is same as last one. Here, instead of modular division, division operation is performed. 6) Write a program to enter an integer number and display its equivalent values in octal and hexadecimal. # include <stdio.h> # include <conio.h> void main() { int x; clrscr(); printf ("\n Eneter a number : "); scanf ("%d",&x); printf ("\n Hexadecimal number : %x",x); printf ("\nOctal number : %o",x); } OUTPUT Eneter a number : 95 Hexadecimal number : 5f Octal number : 137 Explanation: In the above program an integer number is entered. The format string %x converts decimal number to hexadecimal and %o converts decimal number to octal. 7) Write a program to convert hexadecimal to decimal numbers. Enter the numbers such as 0x1c, 0x18,

0xbc, 0xcd etc. # include <stdio.h> # include <conio.h> void main() { int x; clrscr(); printf ("\n Enter a number : "); scanf ("%x",&x); printf ("\n Decimal Number : %d",x); } OUTPUT Enter a number: 5f Decimal Number: 95 Explanation The Above program is same as last one. Here, the format string %x is used in scanf () statement to accept number in hexadecimal format. The format string %d converts hexadecimal number to decimal equivalent. 8) Write a program to find the average temperature of five sunny days. Assume the temperature in Celsius.

Page 10: Chapter 3 Operators

21

# include <stdio.h> # include <conio.h> void main() { float a,b,c,d,e,avg; clrscr(); printf("Enter 1st sunny day temperature:"); scanf("%f",&a); printf("Enter 2nd sunny day temperature:"); scanf("%f",&b); printf("Enter 3rd sunny day temperature:"); scanf("%f",&c); printf("Enter 4th sunny day temperature:"); scanf("%f",&d); printf("Enter 5th sunny day temperature:"); scanf("%f",&e); avg=(a+b+c+d+e)/5; printf("\nThe average of five sunny days temperature =%.2f oC ",avg); getche(); } OUTPUT Enter 1st sunny day temperature: 28.2 Enter 2nd sunny day temperature: 27.5 Enter 3rd sunny day temperature: 29.0 Enter 4th sunny day temperature: 26.8 Enter 5th sunny day temperature: 28.1 The average of five sunny day temperature =27.92 oC Explanation In the above program temperature of five days are entered. Sum of temperature is calculated. Average is calculated and displayed. 9) Write a program to enter two numbers. Make the comparison between them with conditional operator.

If the first number is greater than second perform multiplication otherwise division operation. #include<stdio.h> #include<conio.h> void main() { float a,b,c; clrscr(); printf("Enter two numbers:-"); scanf("%f%f",&a,&b); (a>b) ? (c=a*b) : (c=a/b); (a>b)?printf("Multiplication =%g",c):printf("Division =%g",c); getch(); } OUTPUT Enter two numbers:-20 30 Division =0.666667 Enter two numbers:-30 20 Multiplication =600 Explanation In the above program two numbers are entered. Using conditional operator numbers are tested. If the first number is greater than second multiplication of numbers is calculated otherwise division is performed. 10) Write a program to calculate the total cost of the vehicle by adding basic cost with a) excise duty (15%)

b) Sales tax (10%) c) Octroi (5%) and d) Road tax (1%). Input the basic cost.

Page 11: Chapter 3 Operators

22

#include <stdio.h> #include <conio.h> # include <math.h> void main () { float bc,ed,st,oc,rd; clrscr(); printf ("\n Enter basic cost : "); scanf ("\n %f",&bc); ed=bc*.15; st=bc*0.1; oc=bc*.05; rd=bc*.01; bc=bc+ed+st+oc+rd; printf ("\n Excise duty : %g",ed); printf ("\n Sales Tax : %g",st); printf ("\n Octroi : %g",oc); printf ("\n Road Tax : %g",rd); printf ("\n Total cost of the vehicle : %g",bc); } OUTPUT Enter basic cost : 51000 Excise duty : 7650 Sales Tax : 5100 Octroi : 2550 Road Tax : 510 Total cost of the vehicle : 66810 Explanation In the above program basic cost of vehicle is entered. As per given percentage in exercise excise duty, sales tax, octroi, and road tax are calculated and added in the basic cost. At the end total cost with above taxes are displayed. 11) Write a program to display ASCII equivalents of

a) ‘A’, ‘B’,’C’ and ‘a’,’b’,’c’. b) ‘a’-‘C’, ‘b’-‘A’ and ‘c’ – ‘B’. c) ‘a’+’c’, ‘b’*’a’ and ‘c’+12.

#include<stdio.h> #include<conio.h> void main() { clrscr(); printf("ASCII values\n"); printf("A=%d B=%d C=%d a=%d b=%d c=%d",'A','B','C','a','b','c'); printf("\na-C=%d b-A=%d c-B=%d",'a'-'C','b','A','c'-'B'); printf("\na+c=%d b*a=%d c+12=%d",'a'+'c','b'*'a','c'+12); getch(); } OUTPUT ASCII values A=65 B=66 C=67 a=97 b=98 c=99 a-C=30 b-A=98 c-B=65 a+c=196 b*a=9506 c+12=111 Explanation In the above program the alphabets are directly used in the printf () statement. The format string %d displays their equivalent ASCII values.

Page 12: Chapter 3 Operators

23

12) Write a program to enter a number that should be less than 100 and greater than 9. Display the number in reverse order using modular division and division operation

#include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("Enter a number between 10 and 99:"); scanf("%d",&a); b=a/10; a=a%10; c=(10*a)+b; printf("The reverse number is = %d", c); getch(); } OUTPUT Enter a number between 10 and 99:25 The reverse number is = 52 Explanation In the above program by applying modular division and division remainder is obtained. Also by multiplying 10 reverse decimal number is obtained and displayed. 13) Write a program to enter a four-digit number. Display the digits of the number in the reverse order

using modular division and division operation. Perform addition and multiplication of digits. #include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf("Enter a number between 10 and 99:"); scanf("%d",&a); printf ("\n Reverse Number is : "); b=a%10; a=a/10; printf ("%d",b); b=a%10; a=a/10; printf ("%d",b); b=a%10; a=a/10; printf ("%d%d",b,a); getch(); } OUTPUT Enter a number between 10 and 99:4456 Reverse Number is : 6544 Explanation This program is same as last one. Performing division and modular division operations reverse number is displayed. 14) Write a program to display numbers from 0 to 9. Use ASCII range 48 to 59 and control string %c.

Page 13: Chapter 3 Operators

24

#include<stdio.h> #include<conio.h> void main() { int a=48; clrscr(); for (;a<58;a++) printf ("%c ",a); getch(); } OUTPUT 0 1 2 3 4 5 6 7 8 9 Explanation In the above program using for loop and format string %c ASCII codes from 48 to 57. 0 to 9 numbers are displayed. 15) Write a program to evaluate the following expressions and display their results.

a) x2 +2 x3*(2*x)n b) x1+y2+z3 where, x, y and z are integers.

16) Write a program to print whether the number entered is even or odd use conditional operator. #include<stdio.h> #include<conio.h> void main() { int a; clrscr(); printf ("\nEnter a number : "); scanf ("%s",&a); a=a%2; a==0 ? printf ("\n Number is odd ") : printf ("\n Number is even "); getch(); } OUTPUT Enter a number : 10 Number is even Explanation In the above program an integer number is entered. After performing modular division with two, its remainder is obtained. The conditional operator checks the remainder value and displays appropriate messages.