Uploaded by Madhumitha.V

Unit 1 PPS

advertisement
PROGRAMMING FOR PROBLEM SOLVING
UNIT - I
THE PURPOSE OF LEARNING THIS COURSE IS TO:
 CLR -1: Think and evolve a logically to construct an algorithm into a flowchart and a pseudocode that
can be programmed
 CLR -2: Utilize the logical
operators
and expressions to
solve
problems
in engineering
and real-time
 CLR -3: Store and retrieve data in a single and multidimensional array
 CLR -4: Utilize custom designed functions that can be used to perform tasks and can be repeatedly used
in any application
 CLR -5: Create storage constructs using structure and unions. Create and Utilize files to store and
retrieve information
 CLR -6: Create a logical mindset to solve various engineering applications using programming constructs
in C
LEARNING RESOURCES
1.
Zed A Shaw, Learn C the Hard Way: Practical Exercises on the Computational Subjects You
Keep Avoiding (Like C), Addison Wesley, 2015
2.
W. Kernighan, Dennis M. Ritchie, The C Programming Language, 2nd ed. Prentice Hall, 1996
3.
Bharat Kinariwala, Tep Dobry, Programming in C, eBook
4.
http://www.c4learn.com/learn-c-programming-language/
EVOLUTION OF PROGRAMMING & LANGUAGES
 A Computer needs to be given instructions in a programming language that it
understands.
 Programming Language
 controls the behavior of computer
 It is defined through the use of syntactic and semantic rules
 Used to facilitate communication about the task of organizing and manipulating information
EVOLUTION OF PROGRAMMING & LANGUAGES
PROBLEM SOLVING THROUGH PROGRAMMING
 Computer based problem solving is a systematic process of designing, implementing and using
programming tools during the problem solving stage.

This method enables the computer system to be more intuitive with human logic than machine
logic.
 Final outcome of this process is software tools which is dedicated to solve the problem under
consideration.
 Software is just a collection of computer programs and programs are a set of instructions which
guides computer’s hardware.
 These instructions need to be well specified for solving the problem.
 After its creation, the software should be error free and well documented. Software development is
the process of creating such software, which satisfies end user’s requirements and needs.
PROBLEM SOLVING THROUGH PROGRAMMING
 The following six steps must be followed to solve a problem using computer.
 Problem Analysis
 Program Design - Algorithm, Flowchart and Pseudocode
 Coding
 Compilation and Execution
 Debugging and Testing
 Program Documentation
PROGRAMMING PROCESS
• Defining the Problem
• Planning the Solution
• Coding the Program
• Testing the Program
• Documenting the Program
PROBLEM SOLVING THROUGH PROGRAMMING
 Problem Analysis
 Problem analysis is the process of defining a problem and decomposing overall system
into smaller parts to identify possible inputs, processes and outputs associated with the
problem.
 This task is further subdivided into six subtasks namely:
 Specifying the Objective
 Specifying the Output
 Specifying Input Requirements
 Specifying Processing Requirements
 Evaluating the Feasibility
 Problem Analysis Documentation
PROBLEM SOLVING THROUGH PROGRAMMING
 Program Design
 This process of dividing a program into modules and then into sub-modules is
known as “top down” design approach.
 Dividing a program into modules (functions) breaks down a given programming
task into small, independent and manageable tasks.
PROBLEM SOLVING THROUGH PROGRAMMING
 Coding (Programming)
 The coding process can be done in any language (high level and low level). The
actual use of computer takes place in this stage in which the programmer writes a
sequence of instructions ready for execution.
 Good program possess following characteristics :
 Comment clauses in the program help to make the program readable and understandable by
people other than the original programmer.
 It should be efficient.
 It must be reliable enough to work under all reasonable conditions to provide a correct output.
 It must be able to detect unreasonable error conditions and report them to the end user or
programmer without crashing the system.
 It should be easy to maintain and support after installation.
PROBLEM SOLVING THROUGH PROGRAMMING
 Compilation and Execution Process
 A source code must go through several steps before it becomes an
executable program.
 In the first step the source code is checked for any syntax errors.
 After the syntax errors are traced out a source file is passed through a
compiler which first translates high level language into object code (A
machine code not ready to be executed).
 A linker then links the object code with pre-compiled library functions, thus
creating an executable program. This executable program is then loaded
into the memory for execution.
PROBLEM SOLVING THROUGH PROGRAMMING
 Debugging and Testing
 Debugging is the process of finding errors and removing them from a
computer program, otherwise they will lead to failure of the program.
 Testing is performed to verify that whether the completed software package
functions or works according to the expectations defined by the requirements.
PROBLEM SOLVING THROUGH PROGRAMMING
 Program (Programmer's and User's) Documentation
 The program documentation is the process of collecting information about the
program. The documentation process starts from the problem analysis phase
to debugging and testing. Documentation consists two types of
documentation, they are:
 Programmer's Documentation
 User's Documentation
ALGORITHM
 An algorithm is a set of well-defined instructions to solve a particular problem.
It takes a set of input and produces a desired output.
 For example,
 An algorithm to add two numbers:
 Take two number inputs
 Add numbers using the + operator
 Display the result
QUALITIES OF GOOD ALGORITHMS
 Input and output should be defined precisely.
 Each step in the algorithm should be clear and unambiguous.
 Algorithms should be most effective among many different ways to solve a
problem.
 An algorithm shouldn't include computer code. Instead, the algorithm should
be written in such a way that it can be used in different programming
languages.
ALGORITHM 1: ADD TWO NUMBERS ENTERED BY THE USER
Step
Step
Step
Step
1:
2:
3:
4:
Start
Declare variables num1, num2 and sum.
Read values num1 and num2.
Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
ALGORITHM 2: FIND THE LARGEST NUMBER AMONG THREE
NUMBERS
Step
Step
Step
Step
1:
2:
3:
4:
Start
Declare variables a,b and c.
Read variables a,b and c.
If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop
FLOWCHART
 A flowchart is a graphical representations of steps.
 It was originated from computer science as a tool for representing algorithms
and programming logic but had extended to use in all other kinds of processes.
Symbol
Symbol
Name
Purpose
Used at the beginning and end of
Start/Stop the algorithm to show start and
end of the program.
FLOWCHART SYMBOLS
Process
Indicates processes like
mathematical operations.
Input/
Output
Used for denoting program inputs
and outputs.
Stands for decision statements in a
Decision program, where answer is usually
Yes or No.
Arrow
Shows relationships between
different shapes.
Connects two or more parts of a
On-page
flowchart, which are on the same
Connector
page.
Connects two parts of a flowchart
Off-page
which are spread over different
Connector
GUIDELINES FOR DEVELOPING FLOWCHARTS
 These are some points to keep in mind while developing a flowchart −
 Flowchart can have only one start and one stop symbol
 On-page connectors are referenced using numbers
 Off-page connectors are referenced using alphabets
 General flow of processes is top to bottom or left to right
 Arrows should not cross each other
EXAMPLE FLOWCHARTS
 Here is the flowchart for going to the market to purchase a pen.
EXAMPLE FLOWCHARTS
 average of two numbers.
PSEUDOCODE
 Pseudo code is simply an implementation of an algorithm in the form of
annotations and informative text written in plain English.
 Pseudo code is not actual programming language.
 It has no syntax like any of the programming language and thus can’t be
compiled or interpreted by the computer.
USE PSEUDO CODE
 It allows the designer to focus on the logic of the algorithm without being
distracted by details of language syntax.
 It describe the entire logic of the algorithm so that implementation becomes a
routine mechanical task of translating line by line into source code.
ADVANTAGES OF PSEUDO CODE
 Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm
 Acts as a bridge between the program and the algorithm or flowchart
 Also works as a rough documentation, so the program of one developer can be
understood easily when a pseudo code is written out. In industries, the approach
of documentation is essential. And that’s where a pseudo-code proves vital
 The main goal of a pseudo code is to explain what exactly each line of a program
should do, hence making the code construction phase easier for the programmer
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
CONVENTIONS TO WRITE PSEUDO CODE
GUIDELINES FOR WRITING PSEUDO CODE
 Write only one Statement per line
 Example – Pseudo Code for calculating Salary
 READ name, hourly rate, hours worked, deduction rate
 Gross pay = hourly rate * hours worked
 deduction = gross pay * deduction rate
 net pay = gross pay – deduction
 WRITE name, gross, deduction, net pay
GUIDELINES FOR WRITING PSEUDO CODE
 Capitalize Initial Keyword
 Keywords to be written in capital letters
 Examples: READ, WRITE, IF, ELSE, WHILE, REPEAT, PRINT
 Indent to show Hierarchy
 Indentation shows the structure boundaries
 Sequence
 Selection
 Looping
GUIDELINES FOR WRITING PSEUDO CODE
 End Multiline structures
 Each structure must end properly
 Example: IF statement must end with ENDIF
 Keep Statements Language independent
 Resist the urge
to write
Pseudo Code
in any programming language
PSEUDOCODE TO FIND THE SUM OF TWO NUMBERS.
begin
numeric nNum1,nNum2,nSum
display "ENTER THE FIRST NUMBER : "
accept nNum1
display "ENTER THE SECOND NUMBER : "
accept nNum2
compute nSum=nNum1+nNum2
display "SUM OF THESE NUMBER : " nSum
end
PSEUDOCODE TO FIND THE LARGEST OF TWO NUMBERS.
BEGIN
NUMERIC nNum1,nNum2
DISPLAY "ENTER THE FIRST NUMBER : "
INPUT nNum1
DISPLAY "ENTER THE SECOND NUMBER : "
INPUT nNum2
IF nNum1 > nNum2
DISPLAY nNum1 + " is larger than "+ nNum2
ELSE
DISPLAY nNum2 + " is larger than " + nNum1
END
WHY TO STUDY C PROGRAMMING
 Low level programming becomes especially important in the Internet of Things
(IoT) and wearable devices, where efficiency in power consumption is actually the
most important consideration.
 Secondly, all of the high-level languages are built off of low-level languages. You’ll
need low-level programming to sustain and keep developing those high-level
languages.
 While there is a big push to be able to use high level language to be able to write
low level things like drivers for graphics cards, low level languages are still needed
for performance.
 For example, everything relating to encoding or decoding and encryption will
probably use low level programming, with C and probably some assembly to use
extended instruction (like AVX, SSE, etc). Basically, everything that needs highperformance and fine tuning will require a bit of low level programming.
HISTORY & EVOLUTION OF C
 C – General Purpose Programming Language
 Developed by Dennis Ritchie in 1972
 Developed at Bell Laboratories
 Principles taken from BCPL and CPL
 Structured Programming Language
 C Program
 Collection of Functions supported by C library
Father of C Programming
EVOLUTION OF C LANGUAGE
1960
1967
1970
1972
1978
1989
1990
1999
WHY THE NAME “C” WAS GIVEN ?
 Many of C’s principles and ideas were derived from the earlier language B
 BCPL and CPL are the earlier ancestors of B Language (CPL is common
Programming Language)
 In 1967, BCPL Language ( Basic CPL ) was created as a scaled down version of
CPL
 As many of the features were derived from “B” Language the new language
was named as “C”.
CHARACTERISTICS OF ‘C’
 Low Level Language Support
 Structured Programming
 Efficient use of Pointers
 Extensible
 Program Portability
 Memory Management
DISADVANTAGES OF C
 C Programming Language doesn't support Object Oriented
Programming(OOP)
 C doesn't perform Run Time Type Checking. It only does compile time type
checking. At run time, C doesn't ensure whether correct data type is used
instead it perform automatic type conversion.
 C doesn't support the concept of Exception handling.
// Structure of C Program
STRUCTURE OF C
PROGRAM
#include <stdio.h>
1. //Document section
void main()
2. #Pre-processor section
{
3. Global declaration;
//Program Statement;
4. Main() program
//call user_subprogram()
5. #user defined Sub
}
programs()
#include <conio.h>
Document Section
Pre processor Section
Entry Point
Main Program
void user_subprogram()
{
//Program Statement;
}
User defined Sub Program
DOCUMENTATION SECTION
 Used for providing Comments
 Comment treated as a single white space by Compiler
 Ignored at time of Execution: Not Executable
 Comment: Sequence of Characters given between /* and */
 Example: Program Name, Statement description
 /* Program to Find Area of a Circle*/
PRE-PROCESSOR SECTION
 Also called as Preprocessor Directive
 Also called as Header Files
 Not a part of Compiler
 Separate step in Compilation Process
 Instructs Compiler to do required Preprocessing
 Begins with # symbol
 Preprocessor written within < >
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
#define PI 3.1412
GLOBAL DECLARATION SECTION
 Used to Declare Global variable (or) Public variable
 Variables are declared outside all functions
 Variables can be accessed by all functions in the program
 Same variable used by more than one function
MAIN( ) SECTION
 main( ) written in all small letters (No Capital Letters)
 Execution starts with a Opening Brace : {
 Divided into two sections: Declaration & Execution
 Declaration : Declare Variables
 Executable: Statements within the Braces
 Execution ends with a Closing Brace : }
 Note: main( ) does not end with a semicolon
LOCAL DECLARATION SECTION
 Variables declared within the main( ) program
 These variables are called Local Variables
 Variables initialized with basic data types
C PROGRAMMING FUNDAMENTALS
C PROGRAMMING FUNDAMENTALS
C PROGRAMMING FUNDAMENTALS
• C program broken into many C tokens
• Building Blocks of C program
SINGLE LINE AND MULTILINE COMMENTS
 Used to provide information about lines of code
 Provide clarity to the C source code
 Allows others to better understand
what thecode was intended to
 Helps in debugging the code
 Important in large projects
containing
of source code
 Types – Single line and multiline comment
hundreds or thousands of lines
SINGLE LINE AND MULTI LINE COMMENT
 Represented by double slash //
 Multi Line comment represented by /* comment statements */
#include<stdio.h>
int main( ){
//printing information
printf("Hello C");
return 0;
}
#include<stdio.h>
int main( ){
/*printing information
Comment*/
printf("Hello C");
return 0;
}
Multi Line
KEYWORDS
 Keywords – Conveys special meaning to Compiler
 32 keywords
 Cannot be used as variable names
CONSTANTS
 Definition :Value does
not change during
execution
 Can be a Number (or) a
Letter
VARIABLES / IDENTIFIERS
 Identifier for a memory location where data is stored
 Value changes during execution
 Rules for Identifiers
 Combination of alphabets, digits (or) underscore
 First character should be a Alphabet
 No special characters other than underscore can be used
 No comma / spaces allowed within variable name
 A variable name cannot be a keyword
 Variable names are case sensitive
 Variable name length cannot be more than 31 characters
VARIABLE DECLARATION
 A variable must be declared before it is used
 Declaration consists of a data type followed by one or more variable names separated by
commas.
Syntax
datatype variable_name;
Examples
int a, b, c, sum;
float avg;
char name;
VARIABLE INITIALIZATION
 Assigning a value to the declared variable
 Values assigned during declaration / after declaration
Examples
int a, b, c;
a=10, b=20, c=30;
int a=10 ,b=10, c=10;
SCOPE OF VARIABLES
 There are three places where variables can be declared
 Inside a function or a block which is called local variables
 Outside of all functions which is called global variables
 In the
definition of function parameters which
parameters
are called formal
SCOPE OF VARIABLES
 A scope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable it cannot be accessed
 Variable Scope is a region in a program where a variable is declared and used
 The scope of a variable is the range of program statements that can access
that variable
 A variable is visible within its scope and invisible outside it
SCOPE OF VARIABLES : LOCAL VARIABLES
 Variables that are declared inside a function or block are called local variables
 They can be used only by statements that are inside that function or block of
code
 Local variables are created when the control reaches the block or function
containing the local variables and then they get destroyed after that
 Local variables are not known to functions outside their own
SCOPE OF VARIABLES : LOCAL VARIABLES
#include <stdio.h>
int main ( )
{
/* local variable declaration */
int a, b; int c;
/* actual initialization */
a = 10; b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
SCOPE OF VARIABLES : GLOBAL VARIABLES
 Defined outside a function, usually on top of the program
 Hold their values throughout the lifetime of the program
 Can be accessed inside any of the functions defined for the program
 Can be accessed by any function
 That is, a global variable is available for use throughout the entire program
after its declaration
SCOPE OF VARIABLES : GLOBAL VARIABLES
#include <stdio.h>
/* global variable declaration */
int g;
int main ( )
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10; b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
BINDING
 A Binding is an association between an entity and an attribute
 Between a variable and its type or value
 Between a function and its code
 Binding time is the point at which a binding takes place
 Types of Binding
 Design Time
 Compile Time
 Link Time
 Run Time
BINDING
 Design Time
 Binding decisions are made when a language is designed
 Example
 Binding of + to addition in C
 Compile Time
 Bindings done while the program is compiled
 Binding variables to datatypes
 Example
 int a; float b; char c;
BINDING
 Link Time
 Compiled code is combined into a full program for C
 Example
 Global and Static variables are bound to addresses
 Run Time
 Any binding that happens at run time is called Dynamic
 Any binding that happens before run time is called Static
 Values that are dynamically bound can change
DATATYPES
 Defines a variable before use
 Specifies the type of data to be stored in variables
 Basic Data Types – 4 Classes
 int – Signed or unsigned number
 float – Signed or unsigned number having Decimal Point
 double – Double Precision Floating point number
 char – A Character in the character Set
DATATYPES
INTEGER DATA TYPE
 Whole numbers with a range
 No fractional parts
 Integer variable holds integer values only
 Keyword: int
 Memory: 2 Bytes (16 bits) or 4 Bytes (32 bits)
 Qualifiers: Signed, unsigned, short, long
 Examples: 34012, 0, -2457
FLOATING POINT DATA TYPE
 Numbers having Fractional part
 Float provides precision of 6 digits
 Integer variable holds integer values only
 Keyword: float
 Memory: 4 Bytes (32 bits)
 Examples: 5.6, 0.375, 3.14756
DOUBLE DATA TYPE
 Also handles floating point numbers
 Double provides precision of 14 digits
 Integer variable holds integer values only
 Keyword: float
 Memory: 8 Bytes (64 bits) or 10 Bytes (80 bits)
 Qualifiers: long, short
CHARACTER DATA TYPE
 handles one character at a time
 Keyword: char
 Memory: 1 Byte (8 bits)
EXPRESSIONS
 Expression :
An Expression is a collection of operators and operands
that represents a specific value/operation.
 Operator
: A symbol which performs tasks like
operations, logical operations and conditional operations
arithmetic
 Operands : The values on which the operators perform the task
 Expression Types in C
 Infix Expression
 Postfix Expression
 Prefix Expression
EXPRESSIONS
 Infix Expression
 The operator is used between operands
 General Structure : Operand1 Operator Operand2
 Example : a + b
 Postfix Expression
 Operator is used after operands
 General Structure : Operand1 Operand2 Operator
 Example : ab+
 Prefix Expression
 Operator is used before operands
 General Structure : Operator Operand1 Operand2
 Example : +ab
EXPRESSIONS
INPUT AND OUTPUT FUNCTIONS
 Ability to Communicate with Users during execution
 Input Operation
 Feeding data into program
 Data Transfer from Input device to Memory
 Output Operation
 Getting result from Program
 Data Transfer from Memory to Output device
 Header File : #include<stdio.h>
FORMATTED INPUT / OUTPUT STATEMENTS
 Reads and writes all types of data values
 Arranges data in particular format
 Requires Format Specifier to identify Data type
 Basic Format Specifiers
 %d – Integer
 %f – Float
 %c – Character
 %s - String
SCANF ( ) FUNCTION
 Reads all types of input data
 Assignment of value to variable during Runtime
Syntax
scanf(“Control String/Format Specifier”, &arg1, &arg2,… &argn)
PRINTF ( ) FUNCTION
 To print Instructions / Output onto the Screen
 Requires Format Specifiers & Variable names to print data
Syntax
printf(“Control String/Format Specifier”,arg1,arg2,… argn)
EXAMPLE 1 – USING PRINTF ( ) & SCANF ( ) FUNCTION
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
printf(“Enter the Value of a”);
scanf(“%d”, &a);
printf(“Value of a is %d”, a);
getch( );
}
}
EXAMPLE 1 – USING PRINTF ( ) & SCANF ( ) FUNCTION
#include<stdio.h>
#include<conio.h> void main( )
{
int a, b, c;
printf(“Enter the Value of a, b & c”);
scanf(“%d %d %d”, &a, &b, &c);
printf(“Value of a, b & c is %d %d %d”, a, b, c);
getch ( );
}
TRY IT OUT YOURSELF ! WRITE A C PROGRAM TO:
 Add two numbers
 To Multiply two floating point numbers
 To compute Quotient and Remainder
 To Swap two numbers
UNFORMATTED INPUT / OUTPUT STATEMENTS
 Works only with Character Data type
 No need of Format Specifier
 Unformatted Input Statements
 getch(): It will Accepts a Keystroke and never displays it.(So that it can be used in
password). That is, It Never echoes the character on screen. The Arguments to the
function is any key on keyboard ,not necessarily be a character.
 getchar(): It will accepts a character from keyboard & Displays it immediately. On
reading any character, getchar() need to hit any key for proceeding. The argument
is a character i.e alphabet(A-Z).
 gets ( ) – Accepts any string from Keyboard until Enter Key is pressed
UNFORMATTED INPUT / OUTPUT STATEMENTS
 Unformatted Output Statements
 putch() –
Prints only the any alphabets
 putchar ( ) – Prints any character including escape sequences
 puts ( ) – Prints a String to Monitor (Output Device)
OPERATORS IN C
 C supports rich set of built in Operators
 Used to manipulate Constants (Data) & Variables
 Part of Mathematical (or) Logical expressions
 Operator – Definition
 Symbol (or) Special character that instructs the compiler to perform
mathematical (or) Logical operations
ARITHMETIC OPERATORS
 An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).
Operator
Meaning of Operator
+
addition or unary plus
-
subtraction or unary minus
*
multiplication
/
division
%
remainder after division (modulo division)
EXAMPLE – ARITHMETIC OPERATORS
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
ASSIGNMENT OPERATORS
 An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
Operator
Example
Same as
=
a=b
a=b
+=
a += b
a = a+b
-=
a -= b
a = a-b
*=
a *= b
a = a*b
/=
a /= b
a = a/b
%=
a %= b
a = a%b
EXAMPLE – ASSIGNMENT OPERATORS
#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
// c is 5
printf("c = %d\n", c);
c += a;
// c is 10
printf("c = %d\n", c);
c -= a;
// c is 5
printf("c = %d\n", c);
c *= a;
// c is 25
printf("c = %d\n", c);
c /= a;
// c is 5
printf("c = %d\n", c);
c %= a;
// c = 0
printf("c = %d\n", c);
return 0;
}
INCREMENT AND DECREMENT OPERATORS
 Increment ++ increases the value by 1 whereas decrement -- decreases the value
by 1. These two operators are unary operators, meaning they only operate on a
single operand.
EXAMPLE – INCREMENT AND DECREMENT OPERATORS
int main(){
int a = 10, b = 20,c=30,d=40;
printf("a++ = %d \n", a++);
printf("%d \n",a);
printf("--b = %d \n", b--);
printf("%d \n",b);
printf("++c = %d \n", ++c);
printf("%d \n",c);
printf("--d = %d \n", --d);
printf("%d \n",d);
return 0;}
a++
11
--b
19
++c
31
--d
39
= 10
= 20
= 31
= 39
RELATIONAL OPERATORS
 A relational operator checks the relationship between two operands. If the relation
is true, it returns 1; if the relation is false, it returns value 0.
 Relational operators are used in decision making and loops.
Operator
Meaning of Operator
Example
==
Equal to
5 == 3 is evaluated to 0
>
Greater than
5 > 3 is evaluated to 1
<
Less than
5 < 3 is evaluated to 0
!=
Not equal to
5 != 3 is evaluated to 1
>=
Greater than or equal to
5 >= 3 is evaluated to 1
<=
Less than or equal to
5 <= 3 is evaluated to 0
EXAMPLE – RELATIONAL OPERATORS
int main()
{
int a = 5,
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
printf("%d
return 0;
}
b = 5, c = 10;
== %d is %d \n", a, b, a == b);
== %d is %d \n", a, c, a == c);
> %d is %d \n", a, b, a > b);
> %d is %d \n", a, c, a > c);
< %d is %d \n", a, b, a < b);
< %d is %d \n", a, c, a < c);
!= %d is %d \n", a, b, a != b);
!= %d is %d \n", a, c, a != c);
>= %d is %d \n", a, b, a >= b);
>= %d is %d \n", a, c, a >= c);
<= %d is %d \n", a, b, a <= b);
<= %d is %d \n", a, c, a <= c);
5
5
5
5
5
5
5
5
5
5
5
5
== 5 is 1
== 10 is 0
> 5 is 0
> 10 is 0
< 5 is 0
< 10 is 1
!= 5 is 0
!= 10 is 1
>= 5 is 1
>= 10 is 0
<= 5 is 1
<= 10 is 1
LOGICAL OPERATORS
 An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used in
decision making in C programming.
Operator
Meaning
Example
&&
Logical AND. True only
if all operands are true
If c = 5 and d = 2 then,
expression ((c==5) &&
(d>5)) equals to 0.
||
Logical OR. True only if
either one operand is
true
If c = 5 and d = 2 then,
expression ((c==5) ||
(d>5)) equals to 1.
!
Logical NOT. True only if
the operand is 0
If c = 5 then,
expression !(c==5)
equals to 0.
EXAMPLE – LOGICAL OPERATORS
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b) && (a<c);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
(a == b) && (c > b) is 1
(a == b) || (c < b) is 1
!(a != b) is 1
!(a == b) is 0
BITWISE OPERATORS
 During
computation, mathematical operations like: addition, subtraction,
multiplication, division, etc are converted to bit-level which makes processing
faster and saves power.
 Bitwise operators are used in C programming to perform bit-level operations.
Operators
Meaning of operators
&
|
Division
Remainder (R)
Bitwise AND
112 / 2 = 56
0
Bitwise OR
56 / 2 = 28
0
28 / 2 = 14
0
14 / 2 = 7
0
^
Bitwise exclusive OR
~
Bitwise complement
7/2=3
1
<<
Shift left
3/2=1
1
>>
Shift right
1/2=0
1
BITWISE AND OPERATOR &
 The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If
either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
 Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
A
B
Q
0
0
0
0
1
0
1
0
0
1
1
1
EXAMPLE – BITWISE AND OPERATOR &
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
Output = 8
BITWISE OR OPERATOR |
 The output of bitwise OR is 1 if at least one corresponding bit of two operands is
1. In C Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal))
A
B
Q
0
0
0
0
1
1
1
0
1
1
1
1
EXAMPLE – BITWISE OR OPERATOR |
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}
Output = 29
BITWISE XOR (EXCLUSIVE OR) OPERATOR ^
 The result of bitwise XOR operator is 1 if the corresponding bits of two
operands are opposite. It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
^ 00011001
________
00010101 = 21 (In decimal)
A
B
Q
0
0
0
0
1
1
1
0
1
1
1
0
EXAMPLE – BITWISE XOR (EXCLUSIVE OR) OPERATOR ^
#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
}
Output = 21
BITWISE COMPLEMENT OPERATOR ~
 Bitwise compliment operator is an unary operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted by ~.
 2's Complement
 Two's complement is an operation on binary numbers. The 2's complement of a
number is equal to the complement of that number plus 1.
 For example:
Binary number
1’s complement
2’s complement
001
110
111
010
101
110
011
100
101
100
011
100
EXAMPLE – BITWISE COMPLEMENT OPERATOR ~
#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}
Output = -36
Output = 11
RIGHT SHIFT OPERATOR
 Right shift operator shifts all bits towards right by certain number of specified bits.
It is denoted by >>.
212 = 11010100 (In binary)
212>>2 = 00110101 (In binary) [Right shift by two bits]
212>>7 = 00000001 (In binary)
212>>8 = 00000000
212>>0 = 11010100 (No Shift)
LEFT SHIFT OPERATOR
 Left shift operator shifts all bits towards left by a certain number of specified bits.
The bit positions that have been vacated by the left shift operator are filled with 0.
The symbol of the left shift operator is <<.
212 = 11010100 (In binary)
212<<1 = 110101000 (In binary) [Left shift by one bit]
212<<0 = 11010100 (Shift by 0)
212<<4 = 110101000000 (In binary) =3392(In decimal)
EXAMPLE – SHIFT OPERATOR
#include <stdio.h>
int main()
{
int num=212, i;
for (i=0; i<=2; ++i)
printf("Right shift by %d: %d\n", i, num>>i);
printf("\n");
for (i=0; i<=2; ++i)
printf("Left shift by %d: %d\n", i, num<<i);
return 0;
}
Right Shift by 0: 212
Right Shift by 1: 106
Right Shift by 2: 53
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848
OTHER OPERATORS
 Comma Operator
 Comma operators are used to link related expressions together.
 For example:
int a, c = 5, d;
THE SIZEOF OPERATOR
 The sizeof is a unary operator that returns the size of data (constants, variables,
array, structure, etc).
EXAMPLE – SIZE0F() OPERATOR
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of
printf("Size of
printf("Size of
printf("Size of
return 0;
}
int=%lu bytes\n",sizeof(a));
float=%lu bytes\n",sizeof(b));
double=%lu bytes\n",sizeof(c));
char=%lu byte\n",sizeof(d));
Size
Size
Size
Size
of
of
of
of
int = 4 bytes
float = 4 bytes
double = 8 bytes
char = 1 byte
Download