UNIT 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

Unit 1: Introduction to C

Programming Languages
• Programming languages are used to create programs that control the behavior of a system, to express
algorithms or as a mode of human communication.
• Programming languages have a vocabulary of keywords, syntax and semantics for instructing a
computer to perform specific tasks. Such languages include s BASIC, C, C++, COBOL, FORTRAN,
Ada, and Pascal to name a few.
• While programming languages are easy for the humans to read and understand, the computer
understands the machine language that consists of numbers only.
• In between these two languages, there is assembly language which is similar to machine languages, but
is much easier to program in because they allow a programmer to substitute names for numbers.
• The question of which language is best depends on the following factors:
• The type of computer on which the program has to be executed
• The type of program
• The expertise of the programmer
First Generation: Machine Language

• Machine (or low level) language was used to program the first stored-program computer systems. It is the only
language that the computer understands. All the commands and data values are expressed using 1s and 0s.
• In 1950s each computer had its own native language, and programmers had to combine numbers to represent
instructions such as add and subtract. Although there were similarities between each of the machine language but a
computer could not understand programs written in another machine language
• The main advantage of machine language is that the code can run very fast and efficiently, since it is directly
executed by the CPU.
• However, this language is difficult to learn and is far more difficult to edit if errors occur. Moreover, if new
instructions are to be added into memory at some location, then all the instructions after the insertion point would
have to be moved down to make room in memory to accommodate the new instruction.
• Also code written in machine language is not portable. ue to resolve.
First Generation: Machine Language (Contd..)

• This is an example of a machine


language program that will add two
numbers and find the average.

• It is in hexadecimal notation instead of


binary notation because that is how the
computer presented the code to the
programmer.
Second Generation: Assembly Language
• The second generation includes the assembly language which is a symbolic language that use
symbols to represent machine-language instructions. These languages are closely connected to
machine language and the internal architecture of the computer system on which they are used.
• An assembly language statement consists of a label, an operation code, and one or more operands.
• However, like the machine language, assembly language is also machine-dependent. This makes
the code written in assembly language less portable.
• Code written in assembly language will be very efficient in terms of execution time and main
memory usage as the language is also close to the computer.
• Programs written in assembly language need a translator often known as the assembler to convert
them into machine language.
• Even today, some programmers still use assembly language to write parts of applications where
speed of execution is critical, such as video games
Second Generation: Assembly Language(Contd..)

The following instructions are a part of assembly language code to illustrate addition of two numbers
Third Generation Programming Language
• It is a refinement of 2GL which spurred the great increase in data processing that occurred in the
1960s and 1970s. in these languages, the program statements are not closely related to the internal
characteristics of the computer and is therefore often referred to has high-level languages.
• Generally, a statement written in a high-level programming language will expand into several
machine language instructions.
• 3GLs made programming easier, efficient and less prone to errors. They fall somewhere between
natural languages and machine languages. 3GL includes languages like FORTRAN and COBOL.
• A translator is needed to translate the instructions written in high level language into computer-
executable machine language. Such translators are commonly known as interpreters and
compilers.
• 3GLs makes it easier to write and debug a program and gives the programmer more time to think
about its overall logic. The programs written in such languages are portable between machines.
Fourth Generation: Very High-Level Languages
• 4GLs are nonprocedural languages. When writing code using a procedural language, the
programmer has to tell the computer how a task is done. In striking contrast, while using a
nonprocedural language the programmers define only what they want the computer to do, without
supplying all the details of how it has to be done.

Characteristics of 4GLs include:


• The code is written in English-like sentences;
• The code is easier to maintain
• 4GL code enhances the productivity of the programmers as they have to type fewer lines of code
to get something done. A typical example of a 4GL is the query language that allows a user to
request information from a database with precisely worded English-like sentences.
• Example: Generate a report that displays the total number of students enrolled in each class and in
each semester in a school.
TABLE FILE ENROLLMENT
SUM STUDENTS BY SEMESTER BY CLASS
• 4GLs are still evolving and its only down side is that it does not make efficient use of machine’s
resources. However, the benefit of executing a program fast and easily far outweighs the extra
costs of running it.
Fifth-Generation Programming Language

• 5GLs are centered on solving problems using constraints given to the program, rather
than using an algorithm written by a programmer. They are widely used in artificial
intelligence research. Typical examples of a 5GL include Prolog, OPS5, and Mercury.
• Another aspect of a 5GL is that it contains visual tools to help develop a program. A good
example of a fifth generation language is Visual Basic. 5GLs are designed to make the
computer solve a given problem without the programmer.

Algorithm
• “Algorithm" is a formally defined procedure for performing some calculation. If a procedure is
formally defined, then it must be implemented using a programming language.
• The algorithm gives logic of the program, that is, a step-by-step description of how to arrive at a
solution.
• Algorithm provides a blueprint to write a program to solve a particular problem in finite number of
steps.
• Algorithms are mainly used to achieve software re-use.
• In order to qualify as an algorithm, a sequence of instructions must process the following
characteristics:
• Instructions must be precise
• Instructions must be unambiguous
• Not even a single instruction must be repeated infinitely
• After the algorithm gets terminated, the desired result must be obtained
Key Features of an Algorithm
• Any algorithm has a finite number of steps and some steps may involve decision
making, repetition.
• Broadly speaking, an algorithm exhibits three key features that can be given as:
• Sequence: Sequence means that each step of the algorithm is executed in the specified
order.
• Decision: Decision statements are used when the outcome of the process depends on some
condition.
• Repetition: Repetition which involves executing one or more steps for a number of times
can be implemented using constructs like the while, do-while and for loops. These loops
executed one or more steps until some condition is true.
Algorithm to add two numbers
• Step 1: Input first number as A
• Step 2: Input second number as B
• Step 3: Set Sum = A + B
• Step 4: Print Sum
• Step 5: End
Flowchart

• A flow chart is a graphical or symbolic representation of a process. They are basically used to design
and document complex processes to help the viewers to visualize the logic of the process so that they
can gain a better understanding of the process and find flaws, bottlenecks, and other less-obvious
features within it.
• Start and end symbols also known as the terminal symbol is always the first and the last symbol in a
flowchart.
• Generic processing step also called an activity is represents instructions like add a to b, save the result.
• Input/ Output symbols are represented as a parallelogram and are used to get input from users or
display the results to them.
• A Conditional or decision symbol is used to depict a Yes/No question or True/False test.
• Labeled connectors represented by an identifying label inside a circle are used in complex or multi-
sheet diagrams to substitute for arrows.
Flowchart to add two numbers

Start

Read the values


of A and B

Calculate SUM = A + B

Print SUM

End
Advantages of Flowcharts

• A flowchart is a diagrammatic representation that illustrates the sequence of steps that must
be performed to solve a problem. They are usually drawn in the early stages of formulating
computer solutions to facilitate communication between programmers and business people.
• Flowcharts help programmers to understand the logic of complicated and lengthy problems.
• They help to analyze the problem in a more effective manner
• Flowchart is also used for program documentation. Flowchart can be used to debug
programs that have error(s).
Limitations of using Flowcharts

• Drawing flowcharts is a laborious and a time consuming activity.


• Flowchart of a complex program becomes, complex and clumsy. At times, a little bit of
alteration in the solution may require complete re-drawing of the flowchart
• Essentials of what is done may get lost in the technical details of how it is done.
• There are no well defined standards that limits the details that must be incorporated in a
flowchart
Pseudocode
• It is a form of structured English that describes algorithms. It facilitates the designers to focus on
the logic of the algorithm without getting bogged down by the details of language syntax.
• Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language. It is meant for human reading rather than
machine reading, so it omits the details that are not essential for humans. Such details
include keywords, variable declarations, system-specific code and subroutines.
• It is commonly used in textbooks and scientific publications for documenting algorithms, and for
sketching out the program structure before the actual coding is done. This would help even the
non-programmers to understand the logic of the designed solution.
• There are no standards defined for writing a pseudocode because a pseudocode is not an
executable program.
• Flowcharts can be considered as a graphical alternative to pseudocode, but are more spacious on
Pseudocode for adding two numbers
1. Read A
2. Read B
3. Calculate SUM = A + B
4. Print SUM
5. End
To check the equality of two
numbers
Start
Step 1: Input first number as A 1. Read first number as A
Step 2: Input second number as B 2. Read second number as B
Read the values
Step 3: IF A = B 3. IF A = B
of A and B
Print “Equal” Print “Equal”
ELSE ELSE
Print “Not equal” Is Print Not Print “Not Equal
[END of IF] A=B? Equal ENDIF
Step 4: End Yes 4. End
Print
Equal

End
Introduction to C

● C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories


● C was initially developed for writing system software
● 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
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. In this programming approach,
● Unlike PASCAL it supports loose typing (as a character can be treated as an integer and
vice versa)
● Structured language
● Stable language.
● Quick language
● Facilitates low level (bitwise) programming
● Supports pointers to refer computer memory, array, structures and functions.
● C is a core language
● C is a portable language.
● C is an extensible language
● C is 2nd Best language for any given programming task.
Uses of C
• C language is primarily used for system programming. The portability,
efficiency, the ability to access specific hardware addresses and low runtime
demand on system resources makes it a good choice for implementing operating
systems and embedded system applications.
• C has been so widely accepted by professionals that compilers, libraries, and
interpreters of other programming languages are often implemented in C.
• For portability and convenience reasons, C is sometimes used as an intermediate
language by implementations of other languages. Example of compilers which
use C this way are BitC, Gambit, the Glasgow Haskell Compiler, Squeak, and
Vala.
• C is widely used to implement end-user applications.
Structure of C Program
main()
{
Statement 1;
Statement 2;
……………
• A C program is composed of preprocessor commands, a global declaration ……………
Statement N;
section, and one or more functions. }
Function1()
• Function is defined as a group of C statements that are executed together. {
• The statements in a C program are written in a logical sequence to perform Statement 1;
Statement 2;
a specific task. ……………
……………
• Execution of a C program begins at the main() function }
Statement N;

• You can choose any name for the functions. Every program must contain Function2()
{
one function that has its name as main(). Statement 1;
Statement 2;
• All functions(Including main()) are divided into two parts- the declaration ……………
……………
section and the statement section. Statement N;
}
• The declaration section precedes the statement section and is used to ………………….
………………….
describe the data that will be used in the function. FunctionN()
• Data declared within function are known as local declaration as that data is {
Statement 1;
visible only within that function. Statement 2;
……………
• The statement section in a function contains the code that manipulates the ……………
Statement N;
data to perform a specified task. }
Writing the first C Program
#include<stdio.h>
int main()
{
printf("\n Welcome to the world of C ");
return 0;
}

• Output
Welcome to the world of C
Files Used in a C Program
Files in a C program

Source Header Object Executable


File File File 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).
Files Used in a C Program(Contd..)

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.
● Standard Header Files: string.h, stdlib.h, stdio.h, math.h, alloc.h, conio.h
Files Used in a C Program(Contd..)
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
• C is a compiled language. C program must run through a C compiler that can
create an executable file to be run by the computer.
• The programming process starts with creating a source file that consists of the
statements of the program written in C language.
• The source file is then processed by a special program called a Compiler.
• The Compiler translates the source code into an object code.
• The object code contains the machine instructions for the CPU, and calls to OS
API.
• In the next step, the object file is processed with another special program called a
linker.
• The output of the linker is an executable or runnable file.

Source Object Executable


Linker Files
File Files

Library
Files
Compiling and Executing C Programs(contd..)
Pre- Object Executable
Source Linke Files
File processor Compiler Files
r

Library Library
Files Files

• The compilation process shown in above figure 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.
Compiling and Executing C Programs(contd..)
Source Pre- Compiler Object
File proce Files
ss
Library Library Linker Executable
Files Files Files

Source Pre- Compiler Object


File proce Files
ss
Library
Files

• In modular programming, the source code is divided into two or more source files.
• All these source files are complied separately thereby producing multiple object
files.
• These object files are combined by the linker to produce an executable file as
shown in above figure.
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.
C Tokens
• Tokens are the basic building blocks in C language.
• It is the smallest individual unit in a C program.
• There are six main types of tokens in C.
• Keywords
• Variables
• Constants
• Strings
• Special Characters
• Operators
Character Set in C
• Like in natural languages, computer languages also use a character set that defines
the fundamental units used to represent information.
• In C, a character means any letter from English alphabet, a digit or a special
symbol used to represent information.
• These characters when combined together form tokens that act as basic building
blocks of a C program.
• The charcter set of C can therefore be given as:
• English Alphabet: a-z and A-Z
• Digits-0-9
• Special characters: ~, @,#,$,…
• White space
• Escape sequence: \b-blank, \t-tab, \v-vertical return, \r-carriage return, \f-form
feed, \n
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, const, char, continue, default, double, do, else, enum, extern, float,
for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch,
typedef, union, unsigned, void, volatile, while
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: roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code


SIZE IN
DATA TYPE RANGE
BYTES
char 1 -128 to 127
Data Types in C unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed short int 2 -32768 to 32767
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535

long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295

signed long int 4 -2147483648 to 2147483647


float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
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 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..
● Character variables can include any letter from the alphabet or from the ASCII chart and
numbers 0 – 9 that are put between single quotes.
Variables (Contd..)
Declaring Variables
• To declare a variable specify data type of the variable followed by its name.
• Variable names should always be meaningful and must reflect the purpose of their
usage in the program.
• Variable declaration always ends with a semicolon.

Example,
int emp_num;
float salary;
char grade;
unsigned short int acc_no;
Initializing Variables
• While declaring variables, we can also initialize with value.
• int emp_num=7;
• int count, flag=0;
• int count=0, flag=1;
• When variables are declared but not initialized they usually contain garbage values.
Constants
● Constants are identifiers whose value does not change.
● Constants are used to define fixed values like PI or the charge on an electron so that their value does not get changed in
the program even by mistake.
● The value of the constant is known to the compiler at the compile time.
● 4 constants types: int, float, char and string
● Integer constants:
● 1234-int, 1234567L or l-long int, 1234U or u-unsigned int
● Integer literals –expressed in decimal, octal or hexadecimal
● Embedded spaces, commas, & non-digit chars not allowed in integer constants(123 456, 12,56,678, $123)
● -123-decimal, 012-octal(preceded by zero), 0x7F-hexadecimal(preceded with 0Xor0x)
● Floating point Constants:
● FP const-int part, decimal point, fractional part, & exponent field(E or e)
● Literal like 0.07 is by default treated as double.
● 0.02F- float type, 3.141592654L- long double, 0.5e2, -5.6E+3
● Character Constants: single char enclosed in single quotes- ‘a’
● String Constants: sequence of char enclosed in double quotes.
● “a” and ‘a’ is not same
● String chars are stored in successive memory locations.
● Compiler records the address of 1st char and appends a null char(‘\0’) to mark the end.

Constants
● To declare a constant, precede the normal variable declaration with const keyword and assign it
a value.
● For example, const float pi = 3.14;
● Another way to designate a constant is to use the pre-processor command define.
#define PI 3.14159
When the preprocessor reformats the program to be compiled by the compiler, it replaces each
defined name with its corresponding value wherever it is found in the source program. Hence, it
just works like the Find and Replace command available in a text editor.

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.
Operators In C
• An operator is a symbol that specifies the mathematical, logical, or relational
operation to be performed.
● C language supports a lot of operators to be used with variables and constants to
form 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
● Sizeof Operator
Arithmetic Operators
• Consider three variables declare as
• int a=9, b=3, result;
• Here, a and b are called operands and the result of all arithmetic operations are shown in table.
• (+, -, *, /) operators perform the usual arithmetic operations in C.
• Arithmetic operators can be applied to any integer or floating point numbers
• Divide by zero is not possible
• Except %, all arithmetic operators can accept mix of int and float num.
OPERATION OPERATOR SYNTAX COMMENT RESULT
• If both op are int, then res is int.
Multiply * a * b result = a * b 27
Ex. : 5/2=2
Divide / a / b result = a / b 3
• If one or both op are float, then res is float.
Ex. : 5.0/2=2.5 Addition + a + b result = a + b 12

• All operator bind from left to right order. Subtraction - a - b result = a – b 6

• *, /, % have highest precedence over +, -. Modulus % a % b result = a % b 0


Modulus Operator
• The modulus operator (%) is an arithmetic operator finds the remainder
of an integer division
• Can be applied only on int, not for float or double
• Sign of result is always the sign of first operand.
• Ex:
• 16%3=1
• 16%-3=1
• -16%3=-1
• -16%-3=1
Relational Operators
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

• 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.
Ex : 2<3 returns true and 2>3 returns false
• It is used to determine the relationships between the operands and are evaluated
from Left to Right
Relational Operators (Contd…)
• Chars are considered as valid operands. Since they are represented by numeric
values
Ex : ‘A’ < ‘B’ is equivalent to 65 < 66 where ASCII value of A and B are 65 and 66 respectively
• When arithmetic expressions are used on either side of a relational
operator, then first expression will be evaluated, and then the result
will be compared. (because arithmetic opearator have highest
precedence over relational operator)
• Relational operator should not be used for comparing strings.
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
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.

● Logical AND (&&)


● It is a Binary Operator, which simultaneously evaluates two values or relational expressions.
● If both values are TRUE, then it returns TRUE else it returns FALSE
● The truth table of Logical AND (&&) is given in below tables
A B A &&B
0 0 0
0 1 0
1 0 0
1 1 1

Ex: (a<b) && (b>c)


Logical Operators
Logical OR (||)
● It is a Binary Operator, which simultaneously evaluates two values or
relational expressions.
● If both values are FALSE, then it returns FALSE else it returns TRUE
● The truth table of Logical OR (||) is given in below table

Ex : (a<b) || (b>c)

Logical NOT (!)


• The Logical NOT (!) operator takes single expression and negate the value of the
expression.
Ex : int a=1, b
b=!a
Now b=0 as it contains negate value of a
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;
is equivalent to writing
x = x + 1;
y = x;
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.
● int a=5, b=3, c=7, small;
small = (a < b ? ( a < c ? a : c) : ( b < c ? a : c)) ;
Bitwise Operators
● Bitwise operators perform operations at bit level. These operators include:
● bitwise AND,
● bitwise OR,
● bitwise XOR,
● Bitwise NOT,
● 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
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise Shift Operators
• C Supports two bitwise operators
• Shift-left (<<), Syntax : operand op num
• Shift-right (>>), Syntax : operand op num
• 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. For example;
unsigned int x = 11000101;
Assignment Operators
• The assignment operator is responsible for assigning values to the variables.
• While the equal sign (=) is the fundamental assignment operator and has right to left
associativity
• C also supports other assignment operators that provide shorthand ways to represent
common variable assignments and the syntax is : variable op = expression
• They are shown in the table.
OPERATOR SYNTAX EQUIVALENT TO
/= 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 &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount
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);
then result = 2,
Operator Precedence Chart
• C operators have two properties: Priority and Operator Assoc Operator Assoc
associativity.
(), [], . , -> L to R & L to R
• When an expression has more than 1 operator, then
it is the relative priorities of the operators wrt each ++, -- (postfix) R to L ^ L to R
other that determine the order in which the ++, --(prefix), +, -
expression will be evaluated. (unary), !, ~(type), R to L
| L to R
*(indirection),
• Associativity defines the direction in which the &(address), sizeof
operator acts on the operands. It can be Left to
Right / Right to Left. *, /, % L to R && L to R

• Priority is given precedence over associativity to +, - L to R || L to R


determine the order in which the exp are evaluated. <<, >> L to R ?: R to L
• Table lists the operators that C language supports in =, +=, -=, *=,
the order of their precedence (highest to lowest). /=, %=, &=,
<, <=, >, >= L to R R to L
^=, |=, <<=,
• Associativity indicates the order in which the >>=
operators of equal precedence in an expression are
==, != L to R , (comma) L to R
evaluated.
Escape Sequences
• The escape sequence in C is the characters or the sequence of
characters that can be used inside the string literal.
• The purpose of the escape sequence is to represent the characters that
cannot be used normally using the keyboard.
\n New Line It moves the cursor to the start of the next line.

It inserts some whitespace to the left of the cursor and moves the
\t Horizontal Tab
cursor accordingly.

\\ Backlash Use to insert backslash character.

\” Double Quote It is used to display double quotation marks.

• Refer Textbook for more escape sequence characters


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 example,
float x;
int y = 3;
x = y; Now, x = 3.0,
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 into the value of a lower data type.

●For example, we need to explicitly typecast 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.

You might also like