You are on page 1of 94

Unit No:1

Introduction to the C Language Lecture No:L8

Link to Session
ed programming
C i s a structured p r o g r a m m i n g language. It i s also k n o w n a s function orientat Planner (SP):S.No….of SP
s Ritchie at Bell
language. C programming language was developed in the year of 1972 by Denni Date Conducted:
Laboratories in U SA (AT & Page No:
T).

The following are the language before ‘c’ & various versions of ‘c’.
1. ALGOL is introduced first in 1960’s
2. BCPL (Basic Combined Programming Language by Martin Richards in 1967 )
3. B Language (Ken Thompson and Dennis Ritchie at Bell Laboratory in 1969)
4. C Language (Dennis Ritchie at Bell Laboratory in 1972)
Features of C language
1. C is a structured programming language.
2. It is a robust language with rich set of built-in functions and operators that can be used to write
any complex program.
3. The C compiler combines the capabilities of an machine language with features of a high-level
language. (it is called as middle level language)
4. Programs Written in C are efficient and fast. This is due to its variety of data type and powerful
operators.
5. C is highly portable this means that programs once written can be run on another machines with
little or no modification.
6. Another important feature of C program, is its ability to extend itself.
7. A C program is basically a collection of functions that are supported by C library. We can also
create our own function and add it to C library.
8. C language is the most widely used language in operating systems and embedded system
development today.
9. C is a Case Sensitive language
Unit No:1

Structure of C program Lecture No:L9 & L10

Link to Session
Planner (SP):S.No….of SP

Date Conducted:

Page No:
Structure of C program
Documentation Section (optional): The documentation section contains a set of comments
including the name of the program other necessary details. Comments are ignored by
compiler and are used to provide documentation to people who reads that code.
Comments in C programming are represented in two different ways:
1. Single Line Comment
// This is single line comment
2. Multi Line Comment
/* This is
multi line comment */

Example of Line Comments:

Note: comments can not be nested Inner


comment not Closing
allowed token

Left on its
ignored own
C program to use block and line comments u1_ex1.c
Structure of C program
Link Section (Must): The link section consists of header files while contains function
prototype of Standard Library functions which can be used in program. Header file also
consists of macro declaration. Example:
#include <stdio.h>
# is a pre processor director and
include is a preprocessor command
stdio.h is standard input/output header file
< > called angular braces.
There are two types of files to include in our program
1.Standard header files
All the standard header files must be placed in between angular braces
Ex: #include<math.h> to use mathematical functions in our program
2. User defiles files
All the user defiled files must be placed in between double quotes
Ex: #include”program1.c”
Structure of C program
Definition Section(Optional): The definition section defines all symbolic constants. A
symbolic constant is a constant value given to a name which can't be changed in program.
Example:
#define PI 3.14
#define is a preprocessor command to define a constant value
In above code, the PI is a constant whole value is 3.14
Global Declaration Section(Optional): In global declaration
section, global variables can
be declared.
These global variable can be used in both main and user defined functions.
By default
Ex intall
a,global
b, c; variables are initialized to null.
: void main()
{
}
fun1()
{
}
Structure of C program
main function Section(Must): The main () function section is the most important section of any
C program. The compiler start executing C program from main() function. The main() function
is mandatory in C programming.
It has two parts:
Declaration Part - All the variables that are later used in the executable part are declared in this
part.
Executable Part - This part contains the statements that are to be executed by the
compiler. int main()
{
...
..
...
... ..
...
}
int is the return value from main function. It returns zero to OS if program is successfully
executed.
Sub Program Section(Optional): The subprogram section contains all the user defined
functions. A complete and fully functions C program can be written without use of user-
defined function in C programming but the code maybe be redundant and inefficient if user-
defined functions are not used for complex programs.
First C Programs
1. Our first C program is very simple. No preprocessor commands
2. No global declarations. No local definitions.
3. It only prints simple message

C program for hello world u1_ex2.c


Unit No:1

C Character Set Lecture No:L11

Link to Session

The character set in C Language can be grouped into the following categories
Planner (SP):S.No….of SP

1. Letters . Date Conducted:


2. Digits C Special Character-Set Ta Page No:
3. Special Characters , Comma & Ampersand
ble
4. White Spaces . Peroid ^ Caret
; Semicolon * Asterisk
C Character-Set Table
: Colon - Minus sign
Letters Digits
? Question Mark + Plus Sign
Upper Case A to Z 0 to 9
' Aphostrophe < Opening Angle (Less than sign)
Lower Case a to z
" Quotation Marks > Closing Angle (Greater than sign)

C White Spaces Table ! Exclaimation Mark ( Left Parenthesis


| Vertical Bar ) Right Parenthesis
Name
/ Slash [ Left Bracket
Blank space
\ Backslash ] Right Bracket
Horizontal tab ~ Tilde { Left Brace
Carriage Return _ Underscore } Right Brace

New Line $ Dollar Sign # Number Sign


% Percentage Sign
Form Feed
Keywords
Unit No:1

Lecture No:L12

Link to Session
 C programming also has words with specific meaning which are used to con struct c program
Planner (SP):S.No….of SP
instructions.
Date Conducted:
 In C programming language, keywords are special words with predefined me aning.
Page No:

 Keywords are also known as reserved words in C programming language.


 In C programming language, there are 32 keywords. All the 32 keywords has their own
meaning which is already known to the compiler.

auto return doube for int short switch volatile

struct const else goto long signed typedef while

break continue enum if register float union char

case default extern void restrict static unsigned do


Keywords
Properties of Keywords

1. All the keywords in C programming language are defined as lowercase letters so they
must be use only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user defined names like variable, functions, arrays,
pointers etc...
4. Every keyword in C programming language, represents something or specifies
some
kind of action to be performed by the compiler.
Identifiers
Unit No:1

Lecture No:L13

Link to Session
1. One feature present in all computer languages is the identifier. Planner (SP):S.No….of SP

2. Identifier is a user defined name of an entity to identify it uniqu ely


Dateduring
Conducted:the

Page No:
program execution
3. Identifiers allow u s to name data and other objects in the program.
Each
identified object in the computer is stored at a unique address.

4. If we didn’t have identifiers, we would have to know and use object’s addresses.
Instead, we simply give data identifiers and let the compiler keep track of where
they are physically located.
The rules for identifiers are:
1. The first character must be alphabetic character(A-Z, a-z) or
underscore.
2. Must contain only alphabetic characters(A-Z, a-z), digits(0-9) or underscore.
3. First 63 characters of an identifier are significant.
4. Cannot duplicate a keyword.
5. Usually the identifies in the C system libraries start with an underscore, not an
application programs.
Identifiers
Examples of Valid and Invalid Names:

Valid identifiers: Invalid identifiers:


sum 1sum
sum_of_numbers sum-of-numbers
name123 #abc

Rollno rollno ROLLNO is not same

C program for identifiers, keywords u1_ex3.c


Data Types
Unit No:1

Lecture No:L14

Link to Session

1. A data type defines a set of values and a set of operations that can be applied onSP
Planner (SP):S.No….of

those values. Date Conducted:


2. The C language has defined set of types that can divided into four general
categories:
 Primary Data types (Basic Data types O R Predefined Data types)
 Derived Data types (Secondary Data types OR User defined Data types)
 Enumeration Data types
 Void Data type
Primary Data Types
The primary data types in C programming language are the basic data types. All the
primary data types are already defined in the system. Primary data types are also called as
Built-In data types. The following are the primary data types in c programming language...

1. Integer Data type


2. Floating Point Data type
3. Character Data type
Primary Data Types
Primary data types with their sizes, range of values
Data Type Memory (bytes) Range Format Specifier

short int or signed 2 -32,768 to 32,767 %hd


short int

unsigned short int 2=16 bits 0 to 65,535 %hu or %hd


signed int 4=32 bits -2,147,483,648 to 2,147,483,647 %d or %i
unsigned int 4 0 to 4,294,967,295 %d or %u or %i
signed long int 4 -2,147,483,648 to 2,147,483,647 %ld or %li
unsigned long int 4 0 to 4,294,967,295 %ld or %li or %lu
signed long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu
signed char 1=8 bits -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 1.2E-38 to 3.4E+38 %f

double 8 2.3E-308 to 1.7E+308 %lf or %f


long double 12 3.4E-4932 to 1.1E+4932 %Lf

C program for data types u1_ex4.c to u1_ex7.c


Void Type
Unit No:1

Lecture No:L15

Link to Session
1. The void type designated by the keyword void, has values and no operations . Planner (SP):S.No….of SP
2. Which mainly used with functions and pointers. Date Conducted:
3. It is used in three kinds of situations − Page No:

Sr.No. Types & Description


1 Function returns as void

There are various functions in C which do not return any value or you can say they
return void. A function with no return value has the return type as void. For
example, void exit (int status);
2 Function arguments as void

There are various functions in C which do not accept any parameter. A function
with no parameter can accept a void. For example, int rand(void);
3 Pointers to void

A pointer of type void * represents the address of an object, but not its type. For
example, a memory allocation function void *malloc( size_t size ); returns a
pointer to void which can be casted to any data type.
Variables (1 of 2)

Variables are named memory locations that have a type, such as integer or character,
which is inherited from their type. The type determines the values that a variable may
contain and the operations that may be used with its values.

Variable Declaration:
1. Each variable in our program must be declared and defined.
2. In C, a declaration is used to name an object, such as a variable.
3. Definitions are used to create an object.
4. A variable is declared and defined at the same time.
5. Declaration gives them symbolic name and definition reserves memory for them.
6. Once defined, variables are used to hold the data that are required by the program for
its operation
7. A variable can be any data type, such as char, int or real but a variable cannot be void.
(2 of 2)
Variable Initialization:
Variables
1. We can initialize a variable at the same time that we declare it by including an initializer,
the initializer establishes the first value that the variable will contain.
2. To initialize a variable when it is define, the identifier is followed by assignment operator
and the initializer, which is the value the variable is to have when the function starts.
Example: int count=0;
int count=0,sum=0

Note: When a variable is defined, it is not initialized. We must initialize any variable
requiring prescribed data when the function starts.
When variables are defined ,they usually contain garbage(meaningless) values.

C program to illustrate the concept of a variable u1_ex8.c


Unit No:1

Input/output statements(1 of Lecture No:L17

Link to Session
Although our programs have implicitly shown how to print messages, we ha ve not formally
Planner (SP):S.No….of SP
discussed how we use C facilities11)
to input and output data.
Date Conducted:
Stream s Page No:
:1. In C data is input to and output from a stream.
A stream is source of or destination for data.
2. It is Associated with physical device, such as a terminal, or with a file stored in auxiliary
memory. C uses two forms of streams : text and binary.
3. A text stream consists of sequence of characters divided into lines with line terminated by
a newline(\n). A binary stream consists of sequence of data values such as integer, real, or
complex using their memory representation.
4. Here we assume that the source of data is the keyboard and destination of data is the
monitor. Keyboard is known as standard input and monitor is known as standard output
Input/output statements (2 of 11)
Formatted Input/Output:
The C language provides two formatting functions: printf for output formatting and
scanf for input formatting.
Output formatting: printf

1. The printf function takes a set of data values, converts them to a text stream using
formatting instructions contained in a format control string, and sends the resulting text
stream to the standard output(monitor).
2. printf is data to text stream converter.
3. The syntax of printf function is
int printf(“ format control string”, argument list);
Input/output statements (3 of 11)
Output formatting: printf
Format control string
• Input and output
functions use a format
control string.
• Format control string
describes how data is
to be formatted when
read or write.
• Format control string m ay also contain the text to be printed,
su ch as instructions to the user, captions to make the output more readable.
• We can also print control characters, such as (\t), (\n), (a) by including them in
format control string.
Input/output statements (4 of 11)
Output formatting: printf
Conversion specification
1. To insert data into the stream, we use a conversion specification that
contain a start token (%), a conversion code, and up to four optional
modifiers as shown below.
2. The number, order and type of conversion specification must match the
number, order and type of the parameters in the list. Otherwise it
causes unpredictable results resulting in termination of input/output
function.
3. The first element is a conversion specification token (%) and the last
element is the conversion code. Both of these elements are required, the
other elements are optional
Input/output statements (5 of 11)
Conversion codes
Type Size Code Example
char none c %c
short int h d %hd
int none d %d
long int l d %ld
long long int ll d %lld
float none f %f
double none f %f
long double l f %lf

Precision:
If a floating point number is being printed, then we may specify the number
of decimal places to be printed with precision modifier. The precision
modifier has the format
.m ex: %.2f
Where m is the number of decimal digits. If no precision is specified printf
prints six decimal positions.
Input/output statements
Unit No:1

(6 of 11)
Lecture No:L18

Link to Session
Width modifier: Planner (SP):S.No….of SP
1. A width modifier may be used to specify the minimum number ofDateposition Conducted:
in the output. Page No:
2. It is very useful to align the output in columns, such as we need to print a
column of numbers.
3. It we don’t use a width modifier, each output value will take just enough
room for the data.
Ex: often width and precision are used
%2hd //short integer-2 print positions
%4d //integer -4 print positions
%8ld //long int-8 print positions
%7.2f //float-7 print positions. 2 decimal places
%10.3f //long double -10 print positions. 3 decimal places
Flag modifier:
• Flags allows the user to format the output in a desired fashion.
• Four output flags:
1) Justification
2) Padding
3) Sign
4) Alternate form Program for width, precision and size u1_ex15.c
Input/output statements (7 of 11)

The table defines the flag type, flag code and formatting

Program for printf statement with flags u1_ex16.c


Input/output statements (8 of 11)

Input formatting: scanf

1. The standard input formatting function in C is scanf .


2. This function takes a text stream from keyboard, extracts and formats data
from the stream according to a format control string, and the stores the data
in specified program variables.
3. scanf requires variable addresses in the address list.
4. Syntax of scanf statement is
int scanf (“format control string”, & argument list);

Scanf statement with sizes u1_ex17.c


Input/output statements (9 of 11)
Format control string
Like the format control string for prints, the control string for scanf is
enclosed in a set of quotation marks and contains one or more conversion
specifications that describe the data types.
Input/output statements (10 of 11)
Conversion Spécification
To format data from the input stream ,we use a conversion specification that
contains a start token (%), a conversion code, and up to three optional
modifiers as shown below.

1. There is no precision in an input conversion specification.


2. There is only one flag for input formatting, the assignment suppression
flag(*).
3. This flag tells scanf that the next input field is to be read but not stored.
It is discarded.
Ex: scanf(%d%*c%f”, &a,&b)
It reads integer, character and real numbers but only stores integer and
real.
4. The width modifier specifies the maximum number of characters to be
read .With input formatting width is maximum, not a minimum

Program for scanf statement with flags u1_ex18.c


Input/output statements (11 of 11)
Input formatting summary
C Operators
Operator:
An operator is a symbol used to perform arithmetic and
logical operations in a program.
 That means an operator is a special symbol that tells the compiler to
perform mathematical or logical operations.

C programming language supports a rich set of operators that


are classified as follows.

Arithmetic Operators
 Relational Operators
 Logical Operators
 Increment & Decrement Operators
 Assignment Operators
Bitwise Operators
 Conditional Operator
 Special Operators
Arithmetic Operators (+, -, *, /, %)
The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division and
percentage modulo.
The following table provides information about arithmetic operators.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5 % 2 = 1

⇒ The addition operator can be used with numerical data types and character data
type. When it is used with numerical values, it performs mathematical addition and
when it is used with character data type values, It performs
concatenation (appending).

⇒ The remainder of the division


operator is used with I
integer data type only.
/* C program to perform all arithmetic operations */
#include <stdio.h>
int main()
{
int num1, num2;
int sum, sub, mult, mod; float div;
/* * Input two numbers from user */
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
/* * Perform all arithmetic operations */
sum = num1 + num2;
sub = num1 - num2;
mult = num1 * num2;
div = (float)num1 / num2;
mod = num1 % num2;
/* * Print result of all arithmetic operations */
printf("SUM = %d\n", sum);
printf("DIFFERENCE = %d\n", sub);
printf("PRODUCT = %d\n", mult);
printf("QUOTIENT = %f\n", div);
printf("MODULUS = %d", mod);
return 0;
}
OUTPUT:-
Relational Operators (<, >, <=, >=, ==, !=)
• The relational operators are the symbols that are used to compare two values.
•That means the relational operators are used to check the relationship
between two values.
• Every relational operator has two results TRUE or FALSE.
•In simple words, the relational operators are used to define conditions in a
program. The following table provides information about relational operators.
Operator Meaning Example

< Returns TRUE if the first value 10 < 5 is FALSE


is smaller than second value
otherwise returns FALSE

> Returns TRUE if the first value 10 > 5 is TRUE


is larger than second value
otherwise returns FALSE

<= Returns TRUE if the first value 10 <= 5 is FALSE


is smaller than or equal to second
value otherwise returns FALSE
Operator Meaning Example

>= Returns TRUE if the first 10 >= 5 is TRUE


value is larger than or
equal to second value
otherwise returns FALSE

== Returns TRUE if both 10 == 5 is FALSE


values are equal
otherwise returns FALSE

!= Returns TRUE if both 10 != 5 is TRUE


values are not equal
otherwise returns
FALSE
/*C program using relational operators */
#include<stdio.h>
int main()
{
int x = 12, y = 13; printf("x = %d\
n", x); printf("y = %d\
n\n", y);
// Is x is greater than y? printf("x >
y : %d\n", x > y);
// Is x is greater than or equal to y? printf("x
>= y : %d\n", x >= y);
// Is x is smaller than y? printf("x <
y : %d\n", x < y);
// Is x is smaller than or equal to y? printf("x
<= y : %d\n", x <= y);
// Is x is equal to y?
printf("x == y : %d\n", x == y);
// Is x is not equal to y?
printf("x != y : %d\n", x != y);

}
Logical Operators (&&, ||, !)
The logical operators are the symbols that are used to combine multiple
conditions into one condition. The following table provides information
about logical operators.

Operator Meaning Example

&& Logical AND - Returns 10 < 5 && 12 > 10 is FALSE


TRUE if all conditions are
TRUE otherwise returns
FALSE

|| Logical OR - Returns 10 < 5 || 12 > 10 is TRUE


FALSE if all conditions are
FALSE otherwise returns
TRUE

! Logical NOT - Returns !(10 < 5


TRUE if condition is FLASE && 12 >
and returns FALSE if it is 10) is
TRUE
TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the
conditions is FALSE then complete condition becomes
FALSE.

⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the
conditions is TRUE then complete condition becomes TRUE.

Operator Meaning Op1 Op2 Op1 & op2 Op1|| op2

Nonzero Nonzero 1 1
&& Logical AND
|| Logical OR Nonzero 0 0 1

! Logical NOT 0 Nonzero 0 1

0 0 0 0
/* C program using of logical operators */

#include <stdio.h>
int main()
{
int a = 5, b =
5, c = 10,
result;
result = (a
== b) && (c
> b);
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) || (c < b);
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);
Assignment operators
The assignment operator evaluates an expression an expression on the right of
the expression and substitutes it to the value or variable on the left of the
expression.
Example: x = a+b
In addition, C has a set of shorthand assignment operators of the form.
Var operator= exp;
Example : x += 1 is same as x = x+1
The commonly used shorthand assignment operators are as follows
+=, -=, *=, /=, %=
#include <stdio.h>
main()
{
int a = 21;
int c ;
c = a;
printf("Lin
e1-=
Operator
Example,
Value of c
= %d\n", c
);
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n",
c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200; c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n",
c );
}
Increment & Decrement Operators (++ & --)
The increment and decrement operators are called unary operators
because both need only one operand.
The increment operators adds one to the existing value of the operand
and the decrement operator subtracts one from the existing value of
the operand.
The following table provides information about increment and
decrement operators.
Operator Meaning Example
++ Increment - Adds int a = 5;
one to existing a++; ⇒ a = 6
value

-- Decrement - int a = 5;
Subtracts one a--; ⇒ a = 4
from existing
value
Increment & Decrement Operators (++ & --)
The increment and decrement operators are used in front of the
operand (++a) or after the operand (a++). If it is used in front of the
operand, we call it as pre-increment or pre-decrement and if it is used
after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement

 In the case of pre-increment, the value of the variable is increased


by one before the expression evaluation.
 In the case of pre-decrement, the value of the variable is decreased
by one before the expression evaluation.
 That means, when we use pre-increment or pre-decrement, first
the value of the variable is incremented or decremented by one,
then the modified value is used in the expression evaluation.
Example Program for pre increment
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5,j;
j = ++i;
// Pre-
Increme
nt
printf("i =
%d, j =
%d",i,j);
}
Example Program for pre decrement
#include<stdio.h>
void main()
{
int x,i; i=10;
x=--i;
printf("x: %d",x);
printf("i: %d",i);
}
Post-Increment or Post-Decrement
 In the case of post-increment, the value of the
variable is increased by one after the expression
evaluation.
 In the case of post-decrement, the value of the
variable is decreased by one after the expression
evaluation.
 That means, when we use post-increment or post-
decrement, first the expression is evaluated with
existing value, then the value of the variable is
incremented or decremented by one.
Example Program for post increment

#include<stdio.h> void
main()
{
int i =5,j; j = i++;
printf("i = %d \t j =
%d”,i,j);
}
Output:
Example Program for post decrement
#include<stdio.h>
void main()
{
int x,i = 10;
x=i--;
printf("x: %d",x);
printf("i: %d",i);
}
Bitwise Operators

 The C language is well suited to system programming because


it contains operators that can manipulate data at the bit level.
 Those operators are used for testing, complementing or shifting
bits
to the right on left.
 C has two categories of bitwise operators that operate on data at
the bit level:
1. Logical bitwise operators and Operator Meaning
2. Shift bitwise operators. & Bitwise AND

Logical bitwise operators: | Bitwise OR


^ Bitwise
Exclusive OR

<< Shift left


>> Shift right
Bitwise Operators Truth table

~a a^b a|b a&b b a

1 0 0 0 0 0

1 1 1 0 1 0

0 1 1 0 0 1

0 0 1 1 1 1
BITWISE AND:-
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.
BITWISE OR:-
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 |.
BITWISE XOR:-
The result of bitwise XOR operator is 1 if the corresponding bits of two
operands are opposite. It is denoted by ^.
BITWISE COMPLEMENT:-

For any integer n, bitwise complement of n will be -(n+1)


Bitwise Shift Operators
The shift operators moves bits to the right or left.

Bitwise shift-right operator:

The bitwise shift right (>>) is a binary operator that


requires two integral operands .
The first operand is the value to be shifted.
The second operand specifies the number of bits to
be shifted. For unsigned data type,
Ex: a >>= 5; /* shift right 5 bits */ bits positions vacated
by shift are filled with
zeros.
Bitwise Right-Shift Operators

 When we shift a binary numbers, the right-shift operator divides


by a power of 2.
 If we shift a binary number two places to the right, we are dividing by
4.
 If we shift it three places , we are dividing by 8.

2 shift value Divide by Shift Operator

1 2 >>1
2 4 >>2
3 8 >>3
4 16 >>4
….. ……. ……
n 2n >>n
Let’s assume number as 128.
If we shift the number 5 position to the right, the output will be

= 128 >> 5
= 128 / (25)
=128/32
=4.
Bitwise Left-Shift Operators
The bitwise shift right (<<) is a binary
operator that requires two integral
operands .
 The first operand is the value to be shifted.
The second operand specifies the number of
bits to be shifted.
Ex: a <<=3; /* shift right 3 bits */
Bits positions
vacated by shift are
filled with zeros
Bitwise Left-Shift Operators

 When we shift a binary numbers, the Left-shift operator multiplies


by a power of 2.
 If we shift a binary number two places to the left, we are multiplying by
4.
 If we shift it three places , we are multiplying by 8.

2 shift value Multiplies by Shift Operator

1 2 <<1
2 4 <<2
3 8 <<3
4 16 <<4
…. …….. ……
n 2n <<n
Example
Let’s assume the number as 12
If we shift the number 3 position to the left.
Then the output will be,
Example
12 << 3
= 12 *
(23)
= 12 * 8
= 96.
Bitwise Operators (&, |, ^, ~, >>, <<)
Let us consider two variables A and B as A = 25 (11001) and B = 20
(10100).

Operator Meaning Example

& the result of Bitwise AND is 1 if A&B


all the bits are 1 otherwise it is ⇒ 16 (10000)
0

| the result of Bitwise OR is 0 if A|B


all the bits are 0 otherwise it is ⇒ 29 (11101)
1

^ the result of Bitwise XOR is 0 if A^B


all the bits are same otherwise ⇒ 13 (01101)
it is 1
~ the result of Bitwise ~A
once complement ⇒ 6 (00110)
is negation of the
bit (Flipping)

<< the Bitwise left shift A << 2


operator shifts all the ⇒ 100 (1100100)
bits to the left by the
specified number of
positions

>> the Bitwise right shift A >> 2


operator shifts all the ⇒ 6 (00110)
bits to the right by the
specified number of
positions
/*Program for Bitwise operators*/
#include <stdio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101
*/ int c = 0; c = a & b; /* 12 = 0000 1100
*/ printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
Output:
c = a ^ b; /* 49 = 0011 0001 */ Line 1 - Value of c is 12
printf("Line 3 - Value of c is %d\n", c ); Line 2 - Value of c is 61
c = ~a; /*-61 = 1100 0011 */ Line 3 - Value of c is 49
printf("Line 4 - Value of c is %d\n", c ); Line 4 - Value of c is -61
Line 5 - Value of c is 240
c = a << 2; /* 240 = 1111 0000 */ Line 6 - Value of c is 15
printf("Line 5 - Value of c is %d\n",
c ); c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n",
c );
}
Conditional Operator (?:)

The conditional operator is also called a ternary operator because it


requires three operands.
This operator is used for decision making. In this operator, first we verify a
condition, then we perform one operation out of the two operations based
on the condition result. If the condition is TRUE the first option is
performed, if the condition is FALSE the second option is performed.
syntax.

Condition ? TRUE Part : FALSE Part;

Example

A = (10<15)?100:200; ⇒ A value is 100


Conditional Operator in C
The conditional operator is also known as a ternary operator. The
conditional statements are the decision-making statements which depends
upon the output of the expression.
It is represented by two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the


ternary operator.

The behavior of the conditional operator is similar to the 'if-else


' statement as 'if-else' statement is also a decision-making statement.

Syntax of a conditional operator

Expression1? expression2: expression3;


Meaning of the above syntax.

In the above syntax, the expression1 is a Boolean condition that can be either true or
false value.
If the expression1 results into a true value, then the expression2 will execute.
The expression2 is said to be true only when it returns a non-zero value.
If the expression1 returns false value then the expression3 will execute.
The expression3 is said to be false only when it returns zero value.
/*ternary or conditional operator */

#include <stdio.h>
int main()
{
int age; //
variable
declaration
printf("Enter
your age");
scanf("%d",&ag
e);

// taking user
input for age
variable
(age>=18)?
(printf("eligible
for voting")) :
(printf("not
eligible for
voting")); //
conditional
operato
r
return 0;
Special Operators (sizeof, pointer, comma, dot, etc.)
The following are the special operators in c programming language.

sizeof operator

This operator is used to find the size of the memory (in bytes) allocated for a
variable.
syntax.

sizeof(variableName);

Example
sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)


This operator is used to define pointer variables in c programming language.
Comma operator (,)
This operator is used to separate variables while they are declaring, separate
the expressions in function calls, etc.
Dot operator (.)
This operator is used to access members of structure or union.
#include <stdio.h>
int main()
{
int a = 16;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of int data type : %d\n",sizeof(int));
printf("Size of char data type : %d\n",sizeof(char));
printf("Size of float data type : %d\n",sizeof(float));
printf("Size of double data type : %d\n",sizeof(double));
return 0;
}

Output

Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8
When the sizeof() is used with an expression, it returns the size of the
expression.
Example
#include <stdio.h>
int main()
{
char a = 'S';
double b = 4.65;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of an expression : %d\n",sizeof(a+b));
int s = (int)(a+b);
printf("Size of explicitly converted expression : %d\n",sizeof(s));
return 0;
}

Output
Size of variable a : 1
Size of an expression : 8
Size of explicitly
converted expression :
C Expressions
Definition:
An expression is a of operators and operands that
collection
represents a specific value.

In the above definition, an operator is a symbol that performs


tasks like arithmetic operations, logical operations, and conditional
operations, etc.
Operands are the values on which the operators perform the
task. Here operand can be a direct value or variable or address of
memory location.
Precedence
Precedence and Associativity
Operator precedence is used to determine the order of operators
evaluated in an expression. In c programming language every
operator has precedence (priority).

When there is more than one operator in an expression the


operator with higher precedence is evaluated first and the operator
with the least precedence is evaluated last.

Ex: 2+3*4=(2+(3*4))=14
-b++=(-(b++))
Precedence and Associativity
Associativity
Associativity is used to determine the order in which operators
with the same precedence are evaluated in a complex
expression.

Precedence is applied before associativity to determine the


order in which expressions are evaluated.

 Associativity can be left-to-right or right-to-left.


Precedence and Associativity

Left to Right Associativity

All the operators have the same precedence. Their associativity is


from left to right. so they are grouped as follows
 Ex: 3* 8 / 4 % 4 * 5

Right to Left Associativity


All the operators have the same precedence. Their
associativity is from right to left. so they are grouped as
follows
Ex: a += b *= c -= 5 which is (a=a+(b=b*(c=c-5)))
Precedence and Associativity
Operator Description Precedence Associativity

() Parentheses (function call) 1


[] Brackets (array subscript) left-to-right
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement

++ -- Prefix increment/decrement 2 right-to-left


+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary
* value of type)
& Dereference
s Address (of operand)
i Determine size in bytes on this
z implementation
e
o
f
* / % Multiplication/division/modulus 3 left-to-right

+ - Addition/subtraction 4 left-to-right

<< >> Bitwise shift left, Bitwise shift right 5 left-to-right


Precedence and Associativity

< <= Relational less than/less than or equal to 6 left-to-right


> >= Relational greater than/greater than or
equal to

== != Relational is equal to/is not equal to 7 left-to-right


& Bitwise AND 8 left-to-right
^ Bitwise exclusive OR 9 left-to-right
| Bitwise inclusive OR 10 left-to-right
&& Logical AND 11 left-to-right
|| Logical OR 12 left-to-right
?: Ternary conditional 13 right-to-left
= Assignment 14 right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR
<<= >>= assignment
Bitwise shift left/right assignment
, Comma (separate expressions) 15 left-to-right
Expression Evaluation
Now we evaluate expressions as we know associativity
and precedence of operators

Example 1:
a*4+b/2-c*b consider a=3 b=4
c=5 Replace variables by their
values
3 * 4 + 4 /2 –5 * 4
Apply precedence rules
(3 * 4) Associativity
Apply + (4 / 2) – (5 rules
* 4) as they are left to right associative
(((3 * 4) + (4 / 2)) – (5 * 4))
In evaluation of this expressions there are no side effects
Example 3:
Example 2:
Example 4:
Type Conversion
Up to this point, we have assumed that all of our expressions involved data of the
same type. But, what happens when we write an expression that involves two
different data types, such as multiplying an integer and a floating-point number? To
perform these evaluations, one of the types must be converted.
Type conversion is of two types:
1. Implicit Type Conversion
2. Explicit Type Conversion (Cast)

1. Implicit Type Conversion


When the types of the two operands in a binary expression are different, C
automatically converts one type to another. This is known as implicit type
conversion.

Conversion rank:

1. We assign a rank to the integral and floating point arithmetic types.


2.These ranks are known as conversion ranks.
3.Conversion ranks are shown below
The type conversion is the process of converting a data value from one data type to
another data type automatically by the compiler. Sometimes type conversion is also
called implicit type conversion. The implicit type conversion is automatically performed
by the compiler.

For example, in c programming language, when we assign an integer value to a float


variable the integer value automatically gets converted to float value by adding decimal
value 0. And when a float value is assigned to an integer variable the float value
automatically gets converted to an integer value by removing the decimal value.

To understand more about type conversion observe the following...

int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;

i = x ;
=======> x
value 15.5 is
converted as
15 and
assigned to
variable i
Type Conversion

Conversion Rank
Type Conversion
Explicit type conversion (Type casting)
1.In explicit type conversion we convert the data from one type to another type
using explicit type conversion.
2. Explicit type conversion uses the unary type cast operator
3. To cast the data from one type to another, we specify the new type in parentheses
before the value we want to convert.
Ex: (float) a

One use of the cast is to ensure that


the result of a divide is a real
number.

Ex: avg=(float) totalscores/ numscore


here totalscores is integer
numscore is int
but result is float due type cast
operator before totalscores
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\
n",x);
i = ch ;
printf("i value is %d\n",i);
}

Output:
In the above program, we assign i = x, i.e., float variable value is assigned to the
integer variable. Here, the compiler automatically converts the float value
(90.99) into integer value (90) by removing the decimal part of the float value
(90.99) and then it is assigned to variable i.
Similarly, when we assign x = i, the integer value (90) gets converted to float
value (90.000000) by adding zero as the decimal part.
Typecasting

Typecasting is also called an explicit type conversion. Compiler converts data from
one data type to another data type implicitly. When compiler converts implicitly,
there may be a data loss. In such a case, we convert the data from one data type to
another data type using explicit type conversion. To perform this we use the unary
cast operator.
To convert data from one type to another type we specify the target data type in
parenthesis as a prefix to the data value that has to be converted.

syntax of typecasting.
(TargetDatatype) DataValue

Example
int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks /
maxMarks * 100 ;

In the above example code, both totalMarks and maxMarks are integer data values.
When we perform totalMarks / maxMarks the result is a float value, but the
destination (average) datatype is a float. So we use type casting to convert
totalMarks and maxMarks into float data type.
#include<stdio.h>
void main()
{
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf("%d%d%d",&a,&b,&c);
avg = (a + b + c) / 3 ;
printf("avg before casting = %f\n",avg);
avg = (float)(a + b + c) / 3 ;
printf("avg after casting =%f\n",avg);
}

You might also like