UNIT- 2
Arithmetic expressions & Conditional Branching
Arithmetic Expressions consist of numeric literals, arithmetic operators, and numeric variables. They simplify to a single value, when evaluated. Here is an example of an arithmetic expression with no variables: 3.14*10*10 This expression evaluates to 314, the approximate area of a circle with radius 10. Similarly, the expression 3.14*radius*radius would also evaluate to 314, if the variable radius stored the value 10. Note that the parentheses in the last expression helps dictate which order to evaluate the expression. Multiplication and division have a higher order of precedence than addition and subtraction. In an arithmetic expression, it is evaluated left to right, only performing the multiplications and divisions. After doing this, process the expression again from left to right, doing all the additions and subtractions. So, 3+4*5 first evaluates to 3+20 which then evaluates to 23. Consider this expression: 3 + 4*5 - 6/3*4/8 + 2*6 - 4*3*2
First go through and do all the multiplications and divisions: 3 + 20 - 1 + 12 - 24
Integer Division: In particular, if the division has a leftover remainder or fraction, this is simply discarded. For example: 13/4 evaluates to 3 19/3 evaluates to 6 but Similarly, if you have an expression with integer variables part of a division, this evaluates to an integer as well. For example, in this segment of code, y gets set to 2. int x = 8; int y = x/3;
However, if we did the following, double x = 8; double y = x/3; y would equal 2.66666666 (approximately).
The way C decides whether it will do an integer division (as in the first example), or a real number division (as in the second example), is based on the TYPE of the operands. If both operands are ints, an integer division is done. If either operand is a float or a double, then a real division is done. The compiler will treat constants without the decimal point as integers, and constants with the decimal point as a float. Thus, the expressions 13/4 and 13/4.0 will evaluate to 3 and 3.25 respectively. The mod operator (%)
The one new operator is the mod operator, which is denoted by the percent sign(%). This operator is ONLY defined for integer operands. It is defined as follows: a%b evaluates to the remainder of a divided by b. For example, 12%5 = 2 19%6 = 1 14%7 = 0 19%200 = 19
The precedence of the mod operator is the same as the precedence of multiplication and division.
2.1.1 Operators and expression using numeric and relational operators Every expression in C language contains set of operators and operands. Operators are the special symbols which are used to indicate the type of operation whereas operands are the data member or variables operating as per operation specified by operator. One expression contains one or more set of operators and operands. So to avoid the ambiguity in execution of expression, C compiler fixed the precedence of operator. Depending on the operation, operators are classified into following category.
Example: #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("Enter two numbers"); scanf("%d %d",&a,&b); printf("\n Result of addition of %d and %d is %d",a,b,a+b); printf("\n Result of subtraction of %d and %d is %d",a,b,a-b); printf("\n Result of multiplication %d and %d is %d",a,b,a*b); printf("\n Result of division of %d and %d is %d",a,b,a/b); printf("\n Result of modulus of %d and %d is %d",a,b,a%b); getch(); }
Output: Enter two numbers 5 3 Result of addition of 5 and 3 is 8 Result of subtraction of 5 and 3 is 2 Result of multiplication of 5 and 3 is 15 Result of division of 5 and 3 is 1 Result of modulus of 5 and 3 is 2 2. Relational Operators: Relational operator used to compare two operands. Relational operator produce result in terms of binary values. It returns 1 when the result is true and 0 when result is false. Following are the list of relational operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Example: #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("Enter two numbers"); scanf("%d %d",&a,&b); printf("\n Result of less than operator of %d and %d is %d",a,b,a<b); printf("\n Result of greater than operator of %d and %d is %d",a,b,a>b); printf("\n Result of leass than or equal to operator %d and %d is %d",a,b,a<=b); printf("\n Result of greater than or equal to operator of %d and %d is %d", a,b,a>=b); printf("\n Result of double equal to operator of %d and %d is %d",a,b,a==b); printf("\n Result of not equal to operator of %d and %d is %d",a,b,a!=b); getch(); } Output: Enter two numbers 5 3 Result of less than operator of 5 and 3 is 0 Result of greater than operator of 5 and 3 is 1 Result of less than or equal to operator of 5 and 3 is 0 Result of greater than or equal to operator of 5 and 3 is 1 Result of double equal to operator of 5 and 3 is 0 Result of not equal to operator of 5 and 3 is 1
2.1.2 Mixed operands In a statement or expression if one the operand is real (float) and another one is integer then expression is called as Mixed Mode Arithmetic Expression. If in an expression either operand is of real then output is always in real format. If both operands are real then output will be in real formats. Example Real operand and Integer operand = Real operand (Output) Types of Arithmetic Operators used in Mixed Mode Expression "*" - Multiply use for Multiplication Rules for Evaluation Mixed Mode Arithmetic Expression Rule 1 Evaluate Expressions always from Left to Right For Example: 3 + 5 - 4 = 4 Rule 2 Operator Priorities in descending order
Mixed mode operator example Rule 3 Both Real Numbers double a = 2.0; Double add = 2.0 + 3.0 = 5.0 (Result in Real Number only) Both Integer Number int a = 2; Rule 4 If one of the operator is Integer and other one is real then convert integer number to real number and compute the result in real number only. For Example double a = 5.0;
2.1.3 Type conversion Implicit type conversion: Also known as ‘automatic type conversion’.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long is implicitly converted to float).
Example of Type Implicit Conversion:
Output:
x=107, z = 108.000000
Explicit Type Conversion– This process is also called type casting and it is user defined. Here the user can type cast the result to make it of a particular data type. The syntax in C: (type) expression Type indicated the data type to which the result is converted.
2.1.4 Logical operators Logical Operators: Logical operators are used to compare logical values of two operands. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Example: #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("Enter two numbers"); scanf("%d %d",&a,&b); printf("\n Result of logical and operator of %d and %d is %d",a,b,a&&b); printf("\n Result of logical or operator of %d and %d is %d",a,b,a||b); printf("\n Result of logical not operator of %d and and %d is %d",a,b,!(a&&b)); getch(); } Output: Enter two numbers 5 3 Result of logical and operator of 5 and 3 is 1 Result of logical or operator of 5 and 3 is 1 Result of logical not operator of 5 and 3 is 0
2.1.5 Bit operations
A = 0000 1010 and B = 0000 0101
Example: #include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("Enter two numbers"); scanf("%d %d",&a,&b); printf("\n Result of bitwise and operator of %d and %d is %d",a,b,a&b); printf("\n Result of bitwise or operator of %d and %d is %d",a,b,a|b); printf("\n Result of bitwise exclusive operator of %d and %d is %d",a,b,a^b); printf("\n Result of bitwise left shift operator of %d and %d is %d",a,b,a<<b); printf("\n Result of bitwise right shift operator of %d and %d is %d",a,b,a>>b); getch(); } Output: Enter two numbers 5 3 Result of bitwise and operator of 5 and 3 is 1 Result of bitwise or operator of 5 and 3 is 7 Result of bitwise exclusive operator of 5 and 3 is 6 Result of bitwise left shift operator of 5 and 3 is 40 Result of bitwise right shift operator of 5 and 3 is 0
2.1.6 Assignment operator Assignment Operators: Assignment operator is used to assign the value to variable. To understand the operation assume variable A contains value 10 and variable contains value 5. Example: A=B; In the above example value of variable B is assign to variable A. Result of this expression is value of A is 5 and value of B is 5.
2.1.7 Operator precedence and associativity Expression may have one or more operators in it. If expression has multiple operators then these operators are solved according to hierarchy of operators. Hierarchy determines the order in which these operators are executed. Table : Hierarchy of operators
Ex. 1 Find the result of the following operations.
Soln. :
Ex. 2 Using Hierarchy chart, list the order in which following operations would be processed? 1. +,-,* 2. OR,*,< 3. NOT, AND,* 4. AND,OR,NOT 5. NOT,+,\ 6. MOD,\,< 7. <,AND,>,+ Soln. :
|
In conditional branching decision point is based on the run time logic. Conditional branching makes use of both selection logic and iteration logic. In conditional branching flow of program is transfer when the specified condition is satisfied. Fig. Flowchart for conditional branching
2.2.1 Applying if and switch statements, nesting if and else In conditional branching change in sequence of statement execution is depends upon the specified condition. Conditional statements allow programmer to check a condition and execute certain parts of code depending on the result of conditional expression. Conditional expression must be resulted into Boolean value. In C language, there are two forms of conditional statements: 1. if-----else statement: It is used to select one option between two alternatives 2. switch statement: It is used to select one option between multiple alternative
This statement permits the programmer to allocate condition on the execution of a statement. If the evaluated condition found to be true, the single statement following the "if" is execute. If the condition is found to be false, the following statement is skipped. Syntax of the if statement is as follows if (condition) statement1; statement2; In the above syntax, “if” is the keyword and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then compiler will execute statement1 and then statement2. If the condition is not satisfied (false) then compiler will skip statement1 and directly execute statement2. if-----else statement This statement permits the programmer to execute a statement out of the two statements. If the evaluated condition is found to be true, the single statement following the "if" is executed and statement following else is skipped. If the condition is found to be false, statement following the "if" is skipped and statement following else is executed. In this statement “if” part is compulsory whereas “else” is the optional part. For every “if” statement there may be or may not be “else” statement but for every “else” statement there must be “if” part otherwise compiler will gives “Misplaced else” error. Syntax of the “if----else” statement is as follows if (condition) statement1; else statement2; In the above syntax, “if” and “else” are the keywords and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then compiler will execute statement1 and skip statement2. If the condition is not satisfied (false) then compiler will skip statement1 and directly execute statement2. Nested if-----else statements : Nested “if-----else” statements are used when programmer wants to check multiple conditions. Nested “if---else” contains several “if---else” a statement out of which only one statement is executed. Number of “if----else” statements is equal to the number of conditions to be checked. Following is the syntax for nested “if---else” statements for three conditions if (condition1) statement1; else if (condition2) statement2; else if (condition3) statement3; else statement4; In the above syntax, compiler first check condition1, if it trues then it will execute statement1 and skip all the remaining statements. If condition1 is false then compiler directly checks condition2, if it is true then compiler execute statement2 and skip all the remaining statements. If condition2 is also false then compiler directly checks condition3, if it is true then compiler execute statement3 otherwise it will execute statement 4. Note: If the test expression is evaluated to true, • Statements inside the body of if are executed. • Statements inside the body of else are skipped from execution. If the test expression is evaluated to false, • Statements inside the body of else are executed • Statements inside the body of if are skipped from execution.
// Check whether an integer is odd or even #include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number);
// True if the remainder is 0 if (number%2 == 0) { printf("%d is an even integer.",number); } else { printf("%d is an odd integer.",number); }
return 0; } Program to relate two integers using =, > or < symbol
#include <stdio.h> int main() { int number1, number2; printf("Enter two integers: "); scanf("%d %d", &number1, &number2);
//checks if the two integers are equal. if(number1 == number2) { printf("Result: %d = %d",number1,number2); }
//checks if number1 is greater than number2. else if (number1 > number2) { printf("Result: %d > %d", number1, number2); }
//checks if both test expressions are false else { printf("Result: %d < %d",number1, number2); }
return 0; }
This statement permits the programmer to choose one option out of several options depending on one condition. When the “switch” statement is executed, the expression in the switch statement is evaluated and the control is transferred directly to the group of statements whose “case” label value matches with the value of the expression. Syntax for switch statement is as follows: switch(expression) { case constant1: statements 1; break; case constant2: statements 2; break; ………………….. default: statements n; break; } In the above, “switch”, “case”, “break” and “default” are keywords. Out of which “switch” and “case” are the compulsory keywords whereas “break” and “default” is optional keywords.
Example: Program to spell user entered single digit number in English is as follows #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("Enter a number"); scanf("%d",&n); switch(n) { case 0: printf("\n Zero"); break; case 1: printf("\n One"); break; case 2: printf("\n Two"); break; case 3: printf("\n Three"); break; case 4: printf("\n Four"); break; case 5: printf("\n Five"); break; case 6: printf("\n Six"); break; case 7: printf("\n Seven"); break; case 8: printf("\n Eight"); break; case 9: printf("\n Nine"); break; default: printf("Given number is not single digit number"); } getch(); } Output Enter a number 5 Five
2.2.2 Use of break and default with switch In unconditional branching statements are executed without concerning the condition. Unconditional statements allow programmer to transfer the flow of execution to any part of the program. In C language, there are four types of unconditional statements:
break; When “break” statement used inside loops then execution of “break” statement causes the immediate termination of loop and compiler will execute next statement after the loop statement. 2. Goto statement: “goto” statement is used to transfer the flow of program to any part of the program. The syntax of “go to” statement is as follows goto label name; In the above syntax “goto” is keyword which is used to transfer the flow of execution to the label specified after it. Label is an identifier that is used to mark the target statement to which the control is transferred. The target statement must be labeled and the syntax is as follows label name statement; In the above syntax label name can be anything but it should be same as that of name of the label specified in “goto” statement, a colon must follow the label. Each labeled statement within the function must have a unique label, i.e., no two statements can have the same label. 3. Continue statement: It is used mainly with “switch” and “loop” statements. The execution of “continue” instruction, skip the remaining iteration of the loop and transfer he flow of program to the loop control instruction. Syntax of “continue” statement is as follows continue; 4. Return statement: The “return” statement terminates the execution of the current function and return control to the calling function. The “return” statement immediately ends the function, ignoring everything else in the function after it is called. It immediately returns to the calling function and continue from the point that it is called. Return also able to "return" a value which can be use in the calling function.
|
References:
- The C Programming Language. 2nd Edition Book by Brian Kernighan and Dennis Ritchie
- C Programming: A Modern Approach Book by Kim N. King
- C Programming Absolute Beginner’s Guide book by S.D Perry