0% found this document useful (0 votes)
19 views34 pages

BCP Unit Ii

The document provides an overview of the basics of C programming, including C tokens, data types, variables, operators, input/output streams, and constants. It discusses the C character set, identifiers, keywords, and delimiters. It also provides a brief history of the C language and reasons for learning C, such as it being a core language, small, quick, and portable. Standardizations of C by ANSI and ISO are also summarized.

Uploaded by

lopogip564
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views34 pages

BCP Unit Ii

The document provides an overview of the basics of C programming, including C tokens, data types, variables, operators, input/output streams, and constants. It discusses the C character set, identifiers, keywords, and delimiters. It also provides a brief history of the C language and reasons for learning C, such as it being a core language, small, quick, and portable. Standardizations of C by ANSI and ISO are also summarized.

Uploaded by

lopogip564
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit II – Basics of C Programming

Introduction: Structure of a C program, C Tokens - C character set, identifiers and keywords,


data types, Variables- Declaration, initialization, Constants, Input / Output streams.
Operators: Operators and Expressions, Types of Operators, Operator precedence and
Associativity, Type Conversion and casting, Formatted input/output.

Introduction to C

C is a general-purpose programming language. It has been closely associated with


the UNIX system where it was developed, since both the system and most of the programs
that run on it are written in C. The language, however, is not tied to anyone operating
system or machine; and although it has been called a "system programming language"
because it is useful for writing compilers and operating systems, it has been used equally
well to write major programs in many different domains.

History of C Language

 C programming language was developed in 1972 by Dennis Ritchie


at AT&T (American Telephone & Telegraph) Bell laboratories,
located in U.S.A.
 Dennis Ritchie is known as the founder of C language.
 It was developed to overcome the problems of previous languages such as B, BCPL
etc.
 Initially, C language was developed to be used in UNIX operating system. It inherits
many features of previous languages such as B and BCPL.
 Let's see the programming languages that were developed before C language.

Language Year Developed By

ALGOL 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee


ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Why Learn C?
There are a large number of programming languages in the world today—C++, Java,
Ada, BASIC, COBOL, Perl, Pascal, Smalltalk, FORTRAN, etc. Even so, there are several reasons
to learn C, some of which are stated as follows.

 C is a core language In computing, C is a general purpose, cross-platform, block


structured procedural, imperative computer programming language.
 C is a small language C has only thirty-two keywords (and only about twenty of
them are in common use). This makes it relatively easy to learn compared to bulkier
languages.
 C is quick We can write codes which run quickly, and the program can be very ‘close
to the hardware’. By that, you can access low level facilities in your computer quite
easily.
 C is portable C programs written on one system can be run with little or no
modification on other systems. If modifications are necessary, they can often be
made by simply changing a few entries in a header file accompanying the main
program.

Standardizations of C Language

• Both UNIX and C were created at AT&T’s Bell Laboratories in the late 1960s and early
1970s. During the 1970s the C programming language became increasingly popular.

• During the late 1970s and 1980s, versions of C were implemented for a wide variety
of mainframe computers, minicomputers, and microcomputers, including the IBM
PC.

• In the early 1980s, a need was realized to standardize the definition of the C
language which in turn would help C become more widespread in commercial
programming.
• In 1983 the American National Standards Institute (ANSI) formed a committee to
establish a standard specification of C known as ‘ANSI C’.

• This work ended in the creation of the so-called C89 standard in 1989. This version of
the language is often referred to as ANSI C, Standard C, or sometimes C89.
ISO/IECSO/IEC (It is a joint technical committee (JTC) of the International
Organization for Standardization (ISO) and the International Electro technical
Commission (IEC)).

• In 1990, the ANSI C standard (with a few minor modifications) was made by the
International Organization for Standardization (ISO) as ISO/IEC 9899:1990. This
version is sometimes called C90. Therefore, the terms ‘C89’ and ‘C90’ refer to
essentially the same language.

C Tokens
These are smallest individual units. They may represent a single character (or) a group
of characters which has a specific meaning.
The following are the ‘C’ tokens that can be recognized by “C compiler”.

C Tokens

Identifiers Strings Operators Constants

C Character Set

The characters are used to form words, numbers and expressions, and statements. C
Character set includes the following:

Alphabet:
Letters: Uppercase A to Z, Lowercase a to z.
Digits: All decimal digits from 0 to 9
Whitespaces: Blankspace
Horizantal Tab
Vertical Tab
New Line
Formfeed
Special Characters:
Symbo Symbo
Name of the character Name of the character
l l

, Comma = Equal to

. Dot (or) period $ Dollar

; Semicolon ? Question Mark

: Colon & Ampersand

‘ Apostrophe ^ Caret

“ Double Quotes * Asterisk

! Exclamation Mark + Plus

| Vertical Bar - Hiphen(minus)

/ Slash (Forward Slash) > Greater than

Backslash (Backward
\ < Less Than
slash)

~ Tilde () Paranthesis

_ Underscore [] Brackets

% Percentage {} Braces

# Hash(Number Sign) @ At the rate of

Delimiters:
Language pattern of ‘C’ uses special kind of symbols called as Delimiters.

Delimiter Purpose

: (colon) Used for indicating a label

; (Semi colon) Terminates statement

( ) paranthesis Used in expressions and functions

[ ] brackets Used for array declaration

{ } Scope of the statement

# Pre-processor directive

, ( Comma) Separator

/* ……….. */ Comments
Identifiers
 These are the names that are given to the various program elements such as
variables, functions, arrays, structures, etc.
 These are user defined names.
Rules to be followed for Identifiers:
 They should start with an alphabet but not any other character except
underscore.
 It should not start with a digit.
 C is case sensitive, hence uppercase and lowercase characters are significant.
 It should not be a keyword.
 It should be a meaningful name, so as to reflect its use.
 Whitespace between the identifiers is not allowed, means identifier should be a
single word, but to join the words we can use underscore (_).
 The length of an identifier changes from compiler to compiler.
Following are the some of valid and invalid identifiers
Valid Invalid

Name 3name

MAX @MAX

Area_of_rect Area of rect

number Case (keyword)

_sum -sum

Keywords
 These are the words reserved by the compiler, hence they are also called
Reserved words whose meaning and purpose is defined in advance.
 They should be in lower case.
 There are 32 keywords supported by C and standardized by ANSI and these
serve as the basic building blocks of a program statements.
 Following are the ANSI C keywords.

auto double int switch

break else long struct

case enum register typedef

char extern return union

const float short unsigned

continue for signed void


default goto sizeof volatile

do if static while

Constants
These are defined as the fixed values, which doesn’t undergo any change during the
execution a program.

Constants

Numeric Constants Character Constants

1. Integer Constants 1. Single character constants


2. Real Constants 2. String constants

Numeric Constants:

1. Integer Constants:
 These are the sequence of numbers from 0 to 9 without decimal points or
fractional part or any other symbol.
 The number without sign is assumed as positive.
Ex: 187, 15, 25689, -25, -45, -854 etc.,
2. Real Constants:
 These are often known as Floating-point constants.
 Since integer constants are unfit to represent some quantities like length, weight,
height, volume, area, percentage, currency etc.,
 Integer results for some operations will give approximate results, but real
constants gives accurate results, hence to improve accuracy, we will prefer real
constants.
 It has two parts Integer part and fractional part.
Ex: 256.652, 45.623, 5.436 etc.,
Character Constants:
1. Single Character Constants:
 It is a single character enclosed within a pair of single quote marks (‘ ‘).
 These constants include a single letter, single digit, single special character or a
whitespace.
Ex: ‘a’, ‘$’, ‘&’, ‘5’ etc.,
Note: All character constants have integer values known as ASCII values. ASCII
stands for American Standard Code for Information Interchange.
2. String Constants:
These are sequence of characters enclosed within double quotes (“ “).
It is a combination of all kinds of characters, digits and symbols.
Ex: “good”, “Hello”, “2563”, “f@ct”, “56&&” etc.,

Escape Sequence Character Constants:


 C supports some special backslash character constants used in output functions.
 Each one of these constants represents one character even though it consists of 2
characters. These character combinations are also known as Escape Sequences.
 The following table shows escape sequence characters.

Escape Sequence Meaning ASCII Value

‘\n’ New Line 10

‘\b’ Back space 8

‘\f ’ Form Feed 12

‘\t’ Horizantal Tab 9

‘\v’ Vertical Tab 11

‘\a’ Alert (audible) 7

‘\r’ Carriage Return 13

‘\’’ Single Quote 39

‘\” ‘ Double Quote 34

‘\\’ Backslash 92

‘\0’ Null Character 0

‘\?’ Question Mark 63


Variables and Data types
Data types:
 Data type represents the kind of data to be stored, manipulated and possible set
of operations perform on the data.
 C is rich in various data types.
 Programmer has to select the appropriate data type as per the need of an
application.
Classification of data types

Data types

Primary Data types Derived Data types User-defined Data types

 Integer Data type  Arrays  typedef


 Floating-point Data  Structures  Enumerated Data
type  Unions type
 Character Data type  Functions

Primary Data types:

All C compilers support 3 fundamental data types.


1. Integer Data type
2. Floating-point Data type
3. Character Data type
Integer Data Types:
Integers are whole numbers with a range of values supported by a particular machine.
C has three classes of Integer types
1. Integers
2. Short Integers
3. Long Integers
The above three classes are in both signed and unsigned type.
The following table shows all integer types
Data Type Keyword Size Range Format
Equivalent
(In Bytes) Specifier

signed int
Signed
(or) 2 -32768 to +32767 %d
Integer
int

signed short int

(or)
Signed Short
short int 1 -128 to +127 %d
Integer
(or)

short

signed long int

(or) -2147483648
Signed Long
long int 4 to %ld
Integer
(or) +2147483647

long

unsigned int
Unsigned
(or) 2 0 to 65535 %u
Integer
unsigned

unsigned short int


Unsigned
Short (or) 1 0 to 255 %u
Integer
unsigned short

unsigned long int


Unsigned
(or) 4 0 to 4294967295 %lu
Long Integer
unsigned long

Floating – point Data types:

Floating point or Real numbers data type should be identified for those quantities to be
represented with fractions.
Keyword Size Format
Data Type Range
Equivalent (In Bytes) Specifier

Floating
float 4 3.4E-38 to 3.4E+38 %f
point

Double Data
double 8 1.7E-308 to 1.7E+308 %lf
Type

Long Double
long double 10 3.4E-4932 to 3.4E+4932 %lf
Data Type

Character Data Types:


A single character can be defined as a character data type.

Keyword Size Format


Data Type Range
Equivalent (In Bytes) Specifier

Character
char
or
(or) 1 -128 to +127 %c
Signed
signed char
Character

Unsigned unsigned
1 0 to 255 %c
Character char

Variables
When a program is executed many operations are carried on data. These data are stored
in memory in the form of variables.
Definition: A variable is defined as a data name used for storing a data value. In other
words it is a named memory location.
A variable may take different values at different times during execution, means it’s value
may varies (changes).
A variable name can be chosen by the programmer in a meaningful way, so as to reflect
it’s purpose.
Ex: marks, student, average, sum, num, fact etc.,
Rules for defining variables:
 They should start with an alphabet but not any other character except
underscore.
 It should not start with a digit.
 C is case sensitive, hence uppercase and lowercase characters are significant.
 It should not be a keyword.
 It should be a meaningful name, so as to reflect its use.
 Whitespace between the variables is not allowed, means a variable should be a
single word, but to join the words we can use underscore (_).
 The length of a variable changes from compiler to compiler.

Valid Invalid

Name 3name

MAX @MAX

Area_of_rect Area of rect

number Case (keyword)

_sum -sum

Declaration and Initialization of variables


The declaration of variables should be done in the declaration part of the program
They must be declared to the compiler, it basically does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Once a variable is declared, the required memory space gets allocated.
Note: The declaration of variable should be done before they used in the program.
Syntax:
datatype variable_name;
Here, datatype -> any datatype supported by C.
Variable_name -> any valid identifier.
Ex:
int num;
long fact;
char menu;
float avg;

Initialization of variables:
The process of assigning values to the declared variables is called variable initialization.
A variable must be initialized or assigned to a suitable value using an assignment
operator (=), otherwise some random value will be stored.
Syntax:
variable_name = value;
Ex:
num = 10;
fact = 2562;
menu = ‘x’;
avg = 75.562;
We can also combine both declaration and initialization of variables as follows:
Syntax:
datatype variable_name = value;
Ex:
int num = 10;
long fact = 2562;
char menu = ‘x’;
float avg = 75.562;
Note: More than one variable of same type can be declared and initialized, each variable
can be separated by comma.
Ex: int num=2, sum=0, fact=1;

Input and Output Functions

These are the functions used to read data from the keyboard and display results on the
monitor.
These functions are classified as follows:

Input and Output Functions

Formatted IO Functions Unformatted IO Functions

Input Output Input Output

scanf() printf() getc( ) putc( )

getch( ) putch( )

getche( ) putche( )

getchar( ) putchar( )

gets( ) puts( )
Formatted IO Functions:

1. The scanf( ) statement:


 It is a formatted input function used to read data from the keyboard.
 It reads all types of data values.
 It is used for run time assignment of variables.
 It requires a conversion symbol or format specifier to identify the data to be read
during the execution of a program.
 It also requires the address location of a variable to which the value is to be
stored.
Syntax-1:
scanf(“Control String”, variables);
Syntax-2:
scanf(“format specifier”, &variable_name);
Syntax-3:
Scanf(“format specifier [format specifier ……….]”, &variable1[,&variable2,
………]);

Examples:
scanf(“%d”, &num);
scanf(“%d %ld %f %c”, &num, &fact, &avg, &menu);
2. The printf( ) statement:
 It is a formatted output function used to display data on the monitor.
 It displays all types of data values.
 It requires a conversion symbol or format specifier to identify the data.
 The format specifiers and variable names should be same in number.
Syntax-1:
printf(“control string”, variables_names);
Syntax-2:
printf(“format specifier”, variable_name);
Syntax-3:
printf(“format specifier [,format specifier ……….]”, variable1[,variable2,
………]);

Examples:
printf(“%d”, num); /* displays the value of num */
printf(“The value of num is: %d”, num); /* o/p: The value of num is: 25 */

Sample Programs:
1. Write a C program to display a welcome message.
Source Code:
/* Program to display welcome message */
#include<stdio.h>
void main()
{
printf(“Hello! Good Morning \n”);
printf(“Welcome to SRIT”);
}
Output:
Hello! Good Morning
Welcome to SRIT
2. Write a C program to find the sum of three integers.
Source Code:
#include<stdio.h>
void main()
{
int num1, num2, num3, sum;
num1=45;
num2=10;
num3=15;
sum=num1+num2+num3;
printf(“ The sum of %d, %d and %d is %d.” num1, num2, num3, sum);
}

Output:
The sum of 45, 10 and 15 is 70.
3. Write a C program to find the sum of three floating point values.
#include<stdio.h>
void main()
{
float num1, num2, num3, sum;
printf(“ Enter any three floating point numbers:”);
scanf(“%f %f %f”, &num1, &num2, &num3);
sum=num1+num2+num3;
printf(“ The sum of %f, %f and %f is %f” num1, num2, num3, sum);
}

Output:
Enter any three floating point numbers:
45.55
12.56
35.63
The sum of 45.550000, 12.560000 and 35.630000 is 93.740000
4. Write a C program to find the area and perimeter of a rectangle.
Source Code:
#include<stdio.h>
void main()
{
int len, wid;
int area, peri;
printf(“Enter length and width of a rectangle:”);
scanf(“%d %d”, &len, &wid);
area=len *wid;
peri=2*(len+wid);
printf(“ Area of a rectangle is: %d \n”,area);
printf(“Perimeter of a rectangle is: %d”, peri);
}

Output:

Enter length and width of a rectangle:


25
20
Area of a rectangle is: 500
Perimeter of a rectangle is: 90
5. Write a C program to interchange the values of two integer variables.
(Hint: Use a temporary variable)
Source Code:
#include<stdio.h>
void main()
{
int num1, num2, temp;
printf(“Enter any two integers:”);
scanf(“%d %d”, &num1, &num2);
printf(“Before Interchange: num1=%d, num2=%d \n”, num1, num2);
temp=num1;
num1=num2;
num2=temp;
printf(“After interchange: num1=%d, num2=%d” , num1, num2);
}

Output:
Enter any two integers:
45
85
Before Interchange: num1=45, num2=85
After Interchange: num1=85, num2=45

6. Write a C program to interchange the values of two integer variables without


using third variable.
Source Code:
#include<stdio.h>
void main()
{
int num1, num2;
printf(“Enter any two integers:”);
scanf(“%d %d”, &num1, &num2);
printf(“Before Interchange: num1=%d, num2=%d \n”, num1, num2);
num1=num1+num2;
num2= num1-num2;
num1=num1-num2;
printf(“After interchange: num1=%d, num2=%d” , num1, num2);
}

Output:
Enter any two integers:
45
85
Before Interchange: num1=45, num2=85
After Interchange: num1=85, num2=45
Assignment:
1. Write a C program to find the total and average of your SSC marks.
2. Write a C program to find the area and perimeter of a circle.
3. Write a C program to find the product of any two integers.
4. Write a C program to calculate and display Simple Interest using
SI=(p*t*r)/100.
5. Write a C program to convert given days into hours, minutes and seconds as
follows:
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds
Operators and Expressions
C is a rich of many operators to form various types of expressions.
Operator: It is a symbol used to represent some operation or computation.
Operand: It is a data name or data value on which operators performs operations.
Expression: The combination of operators and operands forms an expression which yields a
single value as a result.
Classification of Operators:
1. Unary Operators: These operators perform an operation on only one operand.
2. Binary operators: These operators perform an operation on two operands.
3. Ternary Operators: These operators perform an operation on three operands.
Types of Operators in C:
C supports a variety of operators as follows:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operator
 Bitwise Operators
 Special Operators
Arithmetic Operators:
 These operators are used to perform mathematical arithmetic operations like
addition, subtraction, multiplication and division.
 These are binary operators, hence requires two operands to perform operation.
 These operators can only perform operation on numeric data types supported by C.
Following are the arithmetic operators with examples.

OPERATOR MEANING RETURN VALUE EXAMPLE

+ Addition Sum 28+7=35

- Subtraction Difference 28-7=21


* Multiplication Product 28*7=196

/ Division Quotient 28/7=4

% Modulo Division Remainder 24%7=3

Program:
Write a C Program to perform basic arithmetic operations.
Source Code:
#include<stdio.h>
void main()
{
int num1, num2;
int sum, diff, prod, quot, rem;
printf(“Enter any two integers:”);
scanf(“%d %d”, &num1, &num2);
sum=num1+num2;
diff=num1-num2;
prod=num1*num2;
quot=num1/num2;
rem=num1%num2;
printf(“Sum=%d \n”, sum);
printf(“Difference=%d \n”, diff);
printf(“Product=%d \n”, prod);
printf(“Quotient=%d \n”, quot);
printf(“Remainder=%d \n”, rem);
}
Output:
Enter any two integers:
28
7
Sum=35
Difference=21
Product=196
Quotient=4
Remainder=0

Relational Operators:
 These operators are used to compare two operands or data items or expressions and
gives relation between them. Hence they are also called as comparision operators.
 These are binary operators.
 The result of a relational expression is always a Boolean value ie; either true or false.
 If the relation is True it returns 1, otherwise 0.
 These operators are mainly used in selection and looping statements for framing
conditions.
 Following table shows the list of relational operators with examples.

OPERATOR MEANING EXAMPLE RETURN VALUE

25>15 1 (true)
> Greater than
35>45 0 (false)

>= Greater than or equal to 15>=15 1

35<65 1
< Less than
45<25 0

<= Less than or equal to 15<=15 1

10==10 1
== Equals to
15==10 0
25!=10 1
!= Not Equals to
25!=25 0

Program:
Write a program to illustrate relational operators.
Source Code:
#include<stdio.h>
void main()
{
printf(“25 > 15 = %d”, (25>15));
printf(“25 < 15 = %d”, (25<15));
printf(“25 >= 25 = %d”, (25<=25));
printf(“25 <= 25 = %d”,(25<=25));
printf(“25 == 25 = %d”, (25==25));
printf(“25 != 15 = %d”, (25!=15));
}
Output:
25 > 15 = 1
25 < 15 = 1
25 >= 25 = 1
25 <=25 = 1
25 == 25 = 1
25 != 15 =1
Logical Operators:
 These operators are used to know the logical relationship between two Boolean
expressions.
 The result of these operators is also a Boolean value. i.e; either true(1) or false(0).
 These operators must be applied between two Boolean values.
 Following table shows list of logical operators.

OPERATOR MEANING EXAMPLE RETURN VALUE

&& Logical AND (25>15) && (85<90) 1

|| Logical OR (25>35) || (85<90) 1

! Logical NOT !(25==25) 0

 Generally, these operators are used to combine two or more relational


expressions.
 Logical AND is used when it is required to meet or satisfy “All” constraints or
conditions.
 Logical OR is used when it is required to meet “EITHER” one condition “OR” other
condition.
Assignment Operators:
These operators are used to assign/store some value/the result of an expression to a
variable.
It is denoted as ‘=’.
It is a binary operator, requires two operands on either side of ‘=’.
Syntax:
variable = value/expression;
Examples:
sum = 10; /* the value 10 is assigned to sum. */
sum = 25+45; /* the result of the expression 25+45 is assigned to sum. */
Additionally C has a set of shorthand assignment operators.
Syntax:
variable operator= constant/expression;
Example:
sum = sum + rem;
is also written as
sum += rem;
Increment and Decrement Operators
 C supports two powerful operators called increment and decrement operators used
to increase/decrease the value of its operand by 1 respectively.
 It is denoted as ++ and --.
 These are unary operators.
 The operator ++ adds 1 to its operand.
 The operator -- subtracts 1 from its operand.
 Consider an operand ‘m’
 Increment of m is denoted as m++.
 Decrement of m is denoted as m--.
Increment/ Decrement operators are in two different forms:
1. Preincrement/Postincrement denoted as ++m / m++
2. Predecrement/Postdecrement denoted as --m / m--
Preincrement or Predecrement, increments/decrements the value first by 1, later it assigns
it to the operand.
Example:
suppose
m = 5;
y = ++m;
The value of m = 6, y = 6.
Postincrement or Postdecrement, assigns the value first, later it is incremented /
decremented by 1.
Example:
suppose
m = 5;
y = m++;
The value of m = 6 and y = 5.
Note:
Evaluating post and pre-increment together
Precedence of postfix ++ is more than prefix ++ and their associativity is also different.
Associativity of prefix ++ is right to left and associativity of postfix ++ is left to right.
 Associativity of postfix ++ is left to right
 Associativity of prefix ++ is right to left
Conditional Operator:
 The ternary operator pair ‘?:’ is known as conditional operator.
 It is called ternary, since it requires three operands to perform an operation.
 It is similar to if statements in C.
 This operator is used to construct conditional expressions of the following form:
Syntax:
expr1 ? expr2 : expr3;
Here, expr1 -> Boolean condition
expr2 -> statements to be executed when the condition is true.
expr3 -> statements to be executed when the condition is false.
Example:
max = (a>b) ? a : b;
Values of a and b were compared, if a is greater than b then max=a, otherwise max =
b.
Program:
Write a program to check the eligibility of a person for voting or not.
Source Code:
#include<stdio.h>
void main()
{
int age;
printf(“Enter the age of a person:”);
scanf(“%d”, &age);
(age>=18)? printf(“\n Eligible for voting.”) : printf(“\n Not Eligible for voting.”);
}
Output:
Enter the age of a person: 45
Eligible for voting.
Enter the age of a person: 15
Not Eligible for voting.
Bitwise Operators:
 These operators perform manipulation on bits rather than numbers; hence they are
also called bit manipulation operators.
 Following table shows list of Bitwise operators.

OPERATOR MEANING EXAMPLE

>> Right Shift 25 >> 3

<< Left Shift 25 << 3

& Bitwise AND 18 & 5

| Bitwise OR 18 | 5

~ Bitwise NOT ~25

Bitwise XOR (Exclusive


^ 18 ^ 5
OR)
Right Shift (>>):
If the bits of a given number are shifted towards right side then it is called Right
Shifting and the resultant value is called Right Shited Value.
Example:
Suppose x=15 and it should be shifted towards right for 1 time, then it is indicated as
x>>1.
The 16-bit representation of 15 as binary number as follows:

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1

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

Insert 0.
discarded

∴ If x=15 then x>>1 gives 7.


Shortcut to find Right shifted value:
Formula:
Right Shifted Value = n/2s
Here, n -> Given number
s -> No.of times to be shifted.
Example:
Suppose, n=15 and s=2 then
Right Shifted Value = 15/21 = 15/2 = 7
Left Shift (<<):
If the bits of a given number are shifted towards left side then it is called Left Shifting
and the resultant value is called Left Shited Value.
Example:
Suppose x=15 and it should be shifted towards left for 1 time, then it is indicated as
x<<1.
The 16-bit representation of 15 as binary number as follows:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1

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

∴ If x=15 then x<<1 gives 30 .


Shortcut to find Left shifted value:
Formula:
Left Shifted Value = n*2s
Here, n -> Given number
s -> No.of times to be shifted.
Example:
Suppose, n=15 and s=2 then
Left Shifted Value = 15*21 = 15*2 = 30
Bitwise AND (&):
This operator performs ANDing of corresponding bits in two binary numbers.
Bitwise AND Table:
P Q P&Q
0 0 0
0 1 0
1 0 0
1 1 1
Example:
Consider m=28 and n=15 then m&n= 12
m=28 => 1 1 1 0 0
n= 15 => 0 1 1 1 1
m & n => 0 1 1 0 0 =>12
Bitwise OR (|):
This operator performs ORing of corresponding bits in two binary numbers.
Bitwise OR Table:
P Q P|Q
0 0 0
0 1 1
1 0 1
1 1 1
Example:
Consider m=28 and n=15 then m|n= 31
m=28 => 1 1 1 0 0
n= 15 => 0 1 1 1 1
m | n => 1 1 1 1 1 =>31
Bitwise XOR (^):
This operator performs XORing of corresponding bits in two binary numbers.
Bitwise XOR Table:
P Q P^Q
0 0 0
0 1 1
1 0 1
1 1 0
Example:
Consider m=28 and n=15 then m^n= 19
m=28 => 1 1 1 0 0
n= 15 => 0 1 1 1 1
m ^ n => 1 0 0 1 1 =>19
Bitwise NOT (~):
This operator performs NEGATION (COMPLEMENTING) of bits in a binary number.
Bitwise NOT Table:
P ~P
0 1
1 0
Example:
Consider m=28 then ~m = 3
m=28 => 1 1 1 0 0
~m => 0 0 0 1 1 => 3
Special Operators
C supports three special operators: comma(,), sizeof( ) and Address (&) operators.
Comma Operator (,):
This operator is used as a separator to separate variables, elements etc.
It is denoted by ‘ , ‘.
Ex: int a, b, c;
{ 10, 25, 32, 57 }
sizeof( ) operator:
This operator returns the size of any given data type like variable, array, pointer, structure,
union at any point of time in terms of bytes.
Syntax:
sizeof(datatype);
data type => any data type supported by C.
Examples:
1. m= sizeof(int); gives m=2
2. float num, m; m = sizeof(num); it gives m=4.
Address Operator:
This operator returns the memory address of a given variable. Once a variable is declared
sufficient memory gets allocated to the variable, each memory location is identified by a
unique memory address, to know the address of a variable; the address operator will be
used.
It is denoted by ‘&’.
Address operator returns an unsigned integer value.
Syntax:
&variable_name;
Example:
int num;
Address of num in represented as &num.
Program:
Write a program to illustrate sizeof( ) and Address operator.
Source Code:
#include<stdio.h>
void main()
{
int num;
float avg;
long fact;
char ch;
double per;
printf(“\n Size of num is: %d \t Address of num is: %u”, sizeof(num), &num);
printf(“\n Size of avg is: %d \t Address of avg is: %u”, sizeof(avg), &avg);
printf(“\n Size of fact is: %d \t Address of fact is: %u”, sizeof(fact), &fact);
printf(“\n Size of ch is: %d \t Address of ch is: %u”, sizeof(ch), &ch);
printf(“\n Size of per is: %d \t Address of per is: %u \n”, sizeof(per), &per);
}
Output:
Size of num is: 2 Address of num is: 6356750
Size of avg is: 4 Address of avg is: 6356744
Size of fact is: 4 Address of fact is: 6356740
Size of ch is: 1 Address of ch is: 6356739
Size of per is: 8 Address of per is: 6356728
Type Conversion
When variables and constants of different types are combined in an expression then they
are converted to same data type. The process of converting one type into another is called
type conversion.
Type conversion in c can be classified into the following two types:
1. Implicit type conversion
2. Explicit type conversion
1. Implicit type conversion
When the type conversion is performed automatically by the compiler without
programmers intervention, such type of conversion is known as implicit type
conversion or type promotion.
The compiler converts all operands into the data type of the largest operand.
The sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
1. If either of the operand is of type long double, then others will be converted to long
double and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to
unsigned long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
1. if a long int can represent all values of an unsigned int, the unsigned int is
converted to long int.
2. otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then other will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.
Note:
 It should be noted that the final result of expression is converted to type of
variable on left side of assignment operator before assigning value to it.
 Conversion of float to int causes truncation of fractional part.
 Conversion of double to float causes rounding of digits.
 Conversion of long int to int causes dropping of excess higher order bits.

Example:
1. Consider the following expression:
4.5 * 2 + 3.5 = 12.5
Here, 4.5 is floating-point value
2 is an integer
3.5 is floating-point value
According to the hierarchy shown in above figure, float is the higher type than integer,
hence 2 implicitly converted to float, then floating-point operation will be performed and
the result is also floating-point i.e; 12.5
2.

2. Explicit Type Conversion


We can also force an expression to be of a specific type by using a cast.
The type conversion performed by the programmer by posing the data type of the
expression of specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
Syntax:
(data_type)expression;
where, data_type is any valid c data type
expression may be constant, variable or expression.
Example-1:
x=(int) a+b*d;
Example-2:
float y;
y = 27/2;
Here, the data type of the result in RHS is integer, since integer division operation will be
performed, and the result is also integer.
∴ 27/2 = 13 but not 13.5
since the variable in the LHS is of float type, hence integer automatically converted to float
as 13.000000
∴ y = 13.000000
Hence to get floating- point value as a result it is required to type cast it, since integer
cannot be automatically converted to float.
The above statement can be rewritten as:
y = (float) 27/2;
Now the value of y is 13.500000
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.

Precedence and Associativity of operators


Precedence and Associativity of operators defines the order of evaluation of an
expression. If an expression contains multiple operators, then the precedence and
associativity of operators determines which operation will be performed first and next.
Precedence of operators:
Precedence of operators categorizes all operators into some groups according to the priority
or precedence.
Example:
In case of Arithmetic Operators;
* / % has high precedence than + and -
Associativity of operators:
Associativity of operators is required when two or more operators having same precedence
appeared in an expression.
Example:
The associativity of * / % is Left to Right.

Operators Meaning Associativity Precedence


() Function Call
[] Array Expression
{} Scope of the block Left to Right 1
-> Structure Operator
. Member Operator
+ Unary Plus
- Unary Minus
++ Increment
-- Decrement
! Logical NOT
Right to Left 2
~ Bitwise NOT
* Pointer operator
& Address operator
sizeof Size of an object
(type) Type casting
* Multiplication
/ Division Left to Right 3
% Modulo Division
+ Addition
Left to Right 4
- Subtraction
<< Left Shift
Left to Right 5
>> Right Shift
< Less than
<= Less than or Equals to
Left to Right 6
> Greater than
>= Greater than or Equals 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

?: Conditional Operator Left to Right 13

= *= += -=
<<= >>=
Assignment Operators Right to Left 14
&&= ||= &=
|= ^=

, Comma Left to Right 15

Examples:
1. Find x where x = 4/2+5*3-6+2*4
x=4/2+5*3–6+2*4
i
=2+5*3–6+2*4
ii
= 2 + 15 – 6 + 2 * 4
iii
= 2 + 15 – 6 + 8
iv
= 17 - 6 + 8
v
= 11 + 8
vi
= 19
2. Find y where y = 2 + 30/6+5*2*3+40/5+6
y = 2 + 30 / 6 + 5 * 2 * 3 + 40 / 5 + 6
= 2 + 5 + 5 *2 * 3 + 40 / 5 + 6
= 2 + 5 + 10 * 3 + 40 / 5 + 6
= 2 + 5 + 30 + 40 / 5 + 6
= 2 + 5 + 30 + 8 + 6
= 7 + 30 + 8 + 6
= 37 + 8 + 6
= 45 + 6
= 51

You might also like