[go: up one dir, main page]

0% found this document useful (0 votes)
50 views12 pages

Unit 2 Question PPS

Operators and expressions allow computations and comparisons in C programs. Arithmetic expressions use operators like +, -, *, / to perform math. Logical and bitwise operators allow comparisons and bit manipulations. Type conversion changes a variable's type implicitly, while type casting does so explicitly. Both are necessary when different data types are used together in an expression.

Uploaded by

a2021cse7814
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views12 pages

Unit 2 Question PPS

Operators and expressions allow computations and comparisons in C programs. Arithmetic expressions use operators like +, -, *, / to perform math. Logical and bitwise operators allow comparisons and bit manipulations. Type conversion changes a variable's type implicitly, while type casting does so explicitly. Both are necessary when different data types are used together in an expression.

Uploaded by

a2021cse7814
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT-2

Module – 2 : (Arithmetic expressions & Conditional Branching)


Arithmetic expressions and precedence
Operators and expression using numeric and relational operators
Mixed operands, Type conversion
Logical operators, Bit operations
Assignment operator, Operator precedence and associativity.
Conditional Branching:
Applying if and switch statements
Nesting if and else
Use of break and default with switch
Short Question & Answers
Ques 1 What are C expressions? Give examples.
Ans : An expression is a combination of variables, constants, operators and function call. It
can be arithmetic, logical and relational for example:-
int z = x+y
// arithmatic expression
a>b // relational
a= =b // logical
func(a, b) // function call
Expressions consisting entirely of constant values are called constant expressions. But if i
were declared to be an integer variable, the expression 180 + 2 – j would not represent a
constant expression.
Ques : 2 Define the term C operator. Explain Arithmetic and Logical Operators.
Ans: An operator is a symbol which helps the user to command the computer to do a certain
mathematical or logical manipulation. Operators are used in C language program to operate
on data and variables.
(i) Arithmetic Operators
All the basic arithmetic operations can be carried out in C. Example : +, -, %, / , *, &&, etc.
Both unary and binary operations are available in C language. Unary operators operate on a
single operand, where operand can be a constant, a variable or a valid C expression. Binary
operators operate on two operands. Ternary operators operate on three operands.
Unary Operators: +a (unary plus), -a (unary minus), ++a (pre increment) , !a(logical NOT).
Binary Operators: a+b (binary addition), a-b(binary subtraction),a*b(multiplication),
a / b (division), a % b (Modulus division), x > = y (relational operator)
Ternary Operator: This is also called conditional operator ( ? : )
Test expression ? expression 1 : expression 2
Logical Operators: C has the following logical operators; they compare or evaluate logical
and relational expressions. The output evaluated is either a true value or false value of an
expression. Represented as 0 (false) , 1(True).
A || b is Logical OR, a &&b is Logical AND , !a is Logical NOT
Ques 3. What is the difference between “=” and “= =”?
Ans: = (assignment operator) in C language is used to assign the value of right-hand side
value/variable/expression to the left hand side variable .e.g: a = 4; here constant 4 at
R.H.S is called r-value and identifier a at the L.H.S is called l-value
= = ( Equality Operator )in C language is used to check the value of left hand
variable/expression with the right hand Variable/expression. Whether the two values are
equal or not. It returns true if these are equal else it will return false.
e.g. (2==3) : It means whether 2 is equal to 3 or not which is false so output is 0.
(3==3) : It mean 3 is equal to 3 ,which is true so output is 1
Ques 4. What is the output of arithmetic statement, S = 1/3 * a /4 – 6/ 2 + 2 / 3 * 6 / g ?
Given that (int a = 4 , int g = 3 , assume s to be an int type).**HINT: apply the
concept of type casting.
Ans :
S= 1/3 * a/4 – 6/2 + 2 /3 * 6/g
= 1 /3 * 4 /4 -6 /2 + 2/3 * 6 /3
= 0 * 4 / 4 – 6 /2 + 2 / 3* 6 / 3
= 0 / 4 – 6 /2 + 2 /3 * 6 /3
=0–3+0*2
= -3
Ques 5 . Give the outpu of following code :
void main()
{
float u = 3.5 ;
int v , w , x , y ;
v = ( int ) ( u + 0.5) ;
w = (int) u + 0.5 ;
x = (int) ( ( int) u + 0.5) ;
y = ( u + (int) 0.5 ) ;
printf ( “ %d %d %d %d ” , v , w , x , y ) ;
}
Ans : Output is : 4 3 3 3
Ques 6. What is the difference between the pre-increment operator and the post-
increment Operator? Give example also.
Ans. (i) The pre-increment operator increases the operand's value by 1 first, and then returns
the modified Value.
(ii) The post-increment operator stores a copy of the operand value in a temporary Location
and then increases the operand value by 1. For example given x = 1, the ++x
expression returns 2, while the x++ expression returns1.
EXAMPLE: What is the output of the following C code?
main()
{ int i =5 , ;
printf ( “ %d %d %d %d %d ” , i++ , i-- , ++i , --i , i ) ;
}
Ans: 4 5 5 4 5
Ques 7. Find the output of the following program?
main( )
{
int x=100;
printf(“%d”,10 + x++);
printf(“%d”,10 + ++x);
}
Ans. 110 112
Ques 8. What is the output of the following C code?
main()
{
int i = 0 , j = 1 , k =2 , l ;
l = i && j++ && ++k ;
printf ( “ %d %d %d %d ” , i , j , k , l ) ;
}
Ans: Output : 0 1 2 0
Ques 9. What will be the value of x when the following segment is executed?
int x=10, y=15;
x=(x<y) ? (y+x) : (y-x) ;
Ans. Output = 25
Ques 10. What is the dangling else problem?
Ans: When a program contains more number of if clauses than else clauses, then their exists a
potential ambiguity regarding with which if clause does not match with else clause.
This ambiguity is called Dangling else problem
Ques 11. What is the precedence and associativity of operators?
Ans : Precedence : When an expression hasb more than one operators then relative priorities
of operators with respect to each other is checked to evaluate expression in that order.
E.g: Multiplicative operators ( * , /, % ) have high priority than additive operators ( + - ).
Note : If all the operators in same expression have equal priority then operator which comes
first from left is evaluated first and then we move towards right .
Exmaple : In expression 2 / 3 * 6 % 4 , all are multiplicative operators, hence have same
precedence. So first / is evaluated , then * is evaluated and then % division is performed.
Associativity: This defines the direction in which the operator acts on the operands. It can be
either left to right or right to left.. First precedence is checked then associativity is applied.

++ (prefix /postfix) Right to left


*, / , % Left to right
< , < =, > , >= Left to right
= assignment Right to left
&& , || Left to right.
Long Questions & Answers

Ques 1. Describe the bitwise operators available in C with examples.


Ans: These operators work with bits rather than larger structures such as a byte. For example,
each of the eight bits in a byte can be used as an individual flag to signal yes/no, on/off
(1 or 0) about some condition. The Boolean operators AND, OR and NOT also deal with
individual bits rather than bytes. Bitwise operators are programming commands that
work with individual bits. The primary ones are.
Symbol Function
<< Shift left
>> Shift right
& bitwise AND
| bitwise OR
^ bitwise XOR (Exclusive OR)
~ bitwise NOT (0 to 1; 1 to 0)
Examples : (i) int a = 10 , b = 20 , c = 0;
C = a & b ; Here compiler will first convert int variables a and b in binary form ,
then bit wise AND is performed.
(ii) Shift operator shift the bits either to left or right. The syntax of 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 operator is << and right if operator is >>) = 00011101
X << 1 produces 00111010 Shifting once to the left multiplies the number by 2. Hence
multiple shifts of 1 to the left result in multiplying by 2 several times. If x = 0001 1101
then x >>4 produces 0000 0001. Shifting from right by 1 bit divides the number by 2.
Ques 2. What is meant by type conversion and type casting? Why it is necessary?
Explain about implicit and explicit type conversion with examples.
Ans : When any C expression or statement involves different data types e.g : multiplication of
a float number by integer number , then to get the correct result in terms of values Type
conversion / Type casting is required in programming. In this we change a variable of
one data type to variable of another data type.
** Type conversion is done implicitly by the compiler
** Type casting is performed explicitly by the programmer.
(a) Type conversion : It is done when expression has variables of different data types. To
evaluate the expression , data type is promoted from lower to higher data type (or from
higher to lower).Type conversion is automatically performed.
e.g : float x ;
int y = 3;
x = y ; // Here x will have the value 3.0 as automatically integer value is converted to
its equivalent floating point value.
Conversion hierarchy of data types is as shown below :

long double Higher level


double
Float
Unsigned long int
Long int
Unsigned int
Int Short
char Lower level

** When a char type is operated with an int type char is promoted to int.
** When a float type data is operated with an int , then int is promoted to float.
** When any operand is double then another operand is also converted to double
(b) Type casting : It is also called as forced conversion. It is done when value of higher data
type is to be converted to lower data type. This conversion is under programmer’s control
, not in compiler’s control.
Demotion : float f = 3.5 ;
int I ;
I=f;
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 ; this is called down conversion/demotion. But result is not
correct so explicit type casting is required. Explicit type casting is done by placing the target
data type in parentheses followed by the variable name that has to be converted.
Variable 2 = (data type) variable1
e.g : float salary = 10000.00 ;
int tot_sal =0;
sal = (int ) salary
** When floating point numbers are converted to integers , the digits after decimal are
truncated.
Ques 3. What is conditional branching statement ? Explain switch case statements in
detail , with a proper example.
Ans : The conditional branching statements help to jump from one part of the program to
another depending whether a particular condition is true or false. These decision control
statements include :
(i) if statement (ii) if – else statement (iii) if – else-if statement (iv) switch statement.
A switch case statement is a multi-way decision statement that is simplified version of if –
else block. Statement blocks refer to statements lists that may contain zero or more
statements. These statements are not enclosed within opening and closing braces.
Switch statements are mostly used in following situations :
(a) When there is only one variable to evaluate in the expression.
(b) When many conditions are being tested for.
(c) Switch case is preferable over if –else if many conditions are to be tested.

Syntax of switch – case statement


Switch ( int expression/ int variable) Switch case compares the value of integer
expression/variable with the value of each case
{
statement that comes in that case.If value of switch
Case value1 : expression and case number matches then that
statement block is executed. Default Case : When
Statement Block 1 ;
switch expression does not matches with any case
Break ; value , then statements in default case are executed.
( default case is optional).
Case value 2 :
Use of break in switch case : The break statement
Statement block 2; must be used after each case statement in ideal
conditions. If it is not used then the case which is
Break;……………………………….
matched and all the cases following that case are executed
Case value N : resulting in logical error or incorrect output
Statement block N ;

Break ;

Default :

Statement block D ;

Break ;

Statement x ;
Some Rules of Switch – Case statements
(i) Control expression inside switch must be integer type variable or integral
expression
E.g : switch ( int n) , switch ( int x + 6) etc.
(ii) Each case label should be followed by a constant or a constant expression.
(iii) Every case label must have unique constant expression value.
(iv) Case labels must end with a colon.
(v) Default label can be placed anywhere in switch block. There must be only one default in
switch program.
(vi) case labels should not be logical or relational expressions.
(vii) Order in which case labels are written are not fixed.

Example 1 of switch case with break Example 2 of switch case without break
# include <stdio.h> # include <stdio.h>
# include <conio.h> Int main()
Void main() {
{ Int option =1;
char grade = ‘C ‘ Switch (option)
switch (grade) {
{ Case 1 : printf (“ I am in case 1\n”) ;
Case ‘O ’ : Case 2 : printf ( “ I am in case 2\n”) ;
Printf ( “ \n Outstanding ”) ; Default : printf (“ I am in case default ”) ;
Break ; }
Case ‘ A’ : return 0;
Printf ( “ \n Excellent ”) ; getch();
Break ; }
Case ‘B’ :
Printf ( “ \n GOOD ”) ; **********************************
Break ; Output :
Case ‘C ’ : I am in case 1
Printf ( “ \n Satisfactory ”) ; I am in case 2
Break ; I am in case default.
Case ‘F ’ :
Printf ( “ \n Fail ”) ;
Break ;
Default :
Printf ( “ \n Outstanding ”) ;
Break ;
} getch (); } // End of main()
*************************************
Output : Satisfactory
Important Programs
1. Program to find the simple interest, 2. Ramesh’s basic salary is input through the keyboard.
given principle, rate of interest and time. His dearness allowance is 40% of basic salary, and house
rent allowance is 20% of basic salary. Write a program
to calculate his Gross Salary.
#include <stdio.h> #include<stdio.
#include <conio.h> #include<conio.h>
void main() void main()
{ {
float p, r, si; float bs , da= 0.0, hra=0.0 ,gross=0.0 ;
int t; clrscr() ;
clrscr(); printf(“Enter the basic salary\n”) ;
printf("Enter the values of p,r and t\n"); scanf(“%f” ,&bs) ;
scanf ("%f %f %d", &p, &r, &t); printf(“BASIC SALARY OF RAMESH=%f\n ”,bs) ;
si = (p * r * t)/ 100.0; da = (bs*40) / 100 ;
printf ("Amount = Rs. %5.2f\n", p); hra = (bs *20) /100 ;
printf ("Rate = Rs. %5.2f%\n", r); gross = bs + da + hra ;
printf ("Time = %d years\n", t);
printf ("Simple interest = %5.2f\n", si); printf(“**************************”);
getch() ; printf(“GROSS SALRY OF RAMESH = % f ”,gross) ;
} getch() ;
}

3. Program to find the area of a circle, 4. Program to find the area of a triangle,
given the radius. given three sides a, b and c.
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
#include <math.h>
void main() void main()
{ {
float radius, area; float a, b, c ;
float PI = 3.14; float s =0.0 , area =0.0 ;
clrscr(); clrscr();
printf("Enter the radius of a circle\n"); printf("Enter the values of a,b and c\n");
scanf ("%f", &radius); scanf ("%f %f%f ", &a, &b, &c);
area = PI * radius * radius; s = (a + b + c) / 2; /* computes perimeter */
printf ("Area of a circle = %5.2f\n", area = sqrt ( s * (s-a) * (s-b) * (s-c)); /* compute the
area); area */
getch() ; printf ("Area of a triangle = %f\n", area);
} getch();
}
5. Program to swap the values of two variables 6. Write a C program to check whether a
without using third variable. given integer is odd or even.
#include<stdio.h> #include <stdio.h>
#include<conio.h> #include <conio.h>
void main() void main()
{ {
int a , b ; int x , remainder;
clrscr() ; clrscr();
printf(“Enter the values of a and b \n”) ; printf("Enter an integer :");
scanf(“%d %d” ,&a , &b) ; scanf ("%d", x );
printf(“Values variables before swapping are
a=%d \t b=%d: \n”, a , b) ; if (x % 2 == 0)
a=a+b; {
b=a–b; printf ("%d, is an even integer\n", x );
a=a–b; }
printf(“Values of a and b after swapping Else
are:\n”) ; {
printf(“a=%d\t\t b=%d”,a ,b) ; printf ("%d, is an odd integer\n", x);
getch(); }
} getch ();
}

7. Program for finding the sum of a five digit no. 8. Write a C program to find the largest
without using loop of three numbers.
#include<stdio.h> #include <stdio.h>
#include<conio.h> #include <conio.h>
void main() #include <math.h>
{ void main()
long int num , sum =0 , rem ; {
// Max. five digit no. can be 99999, so long int a, b, c;
int declared clrscr();
clrscr() ; printf("Enter the values of a,b and c\n");
printf(“Enter the five digit number\n”) ; scanf ("%d %d %d", &a, &b, &c);
scanf(“% ld” , &num) ; printf ("a = %d\tb = %d\tc = %d\n", a,b,c);
printf(“The five digit number=%ld\n”, if ( a > b)
num) ; {
rem1 = num%10 ; if ( a > c)
num = num /10 ; {
rem2 = num%10 ; printf ("A is the greatest among three\n");
num = num /10 ; }
rem3 = num%10 ; else
num=num/10 ; {
rem4 = num%10; printf ("C is the greatest among three\n");
num=num/10 ; }
sum = rem1 + rem2 + rem3 + rem4 + num ; }
printf(“Sum of the digits of %ld =% ld”, else if (b > c)
num ,sum) ; {
getch(); printf ("B is the greatest among three\n");
} }
else
printf ("C is the greatest among three\n");
}

9. Program to determine whether a triangle is right angle , scalene, equilateral or


isosceles where the Sides a , b and c are entered by the user. Also check whether the
triangle is possible or not?
#include<stdio.h>
#include<conio.h>
void main()
{ float a , b , c ;
clrscr() ;
printf ( “Enter the sides of the triangle : \n” ) ;
scanf(“%f %f %f ” , & a , & b , &c) ;
if ((a + b < c) || (b + c < a) || ( a + c < b) )
printf (“Triangle is NOT POSSIBLE” ) ;
if ( (a * a = = b * b + c * c) || (b * b = = a * a + c * c) ) || (c * c = = a * a + c * c) ) ;
printf( “ Triangle is RIGHT ANGLED” ) ;
if ((a = = b ) && (b != c)) ;
printf( “Triangle is ISOSCELES”) ;
if ((b = = c ) && (c!= a)) ;
printf( “Triangle is ISOSCELES”) ;
if ((c = = a ) && (a != b)) ;
printf( “Triangle is ISOSCELES”) ;
if ( ( a = = b) && ( b = = c) ) ;
printf( “ Triangle is EQUILATERAL” ) ;
if ( (a != b) && (b != c) && (c!=a) ) ;
printf( “ Triangle is SACLENE” ) ;
getch () ;
}

You might also like