0% found this document useful (0 votes)
39 views

Chapter 9 Introduction To C@4th Nov

Uploaded by

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

Chapter 9 Introduction To C@4th Nov

Uploaded by

kavitha
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 46

Computer

Fundamentals and
Programming in C
2nd Edition
Reema Thareja

1
© Oxford University Press 2016. All rights reserved.
CHAPTER 9
INTRODUCTION TO C

© Oxford University Press 2016. All rights reserved.


INTRODUCTION
• C was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories
• C was initially developed for writing system software (It helps the
computer work and manage its resources. It controls the hardware
and ensures that everything runs smoothly. Ex. OS, Device drivers).
system software helps the computer run, while application
software helps you do things on the computer, like writing,
browsing, or playing music.
• Today, C has become a popular language and various software
programs are written using this language.
• Many other commonly used programming languages such as C++
and Java are also based on C

© Oxford University Press 2016. All rights reserved.


INTRODUCTION
Characteristics of C
• A high-level programming language
• Small size. C has only 32 keywords. This makes it relatively easy to learn
• Makes extensive use of function calls
• C is well suited for structured programming.
• Stable language. C is considered stable because it has been around for decades with very few changes.
• Quick language. C is efficient and provides fast execution times, which is one of the reasons why it's used in system-level
programming and embedded systems.

• Facilitates low level (bitwise) programming. C allows direct manipulation of hardware and memory
through bitwise operators, providing greater control and efficiency at a low level, closer to machine code.

• Supports pointers to refer computer memory, array, structures and functions.


• C is a core language. C forms the basis for many other languages (like C++, Java, Python). Many concepts and syntax in
these languages are derived from C.

• C is a portable language. C programs can be compiled and run on various computer architectures with minimal
changes, making it highly portable.

• C is an extensible language
© Oxford University Press 2016. All rights reserved.
main()

USES OF C {
Statement 1;
Statement 2;
• C language is primarily used for system programming. The portability, efficiency, the ……………
……………
ability to access specific hardware addresses and low runtime demand on system Statement N;
}
resources makes it a good choice for implementing operating systems and embedded Function1()
system applications. {
Statement 1;
• C has been so widely accepted by professionals that compilers, libraries, and Statement 2;
……………
interpreters of other programming languages are often implemented in C. ……………
Statement N;
• For portability and convenience reasons, C is sometimes used as an intermediate }
Function2()
language by implementations of other languages. Example of compilers which use C {
Statement 1;
this way are BitC, Gambit, the Glasgow Haskell Compiler, Squeak, and Vala. Statement 2;
……………
• C is widely used to implement end-user applications. ……………
Statement N;
}
………………….
………………….
FunctionN()
STRUCTURE OF A C PROGRAM {
Statement 1;
Statement 2;
……………
……………
Statement N;
}
A C program contains one or more functions
The statements in a C program are written in a logical sequence to perform a specific task.
Execution of a C program begins at the main() function
You can choose any name for the functions. Every program must contain one function that has its name
as main().

© Oxford University Press 2016. All rights reserved.


Structure of C Language program
Preprocessor directives

Global declarations
main( )
{
Local declarations
Statements
}
Function 1()
{
Local declarations
Statements
}
-------------------------------
Function N()
{
Local declarations
Statements
}
© Oxford University Press 2016. All rights reserved.
YOUR FIRST C PROGRAM

// This is my first program in C

#include<stdio.h>
int main()
{
printf("\n Welcome to the world of C ");
return 0;
}

© Oxford University Press 2016. All rights reserved.


Structure of C Program

1) Preprocessor directive & header file // #include<stdio.h>

// variable that is used throughout the program, for all the


2) Global variable declaration
modules/blocks of the program.

3) main function // two ways main function can be written .


void main()/ main()/ int main()
{
Local variable declaration
Statements  input , processing, output
Return statement // w.r.to main function

// user only defines the steps of the function and also defines the
4) User defined function name of the function

5) Comment lines // to explain the meaning of the statement… syntax: //comment or


/*comment*/

© Oxford University Press 2016. All rights reserved.


Comment line: It indicates the purpose of the program. It is represented as
/*……………………………..*/

•Comment line is used for increasing the readability of the program.


•It is useful in explaining the program and generally used for documentation.
•Comment line can be single or multiple line but should not be nested.
•It can be anywhere in the program except inside string constant & character
constant.

Preprocessor Directive: #include<stdio.h> tells the compiler to include


information about the standard input/output library.
•It is also used in symbolic constant such as #define PI 3.14(value).
•The stdio.h (standard input output header file) contains definition
&declaration of system defined function such as printf( ), scanf( ) etc.
Generally printf() function used to display and scanf() function used to read value

© Oxford University Press 2016. All rights reserved.


Global Declaration: This is the section where variable are
declared globally so that it can be access by all the
functions used in the program. And it is generally
declared outside the function.
main(): It is the user defined function and every
function has one main() function from where actually
program is started and it is encloses within the pair of
curly braces. The main( ) function can be anywhere in
the program , but in general practice it is placed in the
first position.
Syntax :
main()
{ …….. …….. …….. void main(void )
} int main( ) or
{ void main()
return 0; {
} printf (“C
language”);
}
© Oxford University Press 2016. All rights reserved.
Examples :

stdio.h : standard input & output ( functions like printf() ,scanf() are defined.)

conio.h : console input & output. ( getch(), clrscr () are defined.)

string.h : for string handling functions. ( )

math.h : Math functions like pow(), sin(), log() , sqrt() are defined.

stdlib.h : Library functions like exit (),

© Oxford University Press 2016. All rights reserved.


Formatted Input & output functions :
C language supports two formatting functions : printf () and scanf ().
•printf() is used to convert text data stored in the program onto text stream for o/p to the
monitor.
•scanf() is used to convert text stream coming from keyboard to data values and stores
them in program variables.

These are called as formatted Input and output functions because they have special
format to read and write The text from streams and then converting them into binary
stream.

Syntax of printf() :
printf ( “ control string” , var1, var2 …..varn).
Printf (“Hello welcome to C program”)
Printf ( “ %d %d %f ” , a , b , c), where a and b are integer variables and c is float
variable.
%d and %f are known as format specifiers.

Syntax of scanf() : scanf ( “ Control string” , & var1, & var2,.. ,& var n). Format
specifiers : For integer variables ------ %d
For float variables --------%f, For character variables ------- %c
© Oxford University Press 2016. All rights reserved.
Input Statements ( reading input)

© Oxford University Press 2016. All rights reserved.


Output Statement ( displaying output,
displaying a message)
printf()

i)To display a message

Syntax: printf(“message”); //displaying any message

ii)To display a value

Syntax: printf(“format specifier”, name of variable holding


the value);
//format specifier: int-%d, float-%f, char-%c

Example: printf(“%d”, a);


// displaying integer value which is stored
inside variable ‘a’

© Oxford University Press 2016. All rights reserved.


Executing a C Program

In order to execute or run a C program the following steps


needs to be followed -
1.Edit the program using an editor // gedit programname.c
2.Save the program with a proper name.
3.Compile the program // cc programname.c
4.Run the program.// ./a.out

© Oxford University Press 2016. All rights reserved.


Program to Display "Hello,
World!"
• The #include is a preprocessor command that tells
#include the compiler to include the contents of stdio.h
<stdio.h>
(standard input and output) file in the program.
int main()
{
printf("Hello, • The stdio.h file contains functions such as scanf()
World!"); return and printf() to take input and display output
0; respectively.
}
• If you use the printf() function without writing
#include <stdio.h>, the program will not compile.
Outp
ut
Hello, The execution of a C program starts from the main()
World! function.

• printf() is a library function to send formatted


output to the screen. In this program, printf()
displays Hello, World! text on the screen.

• The return 0; statement is the "Exit status" of the


program. The program
© Oxford University ends
Press 2016. All rights with this statement.
reserved.
FILES USED IN A C PROGRAM
Files in a C program

Source File Header File Object File Executable File

Source code file


• The source code file contains the source code of the program. The file extension of any C source code file
is “.c”. This file contains C source code that defines the main function and maybe other functions. The
main() is the starting point of execution when you successfully compile and run the program. A C
program in general may include even other source code files (with the file extension .c).
Header Files
• When working with large projects, it is often desirable to make sub-routines and store them in a
different file known as header file. The advantage of header files can be realized when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes be reflected in all other
programs.
• Conventionally, header files names ends with a “.h” extension and its name can use only letters, digits,
dashes, and underscores.
• While some standard header files are available in C, but the programmer may also create his own user
defined header files

© Oxford University Press 2016. All rights reserved.


FILES USED IN A C PROGRAM
Object Files
• Object files are generated by the compiler as a result of processing the source code file. Object files
contain compact binary code of the function definitions. Linker uses this object file to produce an
executable file (.exe file) by combining the of object files together. Object files have a “.o” extension,
although some operating systems including Windows and MS-DOS have a “.obj” extension for the object
file.
Binary Executable File
• The binary executable file is generated by the linker. The linker links the various object files to produce a
binary file that can be directly executed. On Windows operating system, the executable files have “.exe”
extension.

COMPILING AND EXECUTING C PROGRAMS


The compilation process in the figure 2.5 is done in two steps. In the first step, the preprocessor program
reads the source file as text, and produces another text file as output. Source code lines which begin
with the hash symbol are actually not written in C but in the preprocessor language. The output of the
preprocessor is a text file which does not contain any preprocessor statements. This file is ready to be
processed by the compiler. The linker combines the object file with library routines (supplied with the
compiler) to produce the final executable file.

The preprocessor in programming is a tool that processes the source code before it is
passed to the compiler. It handles directives, typically starting with #, and performs
various transformations. In C, C++, and similar languages, the preprocessor plays an
essential role in preparing the code for compilation .

© Oxford University Press 2016. All rights reserved.


COMPILING AND EXECUTING C PROGRAMS

Source Pre- Compile Object


File proce r Files
ss
Library Library Linker Executable
Files Files Files

Source Pre- Compile Object


File proc r Files
ess
Library
Files

© Oxford University Press 2016. All rights reserved.


USING COMMENTS
• It is a good programming practice to place some comments in the
code to help the reader understand the code clearly.
• Comments are just a way of explaining what a program does. It is
merely an internal program documentation.
• The compiler ignores the comments when forming the object file.
This means that the comments are non-executable statements.
C supports two types of commenting.
• // is used to comment a single statement. This is known as a line
comment. A line comment can be placed anywhere on the line and it
does not require to be specifically ended as the end of the line
automatically ends the line.
• /* is used to comment multiple statements. A /* is ended with */ and
all statements that lie within these characters are commented.

© Oxford University Press 2016. All rights reserved.


TOKENS
• Tokens are basic building blocks in C Language.
• These are smallest individual units in a C Program.
• There are 6 main types of tokens available in C.
-> Keywords
-> Variables
-> Constants
-> Strings
-> Special Characters
-> Operators

© Oxford University Press 2016. All rights reserved.


CHARACTER SET IN C
• In C a character means any letter from English alphabet, a
digit or a special symbol used to represent information.
• The character set in C is defined as
-> English alphabet: Includes lower case and uppercase
letters (a-z and A-Z)
-> Digits : Includes numerical values from 0-9
-> Special Characters: Include symbols like ~,!, @, #, $, %,
^, &,*,(,),_,- ,+,=,/,*,?,<,>, +,:,;, ‘’, “ “, -

© Oxford University Press 2016. All rights reserved.


CHARACTER SET IN C
• -> Whitespace characters: These characters are used to print blank
space on the screen.
\b – Blank space: Moves cursor back to one char
\t-Horizontal tab: Moves cursor forward to tab space
Moves the cursor down to the next vertical tab
\v – vertical return:
position, similar to a new line, but doesn't start at the
beginning of the line.

\r- carriage return: Moves the cursor to the beginning of the current
line without advancing to the next line.
\f – form feed: Advances the cursor to the start of the next page or
screen or clears the current display.
\n – new line: moves the cursor to the new line
-> Escape Sequence: They allow programmers to control formatting, insert
special characters, and handle things like newlines, tabs, and quotes within strings.

© Oxford University Press 2016. All rights reserved.


KEYWORDS
• C has a set of 32 reserved words often known as keywords. All
keywords are basically a sequence of characters that have a fixed
meaning. By convention all keywords must be written in lowercase
(small) letters.
• Example: auto, break, case, char, constant, continue, default, double,
else, enum, extern, float, for, goto, int, long, register, return, short,
signed, sizeof, struct, switch, typedef, union, unsigned, void, volatile,
do, if, static, while

© Oxford University Press 2016. All rights reserved.


IDENTIFIERS
• Identifiers are names given to program elements such as variables, arrays and
functions.
Rules for forming identifier name
 it cannot include any special characters or punctuation marks (like #, $, ^, ?, .,
etc) except the underscore"_".
 There cannot be two successive underscores
 Keywords cannot be used as identifiers
 The names are case sensitive. So, example, “FIRST” is different from “first” and
“First”.
 It must begin with an alphabet or an underscore.
 It can be of any reasonable length. Though it should not contain more than 31
characters.
Example of valid identifiers: roll_number, marks, name, emp_number, basic_pay,
HRA, DA, dept_code
Example of In-valid identifiers: 23_student, %marks, @name, #emp_number,
basic.pay, -HRA, (DA), &dept_code, auto

© Oxford University Press 2016. All rights reserved.


DATATYPES IN C
Signed Data Types
SIZE IN •Can represent both positive and negative
DATA TYPE RANGE
BYTES
numbers.
char 1 -128 to 127
•The first bit (most significant bit) is reserved
unsigned char 1 0 to 255 as the sign bit. If the sign bit is 0, the number
signed char 1 -128 to 127 is positive; if it's 1, the number is negative.
int 2 -32768 to 32767
unsigned int 2 0 to 65535 Unsigned Data Types
signed short int 2 -32768 to 32767
•Can only represent non-negative (positive
and zero) values.
signed int 2 -32768 to 32767
•All bits are used to represent the value, so
short int 2 -32768 to 32767
the range starts from 0 and goes up to a
unsigned short 0 to 65535
2 higher positive value compared to the signed
int
version.
long int -2147483648 to
4
2147483647 Short and Long
unsigned long 0 to 4294967295 •Size and Range: short is smaller and has a
4
int limited range, while long is larger and has a
signed long int
4
-2147483648 to much wider range.
2147483647
•Memory Efficiency: Use short to save
float 4 3.4E-38 to 3.4E+38 memory when working with small values; use
double 8 1.7E-308 to 1.7E+308 long when you need to handle large values.
long double 3.4E-4932 to
10
1.1E+4932

© Oxford University Press 2016. All rights reserved.


VARIABLES IN C
• A variable is defined as a meaningful name given to the data storage location in computer
memory.
• When using a variable, we actually refer to address of the memory where the data is stored. C
language supports two basic kinds of variables.
Numeric Variables: Numeric variables can be used to store either integer values or floating point
values.
• While an integer value is a whole numbers without a fraction part or decimal point, a floating
point number, can have a decimal point in them.
• Numeric values may also be associated with modifiers like short, long, signed and unsigned.
• By default, C automatically a numeric variable signed when we do not specify as
signed/unsigned..

Variables

Numeric Variable Character Variables


© Oxford University Press 2016. All rights reserved.
Character Variables:
Character variables are just single characters enclosed with in single quotes. These can
be any characters from the ASCII char set – letters (‘a’, ‘A’), numerals (‘2’) or special
characters (‘&’).
•In C the number included in quotes is not same as without quotes. (2 is an integer but
‘2’ is treated as a character)

Declaring Variables:
To declare a variable specify data type of the variable followed by its name.
Variable declaration always ends with a semicolon.

int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;

© Oxford University Press 2016. All rights reserved.


In C, variables can be declared anywhere in the program but First variables should
be declared before using them. Second, variables should be declared closest to
their first point of use so that easier to maintain.
C allows multiple variables of the same type to be declared like
float temp_in_Celsius, temp_in_farenheit;

Variables declared inside the function called as local variables and outside all the
functions, called as global variables.
Initializing Variables:
We can also initialize variables with some value.
int emp_num=7;
float salary=2156.35;
char grade=‘A’
int count, flag=1; will initialize only one variable flag to 1.
int count=0, flag=1; will initialize count to 0 and flag to 1.
© Oxford University Press 2016. All rights reserved.
CONSTANTS
• Constants are identifiers whose value does not change.
• Constants are used to define fixed values like mathematical constant PI or the
charge on an electron so that their value does not get changed in the program even
by mistake.
How to Define Constants in C: 4 types – int, floating point, char, string
1.Using #define Directive:
•The #define directive is used to create named constants.
#define PI 3.14

2. Using Const keyword


const int students=30; //integer constant
Here students is an integer constant with a value 30. You can’t change this value
anywhere else in the code.

const float pi=3.14; //floating point constant


const char grade=‘A’ //char constant
const char mystring[]=“This is string constant” //string constant.
Should be enclosed in double quotes.
© Oxford University Press 2016. All rights reserved.
CONSTANTS

Rules that needs to be applied to a #define statement which defines a constant.


• Constant names are usually written in capital letters to visually distinguish them
from other variable names which are normally written in lower case characters.
Note that this is just a convention and not a rule.
• No blank spaces are permitted in between the # symbol and define keyword
• Blank space must be used between #define and constant name and between
constant name and constant value
• #define is a pre-processor compiler directive and not a statement. Therefore, it
does not end with a semi-colon.

© Oxford University Press 2016. All rights reserved.


Input/Output Statements in C:
Streams
•A stream acts in two ways. It is the source of data as well as the destination of
data.
•C programs input data and output data from a stream. Streams are associated with
a physical device such as the monitor or with a file stored on the secondary
memory.
•In a text stream, sequence of characters is divided into lines with each line being
terminated with a new-line character (\n). On the other hand, a binary stream
contains data values using their memory representation.
•Although, we can do input/output from the keyboard/monitor or from any file but
in this chapter we will assume that the source of data is the keyboard and
destination of the data is the monitor. Streams in a C
program
Keyboard Input text Data
stream
Text Stream Binary Stream

Monitor Input text Data


stream
© Oxford University Press 2016. All rights reserved.
THE PRINTF() FUNCTION
• The printf function is used to display information required to the user and also
prints the values of the variables. Its syntax can be given as
printf (“conversion string”, variable list);
• The parameter control string is a C string that contains the text that has to be
written on to the standard output device. The prototype of the control string can
be given as below %[flags][width][.precision][length]type specifier
length Description
When the argument is a short int or unsigned short
flag description h
int.
Left-justify within the data given field l
When the argument is a long int or unsigned long int
- for integer specifiers.
width
When the argument is a long double (used for floating
Displays the data with its numeric sign L
+ point specifiers)
(either + or -) specifier Qualifying Input
Used to provide additional specifiers c For single character
like o, x, X, 0, 0x or 0X for octal and For decimal values
# d
hexa decimal values respectively for
values different than zero. f For floating point numbers
E, e Floating point numbers in exponential format
The number is left-padded with zeroes
0 G, g Floating point numbers in the shorter of e format
(0) instead of spaces
o For Octal number.
s For a sequence of (string of) characters
u For Unsigned decimal value
X,x For Hexadecimal value.
© Oxford University Press 2016. All rights reserved.
THE SCANF() FUNCTION
• The scanf() is used to read formatted data from the keyboard. The syntax of the scanf() can be given as,
scanf (“control string”, arg1, arg2, ………….argn);
• The control string specifies the type and format of the data that has to be obtained from the keyboard and stored in the
memory locations pointed by the arguments arg1, arg2,…, argn. The prototype of the control string can be give as:
[=%[*][width][modifiers]type specifier]
• * is an optional argument that suppresses assignment of the input field. That is, it indicates that data should be read from the
stream but ignored (not stored in the memory location).
• width is an optional argument that specifies the maximum number of characters to be read.
• modifiers is an optional argument that can be h, l or L for the data pointed by the corresponding additional arguments.
Modifier h is used for short int or unsigned short int, l is used for long int, unsigned long int or double values. Finally, L is used
long double data values.
• Type is same as specifier in printf()
• EXAMPLE OF printf() and scanf():
• int num;
• float fnum;
• char ch, str[10];
• double dnum;
• short snum;
• long int lnum;
• printf(“\n Enter the values : “);
• scanf("%d %f %c %s %e %hd %ld", &num, &fnum, &ch, str, &dnum, &snum, &lnum);
• printf("\n num = %d \n fnum = %.2f \n ch = %c \n str = %s \n dnum = %e \n snum = %hd \n lnum = %ld", num, fnum, ch, str, dnum, snum, lnum);

© Oxford University Press 2016. All rights reserved.


OPERATORS IN C
• C language supports a lot of operators to be used in expressions. These operators can be
categorized into the following major groups:
• Arithmetic operators
• Relational Operators
• Equality Operators
• Logical Operators
• Unary Operators
• Conditional Operators
• Bitwise Operators
• Assignment operators
• Comma Operator OPERATION OPERATOR SYNTAX COMMENT RESULT
• Sizeof Operator Multiply * a * b result = a * b 27

Divide / a / b result = a / b 3
ARITHMETIC
Addition + a + b result = a + b 12
OPERATORS
Subtraction - a - b result = a – b 6

Modulus % a % b result = a % b 0

© Oxford University Press 2016. All rights reserved.


RELATIONAL OPERATORS
Also known as a comparison operator, it is an operator that compares two values. Expressions that
contain relational operators are called relational expressions. Relational operators return true or
false value, depending on whether the conditional relationship between the two operands holds or
not.
OPERATOR MEANING EXAMPLE

< LESS THAN 3 < 5 GIVES 1

> GREATER THAN 7 > 9 GIVES 0

>= LESS THAN OR EQUAL TO 100 >= 100 GIVES 1

<= GREATER THAN EQUAL TO 50 >=100 GIVES 0

EQUALITY OPERATORS
• C language supports two kinds of equality operators to compare their operands for strict equality or
inequality. They are equal to (==) and not equal to (!=) operator.


The equality operators have lower precedence than the relational operators.

OPERATOR MEANING

== RETURNS 1 IF BOTH OPERANDS ARE EQUAL, 0 OTHERWISE


!= RETURNS 1 IF OPERANDS DO NOT HAVE THE SAME VALUE, 0 OTHERWISE

© Oxford University Press 2016. All rights reserved.


LOGICAL OPERATORS
• C language supports three logical operators. They are- Logical AND (&&), Logical OR (||) and Logical NOT
(!).
• As in case of arithmetic expressions, the logical expressions are evaluated from left to right.

A B A &&B A B A || B A !A
0 0 0 0 0 0
0 1
0 1 0 0 1 1

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

UNARY OPERATORS
Unary operators act on single operands. C language supports three unary operators. They are
unary minus (-), increment(++) and decrement operators(--).
When an operand is preceded by a minus sign, the unary operator negates its value.
The increment operator is a unary operator that increases the value of its operand by 1. Similarly,
the decrement operator decreases the value of its operand by 1. For example,
int x = 10, y;
y = x++;
is equivalent to writing
y = x;
x = x + 1; whereas, y = ++x; int a, b=10;
is equivalent to writing a = -(b);
x = x + 1; The result is a=-10 bcz variable b has positive
value
y = x; © Oxford University Press 2016. All rights reserved.
CONDITIONAL OPERATOR
• The conditional operator operator (?:) is just like an if .. else statement that can be written
within expressions.
• The syntax of the conditional operator is
exp1 ? exp2 : exp3
Here, exp1 is evaluated first. If it is true then exp2 is evaluated and becomes the result of the
expression, otherwise exp3 is evaluated and becomes the result of the expression. For
example,
large = ( a > b) ? a : b
• Conditional operators make the program code more compact, more readable, and safer to use
as it is easier both to check and guarantee that the arguments that are used for evaluation.
• Conditional operator is also known as ternary operator as it is neither a unary nor a binary
operator; it takes three operands.
Example : Int a=5, b=3, c=7, small;
small = (a<b ? (a < c ? a : c) : (b < c ? b : c ));

© Oxford University Press 2016. All rights reserved.


BITWISE OPERATORS
• Bitwise operators perform operations at bit level. These operators include: bitwise
AND, bitwise OR, bitwise XOR and shift operators.
• The bitwise AND operator (&) is a small version of the boolean AND (&&) as it
performs operation on bits instead of bytes, chars, integers, etc.
• The bitwise OR operator (|) is a small version of the boolean OR (||) as it performs
operation on bits instead of bytes, chars, integers, etc.
• The bitwise NOT (~), or complement, is a unary operation that performs logical
negation on each bit of the operand. By performing negation of each bit, it actually
produces the ones' complement of the given binary value.
• The bitwise XOR operator (^) performs operation on individual bits of the operands.
The result of XOR operation is shown in the table
A B A^B
int x = 5; // Binary: 0101 0 0 0
int y = 3; // Binary: 0011
0 1 1
int result_and = x & y; // Result: 0001 (1 in decimal)
1 0 1
int result_or = x | y; // Result: 0111 (7 in decimal)
int result_xor = x ^ y; // Result: 0110 (6 in decimal) 1 1 0

int result_not = ~x; // Result: Inverts all bits of x 1010


int result_shift_left = x << 1; // Result: 1010 (10 in decimal)
int result_shift_right = x >> 1; // Result: 0010 (2 in decimal)

© Oxford University Press 2016. All rights reserved.


BITWISE SHIFT OPERATORS
In bitwise shift operations, the digits are moved, or shifted, to the left or right.
The CPU registers have a fixed number of available bits for storing numerals,
so when we perform shift operations; some bits will be "shifted out" of the
register at one end, while the same number of bits are "shifted in" from the
other end.
In a left arithmetic shift, zeros are shifted in on the right. For example;
unsigned int x = 11000101;
Then x << 2 = 00010100
If a right arithmetic shift is performed on an unsigned integer then zeros are
shifted on the left.
unsigned int x = 11000101;
Then x >> 2 = 00110001

Ex: a=27 b=39


a & b=
a | b=
~a=
a ^ b=
a << 1= © Oxford University Press 2016. All rights reserved.
ASSIGNMENT OPERATORS
The assignment operator is responsible for assigning values to the variables. While the
equal sign (=) is the fundamental assignment operator, C also supports other
assignment operators that provide shorthand ways to represent common variable
assignments. They are shown in the table.
OPERATO
SYNTAX EQUIVALENT TO MEANING
R
Divides the value of the variable
by the value of an expression
/= variable /= expression variable = variable / expression and assigns the result to the
variable. float a=9.0; b=3.0;
a/=b;
Divides the value of the variable
by the value of an expression
\= variable \= expression variable = variable \ expression
and assigns the integer result to
the variable. int a=9; b=3; a\=b;
*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount© Oxford
variable = variable
University >> amount
Press 2016. All rights reserved.
COMMA OPERATOR
• The comma operator in C takes two operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the
result of the expression.
• Comma separated operands when chained together are evaluated in left-to-right
sequence with the right-most value yielding the result of the expression.
• Among all the operators, the comma operator has the lowest precedence. For
example, int a=2, b=3, x=0; x = (++a, b+=a); Now, the value of x = 6.

SIZEOF OPERATOR
• sizeof is a unary operator used to calculate the sizes of data types.
• It can be applied to all data types. The operator returns the size of the
variable, data type or expression in bytes.
• 'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take. For example,
• sizeof(char) returns 1, that is the size of a character data type. If we
have,
int a = 10;
unsigned int result; result = sizeof(a);
© Oxford University Press 2016. All rights reserved.
TYPE CONVERSION AND TYPE CASTING
• Type conversion and type casting of variables refers to changing a variable of one data
type into another.
• While type conversion is done implicitly, casting has to be done explicitly by the
programmer. We will discuss both of them here.
• Type conversion is done when the expression has variables of different data types. So to
evaluate the expression, the data type is promoted from lower to higher level where
the hierarchy of data types can be given as: double, float, long, int, short and char.
• For example, type conversion is automatically done when we assign an integer value to
a floating point variable. For ex,
float x; int y = 3; x = y;
Now, x = 3.0,

 int a = 5;
 float b = 25, c; ab c
 c = a / b; printf(“%f” , c); 5 25.0 0.25

© Oxford University Press 2016. All rights reserved.


TYPE CONVERSION AND TYPE CASTING

• Type casting is also known as forced conversion. It is done when the value
of a higher data type has to be converted in to the value of a lower data
type. For example, we need to explicitly type cast an integer variable into a
floating point variable.
float salary = 10000.00;
int sal;
sal = (int) salary;
• Typecasting can be done by placing the destination data type in
parentheses followed by the variable name that has to be converted.

 int a = 7, c;
a b c
 float b = 4.0;
 b = a % (int) b; 7 4.0 3
 printf(“%d” , c);
b -> Converted into int & evaluated

© Oxford University Press 2016. All rights reserved.


OPERATOR PRECEDENCE
C operators have two properties: priority/precedence and associativity

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

Ex: variable = expression sum = a +b


Following table provides the Precedence and Associativity of operators:

© Oxford University Press 2016. All rights reserved.


OPERATOR PRECEDENCE
Operator Associativity Precedence (Rank)
( ), [ ] Left to right 1

+, -, ++, -- Right to left 2


!, ~, * ,&

X=3*4+5*6 X = 3 * (4 + 5) * 6 X=3*4%5/2 X = 3 * (4 % 5) / 2
= 12 + 5 * 6 =3*9*6 = 12 % 5 / 2 =3*4/2
= 12 + 30 = 27 * 6 =2/2 =3*2
= 42 = 42 =1 =6

© Oxford University Press 2016. All rights reserved.

You might also like