Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Module 1

Uploaded by

Triveni Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module 1

Uploaded by

Triveni Nagaraj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

INTRODUCTION TO LANGUAGE

TOPICS: Introduction to Language - Algorithm, Pseudo Code, Flow Chart, Background, C


Programs, Identifiers, Data Types, Variables, Constants, Input / Output, Operators(Arithmetic,
Relational, Logical, Bitwise etc.), Expressions, Precedence and Associativity, Expression
Evaluation, Type conversions.

ALGORITHMS
In general terms, an algorithm provides a blueprint to writing a program to solve a particular
problem. It is considered to be an effective procedure for solving a problem in a finite number of
steps. That is, a well- defined algorithm always provides an answer, and is guaranteed to terminate.
Algorithms are mainly used to achieve software re-use. Once we have an idea or a blueprint of a
solution, we can implement it in any high-level language, such as C, C++, Java, and so on. In order
to qualify as an algorithm, a sequence of instructions must possess the following characteristics:
 Be precise
 Be unambiguous
 Not even a single instruction must be repeated infinitely
 After the algorithm gets terminated, the desired result must be obtained

Selecting the Most Efficient Algorithm

The time complexity of an algorithm is basically the running time of a program as a function of
the input size. Similarly, the space complexity of an algorithm is the amount of computer memory
that is required during the program execution as a function of the input size.

Control Structures used in Algorithms


An algorithm has a finite number of steps and some steps may involve decision-making and
repetition. Broadly speaking, an algorithm can employ any of the three control structures.
1. Sequence
2. Decision
3. Repetition.

1
SEQUENCE
Sequence means that each step of the algorithm is executed in the specified order. An algorithm to
add two numbers is given below. This algorithm performs the steps in a purely sequential order.
Step 0: Start
Step 1: Input the first number as A
Step 2: Input the second number as B Step 3: Set SUM = A + B
Step 4: Print SUM
Step 5: End

DECISION
Decision statements are used when the outcome of the process depends on some condition. For
example, if x=y, then print “EQUAL”. Hence, the general form of the if construct can be given as
if condition then process
An algorithm to check the equality of two numbers is shown below.
Step 0: Start
Step 1: Input the first number as A
Step 2: Input the second number as B
Step 3: If A = B Then Print "EQUAL" else PRINT "NOT EQUAL"
Step 4: End

REPETITION
Repetition, which involves executing one or more steps for a number of times, can be implemented
using constructs such as while, do-while, and for loops. These loops execute one or more steps
until some condition is true. An algorithm that prints the first 10 natural numbers as shown below.
Step 0: Start
Step 1: [INITIALIZE] SET i = 0, n = 10
Step 2: Repeat Step while i<=n
Step 3: PRINT i
Step 4: Set i= i + 1
Step 5: End

2
FLOWCHARTS

A flowchart is a graphical or symbolic representation of a process. It is basically used to design


and document virtually complex processes to help the viewers to visualize the logic of the process,
so that they can gain a better understanding of the process and find flaws, bottlenecks, and other
less obvious features within it. When designing a flowchart, each step in the process is depicted
by a different symbol and is associated with a short description. The symbols in the flowchart are
shown below.

Symbols of flowchart

3
The symbols of a flowchart include:

 Start and end symbols are also known as the terminal symbols and are represented as
circles, ovals, or rounded rectangles. Terminal symbols are always the first and the last
symbols in a flowchart.
 Arrows depict the flow of control of the program. They illustrate the exact sequence in
which the instructions are executed.
 Generic processing step, also called as an activity, is represented using a rectangle.
Activities include instructions such as add a to b, save the result. Therefore, a processing
symbol represents arithmetic and data movement instructions. When more than one process
has to be executed simultaneously, they can be placed in the same processing box.
However, their execution will be carried out in the order of their appearance.
 Input/output symbols are represented using a parallelogram and are used to get inputs
from the users or display the results to them.
 Conditional or decision symbol is represented using a diamond. It is basically used to
depict a Yes/No question or a True/False test. The two arrows coming out of it, one from
the bottom vertex and the other from the right vertex, correspond to Yes or True, and No
or False, respectively. The arrows should always be labelled. A decision symbol in a
flowchart can have more than two arrows, which indicate that a complex decision is being
taken.
 Labelled connectors are represented by an identifying label inside a circle and are used in
complex or multisheet diagrams to substitute for arrows. For each label, the „outflow‟
connector must have one or more „inflow‟ connectors. A pair of identically labelled
connectors issued to indicate a continued flow when the use of lines becomes confusing.

4
Example 1: Draw a flowchart to calculate the salary of a daily wager

Example 2: Draw a flowchart to determine the largest of three numbers.

5
PSEUDOCODES
 Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language. It is basically meant for human reading
rather than machine reading, so it omits the details that are not essential for humans. Such
details include variable declarations, system-specific code, and sub-routines.
 Pseudocodes are an outline of a program that can be easily converted into programming
statements. They consist of short English phrases that explain specific tasks within a program‟s
algorithm. They should not include keywords in any specific computer language.
 The sole purpose of pseudocodes is to enhance human understandability of the solution. They
are commonly used in textbooks and scientific publications for documenting algorithms, and
for sketching out the program structure before the actual coding is done. This helps even non-
programmers to understand the logic of the designed solution. There are no standards defined
for writing a pseudocode, because a pseudocode is not an executable program. Flowcharts can
be considered as graphical alternatives to pseudocodes, but require more space on paper.

Example
Write a pseudocode for calculating the price of a product after adding sales tax to its original price.
Solution
1. Read the price of the product
2. Read the sales tax rate
3. Calculate sales tax = price of the item × sales tax rate
4. Calculate total price = price of the product + sales tax
5. Print total price
6. End
Variables: price of the product, sales tax rate, sales tax, total price

Example
Write a pseudocode to read the marks of 10 students. If marks are greater than 50, the student
passes, else the student fails. Count the number of students who pass and the number who fail.
Solution
1. Set pass to 0
2. Set fail to 0
3. Set no of students to 0
4. WHILE no of students < 10
a. input the marks
b. IF marks >= 50 then Set pass = pass + 1
ELSE
Set fail = fail + 1 ENDIF
ENDWHILE
5. End
Variables: pass, fail, no of students, marks

6
PSEUDOCODES

 Pseudocode is an informal list of steps in English like statements which is intended for
human reading.
 It is used in planning of computer program development, for sketching out the structure of
the program before the actual coding takes place.

Advantages:
1. It can be written easily
2. It can be read and understood easily
3. Modification is easy

Disadvantages:
1. There is no standard form.
2. One Pseudocode may vary from other for same problem statement.

Examples:

Pseudocode: Addition of two numbers

1. Begin
2. Read two numbers a, b
3. Calculate sum = a+b
4. Display sum
5. End

Pseudocode: Area of rectangle

1. Begin
2. Read the values of length, breadth
3. Calculate area = l x b
4. Display area
5. End

7
Types of Errors

1. Run Time Errors: It occurs when the program is being run executed. Such errors occur
when the program performs some illegal operations like
 Dividing a number by zero
 Opening file that already exists
 Lack of free memory space
 Finding Square of logarithm of negative numbers Run time errors may terminate program
execution
2. Compile Time Errors: It occurs at the time of compilation of the program. Such errors
can be classified as follows:
i. Syntax errors: They generated only when rules of programming language are violated
ii. Semantic errors: Which may comply with the rules of the programming language but
are not meaningful to the complier
3. Logical Errors: Logical errors are the errors in the program code that result in unexpected
and undesirable output.
4. Linker Errors: These errors occur when the linker is not able to find the function
definition for a given prototype

8
Introduction to C

Introduction
The programming language c was developed in the early 1970‟s by Dennis Ritchie at Bell
Laboratoriesto be used by the UNIX operating system. It was renamed „C‟ because many of
its features were derived from an earlier language. C was designed for developing portable
application software.
History of C

 C is a general purpose, procedural, structured computer programming language


developed by
Dennis Ritchie in the year 1972 at AT&T Bell Labs.
 C language was developed on UNIX and was invented to write UNIX system software.
 C is a successor of B language.
 There are different C standards: K&R C std, ANSI C, ISO C.

Examples of C:
 Operating system
 Language compilers
 Assemblers
 Text editors
 Databases

Characteristics of C
 C is high level language
 C makes extensive use of function calls
 C is well structured Programming
 C is Stable Language
 C facilitates low level language
 C is Portable language
 C is easy to learn.
 C is core language
 C is extensible language
 C is often treated as second best language
 C is a general purpose language.
 It can extend itself.

Uses of C
 C language was primarily used for system programming
 C has been widely accepted by professionals that compilers, libraries and
interpreters ofother languages written in c.
 C is widely used to implement end-user applications
 C can be used as intermediate language

9
Structure of ‘C’ Program

C program consists of different sections. The structure of C program is as shown below.


 Documentation Section: It consists of a set of comment line giving the name of the
program, theauthor and other details. Compiler ignores these comments. There are
two formats:
a) Line comments //Single line comment
b) Block comments /*Multi line comment*/
 Link Section: It provides instruction to the compiler to link functions from system library.
 Definition Section: It defines all symbolic constants.
 Global Declaration Section: The variables which are used in more than one function are
called globalvariables and are declared in this section.
 main( ) Section: Every „C‟ program has one main( ) function and it contains two parts:
i. Declaration Part: Here, all the variables used are declared.
ii. Executable Part: Here, it contains at least one executable statement.

The main( ) function is enclosed within flower brackets and the statements ends with semicolon.

 Sub-program Section: It contains all the user defined functions that are called by main( )
function.

Documentation section
Link section
Definition section
Global declaration section
main( ) Section
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2
-
-
Function n

10
Example:

//Addition of two numbers


#include<stdio.h>
void main( )
{
int a, b, sum;
printf(“Enter two numbers\n”);
scanf(“%d %d”, &a, &b);
sum = a + b;
printf(“The sum is %d”, sum);
}

Writing the first ‘C’ Program

#include <stdio.h>
int main()
{
// printf() displays the string inside quotation
printf("Hello, World! \n");
return 0;
}

Output

Hello, World!

How "Hello, World!" program works?


 The #include is a preprocessor command that tells the compiler to include the contents of stdio.h (standard
input and output) file in the program.
 The stdio.h file contains functions such as scanf()and printf()to take input and display output
respectively.
 If you use the printf() function without writing #include <stdio.h>, the program will not compile.
 The execution of a C program starts from the main() function.
 printf() is a library function to send formatted output to the screen. In this program, printf() displays Hello,
World! text on the screen.
 The return 0; statement is the "Exit status" of the program. In simple terms, the program ends with this
statement.

11
Files used in C Program

Source code files


It contains source code of the program. The extension of any C source code file is .c. This
file containssource code that defines the main function is the starting point of execution
when you successfully compile and run the program.

Header files
When working with large projects, it is often desirable to separate out certain
subroutines from themain() function of the program. There also may be case that the
same subroutine has to be used indifferent programs. This is used by .h extension
Standard Header files are as follows:

stdio.h-for standard input and output functions


stdlib.h-for some miscellaneous functions like exit() function
string.h-for string handling functions
math.h-for mathematical functions like sqrt(), pow(), fabs()
conio.h- for clearing screen like clrscr() function
alloc.h- ofr dynamic memory functions

Object files
Object files are generated by the compiler as a result o processing the source code file.
Object code filecontains a binary code of the source code. It is used with filename .obj
extension.

Binary Executable files


It is generated by the linker. The linker links various object files to produce a binary file
that can bedirectly executed. On windows operating system the executable file have a
.exe extension.

12
Using Comments
C supports two types of comments.
1. Single line Comment
2. Multiline Comment

Single Line comment:


The symbol which is used for the single line comment is //.
A line comment can be replaced anywhere on the line and it does not require to be specifically
ended asthe end of the line automatically ends the line

Multiline Comment:
The symbol which is used for the multiline comment is /* and */
The type of the comment is a block comment. The multiple lines are commented by using
the abovesymbol. Note that commented statements are not executed by the compiler.

C – Tokens

 Tokens are the building blocks in a C language


 It is also called as lexical unit.
 The smallest individual unit in „C‟ program is called as C-Token.
 There are 6 types of „C‟ tokens:
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
vi. Special symbols

Character set in C
A C character set defines the valid characters that can be used in a source program. The basic
C characterset are:
1. English Alphabetss:
Uppercase Letters: A,
B, C,…., ZLowercase
Letters: a, b, c,….., z
2. Digits: 0, 1, 2,….., 9
3. Special characters: ! , @. #, $, %, *, (, ),}, {, ;,:,”,‟,?,>,<,/,,,.,|,\,&,^, etc
4. White spaces: These characters are used to print a Blank space on the screen,
Horizontal tabspace (\t), carriage return, new line character (\n), form
feedcharacter.etc.

13
Keywords
 Keywords are also called as reserved words.
 They already have pre-defined meaning.
 Keywords should always be written in lowercase.
 The keywords meaning can‟t be changed.
 Keywords cannot be used as identifiers.
 There are 32 keywords in „C‟ program.

auto double int struct break do


else long switch goto sizeof if
case enum register typedef default
char extern return union volatile
const float short unsigned while
continue for signed void static

Identifiers

 It help us to identify the data and other objects in the program


 These are the names given to Program elements such as variables, functions, arrays and macros
etc.
 It may be consists of sequence of letters, numerals or underscores.

The Rules for Forming Identifier Names


 It cannot include any special symbol characters or punctuation marks (like #,$^?. And
etc) apart fromunderscore.
 There cannot be Two successive Underscore symbol(_)
 Key words cannot be used as identifiers
 It must contain only alphabets (A to Z, a to z), numbers (0 to 9) and underscore ( _ ).
 It must start with alphabet or underscore but not numeric character.
 It should not have any space.
 Identifiers are case sensitive.
 Maximum length of an identifier is 31 characters.
Examples:
Valid Identifiers: integer, minimum, sum_total,
row1, _cppsInvalid Identifiers: float  It is a
keyword.
I am  It has space
123_Abc  It is starting
with number N1 + n2  It
contains special symbol (+)
14
Basic Data types in C

C language provides few basic data types as shown in the below table.

Data Type Keyword Size in Range Use


used bytes
Character Char 1 -128 to 127 To store
Characters
Integer Int 2 -32768 to To store
32767 Integer
numbers
Floating Float 4 3.4E-38 to To store
Point 3.4E+38 floating point
numbers
Double double 8 1.7E-308 to To store big
1.7E+308 floating point
numbers
Valueless void 0 Valueless -

The detailed data types are given below:

Data Type Size in bytes Range


char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to
2147483647
unsigned long int 4 0 to 4294967295
signed long int 4 -2147483648 to
2147483647
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

 Data type defines the types of data that is stored in a variable.


 There are 3 types:
i. Primary/ Built-in/ Fundamental data type  int, float, double, char, void
ii. Derived data type  array, structure
iii. User defines data type  enum, typedef

15
 Primary/ Built-in/ Fundamental data type: These are the built in data types available in
C. There are5 types. Namely:
1. Integer (int)
2. Floating point (float)
3. Character (char)
4. Double precision floating point (double)
5. Void (void)
1. Integer type:
 It is used to store whole numbers.
 The keyword int is used to declare variable of integer type.
 Int type takes 2B or 4B of storage depending on machine size.
 The classes of integer are:

Unsigned Signed
Data type Keyword Size Data type Keyword Size
Short Integer short int 1B Signed short integer signed short int 1B
Integer int 2B Signed integer signed int 2B
Long Integer long int 4B Long integer long int 4B

2. Floating point data type:


 It is used to store decimal numbers.
 The keyword float is used to declare variable of floating point data type.
 Float type takes 4B or 8B of storage depending on machine size.
 It can be expressed in fractional or exponential form.

Data type Keyword Size


Floating point float 4B
Double double 8B
Long double long double 10B

3. Double:
 It is used to store double precision floating point numbers.
 The keyword double is used to declare variable of floating point data type.
 Double type takes 8B of storage.
 Double precision is related to accuracy of data.

4. Char:
 It is used to store character type of data.
 The keyword char is used to declare variable of character type.
 Char type takes 1B of storage.

5. Void:
 It is a special data type that has no value.
 It doesn‟t have size.
 It is used for returning the result of function that returns nothing.
16
Variables
A variable is defined as a meaningful name given to a data storage location in
computer memory.When using a variable, we actually refer to the address of the
memory where the data is stored.
The variable value will be changed during the execution of program.
 A variable is a name given to memory location whose value changes during execution.

 Declaration:

Syntax: datatype variable_list;


Where, datatype  Any built in data type
variable_list  Identifiers that specifies
variable name.

Example: int a;
Where, int is the built
in data typea
is variable
of type int.

 Initialization:

Syntax: datatype
variable_name =
value;Where,
datatype  Any built in data type
variable_name  Identifier that specifies variable name.
value  The data which will be stored in variable name.
Example: int a = 10;
Where,
int  data type
a  variable name
10  value

17
Numerical Variables
It can be used to store either integer values or floating values. While integer value whole
number withouta fraction part or decimal point, a floating point value can have a decimal
point.
They are also may be associated with modifiers, such as short, long, signed and un-
signed numericvariables.

Character variables
Character variables are just single characters enclosed within single quotes. These
characters variablescould be any character from the ASCII character set-letters („a‟, „A‟),
numerals („2‟) or special character(„&‟)

Declaring variables
To declare a variable, specify the data type of the variable followed by its name. The data
type indicatesthe kind of values that variable will store. Variable declared in a program
always ends with semicolon.
Syntax: datatypename variablename;
Example: int emp_num;
float salary;
char grade;
double balance
amount;
unsigned short
int acc_num;

Initializing variables
While decarting variables, we can initialize them with some value.
Syntax: datatypename variablename= value;
Example: int emp_num=7;
float
salary=21
56.35;
char
grade=‟A
‟;
double balance amount=100000000;

18
Constants
 Constants are the values that don’t changes during the execution of a program.
 A constant is an explicit data value specified by the programmer.
 Constants are used to define the fixed values.

Integer Constant
Numeric
Constant
Real Constant

Constant
Single Character
Constant
Character
Constant
String Constant

 Numerical Constant

Integer Constant: These are the numbers without decimal part.


Decimal: It is an integer constant consisting of numbers from 0-9. It can be preceded by + or –
Octal: It is an integer constant consisting of numbers from 0-7. It is preceded by o
Hexadecimal: It is an integer constant consisting of numbers from 0-9, A-F (A=10,
B=11, C=12,D=13, E=14, F=15). It is preceded by 0x

Real Constant:

 These are the numbers with decimal part.


 These are also called as floating point constant.
 The floating values can be identified by the suffix „F‟ or „f‟
 It can be expressed in
exponential form.Ex: 21.5, 2.15 x
102  2.15e2
 Character Constant

Single Character Constant:


These are the values enclosed within single quotes.
Each character have an integer value called as ASCII (American Standard Code for
InformationInterchange)  A: 65, a: 97
Printable Character: All characters are printable except backslash(\) character
or escapesequence.
Non-Printable Character: The characters with backslash (\) are non printable. Ex: \n, \t
19
String Constant:
A group of characters together
form string. Strings are
enclosed within double quotes.
They end with NULL character
(\0).
Ex: “GCEM” 

G C E M \0

NOTE:
 Qualified Constant/ Memory Constant: These are created by using “const” qualifier.
Const meansthat something can only be read but not modified.
Syntax: const datatype variable_name = value;
Ex: const int a = 10;
const float pi = 3.14;
 Symbolic Constants/ Defined Constant: These are created with the
help of definepreprocessor directive.
Ex: #define PT 3.142
 During processing the PI in the program will be replaced with 3.142.
 The name of constant is written in uppercase just to differentiate from the variables.

 Enumeration Constant: An enumeration is a list of constant integer


values. Names inenumeration must be distinct. The keyword used is
“enum”.
Ex: enum days = {Sun, Mon, Tue, Wed,
Thu, Fri, Sat}Sun  1, Mon  2, …….,
Sat  7
Strings

 A group of characters together form string.


 Strings are enclosed within double quotes.
 They end with NULL
character (\0).Ex:
“GCEM” 

G C E M \0

20
Input Output statements in C

Formatted Input Output Statements

scanf()
 Formatted input refers to an input data that has been arranged in particular format.
 Ex: 152 Rajesh
 In the above example the first part contains integer and the second part contains
characters. This ispossible with the help of scanf function.

Syntax: scanf(“control string”, arg1, arg2,…..,argn);

where
 The control string specifies the field form in which data should be entered
 The arguments arg1, arg2,…..,argn specifies the address of the location
where the data isstored.
 The width of the integer number can be specified using %wd.

Example-1:
– scanf(“%2d %2d”, &a, &b);
%2d two digit integer
%2d  two digit integer 4567 25
a=45 b=67
Note: 25 is not at all stored

 The input field may be skipped using * in the place of field width.
Example-2:
– scanf(“%2d %*d %2d”, &a, &b);
%2d two digit integer
%*d  skip this
integer 45 25 63a=45
25 is skipped b=63
 The scanf function can read single character or more than one character using %c or %s.

Rules for scanf:


 Each variable to be read must have a specification
 For each field specification, there must be a address of proper type.
 Never end the format string with whitespace. It is a fatal error.
 The scanf will read until:
 A whitespace character is found in numeric specification.
 The maximum number of characters have been read
 An error is detected
 The end of file is reached
 Any non-whitespace character used in the format string must have a matching
character in theuser input.

21
 The below table shows the scanf format codes commonly used.

Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, %g Read a floating point
value
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned
decimal integer
%x Read a hexadecimal
integer
%[ ] Read a string of word
The l can be used as a prefix for long integer. Ex: %ld
printf()

The printf function is used for printing the captions and results.

Syntax: printf(“control string”, arg1, arg2, ….., argn);

Where
 The control string specifies the field form in which data should be printed.
 The arguments arg1, arg2,…..,argn specifies the location where the data is
stored to beprinted on the screen

 Control string contains three types of items:


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b.

 The below table shows the printf format codes commonly used.
Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in
exponent form
%f Print a floating point value
without exponent
%g Print a floating point value
with or without exponent
%h Print a short integer
%i Print a decimal integer
%o Print a octal integer
%s Print a string
%u Print an unsigned decimal
integer
%x Print a hexadecimal integer
22
%[ ] Print a string of word

The l can be used as a prefix for long integer. Ex: %ld


 General syntax of field-width/size for different data types:

• %wd  Example: %6d

• %w.pf  Example %6.2f

• %w.ps  Example %10.4s


– w means total field size/width
– P means precision (tells how many decimal places to be printed in case of float)
and
– How many characters to be printed in case of strings

23
Operators
An operator is a symbol that tells the compiler to perform specific mathematical and
logicalfunctions. The different operators supported in „C‟ are:

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Unary Operators  Increment and Decrement
7. Ternary/ Conditional Operator
8. Special Operators

1. Arithmetic Operators: The different arithmetic operators are:

Operator Name Result Syntax Example (b=5, c=2)


+ Addition Sum a=b+c a=7
- Subtraction Difference a=b-c a=3
* Multiplication Product a=b*c a = 10
/ Division Quotient a=b/c a=2
% Modulus Remainder a=b%c a=1

2. Relational Operators: These are used to compare two quantities. The output will be
either 0 (False)or 1 (True). The different relational operators are:

Operator Name Syntax Example (b=5, c=2)


< Lesser than a=b<c a = 0 (False)
> Greater than a=b>c a = 1 (True)
<= Lesser than or Equal to a = b <= c a = 0 (False)
>= Greater than or Equal to a = b >= c a = 1 (True)
== Equal to a = b == c a = 0 (False)
!= Not equal to a = b != c a = 1 (True)

3. Logical Operators: These are used to test more than one condition and make decision.
The differentlogical operators are: NOT, AND, OR

 Logical NOT (!) The output is true when input is false and vice versa. It
accepts only oneinput.

Input Output
X !X
0 1
1 0
24
 Logical AND (&&) The output is true only if both inputs are true. It accepts
two or moreinputs.
Input Output
X Y X && Y
0 0 0
0 1 0
1 0 0
1 1 1

 Logical OR (||) The output is true only if any of its input is true. It accepts two or more
inputs.

Input Output
X Y X || Y
0 0 0
0 1 1
1 0 1
1 1 1

4. Assignment Operators: These are used to assign the result or values to a variable. The
different typesof assignment operators are:

Simple Assignment a = 10
Shorthand Assignment a += 10  a = a + 10
Multiple Assignment a = b = c = 10

5. Bitwise Operators: These works on bits and performs bit by bit operations. The
different types ofbitwise operators are:
i. Bitwise NOT (~)
ii. Bitwise AND (&)
iii. Bitwise OR (|)
iv. Bitwise XOR (^)  Output is True when odd number of 1‟s are present.
v. Bitwise left shift (<<)
vi. Bitwise right shift (>>)

 Bitwise NOT (~)

X ~X
0 1
1 0

25
 Bitwise AND (&), Bitwise OR (|),Bitwise XOR (^)

X Y X&Y X|Y X^Y


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

 Bitwise Left Shift (<<)  Shift specified number of bits to left side.

X 0 1 0 0 0 1 1 0
X<<2 0 0 0 1 1 0 0 0

 Bitwise Right Shift (>>)  Shift specified number of bits to right side.

X 0 1 0 0 0 1 1 0
X>>2 0 0 0 1 0 0 0 1

6. Unary Operators: There are 4 types:

 Unary Plus Operator


Determines Sign
 Unary Minus Operator
 Increment (++)
 Decrement (--)

 Increment (++): It adds one to the operand.

Pre-increment Post-increment
First value of the operand is incremented First value of the operand is used for evaluation
(added) by 1 then, it is used for evaluation. then, it is incremented (added) by 1.

Ex: ++a Ex: a++

 Decrement (--): It subtracts one from the operand.

Pre-decrement Post- decrement


First value of the operand is decremented First value of the operand is used for evaluationthen,
(subtracted) by 1 then, it is used for it is decremented (subtracted) by 1.
evaluation.

Ex: - -a Ex: a- -

26
7. Conditional Operator/ Ternary Operator (?:)

 C Language has an unusual operator, useful for making two way decisions.
 This operator is combination of two tokens ? and : and takes three operands.
 This operator is known as ternary operator or conditional operator.
Syntax:
Expression1 ? Expression2 : Expression3;

Where,
Expression1 is Condition
Expression2 is Statement Followed if
Condition is TrueExpression3 is Statement
Followed if Condition is False

Meaning of Syntax:
1. Expression1 is nothing but Boolean Condition i.e. it results into either TRUE or FALSE
2. If result of expression1 is TRUE then expression2 is executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is executed
5. Expression1 is said to be FALSE if its result is ZERO

Example: Check whether Number is Odd or Even


#include<stdio.h>
void main()
{
int num;
printf("Enter the
Number : ");
scanf("%d",&nu
m);
flag =
((num%2==0)
?1:0);
if(flag==0)
printf("\nEven");
else
printf("\nOdd");
}

8. Special Operator/ Special Symbols

 Comma Operator: It can be used as operator in expression and


as separator in declaringvariables.
 Sizeof Operator: It is used to determine the size of variable or value in bytes.
 Address Operator: It is used to find the address of the operators.

27
Type Conversion
 Converting the value of one data type to another type is called as Type Conversion.
 It occurs when mixed data occurs.
 There are two types:

i. Automatic Type Conversion (Implicit)

 Here, the operand/ variables of smaller data type is automatically converted to data
type of largersize.
 char  int  long int  float  double  long double
 Ex: int a = 5;
float b=25,c; a b c
c=a/b 5 25.0 0.25
printf(“%f”,c);

ii. Manual Type Conversion (Explicit)

 It is a forced conversion used to convert operand/ variables of larger data type to


smaller size orvice versa.
 Ex: int a = 7, c; a b c
float b = 4.0; 7 4.0 3
b=a%(int)b; b  Converted into int & evaluated
printf(“%d”,c);
Expressions

 It is combination of operands (variables, constants) and operators.


 Precedence: The order in which operators are evaluated is based on the priority value.
 Associativity: It is the parsing direction used to evaluate an expression. It can be left to
right or rightto left.
 Evaluation of expressions: Expressions are evaluated using an assignment statement.
 Ex: Variable=expression;
sum=a+b;

28
 Following table provides the Precedence and Associativity of operators:

Operator Description Associativity Precedence(Rank)


() Function call
Left to right 1
[] Array element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
Right to left 2
~ Ones complement
* Pointer to reference
& Address
Sizeof Size of an object
(type) Type cast (conversion)

* Multiplication
/ Division Left to right 3
% Modulus
+ Addition
Left to right 4
- Subtraction
<< Left shift
Left to right 5
>> Right Shift
< Less than
<= Less than or equal to
Left to right 6
> Greater than
>= Greater than or equal to

== Equality
Left to right 7
|= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12

29
?: Conditional expression Right to left 13
=
*= /= %=
+= -= &= Assignment operators Right to left 14
^= |=
<<= >>=

, Comma operator Left to right 15

30
31

You might also like