Amazon

Wednesday, May 18, 2016

ARITHMETIC/CONDITIONAL OPERATIONS IN C LANGUAGE

Text Box: 7
ARITHMETIC/CONDITIONAL OPERATIONS IN C LANGUAGE

Please keep this blog running.

  1. Download the .Doc Format of this article. Click here and wait for the ads to load, then click skip add at upper right.
  2. Download the .Pdf Format of this article. Click here and wait for the ads to load, then click skip add at upper right.
  3. Download the Q&A of this article. Click here and wait for the ads to load, then click skip add at upper right.

PART A - STATEMENTS, EXPRESSIONS, AND OPERATORS
                       

§  STATEMENTS

       A statement is a complete direction instructing the computer to carry   out  some task. In   C, statements are usually written one per line, although some statements span multiple lines. C statements always end with a semicolon (except  for preprocessor directives such as #define and  #include). You've already been   introduced to some of C's statement types. For example:

x = 2 + 3;

     is an assignment statement. It instructs the computer to add 2 and 3 and to  assign the  result to the variable x.

 

Statements and White Space

  The term white space refers to spaces, tabs, and blank lines in your source code. The C          compiler isn't sensitive to white space. When the compiler reads a statement in your source   code, it looks for the characters in the statement and for the terminating semicolon, but it ignores white space. Thus, the statement
                               
x=2+3; is equivalent to this statement: x = 2 + 3;
                       
                                    It is also equivalent to this:
                           x        =
            2
            +
            3;

    However, the rule that C doesn't care about white space has one exception: Within   literal string constants, tabs and spaces aren't ignored; they are considered part of the string. A   string is a series of characters. Literal string constants are strings that are enclosed within quotes and interpreted literally by the compiler, space for space. Although it's extremely bad  form, the following is legal:
                               printf(
            "Hello, world!");
                       
                        This, however, is not legal:
                               
                               printf("Hello,
            world!");
 
    To break a literal string constant line, you must use the backslash character (\) just  before the break. Thus, the following is legal:
                               
                               printf("Hello,\
            world!");
 

                        Null Statements

If you place a semicolon by itself on a line, you create a null statement--a statement that doesn't perform any action. This is perfectly legal in C. Later, you will learn how the null statement can be useful.

  Compound Statements

                    A compound statement, also called a block, is a group of two or more C                                     statements enclosed in braces. Here's an example of a block:
                               
                               {
             printf("Hello, ");
             printf("world!");
            }
 
       In C, a block can be used anywhere a single statement can be used. Note that   the enclosing braces can be positioned in different ways. The following is equivalent to the   preceding example:
 
                     {printf("Hello, ");
            printf("world!");}

         It's a good idea to place braces on their own lines, making the beginning and end of   blocks clearly visible. Placing braces on their own lines also makes it easier to see whether  you've left one out.

 

§  EXPRESSIONS

        In C, an expression is anything that evaluates to a numeric value. C expressions come in all     levels of complexity.

 

                        Simple Expressions

                                    The simplest C expression consists of a single item: a simple variable, literal                                             constant, or symbolic constant. Here are four expressions:
Expression
Description
PI
A symbolic constant (defined in the program)
20
A literal constant
rate
A variable
-1.25
Another literal constant
             A literal constant evaluates to its own value. A symbolic constant evaluates to the value        it was given when you created it using the #define   directive. A variable evaluates to the    current value assigned to it by the program. #define command has no equal (=) symbol  between the constant name and its corresponding value. Ex.

#define Pi 3.1416

  Take note, there is no semicolon symbol after the constant value.

           

    Complex Expressions

    Complex expressions consist of simpler expressions connected by    operators. For example:
2 + 8
          is an expression consisting of the sub expressions 2 and 8 and the addition operator +.       The expression 2 + 8 evaluates, as you know, to 10. You can also write C expressions of great  complexity:
 
1.25 / 8 + 5 * rate + rate * rate / cost

When an expression contains multiple operators, the evaluation of the     expression depends on operator precedence. C expressions get even more interesting. Look at the following assignment statement:

x = a + 10;
 
         This statement evaluates the expression a + 10 and assigns the result to x. In addition,  the entire statement x = a + 10 is itself an expression that evaluates to the value of the variable on the left side of the equal sign.
 

§  OPERATORS

An operator is a symbol that instructs C to perform some operation, or  action, on one or   more operands. An operand is something that an operator acts on.   In C, all operands are   expressions. C operators fall into several categories:
·         The assignment operator
·         Mathematical operators
·         Relational operators
·         Logical operators

 

   The Assignment Operator

        The assignment operator is the equal sign (=). Its use in programming is somewhat             different from its use in regular math. If you write

x = y;
 
    in a C program, it doesn't mean "x is equal to y." Instead, it means   "assign the value of y          to x." In a C assignment statement, the right side can be any expression, and the left side must  be a variable name. Thus, the form   is as follows:
 
variable = expression;

        When executed, expression is evaluated, and the resulting value is assigned to variable.

   Mathematical Operators

             C's mathematical operators perform mathematical operations such as addition and           subtraction. C has two unary mathematical operators and five binary mathematical operators.

                                   

                                    Unary Mathematical Operators

Table 4.1. C's unary mathematical operators.

Operator
Symbol
Action
Examples
Increment
++
Increments the operand by one
++x, x++
Decrement
--
Decrements the operand by one
--x, x--
       The increment and decrement operators can be used only with variables. The  operation performed is to add one to or subtract one from the operand. In other words,   the statements
++x;
--y;
                                    are the equivalent of these statements:
x = x + 1;
y = y - 1;
 You should note from Table 4.1 that either unary operator can be  placed before    its operand (prefix mode) or after its operand (postfix   mode). These two modes are   not equivalent. They differ in terms of when the increment or decrement is performed:
·         When used in prefix mode, the increment and decrement operators modify their operand before it's used.
·         When used in postfix mode, the increment and decrement operators modify their operand after it's used.
   An example should make this clearer. Look at these two statements:
x = 10;
y = x++;
         After these statements are executed, x has the value 11, and y has the value 10.  The value of x was assigned to y, and then x was incremented. In contrast, the  following statements result in both y and x having the value 11. x is incremented, and      then its value is assigned to y.
x = 10;
y = ++x;
     After these statements are executed, x has the value 11, and y has the value 11.

  Binary Mathematical Operators

           C's binary operators take two operands. The binary operators, which include the           common mathematical operations found on a calculator, are listed in Table 4.2.

Table 4.2. C's binary mathematical operators.

Operator
Symbol
Action
Example
Addition
+
Adds two operands
x + y
Subtraction
-
Subtracts the second operand from the first operand
x - y
Multiplication
*
Multiplies two operands
x * y
Division
/
Divides the first operand by the second operand
x / y
Modulus
%
Gives the remainder when the first operand is divided by the second operand
x % y

 

  Operator Precedence and Parentheses

   In an expression that contains more than one operator, what is the order in   which operations are performed? The importance of this question is illustrated by the  following assignment statement:

x = 4 + 5 * 3;
 
    Performing the addition first results in the following, and x is                                                                     assigned the value 27:

x = 9 * 3;
 
      In contrast, if the multiplication is performed first, you have                                                                       the following, and x is assigned the value 19:

x = 4 + 15;
 
       Clearly, some rules are needed about the order in which operations are   performed. This order, called operator precedence, is strictly spelled out in C. Each    operator has a specific precedence. When an expression is evaluated, operators with     higher precedence are performed first. Table 4.3 lists the precedence of C's      mathematical operators. Number 1 is the highest precedence and thus is evaluated first.

Table 4.3. The precedence of C's mathematical operators.

Operators
Relative Precedence
++ --
1
* / %
2
+ -
3
                                               
    Looking at Table 4.3, you can see that in any C expression,    operations are performed in the following order:
·         Unary increment and decrement
·         Multiplication, division, and modulus
·         Addition and subtraction
 If an expression contains more than one operator with the same  precedence  level, the operators are performed in left-to-right order as  they appear in the  expression. For example, in the following expression, the % and * have the same    precedence level, but the % is the leftmost operator, so it is performed first:

12 % 5 * 2

  The expression evaluates to 4 (12 % 5 evaluates to 2 times 2 is 4). A   sub   expression enclosed in parentheses is evaluated first, without regard to operator   precedence. Thus, you could write

x = (4 + 5) * 3;
 
    The expression 4 + 5 inside parentheses is evaluated first, so  the value assigned to x is 27. Look at the following complex    expression:
 
x = 25 - (2 * (10 + (8 / 2)));
 
     The evaluation of this expression proceeds as follows:
1. The innermost expression, 8 / 2, is evaluated first, yielding the value 4:
25 - (2 * (10 + 4))
2. Moving outward, the next expression, 10 + 4, is evaluated, yielding the value 14:          
25 - (2 * 14)
3. The last, or outermost, expression, 2 * 14, is evaluated, yielding the value 28:   
25 - 28
4. The final expression, 25 - 28, is evaluated, assigning the value -3 to the variable x:
x = -3

 Relational Operators

        C's relational operators are used to compare expressions, asking   questions such as, "Is x        greater than 100?" or "Is y equal to 0?" An   expression containing a relational operator evaluates to    either true (1) or false (0). C's six relational operators are listed in Table 4.4. Table 4.5 shows some examples of how relational operators might be used. These examples use literal constants, but the same principles hold with variables.


NOTE: "True" is considered the same as "yes," which is also considered the same as 1. "False" is considered the same as "no," which is considered the same as 0.


 


Table 4.4. C's relational operators.

Operator
Symbol
Question Asked
Example
Equal
= =
Is operand 1 equal to operand 2?
x = = y
Greater than
> 
Is operand 1 greater than operand 2?
x > y
Less than
< 
Is operand 1 less than operand 2?
x < y
Greater than or equal to
>=
Is operand 1 greater than or equal to operand 2?
x >= y
Less than or equal to
<=
Is operand 1 less than or equal to operand 2?
x <= y
Not equal
!=
Is operand 1 not equal to operand 2?
x != y

 

Table 4.5. Relational operators in use.

Expression
How It Reads
What It Evaluates To
5 = = 1
Is 5 equal to 1?
0 (false)
5 > 1
Is 5 greater than 1?
1 (true)
5 != 1
Is 5 not equal to 1?
1 (true)
(5 + 10) = = (3 * 5)
Is (5 + 10) equal to (3 * 5)?
1 (true)

PART B - C'S CONDITIONAL STATEMENTS
§  If Statement
o   This is the simplest form of the branching statements.
o   It takes an expression in parenthesis and a statement or block of statements.
o   if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
NOTE: Expression will be assumed to be true if its evaluated values are non-zero.
if statements take the following SYNTAX:

    


if (expression)
            statement;
-----------OR----------------

      if (expression)
            {
            Block of statements;
            }
----------OR----------------
      if (expression)
            {
            Block of statements;
            }
      else
            {
Block of statements;
            }

-------------OR----------------
      if (expression)
            {
            Block of statements;
            }
      else if(expression)
            {
            Block of statements;
            }
      else
            {
            Block of statements;
            }



o   If expression evaluates to true, statement is executed.
o   If expression evaluates to false, statement is not executed.
o   In either case, execution then passes to whatever code follows the if statement.

The order of precedence of C's relational operators.
Operators
Relative Precedence
< <= > >=
1
!=     = =
2

§  Logical Operators
o   C's logical operators let you combine two or more relational expressions into a single expression that evaluates to either true or false. Table 4.7 lists C's three logical operators.

Table 4.7. C's logical operators.

Operator
Symbol
Example
AND
&&
exp1 && exp2
OR
||
exp1 || exp2
NOT
!
!exp1
                        The way these logical operators work is explained in Table 4.8.

Table 4.8. C's logical operators in use.

Expression
What It Evaluates To
(exp1 && exp2)
True (1) only if both exp1 and exp2 are true; false (0) otherwise
(exp1 || exp2)
True (1) if either exp1 or exp2 is true; false (0) only if both are false
(!exp1)
False (0) if exp1 is true; true (1) if exp1 is false
           You can see that expressions that use the logical operators evaluate to either true or   false, depending on the true/false value of their operand(s). Table 4.9 shows some actual code     examples.

Table 4.9. Code examples of C's logical operators.

Expression
What It Evaluates To
(5 = = 5) && (6 != 2)
True (1), because both operands are true
(5 > 1) || (6 < 1)
True (1), because one operand is true
(2 = = 1) && (5 == 5)
False (0), because one operand is false
!(5 = = 4)
True (1), because the operand is false
        You can create expressions that use multiple logical operators. For example, to ask the                         question "Is x equal to 2, 3, or 4?" you would write
(x = = 2) || (x = = 3) || (x = = 4)
 
§  Switch Case Statement
o   The switch statement is much like a nested if .. else statement.
o   It's mostly a matter of preference which you use; switch statement can be slightly more efficient and easier to read.
SYNTAX:
switch( expression )
     {
        case constant-expression1:   statements1;
        [case constant-expression2   :statements2;]   
        [case constant-expression3:statements3;]
        [default : statements4;]
     }
EXAMPLE:
char  Grade = 'A';
     switch( Grade )
     {

        case 'A' : printf( "Excellent\n" );
        case 'B' : printf( "Good\n" );
        case 'C' : printf( "OK\n" );
        case 'D' : printf( "Mmmmm....\n" );
        case 'F' : printf( "You must do better than this\n" );   
        default  : printf( "What is your grade anyway?\n" );
     }
o   Using break keyword           
            If a condition is met in switch case then execution continues on into the next case clause also if it is not explicitly specified that the execution should exit the switch statement. This is achieved by using break keyword.
EXAMPLE:
int  Grade = 'B';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }

SUMMARY of C operator precedence.

Level
Operators
1
() [] -> .
2
! ~ ++ -- * (indirection) & (address-of) (type)

sizeof + (unary) - (unary)
3
* (multiplication) / %
4
+ -
5
<< >>
6
< <= > >=
7
= =   !=
8
& (bitwise AND)
9
^
10
|
11
&&
12
||
13
?:
14
= += -= *= /= %= &= ^= |= <<= >>=
15
,
() is the function operator; [] is the array operator.



This Workshop provides quiz questions to help you solidify your understanding of the material covered and to provide you with experience in using what you've learned.

Answer the following:
1. What is an expression?
               Answer: __________________________________________________________________________
2. In an expression that contains multiple operators, what determines the order in which operations are performed?
               Answer: __________________________________________________________________________
3. If the variable x has the value 10, what are the values of x and a after each of the following statements is executed separately?
                               a = x++;
                               a = ++x;
               Answer: __________________________________________________________________________
4. To what value does the expression 10 % 3 evaluate?
               Answer: __________________________________________________________________________
5. To what value does the expression 5 + 3 * 8 / 2 + 2 evaluate?
               Answer: __________________________________________________________________________
6. Rewrite the expression in question 5, adding parentheses so that it evaluates to 16.
               Answer: __________________________________________________________________________
7. If an expression evaluates to false, what value does the expression have?
               Answer: __________________________________________________________________________

8. To what value do each of the following expressions evaluate?
            a. (1 + 2 * 3)
            Answer: _________
            b. 10 % 3 * 3 - (1 + 2)
            Answer: _________
            c. ((1 + 2) * 3)
            Answer: _________
            d. (5 == 5)
            Answer: _________
            e. (x = 5)
            Answer: _________
9. If x = 4, y = 6, and z = 2, determine whether each of the following evaluates to true or false.
            a. if( x == 4)
            Answer: _________
            b. if(x != y - z)
            Answer: _________
            c. if(z = 1)
Text Box: 7            Answer: _________
            d. if(y)
            Answer: _________


PART C - PROGRAM DEVELOPMENT
§  Set01 (10pts)
                Problem:
Text Box: 7         Input two numbers (use variable X and Y). Create a C Program that determine the                               difference between X and Y. If X-Y is negative, compute R=X+Y; if X-Y is zero, compute R=2X+2Y; and if X-Y is   positive, compute R=X*Y, Print out the values of X, Y and R.
                Sample Output:
                                Enter 1st Number(X): 5
                                Enter 2nd Number(Y): 7
                                The value of R is: 12
§  Set02 (10pts)
                Problem:
                                Create a C program that will accept three (3) integer numbers and will print the largest     number.
                Sample Output:
                                Enter 1st Number: 5
                                Enter 2nd Number: 8
                                Enter 3rd number: 7
                                The largest number is: 8




Please keep this blog running. 
    Text Box: 7Text Box: 7
  1. Download the .Doc Format of this article. Click here and wait for the ads to load, then click skip add at upper right.
  2. Download the .Pdf Format of this article. Click here and wait for the ads to load, then click skip add at upper right.
  3. Download the Q&A of this article. Click here and wait for the ads to load, then click skip add at upper right.

No comments:

Post a Comment