MAP

OPERATORS IN C


Operator is symbol, which represents, a particular operation that can be performed on some data. The data itself (which can be either a variable or a constant) is called the “operand”. The operator thus operates on operand. They are classified as
(1)        Arithmetic                   (2)        relational                     (3)        logical
(4)        Assignment                 (5)        increment/decrement
(6)        Conditional                 (7)        bitwise                         (8)        special

Arithmetic operators: -

There are five arithmetic operators in “C”. They are:

            OPERATOR
PURPOSE
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Remainder after integer division


Examples (Suppose A=10 and B=3)

Expression
Values
A+b
13
a-b
7
A*b
30
A/b
3
A%b
1

Relational Operators: -

There are four relational operators in “C”. They are:
            <                      less than
            <=                    less than or equal to
            >                      greater than
            >=                    greater than or equal to
The associatively of these operators is left-to-right. Closely associated with the relational operator are the following two equality operators:
            = =                   equal to
! =                    not equal to

Suppose that i, j and k integer variable whose values are 1,2 and 3 respectively, Seven logical expressions involving these variables are shown below. :

Expression
Interpretation
Value
i<j
True
1
(i+j)>=k
True
1
(j+k)>(I+5)
False
0
K!=3
False
0
J = = 2
True
1


  Logical Operators:

       ‘C’ provides three logical operations. They are:

Operator                                              Meaning
   &&                                                   AND
    ||                                                       OR
     !                                                      NOT

These operators are referred to as logical AND logical OR and logical NOT respectively.
The following table shows the result of the combined expressions depending on the value of the expression:

Operands
Results
Exp1
Exp2
Exp1 && exp2
Exp1 || exp2
0
0
0
0
0
Non-zero
0
1
Non-zero
0
0
1
Non-zero
Non-zero
1
1

The associatively us left-to-right.

Assignment Operators:

Assignment operators are use to form assignment expressions, which assign the value of an expression to an identifier. The most commonly used assignment operator is =. Assignment expression that make use of this operator are written in the form


Identifier = Expression
a= a+1                                                 a+=1
a=a-1                                                   a-=1
a=a*( c + d)                                         a*=(c + d)
a=a/(n-1)                                              a/=(n-1)
a=a%10                                               a%=10

 

Increment and Decrement Operators:

 “C” offers two special operator ++ and – called increment and decrement operators, respectively. There are “unary” operators since they operator on only one operand. The operand has to be a variable and not a constant. Thus the expression a++ is valid as 6++ is invalid. The use of these operates resulting incrementing or decrementing value of the variable is 1. So the expression a++ increment the value of a by 1 and the expression a- - decrements a by 1. These operators can be used either before or after their operand. (i.e. in either “prefix” or “postfix” position) so we can have a++(postfix) and ++a (prefix). Prefix and postfix have some effect if they are used in an isolated statement. For example, the effect of the following statements would be same:
a++;        ++a;
However prefix and postfix operators have different effects when used in association with some other operator in “c” statement. For example, if we assume the value of a variable to be 5 and then assign that new value to b. The effect is exactly same. If the following two statements have been executed :
b = a++; b=++a;
On the other had, execution of the statement b = a++; will be first set the value of b to 5 and then increases the value of a to 6. The effect is now same as if the following statement had been executed :
b = a;   b= a+1;
 [ Note : First precedence : R->L associatively)

Conditional operators:

Simple conditional operations can be carried out with the conditional operator (?:) An expression that makes the use of the conditional operator is called a conditional expression. Conditional operators are also known as turnery operators.
Syntax:
(condition) ?  true : false
Exp1          ?  Exp2 : Exp3
Here if condition is evaluated as true then value of exp2 will be return and if condition is evaluated as false then exp3 will be return.
For example
T=(I<0) ? 0 : 100
If I variable value is less then 0 then condition is evaluated as true and T will be assigned with 0 but if I variable value is greater then 0 then condition is evaluated as false and 100 will be assign to variable T.  For example
Printf(“%d”, (I<0) ? 0:100);

 

Sizeof Operator:

The size of a compile time operator and when used with an operand, it returns the number of bytes the operand occupies. The operand may be variable, a constant or a data type qualifies.
            M = sizeof(sum);
             N= sizeof(long int);
             K= sizeof(253L);
The size of operator is normally used to determine the length of array and structures, when their sizes are not known to the programmer. It is used to allocate memory space dynamically to variable during execution of a program.

Bitwise operators:

Some applications require the manipulation of individual bits within a word of memory. Assembly language or machine language is normally required for operations of this type. However C contains several special operators that allow such bitwise operations to be carried out easily and efficient. These bitwise operators can be divided into three general categories: the one’s complement operator, the logical bitwise operators, and the shift operators. “C” also contains several operators that combine bitwise operations with ordinary assignment.

The One’s Complement operator:

The one’s complement operator (~) is a unary operator that causes the bits of its operand to be inverted (i.e. reversed) so that is become so a so become is. This operator always precedes its operand. The operand must be an integer type quantity (including integer, long, short, unsigned, or char).(Linearly the operand will be an unsigned octal or an unsigned hexadecimal quantity, though this is not a firm requirement.
Suppose int a=16 with 2 byte=16 bit pattern
 it will be à  00000000 00010000
b=~a
the b will have 16 bit pattern like à 11111111 11101111

Logical bit wise operators :

There are three logical bitwise operators : bitwise and ($), bitwise exclusive or(^) and bitwise or(!). Each of these operators requires two integer type operands. The operations are carried out independently on each pair of corresponding bits within the two operands will be. Thus the least significant bits( i.e. the rightmost bits) within the two operands will be compared then the least significant bits. And so on. Until these comparisons are :

B1
B2
B1&b2
B1^b2
B1 | b2
1
1
1
0
1
1
0
0
1
1
0
1
0
1
1
0
0
0
0
0
The associatively for each bitwise operator is left-to-right.

Shift operators:

The two bitwise shift operator is shift left (<<) and shift right(>>). Each operator requires two operands. The first is an integer-type operand that represents the bit pattern to be shifted. The second is an unsigned integer that indicates the number of displacements (i.e. whether the bits in the first operand will be shifted by 1 bit position, 2 bit position, 3 bit positions and so on). This value cannot exceed the number of bits associated with the word size of the first operand.
The left-shift operator causes the left by the bits in the first operand to be shifted to the left by the number of position indicated by the second operand. The leftmost bit positions that become vacant will be tilled with us.
A = 01101101 10110111
A<<6 = 0110 1100 0000 = 0x5dc0
 All the bits originally assigned to a are shifted to the left six places, as the arrows indicate. The leftmost 6 bits (originally 011011) are lost. The rightmost 6 bits positions are filled with 00 0000.
The right shift operator causes all the bits in the first operand to be shifted to the right by the number of positions indicated by the second operand. The rightmost bits(i.e. the underflow bits) in the original bit pattern will be lost. If the bit pattern being shifted represents an unsigned integer, then the leftmost bit positions that become vacant will be filled with 0s. Hence, the behavior of the right-shift. When the first operand is an unsigned integer.
A= 0110 1101 1011 0111
A>>6 = 000 0001 1011 0110 = 061bc
We see that all the bits originally assigned to a are shifted to the right six places, as the arrows indicate. The rightmost 6 bits ( originally 11 011) are lost. The leftmost 6 bits positions are filled with 00 0000.

Comma Operator:

The comma operators are use primarily in conjunction with the for statement. This operator permits two different expressions to upper in situation where only one expression would ordinarily be used. For example, it is possible to write
For (expression la, expression lb; expression2; expression3) Statement
Where expression la and lb are the two expression, separated by the comma operator, where only one expression would normally appear. These two expression would typically initialize two separate indices that would be used simultaneously within the for loop.
Similarly, a for statement might make use of the comma operator in the following manner.
For (expression 1a; expression2;expression3a, expression3b) statement;
Here expression 3a and expression 3b separated by the comma operator, appear in place of the usual single expression. In this application the two separate expressions would typically be used to alter the two different indices used simultaneously within the loop. For example, one index might count forward while the order counts backward. In for loops.
            For(n=1,m=10; n<=m; m++, n++)

 

 

 

 

















 

Precedence and Associativity Table

Precedence is a priority of the operator for evaluation or execution when there are more then 1 operator in a single expression or statement. If there are operators of same precedence then the expression will evaluated either from LEFT-TO-RIGHT or RIGHT-TO-LEFT. This is called an associativity of an operator.


Description
Operator
Associativity
Precedence
Function expression
( )
L TO R

1
Array expression
[ ]
L TO R
Structure operator
->
L TO R
Structure operator
.
R TO L
Unary minus
-
R TO L




2
Increment/Decrement
++ --
R TO L
One’s complement

R TO L
Negation
!
R TO L
Address of
&
R TO L
Value of address
*
R TO L
Type cast
(type)
R TO L
Size in bytes
Size of
R TO L
Multiplication
*
L TO R

3
Division
/
L TO R
Modulus
%
L TO R
Addition
+
L TO R
4
Subtraction
-
L TO R
Left Shift
<< 
L TO R
5
Right Shift
>> 
L TO R
Less than
< 
L TO R


6
Less than equal to
<=
L TO R
Greater than
> 
L TO R
Greater than or equal to
>=
L TO R
Equal to
= =
L TO R
7
Not equal to
!=
L TO R
Bitwise AND
&
L TO R
8
Bitwise exclusive OR
^
L TO R
9
Bitwise inclusive OR
|
L TO R
10
Logical AND
&&
L TO R
11
Logical OR
||
L TO R
12
Conditional
? :
R TO L
13
Assignment
= *,= ,/=, %=
+=,-=,^=,|=,&=
<<=,>>=
R TO L
14


Comma
,
R TO L
15

DATA TYPES IN C


C language has very rich set of data types. At presently we will go through some of the basic data types available in C.

Variable Type
Keyword
Bytes
Required
Range
Format
Character
(Signed)
Char
1
-128 to +127
%c
Integer
 (Signed)
Int
2
-32768 to +32767
%d
Float
(Signed)
Float
4
-3.4e38 to +3.4e38
%f
Double
Double
8
-1.7e308 to + 1.7e308
%lf
Long integer
(Signed)
Long
4
-2,147,483,648 to 2,147,438,647
%ld
Character
 (Unsigned)
Unsigned char
1
0 to 255
%c
Integer
 (Unsigned)
Unsigned int
2
0 to 65535
%u
Unsigned long integer
Unsigned long
4
0 to 4,294,967,295
%lu
Long double
Long double
10
-1.7e932 to +1.7e932
%Lf

Character:

 To access and to store single character it use char data type in C. Char data type occupies  1 bytes. It means that char data type use 1 byte of memory to store some character value.

Declaration of character variable:
char ans;       
Assigning values to character variable:
Ans=’y’;

8          7          6          5          4          3          2          1
Sign







27         26         25         24         23         22         21         20

Above given is a general structure of character variable. The leftmost bit is used to indicate the positive or negative value of a variable. So the range for character variable is –27 to 27 –1 .means –128 to 127.

Integer:

 To access and to store any integer value int data type is use. C’s int data type occupies 2 bytes in the memory.
To declare any integer variable:
Int rollno;
Int accno;
To assign or to store integer value in this variable:
Rollno=10;
Accno=100;
16   15   14    13   12   11    10   9     8      7     6     5     4     3     2      1
Sign















215    214   2 13    212   211    210   2 9      2 8    27      26     25       24     2 3      22     21     20

Above given is a general structure of integer variable. The leftmost bit is used to indicate the positive or negative value of a variable. So the range for integer variable is –215 to 215 –1 .means –32768 to 32767.

Float:

To access and to store any real value float data type is use. C’s float data type occupies 4 bytes in the memory.

To declare any float variable:
Float per;
Float rate;
To Assign or to store some real value
Per=70.20;
Rate=123.45
32                                                                                                                                               1
Sign































231                                                                                                                                                                                               20
Above given is a general structure of float variable. The leftmost bit is used to indicate the positive or negative value of a variable. So the range for float variable is –231 to 231 –1 .
Means -3.4e38 to +3.4e38

Long:

To access and to store any integer value long data type is use. C’s long data type occupies 4 bytes in the memory.
To declare any long variable:
long account;
long price;
To Assign or to store some long value
account=123456;
Rate=98765;
32                                                                                                                                               1
Sign































231                                                                                                                                                                                               20
Above given is a general structure of long variable. The leftmost bit is used to indicate the positive or negative value of a variable. So the range for long variable is –231 to 231 –1 .
Means - 2,147,483,648 to +2,147,438,647

KEYWORDS OF C LANGUAGE

There are words with specific meaning to “C” language system. They are known as keywords of “C” language. Keyword must not be used as variable names. There are 32 keywords in “C” language. Which are as under : Auto double int struct break Else long switch case enum Register typeof char external return Union const float short unsigned Continue for signed void default Goto sizeof volatile do if Static while

VARIABLES

A variable is a named data storage location in your computer’s memory. By using a variable’s name in your program, you are, in effect, referring to the data stored there. VARIABLE NAMING CONVENTION To use variables in your C programs, you must know ho to create variable names in C,variables names must adhere to the following rules: • The name can contain letters, digits, and the underscore character(_). • The first character of the name must be a letter. The underscore is also a legal first character, but its use is not recommended. • Case matters (that is uppercase and lowercase letters). Thus, the names count and Count refer to two different variables. • C keywords can’t be used as variable names. A keyword is a word that is part of the C language.

BASIC STRUCTURE OF C PROGRAM

C program can be viewed a s group of building blocks called functions. A function is a subroutine that may include one or more statement designed to perform a specific task. A C program may contain one or more section as shown below: Documentation Section: This section contains set of comments lines consist of details like program name, author name and purpose or functionality of the program. Link Section: This section consist of instructions to be given to the compiler to link functions from the system library. For example if you want to use some mathematical function then you have to define link for math.h file in link section. For Example # include # include Definition Section: This section defines all the symbolic constants. For example PI=3.14. By defining symbolic constant one can use these symbolic constant instead of constant value. # define PI 3.14 # define Temp 35 Global Declaration Section: This section contains the declaration of variables which are used by more then more then one function of the program. Main Function Section: A main () function is a heart of any ‘C’ language program. Any C program is made up of 1 or more then 1 function. If there is only 1 function in the program then it must be the main program. An execution of any C program starts with main () function. Subprogram Or Sub Function Section: They are the code section which are define outside the boundary of main function. This function can be called from any point or anywhere from the program. Generally they are define to solve some frequent tasks.

What is Flowchart?

• Flow chart is a step by step procedure which is used to solve complex program. • It is a pictorial representation. It is same as algorithm. • It is represented in symbols. • It can be read from top to bottom and left to right. • Symbols are simple and easy to learn. These are very important planning and working tools in programming. • After the programming is completed, the flowchart is very important tool for the programmers for tracing the flow of information and logical sequence in a program. • This helps a new programmer to understand the logic that is used by some other programmer to solve a problem. 2. Advantages of Flowchart. Ans. The following are the advantages of the flow chart: - • Provide better communication. It provides better communication. The teachers, students, programmer, computer operators and users can get ideas and description of algorithms very quickly and easily. • Help in algorithm design. A flowchart can be easily drawn in comparison to writing a program and testing it. The program flow can be easily shown with the help of flowchart. Different algorithm can be easily experimented with flowchart. • Check program logic. With the help of flowchart we can see the portion of the program. So accuracy in logic flow is maintained. • Modification becomes easy. If u want to some modification in your existing program then it is possible with the help of flowchart. You can modify your program without disturbing the program flow.

C AS MIDDLE LEVEL LANGUAGE

All programming languages can be divided into two categories: Problem oriented languages or high languages: Examples of languages falling in this category are FORTRAN, BASIC, Pascal, etc. These languages have been designed to give a better programming efficiency, faster program development. Generally these languages have better programming capability but they are less capable to deal with hardware or Hardware related programming. Machine oriented languages of Low Level Languages: Examples of languages falling in this category are Assembly language and Machine Language. This languages have been designed to give a better machine efficiency i.e. faster program execution. Generally these languages have better hardware programming capability but it is very difficult and tedious to do create complex application like and business application or some commercial application C as Middle Level Language: C stands in between these two categories. That’s why it is called a Middle Level Language, since it was designed to have both; a relatively good programming efficiency (as compared to Machine Oriented Language) and a relatively good machine efficiency (as compared to Problem Oriented Language).

FEATURES OF C LANGUAGE

There are several reasons why many computer professionals feel that C is at the top of the list : FLEXIBLILITY: C is a powerful and flexible language. C is used for projects as diverse as operating system, word processor, graphics, spreadsheets and even compilers for other language. C is a popular language preferred by professional programmers. As a result, a wide variety of C compilers and helpful accessories are available. PORTABILITY: C is a portable language. Portable means that a C program written for one computer system can be run on another system with little or no modification. Portability is enhanced by the ANSI standard by C, the set of rules for C compilers. COMPACTNESS: C is a language of few words, containing only a handful terms, called keywords, which serve as the base on which the language’s functionality is built. You might think that a language with more keyword would be more powerful. This isn’t true. As you will find that it can be programmed to do any task. REUSABILITY: C is modular, C code can and should be written in routine called functions. These functions can be reused in other applications or programs. By passing pieces of information to the function, you can create useful, reusable code.

WHAT IS LANGUAGE TRANSLATORS?

As we know that computer understand only the instruction written in the Machine language. Therefore a program written in any other language should be translated to Machine language. For this purpose special program are available they are called translators or language processors. This special programs accept the user program and check each statement and produces a corresponding set of Machine language instructions. There are two types of Translators. (1) Compiler: - A Compiler checks the entire program written by user and if it is free from error and mistakes then produces a complete program in Machine language known as object program. But if it founds some error in program then it does not execute the single statement of the program. So compiler translate whole program in Machine language before it starts execution. (2) Interpreters: - Interpreters performs the similar job like compiler but in different way. It translates (Interprets) one statement at a time and if it is error – free then executes that statement. This continues till the last statement in the program has been translated and executed. Thus Interpreter translates and executes the statement before it goes to next statement. When it founds some error in statement it will immediately stop the execution of the program. Since compiler of Interpreter can translate only a particular language for which it is designed one has to use different compiler for different languages. Difference of Compiler – Interpreter :- Error finding is much easier in Interpreter because it checks and executes each statement at a time. So wherever it fine some error it will stop the execution. Where Compiler first check all the statement for error and provide lists of all the errors in the program. Interpreter take more time for the execution of a program compared to Compilers because it translates and executes each statement one by one.

WHAT IS A LANGUAGE?

Language is a collection of words and symbols which can be used to perform certain task or activities and to establish a communication between person to person. In the same manner computer languages are the collection of predefine key words which can be used to perform certain task and to communicate between to entities like between two machines or between human and computers or computers and others peripherals. There are three different level of programming languages. They are (1) Machine languages (low level) (2) Assembly languages (3) Procedure Oriented languages (high level) (4) Fourth Generation languages (4 GLS) (1) Machine Languages: - Computers are made of No. of electronic components and they all are two – state electronic components means they understand only the 0 – (pulse) and 1 (non – pulse). Therefore the instruction given to the computer must be written using binary numbers. 1and 0. Computers do not understand English or any other language but they only understand or respond to binary numbers (0 and 1). So each computer has its own Machine languages. (2) Assembly Languages: - As it was very tedious to understand and remember 0’s representing numerous data and instruction. So to resolve this problem mnemonics codes were developed. For example add is used as symbolic code to represent addition. SUB is used for subtraction. They are the symbolic representation of certain combination of binary numbers for example S U B Which represents certain actions as computer understand only Machine language instructions a program written in Assembly Language must be translated into Machine languages. Before it can be executed this translation if done by another program called assembler. This assembler will translate mnemonic codes into Machine languages. (3) Procedure Oriented Languages In earlier assembly languages assembler programs produced only one Machine languages instruction for every assembly languages instruction. So to resolve this problem now assembler were introduced. Which can produce several machine level instructions for one assembly language instruction. Thus programmer was relieve from the task of writing and instruction for every machine operation performed. These languages contains set of words and symbols and one can write program with the combination of these keywords. These languages are also called high level languages. Basic, Fortran, Pascal and COBOL. The most important characteristic of high level languages is that it is machine independent and a program written in high level languages can be run on any computers with different architecture with no modification or very little modification.

C - PRACTICAL EXAMPLES & ASSIGNMENT - 2

1.What is the purpose of a header file? Is the use of a header file absolutely necessary? 2. Why and when do we use #include directive? 3. Why and when do we use #define directive? 4. Why do we need to use comment in program? 5. Describe the basic data types in C. 6. What is ASCII? How common is its use? 7. Describe the different types of operators. 8. What is the difference between prefix and postfix of – and ++ operators? 9. Describe the use of the conditional operator to form a conditional expression. 10. What are formatted input and output statements in C? Give suitable example. 11. Find the errors, if any /* A simple program int main() { /* Does nothing*/ } 12. Find the errors, if any #include(stdio.h) void main(void) { printf(“Hello C”); } 13.Find the errors, if any Include main{} ( FLOAT X; X = 2.5 ; Y = exp(x) ; Print(x,y); ) 14. Find the output of the program : #include void main() { int x=3,y=5,z=7,w; w=x%y + y%x - z%x - x %z; printf(“%d\n”,w); w=x/z + y/z + (x+y)/z; printf(“%d”,w); } 15.Find the output of the program : #include void main() { int x=3,y=5,z=7,w=9; w += x + y -( z -= w ); printf(“w=% d, z=%d\n”,w,z); w += x -= y %= z; printf(“w=%d, y=%d, z=%d”,w,y,z); } 16. Find the output of the program : #include void main() { int x=3,y=5; x = y++ + x++; y = ++y + ++x; printf(“x=% d, y=%d”,x,y); }

Twitter Delicious Facebook Digg Stumbleupon Favorites More