Friday, July 10, 2015

Operators and Expressions


Operators and Expression – An expression consists of variables and constants separated by operators. C language uses many type of operators as listed below:-
1.      Arithmetic Operators
2.      Relational Operators
3.      Logical Operators
4.      Increment and Decrement Operators
5.      Assignment Operators
6.      Conditional Operators
7.      Bitwise Operators

Arithmetic Operators - The basic arithmetic operators in C are the same as in most other computer languages, and correspond to our usual mathematical/algebraic symbolism. The following arithmetic operators are present in C:

Operators
Meaning
Example
Result
+
Addition
4+2
6
-
Subtraction
4-2
2
*
Multiplication
4*2
8
/
Division
4/2
2
%
Modulus operator to get remainder in integer division
5%2
1

Some of the examples of algebraic expressions and their C notation are given below:

Expression
C notation
b*g / b
(b*g) / b
a^3+cd
(a*a*a)+cd

Parentheses can be used in C expression in the same manner as algebraic expression For example,
a * (b + c).


The operands in arithmetic expressions can be of integer, float, double type. In order to effectively develop C programs, it will be necessary for you to understand the rules that are used for implicit conversation of floating point and integer values in C.
They are mentioned below:
         An arithmetic operator between an integer and integer always yields an integer result.
         Operator between float and float yields a float result.
         Operator between integer and float yields a float result.
         If the data type is double instead of float, then we get a result of double data type.
For example:
Operation
Result
5/3
               1
5.0/3
1.3
5/3.0
1.3
5.0/3.0
1.3

The rules of arithmetic precedence are as follows:

1.      Parentheses are at the “highest level of precedence”. In case of nested parenthesis, the innermost parentheses are evaluated first.
For example:
( ((3+4)*5)/6 )
The order of evaluation is given below.
( ( (3+4) * 5) / 6 )
                    ↓     ↓       ↓
                    1     2       3

2.      Multiplication, Division and Modulus operators are evaluated next. If an expression contains several multiplication, division and modulus operators, evaluation proceeds from left to right. These three are at the same level of precedence.
For example:
5*5+6*7
The order of evaluation is given below.
5*5+6*7
              ↓  ↓   ↓
              1  3   2

3.      Addition, subtraction are evaluated last. If an expression contains several addition and subtraction operators, evaluation proceeds from left to right. Or the associativity is from left to right.
For example:
8/5-6+5/2
The order of evaluation is given below.
8/5-6+5/2
 ↓  ↓  ↓  ↓
 1  3  4  2

Library Function (Intrinsic Functions or Math Functions) – To perform standard mathematical operations such as square root, absolute value and so on, built-in programs called library functions are available with the compiler. These functions can be used in an expression by mentioning their names with required number of arguments in parenthesis. Following are the commonly used mathematical library functions:-
(Click image for large view)

Note – The argument x used in this function is declared float or double and the complier directive #include<math.h>is used to include any of these functions in a C program.

Unary Plus ( + ) or Unary Minus ( – ) operations – When only one operand is used with + or – operators, the operation is called unary plus or unary minus, which does not actually refer to addition or subtraction. 
  
Relational Operators– Relational operators are used to compare the value of operands (expressions) to produce a logical value. A logical value is either true or false. Following are the relational operators used in C language:-

Operators
Meaning
Example
Result
< 
Less than
5>2
False
> 
Greater than
5>2
True
<=
Less than or equal to
5<=2
False
>=
Greater than or equal to
5>=2
True
==
Equal to
5==2
False
!=
Not equal to
5!=2
True

Note – In C language the logical value true is represented by integer 1 and false by 0 (zero).


Logical Operators – Logical operators are used to connect more relational operations to form a complex expression called logical expression. A value obtained by evaluating a logical expression is always logical, i.e. either true or false. Following are the logical operators in C:-

Operator
Meaning
Example
Result
&&
Logical AND
(5<2)&&(5>3)
False
||
Logical OR
(5<2)||(5>3)
True
!
Logical NOT
!(5<2)
True

Note – Logical not ( ! ) is an unary operator which requires only one operand. It is also referred as invertor which converts the value of the operand from true to false and vice versa.

The following truth tables to understand the logical values obtained using the logical operators:-
&&
Operand 1
Operand 2
Result
True
True
True
True
False
False
False
True
False
False
False
False

||
Operand 1
Operand 2
Result
True
True
True
True
False
True
False
True
True
False
False
False

!
Operand
Result
False
True
True
False


Increment ( ++) and Decrement ( -- ) Operators - The increment operator increments the variable by one and decrement operator decrements the variable by one. These operators can be written in two forms i.e. before a variable or after a variable. If an increment / decrement operator is written before a variable, it is referred to as pre-increment / pre-decrement operators and if it is written after a variable, it is referred to as post-increment / post-decrement operator.
For example:
a++ or ++a is equivalent to a = a+1 and
a-- or - -a is equivalent to a = a -1

The importance of pre and post operator occurs while they are used in the expressions. Pre-incrementing (Pre-decrementing) a variable causes the variable to be incremented (decremented) by 1, then the new value of the variable is used in the expression in which it appears. Post-incrementing (post-decrementing) the variable causes the current value of the variable are used in the expression in which it appears, then the variable value is incremented (decrement) by 1.

The explanation is given in the table below:

Operators
Meaning
++a
Increment a by 1, then use the new value of a
a++
Use value of a, then increment a by 1
--b
Decrement b by 1, then use the new value of b
b--
Use the current value of b, then decrement by 1

The precedence of these operators is right to left. Let us consider the following examples:
int a = 2, b=3;
int c;
c = ++a – b- -;
printf (“a=%d, b=%d,c=%d\n”,a,b,c);
OUTPUT
a = 3, b = 2, c = 0.
Since the precedence of the operators is right to left, first b is evaluated, since it is a post decrement operator, current value of b will be used in the expression i.e. 3 and then b will be decremented by 1.Then, a pre-increment operator is used with a, so first a is incremented to 3. Therefore, the value of the expression is evaluated to 0.
Let us take another example,
int a = 1, b = 2, c = 3;
int k;
k = (a++)*(++b) + ++a - --c;
printf(“a=%d,b=%d, c=%d, k=%d”,a,b,c,k);
OUTPUT
a = 3, b = 3, c = 2, k = 6
The evaluation is explained below:
k = (a++) * (++b)+ ++a - --c
= (a++) * (3) + 2 - 2                step1
= (2) * (3) + 2 – 2                    step2
= 6                                           final result 

Assignment Operator (C Shorthand) – Assignment operators are used to perform arithmetic operations while assigning a value to a variable.

Operator
Example
Equivalent Expression (m=15)
Result
+=
m +=10
m = m+10
25
-=
m -=10
m = m-10
5
*=
m *=10
m = m*10
150
/=
m /=
m = m/10
1
%=
m %=10
m = m%10
5

Conditional Operator ( ? : ) or Ternary Operators  - C provides an called as the conditional operator (?:) which is closely related to the if/else structure. The conditional operator is C’s only ternary operator - it takes three operands. The operands together with the conditional operator form a conditional expression. The first operand is a condition, the second operand represents the value of the entire conditional expression it is the condition is true and the third operand is the value for the entire conditional expression if the condition is false.

The syntax is as follows:
(condition)? (expression1): (expression2);

If condition is true, expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression i.e. the case of nested if statement (will be discussed in the next unit).

Let us see the following examples:
(i) x= (y<20) ? 9: 10;
This means, if (y<20), then x=9 else x=10;

(ii) printf (“%s\n”, grade>=50? “Passed”: “failed”);
The above statement will print “passed” grade>=50 else it will print “failed”

(iii) (a>b) ? printf (“a is greater than b \n”): printf (“b is greater than a \n”);

If a is greater than b, then first printf statement is executed else second printf statement is executed. 

Bitwise Operators– Bitwise operators are used to perform operations at binary digit level. These operators are not commonly used and are used only in special applications where optimized use of storage is required.

Operator
Meaning
<< 
Shifts the bits to left
>> 
Shifts the bits to right
~
Bitwise inversion (one’s complement)
&
Bitwise logical end
|
Bitwise logical or
^
Bitwise exclusive or

 Additional Operators – There two other operators that can be used in a C Program:-
1.      Sizeof operator
2.      Comma operator

Sizeof operator - C provides a compile-time unary operator called sizeof that can be used to compute the size of any object. The expressions such as:

sizeof object and sizeof(type name)

Result in an unsigned integer value equal to the size of the specified object or type in bytes. Actually the resultant integer is the number of bytes required to store an object of the type of its operand. An object can be a variable or array or structure. An array and structure are data structures provided in C, introduced in latter units. A type name can be the name of any basic type like int or double or a derived type like a structure or a pointer.
Example:
sizeof(char) = 1bytes
sizeof(int) = 2 bytes

Comma Operator - A comma operator is used to separate a pair of expressions. A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the value of the type and value of the right operand. All side effects from the evaluation of the left operand are completed before beginning evaluation of the right operand. The left side of comma operator is always evaluated to void. This means that the expression on the right hand side becomes the value of the total comma-separated expression.
Example:
x = (y=2, y - 1);

First assigns y the value 2 and then x the value 1. Parenthesis is necessary since comma operator has lower precedence than assignment operator.

Generally, comma operator (,) is used in the for loop (will be introduced in the next unit)

For example:
for (i = 0,j = n;i<j; i++,j--)
{
printf (“A”);
}

In this example for is the looping construct. In this loop, i = 0 and j = n are separated by comma (,) and i++ and j—are separated by comma (,). The example will be clear to you once you have learnt for loop.

Essentially, the comma causes a sequence of operations to be performed. When it is used on the right hand side of the assignment statement, the value assigned is the value of the last expression in the comma-separated list.






Like it ? Share it.

Thursday, July 9, 2015

Constants and Variables and Data Types


Constants -A constant is an identifier whose value cannot be changed throughout the execution of a program whereas the variable value keeps on changing. In C there are four basic types of constants. They are:

Numeric Constant:
1.      Integer constants
2.      Floating point constants

String or Character Constants:
1.      Single character string constant / Character constants
2.      String of characters constant / String constants

Numeric constants:
1.      Integer Constant An integer constant is signed or unsigned whole number.
Ex: - 34, -48, +45 etc.


2.      Real or Floating Point Constant An signed or unsigned number with fractional part is called real or floating point constant.
Ex: - 0.45, -5.64, 0.45e2 etc.
            where e = exponential.

Rules to form Integer and Floating Point Constants
         No comma or blank space is allowed in a constant.
         It can be preceded by – (minus) sign if desired.
         The value should lie within a minimum and maximum permissible range decided by the word size of the computer.

String or Character constants:
1.      Single character string constant / Character constants – Any letter or character enclosed in single apostrophe is called Single character string constant / Character constant.
Ex: - ‘y’ ‘$’ ‘T’  ‘3’

2.      String of characters constant / String constants – Any string of characters consisting of letters, digits and symbols enclosed in double quotes is called String of characters constant / String constants.
Ex:- “Total Amount”  “Jail-420”  “Average=”

Symbolic constants - Symbolic Constant is a name that substitutes for a sequence of characters or a numeric constant, a character constant or a string constant. When program is compiled each occurrence of a symbolic constant is replaced by its corresponding character sequence. The syntax is as follows:
#define name text
where name implies symbolic name in caps. text implies value or the text.

For example:
#define printf print
#define MAX 100
#define TRUE 1
#define FALSE 0
#define SIZE 10

The # character is used for preprocessor commands. A preprocessor is a system program, which comes into action prior to Compiler, and it replaces the replacement text by the actual text. This will allow correct use of the statement printf.


Advantages of using Symbolic Constants are:
         They can be used to assign names to values
         Replacement of value has to be done at one place and wherever the name appears in the text it gets the value by execution of the preprocessor. This saves time. if the Symbolic Constant appears 20 times in the program; it needs to be changed at one place only.


Variables: - A variable is an identifier or a name which is used to refer a value and this value varies or changes during the program execution. A variable is written with a combination of letters, numbers and special character _ (underscore) with the first letter being an alphabet. Maximum of 31 letters can be used to write a variable.
Ex: - c, fact, h34, total_amount etc
All variables have three essential attributes:
         the name
         the value
         the memory, where the value is stored.

For example, in the following C program a, b, c, d is the variables but variable eis not declared and is used before declaration. After compiling the source code and look what gives?
main ( )
{
int a, b, c;
char d;
a = 3;
b = 5;
c = a + b;
d = ‘a’;
e=d;
……….
……….
}
After compiling the code, this will generate the message that variable e not defined.

Note the following points while writing a variable in C language:-
         Upper and Lower case alphabets are taken differently, so the variable SUM and sum are referring to different value.

         No special characters other than underscore ( _ ) are permitted.

         Some C compliers will not accept more than 8 characters.

         All variables used in a C program are declared with appropriate data types before the variable is assigned any value.

         Reserved words cannot be used as variables.

Variable Declaration- Before any data can be stored in the memory, we must assign a name to these locations of memory. For this we make declarations. Declaration associates a group of identifiers with a specific data type. All of them need to be declared before they appear in program statements, else accessing the variables results in junk values or a diagnostic error. The syntax for declaring variables is as follows:

data- type variable-name(s);

For example,
int a;
short int a, b;
int c, d;
long c, f;
float r1, r2;

Initializing variables- When variables are declared initial, values can be assigned to them in two ways:

1.      Within a Type declaration
The value is assigned at the declaration time.
For example,
int a = 10;
float b = 0.4 e –5;
char c = ‘a’;

2.      Using Assignment statement
The values are assigned just after the declarations are made.
For example,
a = 10;
b = 0.4 e –5;
c = ‘a’;

Basic Data Type – There are four basic data types in C language. They are given below along with number of bytes occupied by them in the computer memory (RAM).

Data Type
Bytes Occupied in RAM
char
1 byte
int
2 bytes
float
4 bytes
double
8 bytes


char – It refers to character. It can hold one letter/symbol. Char in C language is associated with integers to refer a letter/symbol as per ASCII which has assigned integer value for all letters/symbols used in programming.

int – It refers integer. It can hold a signed or unsigned or unsigned whole number within the specified range.

float – It refers floating point or real number. It can hold a real number like 3.245453 or 5.87e3 with six decimal digits in decimal or exponential form. A float number using 6 decimal digits is called a single precision number.

double – It also refers to floating point or real number. It can hold a real number in double precision. A double precision number uses 12 decimal digits like 4.657835876582 or 3.67823574825e14.

Additional Data Types– There are some additional data type which is used in advance programming.

Data Type
Byte Occupied in RAM
unsigned char
1 byte
short int
1 byte
unsigned short int
1 byte
unsigned int
2 bytes
long int
4 bytes
unsigned long int
4 bytes
long double
10 bytes

Note – unsigned is used when positive values are expected for a variable like age of a person.

Consider the following examples to declare variables in C program: -
         unsigned short int marks, age;
         unsigned int total, years;
         int m, amount;
         float x, y, z;
         double cd, pi;
         char sex, sname [20], address [50];
In this declaration, sname [20] refers to the variable sname to hold a string of maximum 20 characters; address [50] holds string of 50 characters; and sex holds a single character such as ‘m’ for male and ‘f’ for female.







Like it ? Share it.