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

Unit 1

Uploaded by

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

Unit 1

Uploaded by

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

UNIT I BASICS OF C PROGRAMMING

CS8251 - PROGRAMMING IN C
Unit 1

1 Introduction to programming paradigms

2 Structure of C program, Data Types

3 Storage classes, Constants, Enum

4 Keywords, Operators, Expressions


Input / Output statements, Assignment statements
5 Decision making statements

6 Pre-processor directives, Compilation process

2 © 2011 Wipro Ltd


PS Skill

 Understand the problem


 Analyse the problem
 Design the solution
 Programming skill or coding skill
 Test the solution
 Maintain the solution by modifyin it according to
the need

3 © 2021 UCEN
 Problem Solving

Problem is transformed to Solution

Problem Domain Solution Domain

(P) (S)

F:P S
Problem Solving Using Computers

 Conversion of Problem domain to Solution


Domain
 Problem Domain
 Sector to which the problem belongs
 Solution Domain
 Subject matter that is of concern to the computer
system and implementer of the system

5 © 2021 UCEN
 Program

Input is transformed to Output

Input Output

F:I O
Programming Language

 The solution to a problem is written in the form of


program while computer is used.
 A program is a set of instructions written in a
programming language.
 A programming language provides the medium
for conveying the instructions to the computer.

7 © 2021 UCEN
Introduction of Programming Paradigms
 Paradigm can also be termed as method to solve
some problem or do some task
 Programming paradigm is an approach to solve
problem using some programming language or also
we can say it is a method to solve a problem using
tools and techniques that are available to us following
some approach
 There are lots for programming language that are
known but all of them need to follow some strategy
when they are implemented and this
methodology/strategy is paradigms.

8 © 2021 UCEN
9 © 2021 UCEN
Imperative programming paradigm

 one of the oldest programming paradigm.


 machine architecture
 It is based on Von Neumann architecture.
 It performs step by step task by changing state.
 Advantage:
 Very simple to implement
 It contains loops, variables etc.
 Disadvantage:
 Complex problem cannot be solved
 Less efficient and less productive
 Parallel programming is not possible

10 © 2021 UCEN
Procedural programming paradigm

 This paradigm emphasizes on procedure in terms of


under lying machine model
 There is no difference in between procedural and
imperative approach.
 reusability.
 Examples of Procedural programming paradigm:
 C : developed by Dennis Ritchie and Ken Thompson
 C++ : developed by Bjarne Stroustrup
 Java : developed by James Gosling at Sun
Microsystems
 Pascal : developed by Niklaus Wirth

11 © 2021 UCEN
Object oriented programming

 The program is written as a collection of classes and object


which are meant for communication
 The smallest and basic entity is object and all kind of
computation is performed on the objects only.
 More emphasis is on data rather procedure.
 It can handle almost all kind of real life problems which are today
in scenario.
 Advantages:
 Data security
 Inheritance
 Code reusability
 Flexible and abstraction is also present
 Examples
 Java : developed by James Gosling at Sun Microsystems
 C++ : developed by Bjarne Stroustrup

12 © 2021 UCEN
Parallel processing approach

 Parallel processing is the processing of program


instructions by dividing them among multiple
processors.
 A parallel processing system posses many
numbers of processor with the objective of
running a program in less time by dividing them.
 This approach seems to be like divide and
conquer.
 Examples are NESL (one of the oldest one) and
C/C++ also supports because of some library
function.

13 © 2021 UCEN
Declarative programming paradigm

 Declarative programming is a style of building


programs that expresses logic of computation
without talking about its control flow.
 The focus is on what needs to be done rather
how it should be done basically emphasize on
what code code is actually doing.

14 © 2021 UCEN
Logic programming paradigms
 It can be termed as abstract model of
computation.
 It would solve logical problems like puzzles,
series etc
 In logic programming we have a knowledge
base which we know before and along with
the question and knowledge base which is
given to machine, it produces result.
 In normal programming languages, such
concept of knowledge base is not available
 Example
 Prolog
15 © 2021 UCEN
Functional programming paradigms
 The functional programming paradigms has
its roots in mathematics and it is language
independent
 The central model for the abstraction is the
function which are meant for some specific
computation and not the data structure.
 Data are loosely coupled to functions.
 Function can be replaced with their values
without changing the meaning of the program
 Example:
 perl
 javascript

16 © 2021 UCEN
Database/Data driven programming
approach
 This programming methodology is based
on data and its movement
 Program statements are defined by data
rather than hard-coding a series of steps.
 A database program is the heart of a
business information system and provides
file creation, data entry, update, query and
reporting functions
 Examples:
 SQL
17 © 2021 UCEN
Generation of programming
Languages
 First – FORTRAN I, ALGOL 58
 Second - FORTRAN II, Algol60, COBOL
 Third – Pascal, C
 Structured programming Approach
 Fourth – C++, Java, C#
 Object oriented programming

18 © 2021 UCEN
Types of Programming Languages
 Based on closeness to computer
 High Level - Closer to Human only
 Assembly level - Closer to Human and Machine
 Machine Level - Closer to Machine only
 Based on the ways and means of dealing the logic
 Imperative or Procedural or Structured - Collection of statements and
functions to manipulate data
 Logical -Collection of logical reasoning with rules and inferences
 Functional - Collection of mathematical functions
 Object oriented - Collection of interacting objects
 Based on Generation
 First Generation -Machine Language
 Second Generation -Assembly Language
 Third Generation - Structured and Object oriented Language
 Fourth Generation -Domain Specific and Data Management
Languages
 Fifth Generation -Language for Artificial Intelligence

19 © 2021 UCEN
Structured programming Approach

 Each function is independent of each other


 Each function has its own data & algorithm
 Parameter passing mechanism is evolved
 Function abstraction
 User defined data type is possible
 Scope & visibility of data are introduced
 Rich set of control structures

20 © 2021 UCEN
Structured programming -contd

 Algorithmic oriented approach


 Depend on problem domain and not on problem
domain
 Top-down approach is followed
 Reuse of software is supported
 Fairly complex and simple problems can be
solved

21 © 2021 UCEN
Evolution of new paradigm

 Evolution of New approach is required to


 Produce a reliable software
 Reduce production cost
 Develop reusable modules
 Reduce maintenance cost
 Quicken the completion time

22 © 2021 UCEN
Object model

 Resulted in OOP
Function  Verbs
Data Items  Nouns
 Structured programming is organized around
verbs
 OOP is organized around nouns
 OOP reflects the natural way of solving problems

23 © 2021 UCEN
Structured Programming Languages

 C
 Pascal

24 © 2021 UCEN
Basic Terminologies

 Computers -really dumb machines because they do


only what we are told to do.

 A computer program - is just a collection of the


instructions necessary to solve a specific problem.

 Algorithm-The approach or method that is used to


solve the problem.

25 © 2021 UCEN
Continue..

For example: Develop a program that tests if a number


is odd or even.
 First express the solution to the problem in terms of
an algorithm
 Then develop a program that implements that
algorithm.

Algorithm for above problem


1. First, divide the number by two.
2. If the remainder of the division is zero, the number
is even;
3. Otherwise, the number is odd.

26 © 2021 UCEN
1. Machine Level Language - Binary numbers that
corresponded directly to specific machine
instructions and locations in the computer’s memory.
2. Low-Level Language (Assembly language) -
permits the programmer to use symbolic names to
perform various operations and to refer to specific
memory locations.
Assembler - A special program that translates the
assembly language program from its symbolic format
into the specific machine instructions of the
computer system

27 © 2021 UCEN
Disadvantage of Assembly language
 Machine dependent -Different processor types have
different instruction sets. Assembly language
program will not run on a different processor type
without being rewritten.
 Not Portable - Programmer learn the instruction set
of the particular computer system to write a program
in assembly language.

28 © 2021 UCEN
3. Higher-level languages (HLL)-came to overcome
the machine dependent issue of low-level language.
 FORTRAN (FORmula TRANslation) was the first
higher-level language.
 Merits: Machine independent - A program could be
written in any language is to be run on any machine
that supported the language with few or no changes.

29 © 2021 UCEN
Compiler

 To support HLL, a special computer program is


used to translates the statements of the HLL into
particular instructions of the computer.
 First, Analyzes a program which written in a
particular computer language (HLL)
 Then translates it into a form that is suitable for
execution on particular computer system.

30 © 2021 UCEN
Operating system - A program that controls the entire
operation of a computer system.
 All I/O operations that are performed on a computer
system are channelled through the operating
system.
 Also manage the computer system’s resources.
 Handle the execution of programs.
 Most popular operating systems today is the Unix,
Microsoft Windows XP.

31 © 2021 UCEN
Compilation Process
1. Write Source Program using Text Editor
 The program that is to be compiled is first typed
into a file on the computer system.
 A text editor is usually used to enter the C program
into a file.
 C programs can typically be given any name
provided the last two characters are “.c”.
 For example, vi is a popular text editor used on Unix
systems. The program that is entered into the file is
known as the source program because it
represents the original form of the program
expressed in the C language.

32 © 2021 UCEN
2. Debugging Phase: Compiler checks each program
statement in source program to conforms the syntax
and semantics of the language.
*unbalanced parentheses (syntactic error)
* variable that is not “declared” (semantic error)
 If any mistakes are discovered then it reported to the
user and the compilation process ends right there.
 So errors have to be corrected in the source
program (with the use of an editor), and the
compilation process must be restarted.

33 © 2021 UCEN
Creation of Object code file
 Once all syntactic and semantic errors have been
removed from the program, the compiler then
proceeds to take each statement of the program and
translate it into a “lower” form. (translated into the
equivalent statements in assembly language)
 Next the assembler takes each assembly language
statement and converts it into a binary format known
as object code, which is then written into another
file on the system.
 This file typically has the same name as the source
file with the last letter an “o” (in unix) or “obj” (in
windows) instead of a “c”.

34 © 2021 UCEN
3. Linking Process (Creation of executable object code)
 Now object code is ready to be linked. If the program
uses other programs that were previously processed by
the compiler, then those programs are linked together.
 Programs that are used from the system’s program
library are also searched and linked together with the
object program during this phase.
 The process of compiling and linking a program is often
called building.
 The final linked file is an executable object code which
is ready to be run or executed. It is stored in another file
on the system, (In Unix, this file is called “a.out”, In
Windows, same name as the source file, with “exe”
extension).

35 © 2021 UCEN
4. Loading & Execution
 To run the program, an executable object code file must
be loaded into the computer’s memory and initiating its
execution.
 When the program is executed, each of the statements of
the program is sequentially executed in turn.
 If the program requests any data from the user, known as
input, the program temporarily suspends its execution so
that the input can be entered. Or, the program might
simply wait for an event, such as a mouse being clicked,
to occur.
 Results that are displayed by the program, known as
output, appear in a window called the console. Or, the
output might be directly written to a file on the system.

36 © 2021 UCEN
 If all goes well, the program performs its intended
functions.
 If the program does not produce the desired results,
it is necessary to go back and reanalyze the
program’s logic. This is known as the debugging
phase, during which an attempt is made to remove
all the known bugs from the program.
 To do this, make changes to the original source
program. So the entire process of compiling, linking,
and executing the program must be repeated until
the desired results are obtained.

37 © 2021 UCEN
38 © 2021 UCEN
Compiler Vs Language Interpreters
 Another method used for analyzing and executing programs
developed in a higher-level language.
 Source Programs are not compiled but are interpreted.
 An interpreter analyzes and executes the statements of a
program at the same time. This method usually allows
programs to be more easily debugged.
 It is slower than compilation because statements are not
converted into their lowest-level form in advance of their
execution.
Example
 BASIC and Java are two programming languages in which
programs are often interpreted and not compiled.
 Other examples include the Unix system’s shell and Python.
 Some vendors also offer interpreters for the C programming
language.

39 © 2021 UCEN
Integrated Development Environment
 The process of editing, compiling, running, and
debugging programs is managed by a single integrated
application known as an IDE.
 An IDE is a windows-based program that allows you to
easily manage large software programs, edit files in
windows, and compile, link, run, and debug your
programs.
 Most IDEs also support program development in several
different programming languages in addition to C, such
as C# and C++.
Example
 In Mac OS X, CodeWarrior and Xcode are two IDEs
used.
 In Windows, Microsoft Visual Studio is a popular IDE.
 Kylix is a popular IDE for developing applications under
Linux.

40 © 2021 UCEN
Programming paradigms
 Way to classify programming languages based on
their features.
 Languages can be classified into multiple paradigms.
 Some paradigms are concerned mainly with
implications for the execution model of the
language,
 Other paradigms are concerned mainly with the way
that code is organized.
 Yet others are concerned mainly with the style of
syntax and grammar.

41 © 2021 UCEN
Execution model & Side effects
 Execution model specifies how work takes
place.
 Every programming language has an execution model cover
What is an indivisible unit of work? & What are the
constraints on the order in which those units of work take
place?
 This order may be chosen ahead of time, or it can be
dynamically determined as the execution proceeds.
 The implementation of an execution model can be
via compiler/ interpreter, and includes a runtime system.
 Side effects -way that a program interacts with the
outside world (people, file systems, other computers on
networks). But the degree to which side effects are used
depends on the programming paradigm.
42 © 2021 UCEN
Example:
C programming language has a concept called a
statement.
Statements are indivisible units of work and that they
proceed in the same order as their syntactic
appearance in the code (except when a control
statement such as IF or WHILE modifies the order).
The C language actually has an additional level to its
execution model, which is the order of precedence. It
states the rules for the order of operations within a
single statement.

43 © 2021 UCEN
Common programming paradigms

 Imperative which allows side effects. (in which the


programmer instructs the machine how to change its
state)
o Object-oriented which groups instructions together
with the part of the state they operate on.
o Procedural which groups instructions into procedures.
 Declarative in which the programmer merely
declares properties of the desired result, but not how
to compute it.
 Functional in which the desired result is declared as
the value of a series of function applications.
 Logic in which the desired result is declared as the
answer to a question about a system of facts and rules.
 Mathematical in which the desired result is declared
as the solution of an optimization problem
44 © 2021 UCEN
 Imperative paradigm has two main features: they
state the order in which operations occur and they
allow side effects. Most object-oriented languages
are also imperative languages.
 Declarative paradigm does not state the order in
which to execute operations. Instead, they supply a
number of operations that are available in the
system, along with the conditions under which each
is allowed to execute. The execution model tracks
which operations are free to execute and chooses
the order on its own.

45 © 2021 UCEN
Languages support single/multiple
paradigms

 Languages are designed to support one paradigm


(Smalltalk supports object-oriented
programming, Haskell supports functional
programming).
 Multi paradigm supported languages can be
purely procedural, purely object-oriented, or can
contain elements of both or other paradigms.
 Example: Object Pascal, C++, Java, C#, Scala, Visual
Basic, Lisp, Scheme, Perl, PHP, Python, Ruby, Oz,
and F#
 Software designers and programmers decide how to
use those paradigm elements.
46 © 2021 UCEN
Introduction To C

47 © 2021 UCEN
C programming

 C is a high level, structured and third generation


programming Language
 It is also a system programming language since it
is used to develop system programs such as
UNIX operating system and compilers.
 C is one of the most dominant development
languages for general purpose applications such
as utility software and low-level software for many
devices.

48 © 2021 UCEN
Evolution of C - ALGOL, CPL and BCPL
• ALGOL 60 - Algorithmic language Developed by an International
Committee, 1960
 CPL – Cambridge Programming Language or Combined
Programming Language or Cambridge Plus London (1963)
 Invented by D.W. Barron and Christopher Strachey, et al.
 Jointly from University of Cambridge and University of London
 Heavily influenced by Algol 60

 BCPL – Basic CPL (1967)


 Invented by Martin Richards
at Cambridge University
 It was not so powerful and hence failed

49 © 2021 UCEN
B Programming Language

 B Programming Language (1969)


 Invented by Ken Thompson
 Implemented on minicomputers DEC PDP-7
and PDP-11
 B was used to write UNIX Operating System in
the Multics project
 B was heavily influenced by BCPL
 Not named after the B in BCPL.

50 © 2021 UCEN
Evolution of C

• B evolved into "New B" and then C


 New B (NB)
 Invented by Dennis Ritchie I 971
 C was developed in 1972 as a proper
successor of B
 K&R C – C standard (1978)

51 © 2021 UCEN
Taxonomy of C Language

ALGOL

BCPL

Traditional C

K&RC

ANSI C

ANSI / ISO C

C 95

C99

52 © 2021 UCEN
Standards of C

 ANSI C or C89 - First official C Standard (1989)


 ISO/IEC 9899 C90 – Second official C standard
(1990)
 ISO/IEC 9899 C99 – Third official C standard (1999)
 ISO/IEC 9899 C11 – Fourth official C standard (2011)
 Visit the following web site for the current standard
http://www.open-std.org/jtc1/sc22/wg14/www/projects#9899

53 © 2021 UCEN
Characteristics of C
 It is a robust language with a rich set of built-in
functions and operators that can be used to write any
complex program.
 It is a high level programming language
 Small Size- only 32 keywords
 Function Call
 Well suited structured programming
 Stable language
 Quick
 Facilitate low level programming (Bitwise operator)
 Supports pointer
 Core language (Any other language is easy)
 Portable
54  Extensible © 2021 UCEN
Structure of C program
Preprocessor Directives
Global Declaration

main()
{
Local Declarations
Statements
}

Function 1()
{
Local Declarations
Statements
}

………………………………………….
Function N()
{
Local Declarations
Statements
}
55 © 2021 UCEN
Writing First C Program

#include <stdio.h> /* Preprocessor Directives */


int main() /* Starting Point */
{
printf("Hello, World! \n"); /* output Statement */
return 0; /* Return Command */
}
Output:
Hello World

56 © 2021 UCEN
C program

 Any C program is basically a collection of functions that are


supported by the C library.User defined functions can be
added to the C library.
 The main( ) is a special function used by the C system to tell
the computer where the program starts.
 The set of statements belonging to a function are enclosed
within a pair of braces,{ }.
 Any Variable used in the program must be declared before
using it.
 C program statements are written in lowercase letters and
end with semicolon.
 Uppercase letters are used only for symbolic constants.

57 © 2021 UCEN
Escape Sequence
Escape Sequence Meaning

\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\nnn octal number
\xhh hexadecimal number

58 \0 Null © 2021 UCEN


Comment

• A comment explains briefly what a program does.


• Comments should be included in appropriate
places to improve the readability of a program.
• In C programs, the characters between /* and */
are treated as comments and are ignored by the
compiler when the program is compiled.
• Comments may appear anywhere in a C
program, but not within string constants or
character constants.
 // Single line Comment
 /* */ Multi line comment

59 © 2021 UCEN
Tokens
A token may be a single character or a group of
characters which has a specific meaning.
The following are the tokens that can be identified by a
C compiler during the translation process.

Tokens in C
Keywords
Variables
Constants
Strings
Special Characters
Operators

60 © 2021 UCEN
Character set

 Alphabets
 Upper Case(A-Z)
 Lower Case (a-z)
 Digits (0-9)
 Special characters
 ~%|@+<_->#=&$/()*\':[]";!,{}?.
 Escape Sequence
 whitespace characters
 \b blank space
 \t horizontal tab
 \v vertical tab
 \r carriage return
 \f form feed
61  \n new line © 2021 UCEN
Keywords

 Reserved Words with Fixed Meaning


 Cannot be used as identifier

auto break case char const continu default do


e

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigne void volatile while


d

62 © 2021 UCEN
identifiers

 C identifiers represent the name in the C program, for example,


variables, functions, arrays, structures, unions, labels, etc.
 composed of letters such as uppercase, lowercase letters, underscore,
digits, but the starting letter should be either an alphabet or an
underscore
 Rules:
 The first character of an identifier should be either an alphabet or an
underscore, and then it can be followed by any of the character, digit, or
underscore.
 It should not begin with any numerical digit.
 In identifiers, both uppercase and lowercase letters are distinct.
Therefore, we can say that identifiers are case sensitive.
 Commas or blank spaces cannot be specified within an identifier.
 Keywords cannot be represented as an identifier.
 The length of the identifiers should not be more than 31 characters.
 Identifiers should be written in such a way that it is meaningful, short,
and easy to read.

63 © 2021 UCEN
Example

 valid identifiers
 total, sum, average, _m _, sum_1, etc.

 Invalid identifiers
 2sum (starts with a numerical digit)
 int (reserved word)
 char (reserved word)
 m+n (special character, i.e., '+')

64 © 2021 UCEN
DataTypes
 Data types in c refer to an extensive system used
for declaring variables or functions of different
types.
 The type of a variable determines how much
space it occupies in storage and how the bit
pattern stored is interpreted.

65 © 2021 UCEN
Types- Data Types

Sr.No. Types & Description


1 Basic Types
(a) integer types and (b) floating-point types. (c) Character (d)
Double

2 Enumerated types
They are again arithmetic types and they are used to define
variables that can only assign certain discrete integer values
throughout the program.
- Enum

3 The type void


The type specifier void indicates that no value is available.

4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types,
(d) Union types and (e) Function types.

66 © 2021 UCEN
Basic Data Types - Integer
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
short int 2 bytes -32,768 to 32,767
unsigned short int 2 bytes 0 to 65,535

signed short int 4 bytes -32,768 to 32,767


long int 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long int 4 bytes 0 429467295

signed long int 4 bytes -2,147,483,648 to 2,147,483,647


float 4 bytes 3.4 E-4932 to 1.1E+ 4932
double 8 bytes 1.7E -308 to 1.7E +308

67 long double 10 bytes 3.4 ©E-4932


2021 UCEN
to 1.1E+ 4932
Memory allocation is done by OS.
int i=4;
float f=3.14;
char ch=‘a’;

68 © 2021 UCEN
The void Type
 The void type specifies that no value is available.
It is used in three kinds of situations
Sr.No. Types & Description
1 Function returns as void
There are various functions in C which do not return any value
or you can say they return void. A function with no return value
has the return type as void. For example, void exit (int
status);
2 Function arguments as void
There are various functions in C which do not accept any
parameter. A function with no parameter can accept a void. For
example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object,
but not its type. For example, a memory allocation
function void *malloc( size_t size ); returns a pointer to void
which can be casted to any data type.

69 © 2021 UCEN
Variables
 A variable is nothing but a name given to a storage area
that our programs can manipulate
 Each variable in C has a specific type, which determines
the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set
of operations that can be applied to the variable.
 Two basic kinds of variables
 Numeric variables
 Store integer or float values
 Character variables
 Single character enclosed with ‘’

70 © 2021 UCEN
Variable Declaration

 A variable declaration provides assurance to the compiler that


there exists a variable with the given type and name so that the
compiler can proceed for further compilation without requiring
the complete detail about the variable.
 A variable definition has its meaning at the time of compilation
only, the compiler needs actual variable definition at the time of
linking the program.
 Int emp;
 float salary;
 char grade;
 double balance;
 float a,b;
 Variables declared inside function is called local variables
 Variables declared outside function is called global variables
 Variable can not be void

71 © 2021 UCEN
Initializing variable

 When declaring variables, we can also initialize them


with value.
 int a=10;
 float b=20.2;
 char x=‘a’;
 int x=10, y=20;

72 © 2021 UCEN
Constants / Literals

 Constants refer to fixed values that the program may


not alter during its execution.
 These fixed values are also called literals.
 Constants can be of any of the basic data types like an
integer constant, a floating constant, a character
constant, or a string literal. There are enumeration
constants as well

73 © 2021 UCEN
Integer Constants
 An integer literal can be a decimal, octal, or hexadecimal
constant.
 A prefix specifies the base or radix: 0x or 0X for hexadecimal,
0 for octal, and nothing for decimal.
 An integer literal can also have a suffix that is a combination
of U and L, for unsigned and long, respectively.
 The suffix can be uppercase or lowercase and can be in any
order.
 Example
 85 /* decimal */
 0213 /* octal */
 0x4b /* hexadecimal */
 30 /* int */
 30u /* unsigned int */
 30l /* long */
 30ul /* unsigned long */
74 © 2021 UCEN
Floating-point Literals / Constant

 A floating-point literal has an integer part, a decimal


point, a fractional part, and an exponent part.
 You can represent floating point literals either in decimal
form or exponential form.
 While representing decimal form, you must include the
decimal point, the exponent, or both;
 While representing exponential form, you must include
the integer part, the fractional part, or both. The signed
exponent is introduced by e or E.
 Example:
 3.14159 /* float */
 314159E-5L /* float */

75 © 2021 UCEN
Character Constants

 Character literals are enclosed in single quotes, e.g.,


'x' can be stored in a simple variable of char type.
 A character literal can be a plain character (e.g., 'x'),
an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').

76 © 2021 UCEN
String Literals / Constants
 String literals or constants are enclosed in double
quotes "".
 A string contains characters that are similar to
character literals: plain characters, escape
sequences, and universal characters.
 You can break a long line into multiple lines using
string literals and separating them using white
spaces.
 Here are some examples of string literals. All the
three forms are identical strings.
 "hello, dear" "hello, \ dear"

77 © 2021 UCEN
Declaring constants
 There are two simple ways in C to define
constants −
 Using #define preprocessor.
 Using const keyword.
 The #define Preprocessor
 Syntax: #define identifier value
 It is also called symbolic constant

78 © 2021 UCEN
Example

#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}

79 © 2021 UCEN
The const Keyword - Example

#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
int area; area = LENGTH * WIDTH;
printf("value of area : %d", area);
return 0;
}

80 © 2021 UCEN
Input & Output Statments

81 © 2021 UCEN
Input / Output statements
Streams
 A Stream act in to ways. It is the source of data as well
as destination of data.
 C uses two forms of streams
 Text Streams
 Binary Streams

Input Text
Keyboard Data
Stream

Output Text
Monitor Data
Stream

82 © 2021 UCEN
Formatting Input / Output
 The most fundamental operation in a C program is to accept input values
from a standard input device(keyboard) and output the data produced by
the program to a standard output device(Monitor).
 we can assign values to variables using the assignment operator ‘=’.
 Example: int a = 3;
 What if we want to assign value to variable a that is inputted from the user
at run-time?
 This is done by using the scanf function that reads data from the
keyboard.
 for outputting results of the program, printf function is used that sends
results to a terminal.
 Like printf and scanf, there are different functions in C that can carry out
the input–output operations.
 These functions are collectively known as Standard Input/Output Library.
 A program that uses standard input/output functions must contain the
following statement at the beginning of the program:
#include <stdio.h>
83 © 2021 UCEN
printf ()
 The printf function is used to display information required by the user
and also prints the values of the variables
 Printf- print Formatting
 It takes data values and convert into the text stream is described using
a separate conversion specification in Control string
 Syntax
 printf ("control string", variable list);
 Control string may contain text to be printed like instructions to the user,
captions, identifiers or any other text to make the output readable
 Control characters also included in control string, like \n,\t,\a etc.,
 Prototype of control string can be given below
 %[flags][width][.precision][length modifier] type specifier
 Each control string must begin with a % sign
 flags is an optional argument, which specifies output justification like
decimal point, numerical
sign, trailing zeros or octadecimal or hexadecimal prefixes.
84 © 2021 UCEN
printf () - Continues
 Flag
Flags Description
– Left–justify within the given field width
+ Displays the data with its numeric sign (either + or –)
Used to provide additional specifiers like o, x, X, 0, 0x, or 0X for
#
octal and hexadecimal values respectively for values different than zero
0 The number is left–padded with zeroes (0) instead of spaces

Note : When data is shorter than specified width, by default data is right justified
 To left justify data use minus symbol in the flag field
 Padding is used to fill unused space
 Defualt padding symbol is space
 width is an optional argument which specifies the minimum number of
positions that the output characters will occupy.
 If the number of output characters is smaller than the specified width, then the
output would be right justified with blank spaces to the left.
 However, if the number of characters is greater than the specified width, then
all the characters would be printed.
85 © 2021 UCEN
printf () - Continues
 Flag
Flags Description
– Left–justify within the given field width
+ Displays the data with its numeric sign (either + or –)
Used to provide additional specifiers like o, x, X, 0, 0x, or 0X for
#
octal and hexadecimal values respectively for values different than zero
0 The number is left–padded with zeroes (0) instead of spaces

Note : When data is shorter than specified width, by default data is right justified
 To left justify data use minus symbol in the flag field
 Padding is used to fill unused space
 Defualt padding symbol is space
 width is an optional argument which specifies the minimum number of
positions that the output characters will occupy.
 If the number of output characters is smaller than the specified width, then the
output would be right justified with blank spaces to the left.
 However, if the number of characters is greater than the specified width, then
all the characters would be printed.
86 © 2021 UCEN
printf () - Continues
 Precision is an optional argument which specifies the maximum number of
characters to print.
 For integer specifiers (d, i, o, u, x, X) : precision flag specifies the minimum
number of digits to be written.
 However, if the value to be written is shorter than this number, the result is
padded with leading zeros.
 Otherwise, if the value is longer, it is not truncated.
 For character strings, precision specifies the maximum number of characters to
be printed.
 For floating point numbers, the precision flag specifies the number of decimal
places to be printed.
 Its format can be given as .m, where m specifies the number of decimal digits.
 When no precision modifier is specified, printf prints six decimal positions.
 When both width and precision fields are used, width must be large enough to
contain the integral value of the number, the decimal point and the number of
digits after the decimal point.
 Therefore, a conversion specification %7.3f means print a floating point value of
maximum 7 digits where 3 digits are allotted for the digits after the decimal point

87 © 2021 UCEN
printf () - Continues
 Length Modifiers

Length Description
h When the argument is a short int or unsigned
short int
l When the argument is a long int or unsigned
long int for integer specifiers
L When the argument is a long double (used for
floating point specifiers)

88 © 2021 UCEN
printf () - Continues
 Type Specifiers
 used to define the type and the interpretation of the value of the corresponding argument

Type Qualifying input


c For single characters
d For integer values
F For floating point numbers
E,e Floating point numbers in exponential format
G,g Floating point numbers in the shorter of e format
o For octal numbers
s For a sequence of characters
u For unsigned integer values
x,X For hexadecimal values
 Note: If the user specifies a wrong specifier then some strange things will be
seen on the screen and the error might propagate to other values in the printf()
list.
89 © 2021 UCEN
printf () - Continues
 The most simple printf statement is
 Printf(“Welcome to the world of C language”);
Examples
 printf("\n Result: %d%c%f", 12, ‘a’, 2.3);
 Result:12a2.3
 printf ("\n Result: %d %c %f", 12, ‘a', 2.3);
 Result: 12 a 2.3
 printf ("\n Result: %d\t%c\t%f", 12, 'a', 2.3);
 Result: 12 a 2.3
 printf ("\n Result: %d\t%c\t%6.2f", 12, 'a’, 245.37154);
 Result:12 a 245.37
 printf("\n Result: %5d \t %x \t %#x", 234, 234, 234);
 Result: 234 EA OxEA
 printf ("\n The number is %6d", 12);
 The number is 12
 printf (\n The number is %2d", 1234);
 The number is 1234
 printf("\n The number is %6d", 1234);
 The number is 1234
 printf("\n The number is %-6d", 1234) ;
 The number is 1234
 printf ("\n The number is %06d", 1234);
 The number is 001234
 printf ("\n The price of this item is %09.2f rupees", 123.456);
 The price of this item is 000123.45 rupees
 printf ("\n This is \'so\' beautiful");
 This is so beautiful
 printf ("\n This is \"so\" beautiful");
 This is so beautiful
 printf ("\n This is \\ so beautiful ");
 This is \ so beautiful

90 © 2021 UCEN
char str[] = "Good Morning";
printf ("\n %s", str);
printf("\n %20s", str);
printf ("\n %20.10s", str);
printf("\n %.7s", str) ;
printf ("\n %-20.10s", str);
printf("\n %7s", str);
Good Morning
Good Morning
Good Morni
Good Mo
Good Morni
Good Morning

91 © 2021 UCEN
scanf()
 The scanf()function is used to read formatted data from the keyboard.
 scanf- scan formatting
 The syntax of the scanf() function can be given as
 scanf ("control string", arg1, arg2, arg3...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 given as,
 %[*][width][modifier]type
 * 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. However, if the scanf function encounters a white space or an unconvertible
character, input is terminated.
 modifier is an optional argument (h, l, or L) , which modifies the type specifier. 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 for long double data values.
 type specifies the type of data that has to be read. It also indicates how this data is
expected to be read from the user.
(refer printf table)
92 © 2021 UCEN
scanf()
 The scanf function ignores any blank spaces, tabs, and newlines entered
by the user.
 The function simply returns the number of input fields successfully
scanned and stored
 Now let us quickly summarize the rules to use a scan function in our C
programs
 Rule 1: The scanf function works until
 (a) the maximum number of characters has been processed,
 (b) a white space character is encountered,
 (c) an error is detected.
 Rule 2: Every variable that has to be processed must have a conversion
specification associated with it.
 Therefore, the following scanf statement will generate an error as num3
has no conversion specification associated with it
 scanf(“%d %d”, &num1, &num2, &num3);

93 © 2021 UCEN
scanf()
 Rule3: There must be a variable address for each conversion specification, Therefore, the
following scanf statement will generate an error as no variable address is given for the third
conversion specification
 scanf (“%d %d %d", &num1, &num2);

 Remember that the ampersand operator (& before each variable name specifies the
address of that variable name
 Rule 4: An error would be generated if the format string is ended with a white space
character
 Rule 5: The data entered by the user must match the character specified in the control
string (except white space or a conversion specification), otherwise an error will be
generated and scanf will stop its processing.
 For example, consider the scanf statement given below.
 scanf (“%d / %d", &num1, &num2);
 Here, the slash in the control string is neither a white space character nor a part of conversion
specification, so the users must enter data of the form 21/46.
 Rule 6: Input data values must be separated by spaces
 Rule 7: Any unread data value will be considered as a part of the data input in the next call
to scanf.
 Rule 8: When the field width specifier is used, it should be large enough to contain the
input data size

94 © 2021 UCEN
Scanf() examples

 int num;
scanf(“%d”, &num);
 float num;
scanf(“%f”, &num);
 char ch;
scanf(“%c”, &ch);
 char str[10];
scanf(“%s”, str);

95 © 2021 UCEN
Program

Find out the output of the following program:

#include <stdio.h>
main()
{
int a, b;
printf("\n Enter two four digit numbers : ");
scanf("%2d %4d", &a, &b);
printf("\n The two numbers are : %d and %d", a, b);
return 0;
}

96 © 2021 UCEN
Output

Enter two four digit numbers : 1234 5678


The two numbers are : 12 and 34

97 © 2021 UCEN
Program
 Write a program to demonstrate the use of printf statement to
print values of variables of different data types
#include <stdio.h>
Int main()
{
// Declare and initialize variables
int num = 7;
float amt = 123.45;
char code = 'A';
double pi = 3.1415926536;
long int population_of_india = 10000000000;
char msg[] = "Hi";
// Print the values of variables
printf("\n NUM = %d \t AMT = %f \t CODE = %c \n PI = %e \t
POPULATION OF INDIA = %ld \n MESSAGE = %s", num, amt, code,
pi, population_of_india, msg);
return 0;
}

98 © 2021 UCEN
Output

 NUM = 7
 AMT = 123.450000
 CODE = A
 PI = 3.141590e+00
 POPULATION OF INDIA = 10000000000
 MESSAGE = HI

99 © 2021 UCEN
Write a program to demonstrate the use of printf and scanf
statements to read and print values of variables of
different data types
#include <stdio.h>
Int main()
{
int num;
float amt;
char code;
double pi;
long int population_of_india;
char msg[10];
printf("\n Enter the value of num : ");
scanf("%d", &num);
printf("\n Enter the value of amt : ");
scanf("%f", &amt);
printf("\n Enter the value of pi : ");
scanf("%e", &pi);
printf("\n Enter the population of india : ");
scanf("%ld", &population_of_india);
printf("\n Enter the value of code : ");
scanf("%c", &code);
printf("\n Enter the message : ");
scanf("%s", msg);
printf("\n NUM = %d \n AMT = %f \n PI = %e \n POPULATION OF INDIA = %ld \n CODE = %c \n MESSAGE = %s", num, amt, code,
pi, population_of_india, msg);
return 0;
}

100 © 2021 UCEN


Output

Enter the value of num : 5


Enter the value of amt : 123.45
Enter the value of pi : 3.14159
Enter the population of India : 12345
Enter the value of code : c
Enter the message : Hello
NUM = 5
AMT = 123.450000
PI = 3.141590e+00
POPULATION OF INDIA = 12345
CODE = C
MESSAGE = Hello

101 © 2021 UCEN


Write a program to calculate the area of a triangle using
Hero’s formula
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
float a, b, c, area, S;
printf("\n Enter the lengths of the three sides of the triangle : ");
scanf("%f %f %f", &a, &b, &c);
S = ( a + b + c)/2; /* sqrt is a mathematical function defined in
math.h header file */
area = sqrt(S*(S-a)*(S-b)*(S-c));
printf("\n Area = %f", area);
return 0;
}

102 © 2021 UCEN


Output

Enter the lengths of the three sides of the triangle :


12 16 20
Area = 96

103 © 2021 UCEN


Write a program to calculate the distance between
two points
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int x1, x2, y1, y2;
float distance;
printf("\n Enter the x and y coordinates of the first point : ");
scanf("%d %d", &x1, &y1);
printf("\n Enter the x and y coordinates of the second point :");
scanf("%d %d", &x2, &y2); /* sqrt and pow are mathematical functions
defined in math.h header file */
distance = sqrt(pow((x2-x1), 2)+pow((y2-y1), 2));
printf("\n Distance = %f", distance);
return 0;
}

104 © 2021 UCEN


Output

Enter the x and y coordinates of the first point : 2 5


Enter the x and y coordinates of the second point :
37
Distance = 2.236068

105 © 2021 UCEN


Operators

106 © 2021 UCEN


C Expressions & Operators
 Traditional mathematical expressions
y = a*x*x + b*x + c;
 An Operator is a symbol that tells the computer to perform certain
mathematical or logic manipulations.
 C language supports different types of operators, which can be used with
variables and constants to form expressions.
• These operators can be categorized into the following major groups:
• Arithmetic operators
• Equality operators
• Unary operators
• Bitwise operators
• Comma operator
• Relational operators
• Logical operators
• Conditional operator
• Assignment operators
107 • Sizeof operator © 2021 UCEN
Arithmetic Operators
 Consider three variables declared as,int a=9, b=3, result;
 The modulus operator (%) finds the remainder of an integer division. This
operator can be applied only on integer operands and cannot be used on
float or double operands.
 Except for modulus operator, all other arithmetic operators can accept a
mix of integer and floating point numbers.
 If both operands are integers, the result will be an integer; if one or both
operands are floating point numbers then the result would be a floating
point number
 All the arithmetic operators bind from left to right.

Operation Operator Syntax Comment Result


Multiply * a*b result = a * b 27
Divide / a/b result = a / b 3
Addition + a+b result = a + b 12
Subtraction – a–b result = a – b 6
Modulus % a%b result = a % b 0

108 © 2021 UCEN


Rules of operator precedence:

109 © 2021 UCEN


Write a program to perform addition, subtraction,
division, integer division, multiplication, and modulo
division on two integer numbers.

#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2;
int add_res=0, sub_res=0, mul_res=0, idiv_res=0, modiv_res=0; float fdiv_res=0.0;
clrscr();
printf("\n Enter the first number : ");
scanf("%d", &num1);
printf("\n Enter the second number : ");
scanf("%d", &num2);
add_res= num1 + num2;
sub_res= num1 - num2;
mul_res = num1 * num2;
idiv_res = num1/num2;
modiv_res = num1%num2;
fdiv_res = (float)num1/num2;
printf("\n %d + %d = %d", num1, num2, add_res);
printf("\n %d - %d = %d", num1, num2, sub_res);
printf("\n %d ¥ %d = %d", num1, num2, mul_res);
printf("\n %d / %d = %d (Integer Division)", num1, num2, idiv_res);
printf("\n %d %% %d = %d (Moduluo Division)", num1, num2, modiv_res);
printf("\n %d / %d = %.2f (Normal Division)", num1, num2, fdiv_res);
return 0;
}

110 © 2021 UCEN


Output

Enter the first number : 9


Enter the second number : 7
9 + 7 = 16
9–7=2
9 * 7 = 63
9 / 7 = 1 (Integer Division)
9 % 7 = 2 (Modulo Division)
9 / 7 = 1.29 (Normal Division)

111 © 2021 UCEN


Relational Operators
 A relational operator, also known as a comparison
operator, is an operator that compares two values or
expressions.
 Relational operators return true or false value,
depending on whether the conditional relationship
between the two operands holds or not
 For example, to test if x is less than y, relational
operator < is used as x < y. This expression will return
true value if x is less than y; otherwise the value of the
expression will be false.
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
112 © 2021 UCEN
Write a program to show the use of relational
operators
#include <stdio.h>
main()
{
int x=10, y=20;
printf("\n %d < %d = %d", x, y, x<y);
printf("\n %d == %d = %d", x, y, x==y);
printf("\n %d != %d = %d", x, y, x!=y);
printf("\n %d > %d = %d", x, y, x>y);
printf("\n %d >= %d = %d", x, y, x>=y);
printf("\n %d <= %d = %d", x, y, x<=y);
return 0;
}

113 © 2021 UCEN


Output

10 < 20 = 1
10 == 20 = 0
10 != 20 = 1
10 > 20 = 0
10 >= 20 = 0
10 <=20 = 1

114 © 2021 UCEN


Equality Operators
 C language also supports two equality operators to
compare operands for strict equality or inequality.
 They are equal to (==) and not equal to (!=) operators.
The equality operators have lower precedence than the
relational operators.
 The equal-to operator (==) returns true (1) if operands
on both sides of the operator have the same value;
otherwise, it returns false (0). On the contrary, the
notequal-to operator (!=) returns true (1) if the operands
do not have the same value; else it returns false (0).
Operator Meaning
Returns 1 if both operands are
==
equal, 0 otherwise
Returns 1 if operands do not
!=
have the same value, 0 otherwise
115 © 2021 UCEN
Logical Operators
 C language supports three logical operators. They are
logical AND (&&), logical OR (||), and logical NOT (!).
 As in case of arithmetic expressions, logical
expressions are evaluated from left to right.
 Logical AND (&&)
 Logical AND is a binary operator, which simultaneously evaluates two
values or relational expressions.
 If both the operands are true, then the whole expression is true.
 If both or one of the operands is false, then the whole expression
evaluates to false.
 For example, A B A && B
(a < b) && (b > c) 0 0 0
0 1 0
1 0 0
1 1 1

116 © 2021 UCEN


Logical Operators
 Logical OR (||)
 Logical OR returns a false value if both the operands are
false. Otherwise it returns a true value.
 For example,
(a < b) || (b > c)
 The whole expression is true if either b is greater than a
or b is greater than c or b is greater than both a and c

A B A|| B

0 0 0

0 1 1

1 0 1

1 1 1

117 © 2021 UCEN


Logical Operators
 Logical NOT (!)
 The logical NOT operator takes a single expression
and produces a zero if the expression evaluates to a
non-zero value and produces 1 if the expression
produces a zero.

A !A && B

0 1

1 0

118 © 2021 UCEN


Unary Operator
 It operates on single operand
 Unary Minus(-)
 When an operator is preceded by the – sign, it negates its value
 Example
 Int a,b=12;
 a = -(b);

 Increment(++) & Decrement Operator(--)


 Two variants
 Prefix
 Postfix
 ++ variable name (Pre Increment)
 variable name++ (Post Increment)
 – –variable name (Pre Decrement)
 variable name– – (Post Decrement)
 Unary Operator has higher precedence than binary Operator

119 © 2021 UCEN


Increment & Decrement Operators
 The increment and decrement operators are unary
operators.
 The operator ++ adds 1 to the operand while - -subtracts
1.They take the following form:
++m(pre increment); or m++(post increment);
--m(pre decrement); or m--(post decrement);

Prefix operator first does the operation and then result is


assigned to the variable.

Postfix operator first assigns the value to the variable and


then does the operation.

120 © 2021 UCEN


Increment and Decrement Operators

Consider the following


m = 5;
y = ++m; (prefix) //y=m+1;

value of y and m would be 6

m = 5;
y = m++; (post fix) //y=m+1;
value of y will be 5 and that of m will be 6.

121 © 2021 UCEN


Sample Program
#include <stdio.h>
main()
{
int num = 3;
// Using unary postfix increment operator
printf("\n The value of num = %d", num);
printf("\n The value of num++ = %d", num++);
printf("\n The new value of num = %d", num);
// Using unary postfix decrement operator
printf("\n\n The value of num = %d", num);
printf("\n The value of num = %d", num--);
printf("\n The new value of num = %d", num);
return 0;
}

O/P:
The value of num = 3
The value of num++ = 3
The new value of num = 4

The value of num = 4


The value of num = 4
The new value of num = 3

122 © 2021 UCEN


Conditional/ Ternary Operator
 A Ternary operator pair “ ? :”is available in C to
construct conditional expression of the form
 It is just like if..else expression
Syntax:
expression1 ? expression2 : expression3
Eg:
a=10;
b=15;
x=(a>b) ? a : b;
x will be assigned to the value of b.

123 © 2021 UCEN


Ternary Operator: Example
Write a program to display the greatest of two numbers.
#include<stdio.h>
#include <conio.h>
void main ( )
{
int a=5,b=8,c;
clrscr( );
c = a>b?a:b; //Conditional operator
printf(" \n The Larger Value is%d",c);
getch( );
}

Output: The Larger Value is 8

124 © 2021 UCEN


Ternary Operator: Example
 . Write a program to find the largest of three numbers using ternary operator.*/

#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2, num3, large;
clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
large = num1>num2?(num1>num3?num1:num3):(num2>num3?num2:num3);
printf("\n The largest number is: %d", large);
return 0;
}

O/P:
Enter the first number: 12
Enter the second number: 34
Enter the third number: 23
The largest number is: 34

125 © 2021 UCEN


Bitwise Operators
 Perform operation on bit level

Operator Meaning

& Bitwise AND


| Bitwise OR
^ Bitwise Exclusive
<< Shift left
>> Shift right

126 © 2021 UCEN


Truth table of the bitwise operators

X Y X&Y X|Y X^Y ~X ~Y

0 0 0 0 0 1 1

0 1 0 1 1 0

1 0 0 1 1 0 1

1 1 1 1 1 0

127 © 2021 UCEN


Bitwise shift operators
 Two types of bitwise shift operators exist in C
programming.
 The bitwise shift operators will shift the bits either on
the left-side or right-side
 Left-shift operator
 It is an operator that shifts the number of bits to the left-
side.
 Operand << n
 Operand is an integer expression on which we apply the left-shift
operation.
 n is the number of bits to be shifted
 In the case of Left-shift operator, 'n' bits will be shifted on
the left-side. The 'n' bits on the left side will be popped
out, and 'n' bits on the right-side are filled with 0.
128 © 2021 UCEN
Bitwise shift operators

 Suppose we have a statement:


 int a = 5;
 The binary representation of 'a' is given below:
 a = 0101
 If we want to left-
shift the above representation by 2, then the state
ment would be:
 a << 2;
 0101<<2 = 00010100

129 © 2021 UCEN


Bitwise shift operators
 Right-shift operator
 It is an operator that shifts the number of bits to the
right side.
 Operand >> n;
 Operand is an integer expression on which we apply the
right-shift operation.
 N is the number of bits to be shifted.
 In the case of the right-shift operator, 'n' bits will be
shifted on the right-side. The 'n' bits on the right-side
will be popped out, and 'n' bits on the left-side are
filled with 0.

130 © 2021 UCEN


Bitwise shift operators
 Suppose we have a statement,
 int a = 7;
 The binary representation of the above variable would
be:
 a = 0111
 If we want to right shift the above representation by 2,
then the statement would be:
 a>>2;
 0000 0111 >> 2 = 0000 0001

131 © 2021 UCEN


Example
#include <stdio.h>
main()
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0; c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\n", c );
}
O/P:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

132 © 2021 UCEN


Assignment Operators
•Assign value to the variable (=)

Operator Example Equivalent expression


+= index += 2 index = index + 2
-= Index -= 1 index = index - 2
*= bonus *= increase bonus = bonus * increase
/= time /= hours time = time / hours
%= allowance %= 1000 allowance = allowance %
1000

<<= result <<= num result = result << num


>>= form >>= 1 form = form >> 1
&= mask &= 2 mask = mask & 2
^= test ^= pre_test test = test ^ pre_test
|= flag |= ON flag = flag | ON

133 © 2021 UCEN


Example

#include <stdio.h>
main()
{
int num1 = 3, num2 = 5;
printf("\n Initial value of num1 = %d and num2 = %d", num1,
num2);
num1 += num2 * 4 - 7;
printf("\n After the evaluation of the expression num1 = %d and
num2 = %d", num1, num2);
return 0;
}

O/P:
Initial value of num1 =3 and num2 = 5
After the evaluation of the expression num1 = 16 and num2 = 5

134 © 2021 UCEN


Comma Operator

 Comma operator represented by ‘,’ ensures the


evaluation from left to right, one by one, of two or
more expressions, separated with commas, and result
of entire expression is value of rightmost expression
 Example
int a = 10, b = 20, c = 30;
int x;
printf("Value of exp. "x = a + b, b + c, c + a;" is %d\n",
(x = a + b, b + c, c + a));
Another Ex:
int x, y, z, a = 10, b = 20, c = 30;

135 © 2021 UCEN


sizeof operator
 It is a compile-time unary operator and used to
compute the size of its operand.
 It returns the size of a variable.
 It can be applied to any data type, float type, pointer
type variables.
 When sizeof() is used with the data types, it simply
returns the amount of memory allocated to that data
type.
 The output can be different on different machines like
a 32-bit system can show different output while a 64-
bit system can show different of same data types.

136 © 2021 UCEN


Example

#include <stdio.h>
int main()
{
int a = 16;
printf("Size of variable a : %d\n",sizeof(a));
printf("Size of int data type : %d\n",sizeof(int));
printf("Size of char data type : %d\n",sizeof(char));
printf("Size of float data type : %d\n",sizeof(float));
printf("Size of double data type : %d\n",sizeof(double));
return 0;
}

Output
Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8

137 © 2021 UCEN


Operator precedence Chart
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= Right to left
^= |=
Comma , Left to right
138 © 2021 UCEN
Type Conversions
 When an operator has operands of different types, they
are converted to a common type according to a small
number of rules.
 When Low to high – Converts automatically

 The following informal set of rules will suffice:


 If either operand is long double, convert the other to long double.
 Otherwise, if either operand is double, convert the other to double.
 Otherwise, if either operand is float, convert the other to float.
 Otherwise, convert char and short to int.
 Then, if either operand is long, convert the other to long.

 Conversions take place across assignments; the value of


the right side is converted to the type of the left, which is
the type of the result.

139 © 2021 UCEN


Type Conversions (Contd.).
 Consider the following assignments:
int i; Int Char
char c;
i = c;

 In the aforesaid assignment, the data type on the right


(char) is converted to the data type on the left (int) which is
the type of the result.

 If x is float and i is int, then x = i and i = x both cause


conversions; float to int causes truncation of any fractional
part. When a double is converted to float, whether the
value is rounded or truncated is implementation
dependent.

140 © 2021 UCEN


Explicit Type Conversion (Type casting)
 In the construction (type name) expression, the
expression is converted to the named type by the
conversion rules above.

 Consider the following example:


int i, j;
double d;
d = i / j; /* double assigned the result of the division of two integers */

 The problem with the above assignment is that the


fractional portion of the above division is lost, and d is
effectively assigned the integer quotient of the two
integers i and j.

141 © 2021 UCEN


Explicit Type Conversion (Contd.).
 To resolve this, the variable i can be type cast into a
double as in:
d = (double)i / j;

 int i is converted to a double using the explicit cast


operator. Since one of the operands is a double, the
other operand (j) is also converted to a double, and
the result is a double.

 The result is assigned to a double with no side


effects. The cast operator can be done only on the
right-hand side of an assignment.

142 © 2021 UCEN


Write a program to convert a floating point
number into the corresponding integer

#include <stdio.h>
#include <conio.h>
int main()
{
float f_num;
int i_num;
clrscr();
printf("\n Enter any floating point number: ");
scanf("%f", &f_num);
i_num = (int)f_num;
printf("\n The integer variant of %f is = %d", f_num, i_num);
return 0;
}

143 © 2021 UCEN


Write a program to convert an integer into the
corresponding floating point number

#include <stdio.h>
#include <conio.h>
int main()
{
float f_num;
int i_num;
clrscr();
printf("\n Enter any integer: ");
scanf("%d", &i_num);
f_num = (float)i_num;
printf("\n The floating point variant of %d is = %f", i_num,
f_num);
return 0;
}

144 © 2021 UCEN


Decision Control &
Looping Statements

145 © 2021 UCEN


Control Structures
 These are the statements which alter the normal
(sequential)execution flow of a program.
 Helps to jump from one part of the program to another
depending on whether particular condition is satisfied.
 There are three types of Control Statements in C
Decision Making Looping Unconditional

If For Break

If-else While Continue

If-else-if Do..while goto

switch

146 © 2021 UCEN


if statement
The general form :
if(test expression)
{
statement–block; Entry

}
statement-x; True
test expression ?

statement–block
False

Statement-x

147 © 2021 UCEN


Example
 Write a program to determine whether a person is eligible to
vote
#include <stdio.h>
#include <conio.h>
main()
{
int age;
printf("\n Enter the age: ");
scanf("%d", "&age");
if(age >= 18)
printf("\n You are eligible to vote");
getch();
return 0;
}

148 © 2021 UCEN


Write a program to determine the character
entered by the user
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
main()
{
char ch;
printf("\n Press any key: ");
scanf("%c", &ch);
if(isalpha(ch)>0)
printf("\n The user has entered a character");
if(isdigit(ch)>0)
printf("\n The user has entered a digit");
if(isprint(ch)>0)
printf("\n The user has entered a printable character");
if(ispunct(ch)>0)
printf("\n The user has entered a punctuation mark");
if(isspace(ch)>0)
printf("\n The user has entered a white space character");
getch();
return 0;
}

149 © 2021 UCEN


if….else statement
The if….else statement is an extension of simple if statement. The general
form is,

if(test expression) Entry


{
true-block statements;
} False
else True Test expression?
{
False-block statements;
} True-block False-block
statement-x;

Statement-x

150 © 2021 UCEN


Example – Largest of 2 numbers
#include <stdio.h>
main()
{
int a, b, large;
printf("\n Enter the values of a and b: ");
scanf("%d %d", &a, &b);
if(a>b)
large = a;
else
large = b;
printf("\n LARGE = %d", large);
return 0;
}
151 © 2021 UCEN
Example - if- else Construct

The following function checks whether the character start


entered by the user is a star (*) character.

#include <stdio.h> ch = ‘ ‘
main( )
{
char ch;
Input ch
ch = getchar( );
fflush(stdin);
if (ch = = ‘*’) true
puts (“You have entered the star is ch = ‘*’ Print *
character”);
else false
puts (“You have not entered the star
character”);
Not a *
}

stop

152 © 2021 UCEN


Example - if- else Construct (Contd.).
/* Write a program to fi nd whether the given number is even or
odd.*/

#include <stdio.h>
#include <conio.h>
main()
{
int num;
clrscr();
printf("\n Enter any number: ");
scanf("%d",&num);
if(num%2 == 0)
printf("\n %d is an even number", num);
else
printf("\n %d is an odd number", num);
return 0;
}

153 © 2021 UCEN


Example
/*Write a program to enter a character and then determine whether it is a vowel
or not.*/

#include <stdio.h>
#include <conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter any character: ");
scanf("%c", &ch);
if(ch ='a' ||ch =='e' ||ch=='i' ||ch=='o' ||ch=='u' || ch=='A' ||ch=='E' ||ch=='I' ||ch=='O'
||ch=='U' )
printf("\n %c is a VOWEL", ch);
else
printf("\n %c is not a vowel");
getch();
return 0;
}
154 © 2021 UCEN
Example
/* Write a program to fi nd whether a given year is a leap year or not.*/

#include <stdio.h>
#include <conio.h>
int main()
{
int year;
clrscr();
printf("\n Enter any year: ");
scanf("%d",&year);
if((year%4 == 0) && ((year%100 !=0) || (year%400 == 0)))
printf("\n Leap Year");
else
printf("\n Not A Leap Year");
return 0;
}

155 © 2021 UCEN


Cascading if- else Construct
(if –else – if statement)

 The cascading if-else construct is also known as


the multiple if-else construct.

 On the first condition evaluating to false, the else


part of the first condition consists of another if
statement that is evaluated for a condition.

 If this condition evaluates to false, the else part of


this if condition consists of another if statement
that is evaluated for a condition, and so on.

156 © 2021 UCEN


Example - Cascading if - else

/* Function to determine for input of numbers 0 through 9 */


#include <stdio.h>
main( )
{char chr;
chr = getchar( );
if (chr = = ‘0’)
puts(“You entered the number 0”);
else if (chr = = ‘1’)
puts(“You entered the number 1”);
else if (chr = = ‘2’)
puts(“You entered the number 2”);
..
else if (chr = = ‘9’)
puts(“You entered the number 9”);
else
puts(“You did not enter a number”);
}

157 © 2021 UCEN


Example
/* Write a program to demonstrate the use of nested if
structure.*/

#include <stdio.h>
{
int x, y;
printf("\n Enter two numbers: ");
scanf("%d %d", &x, &y);
if(x == y)
printf("\n The two numbers are equal");
else if(x > y)
printf("\n %d is greater than %d", x, y);
else
printf("\n %d is less than %d", x, y);
return 0;
}
158 © 2021 UCEN
/*Write a program to test whether a number entered is positive, negative or
equal to zero.*/

#include <stdio.h>
main()
{
int num;
printf("\n Enter any number: ");
scanf("%d", &num);
if(num==0)
printf("\n The value is equal to zero");
else if(num>0)
printf("\n The number is positive");
else
printf("\n The number is negative");
return 0;
}

159 © 2021 UCEN


A company decides to give bonus to all its employees on Diwali. A 5% bonus on
salary is given to the male workers and 10% bonus on salary to the female workers.
Write a program to enter the salary and sex of the employee. If the salary of the
employee is less than Rs 10,000 then the employee gets an extra 2% bonus on
salary. Calculate the bonus that has to be given to the employee and display the
salary that the employee will get
#include <stdio.h>
#include <conio.h>
main()
{
char ch;
float sal, bonus, amt_to_be_paid;
printf("\n Enter the sex of the employee (m or f): ");
scanf("%c", &ch);
printf("\n Enter the salary of the employee: ");
scanf("%f", &sal);
if(ch == 'm')
bonus = 0.05 * sal;
else
bonus = 0.10 * sal;
if (sal < 10000)
bonus += 0.20 * sal;
amt_to_be_paid = sal + bonus;
printf("\n Salary = %f", sal);
printf("\n Bonus = %f", bonus);
printf("\n ***************************");
printf("\n Amount to be paid: %f", amt_to_be_paid);
getch();
return 0;
160 }
© 2021 UCEN
Write a program to display the examination
result
#include <stdio.h>
main()
{
int marks;
printf("\n Enter the marks obtained: ");
scanf("%d", &marks);
if ( marks >= 75)
printf("\n DISTINCTION");
else if ( marks >= 60 && marks <75)
printf("\n FIRST DIVISION");
else if ( marks >= 50 && marks < 60)
printf("\n SECOND DIVISION");
else if ( marks >= 40 && marks < 50)
printf("\n THIRD DIVISION");
else
printf("\n FAIL");
return 0;
}
161 © 2021 UCEN
Write a program to find the greatest three numbers
#include <stdio.h>
#include <conio.h>
int main()
{
int num1, num2, num3, big=0;
clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
if(num1>num2)
{
if(num1>num3)
printf("\n %d is greater than %d and %d", num1, num2, num3);
else
printf("\n %d is greater than %d and %d", num3, num1, num2);
}
else if(num2>num3)
printf("\n %d is greater than %d and %d", num2, num1, num3);
else
printf("\n %d is greater than %d and %d", num3, num1, num2);
return 0;
}

162 © 2021 UCEN


/* Write a program to input three numbers and then find the largest of them
using && operator.*/
#include <stdio.h>
#include <conio.h>
main()
{
int num1, num2, num3;
clrscr();
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
if(num1>num2 && num1>num3)
printf("\n %d is the largest number", num1);
if(num2>num1 && num2>num3)
printf("\n %d is the largest number", num2);
else
printf("\n %d is the largest number", num3);
getch();
return 0;
}
163 © 2021 UCEN
/* Write a program to enter the marks of a student in four subjects. Then calculate the total, aggregate, and display the grades obtained by
the student.*/
#include <stdio.h>
#include <conio.h>
{
int marks1, marks2, marks3, marks4, total = 0;
float avg =0.0;
clrscr();
printf("\n Enter the marks in Mathematics: ");
scanf("%d", &marks1);
printf("\n Enter the marks in Science: ");
scanf("%d", &marks2);
printf("\n Enter the marks in Social Science: ");
scanf("%d", &marks3);
printf("\n Enter the marks in Computer Science: ");
scanf("%d", &marks4);
total = marks1 + marks2 + marks3 + marks4;
avg = total/4;
printf("\n Total = %d", total);
printf("\n Aggregate = %.2f", avg);
if(avg >= 75)
printf("\n DISTINCTION");
else if(avg>=60 && avg<75)
printf("\n FIRST DIVISION");
else if(avg>=50 && avg<60)
printf("\n SECOND DIVISION");
else if(avg>=40 && avg<50)
printf("\n THIRD DIVISION");
else
printf("\n FAIL");
return 0;
164 } © 2021 UCEN
Nested if Construct

 A nested if statement is encountered if the


statement to be executed after a condition
evaluates to true is another if statement.

 Both the outer if statement and the inner if


statement have to evaluate to true for the
statement following the inner if condition to be
executed.

165 © 2021 UCEN


Nested if Construct: Syntax
if (condition1)
{
if (condition2)
If
{ Condition
True statements; 1
} False
else True
Statements2
{
False statements; True
If
False
} Condition
} 2
else
{
True False
False statements2; statements statements
}

166 © 2021 UCEN


Example
#include <stdio.h>
int main()
{
int dig1, dig2, dig3;
printf("Enter three numbers: ");
scanf("%d%d%d", &dig1, &dig2, &dig3);
if(dig1 > dig2)
{
if(dig1 > dig3)
{
printf("dig1 is the maximum");
}
else
{
printf("dig3 is the maximum");
}
}
else
{
if(dig2 > dig3)
{
printf("dig2 is the maximum");
}
else
{
printf("dig3 is the maximum");
}
}
return 0;
}
167 © 2021 UCEN
switch statement
 The switch statement tests the value of a given variable(or
expression) against a list of case values and when a match is
found, a block of statements associated with that case is
executed.

 The break statement at the end of each block signals the end
of particular case and causes an exit from the switch
statement, transferring the control to the statement-x.

 The default is an optional case. When present, it will be


executed if the value of the expression does not match any of
the case values.

 If default not present, no action takes place if all matches fail


and control goes to statement-x.

168 © 2021 UCEN


switch statement
Syntax
switch (expression) switch(expression)
{
case constant 1:
case 1:
block1;
break;
case constant 2:
block2; case 2:
break;
.
. default:
default :
default block;
break;
}

169 © 2021 UCEN


Example – switch statement
/*Write a program to determine whether an entered character is a vowel or not.*/
#include <stdio.h>
int main()
{
char ch;
printf("\n Enter any character: ");
scanf("%c", &ch);
switch(ch)
{
case 'A':
case 'a':
printf("\n % c is VOWEL", ch);
break;
case 'E':
case 'e':
printf("\n % c is VOWEL", ch);
break;
case 'I':
case 'i':
printf("\n % c is VOWEL", ch);
break;
case 'O':
case 'o':
printf("\n % c is VOWEL", ch);
break;
case 'U':
case 'u':
printf("\n % c is VOWEL", ch);
break;
default:
printf("%c is not a vowel", ch);
}
170 return 0; } © 2021 UCEN
#include <stdio.h>
#include <conio.h>
int main()
{
int day;
clrscr();
printf("\n Enter any number from 1 to 7: ");
scanf("%d",&day);
switch(day)
{
case 1: printf("\n SUNDAY");
break;
case 2: printf("\n MONDAY");
break;
case 3: printf("\n TUESDAY");
break;
case 4: printf("\n WEDNESDAY");
break;
case 5: printf("\n THURSDAY");
break;
case 6: printf("\n FRIDAY");
break;
case 7: printf("\n SATURDAY");
break;
default: printf("\n Wrong Number");
}
return 0;
}

171 © 2021 UCEN


Iterative Constructs - The while Loop

 In a while loop, the loop condition


is written at the top followed by
the body of the loop.

 Therefore, the loop condition is False


evaluated first, and if it is true,
the loop body is executed. condition
 After the execution of the loop
body, the condition in the while True
statement is evaluated again.
This repeats until the condition
becomes false. Body of The loop

 General form
while(test-condition)
{
body of the loop
}

172 © 2021 UCEN


Example
Write a program to calculate the sum of first 10 numbers.

#include <stdio.h>
int main()
{
int i = 0, sum = 0;
while(i<=10)
{
sum = sum + i;
i = i + 1; // condition updated
}
printf("\n SUM = %d", sum);
return 0;
}

173 © 2021 UCEN


Write a program to calculate the sum of
numbers from m to n.
#include <stdio.h>
#include <conio.h>
int main()
{
int n, m, sum =0;
clrscr();
printf("\n Enter the value of m: ");
scanf("%d", &m);
printf("\n Enter the value of n: ");
scanf("%d", &n);
while(m<=n)
{
sum = sum + m;
m = m + 1;
}
printf("\n SUM = %d", sum);
return 0;
}

174 © 2021 UCEN


Write a program to read the numbers until –1 is encountered. Also count the negative, positive,
and zeros entered
by the user.
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int negatives=0, positives=0, zeros=0;
clrscr();
printf("\n Enter -1 to exit….");
printf("\n\n Enter any number: ");
scanf("%d",&num);
while(num != -1)
{
if(num>0)
positives++;
else if(num<0)
negatives++;
else
zeros++;
printf("\n\n Enter any number: ");
scanf("%d",&num);
}
printf("\n Count of positive numbers entered = %d", positives);
printf("\n Count of negative numbers entered = %d", negatives);
printf("\n Count of zeros entered = %d", zeros);
getch();
return 0;
}
175 © 2021 UCEN
do…while loop

 The general form of do..while


loop is
do Body of The loop
{
body of the loop
} while (test-condition) ;
True

 The do..while construct condition


provides an exit-controlled
loop as the test-condition is False
evaluated at the bottom of
the loop and therefore the
body of the loop is always
executed at least once.

176 © 2021 UCEN


Example – do…while loop

/* This is an example of a do-while loop */


main()
{
int i;
i = 0;
do {
printf("The value of i is now %d\n",i);
i = i + 1;
} while (i < 5);
}

177 © 2021 UCEN


. Write a program to calculate the average of first n numbers

#include <stdio.h>
int main()
{
int n, i = 0, sum =0;
float avg = 0.0;
printf("\n Enter the value of n: ");
scanf("%d", &n);
do
{
sum = sum + i;
i = i + 1;
}
while(i<=n);
avg = sum/n;
printf("\n The sum of first n numbers = %d", sum);
printf("\n The average of first %d numbers = %f", n, avg);
return 0;
}

178 © 2021 UCEN


for loop
 The for loop is another
entry-controlled loop that
provides a more concise Initialization
loop structure

for(initialization;test-
condition;increment)
Inc / Decrement
{

}
body of the loop
Body of the loop

condition
 Initialization of the True
control variable is false
done first, using
assignment
statements
179 © 2021 UCEN
Example – for loop

#include <stdio.h>
/* this function displays a message 10
times */
main( )
{
int i;
for( i = 0; i <= 9; i = i + 1)
{
puts( “message %d”,i);
}
}

180 © 2021 UCEN


Features of for loop
 Initializing, testing and incrementing are placed in the for loop itself,
thus making them visible to the programmers and users, in one place.

 The for statement allows for negative increments. More than one
variable can be initialized at a time.
 for (p=1,n=0;n<17;++n)

 The increment section can also have more than one part.
 for (n=1,m=50;n<=m;m++,n--)

 One or more sections can be omitted, if necessary.


 for(;m!=0;)
 ** The semicolons separating the sections must remain.

 If the test-condition is not present, the for statement sets up an infinite


loop.
 for(i=0; ;i++)

181 © 2021 UCEN


Control of Loop Execution

 A loop construct, whether while, or do-while, or a


for loop continues to iteratively execute until the
loop condition evaluates to false.

 The break statement is used to exit early from all


loop constructs (while, do-while, and for)

 The continue statement used in a loop causes all


subsequent instructions in the loop body (coming
after the continue statement) to be skipped.

182 © 2021 UCEN


break and continue statements
 When a break statement is encountered in a loop,the loop is
exited and the program continues with the statements
immediately following the loop.

 When the loops are nested,the break would only exit from the
loop containing it.

 continue statement causes the loop to be continued with the


next iteration after skipping any statements in between.

 In while and do loops,continue causes the control to go


directly to the test-condition and then continue the iteration
process.

 In case of for loop, the increment section of the loop is


executed before the test-condition is evaluated

183 © 2021 UCEN


Example: (continue & break)
int i;
for (i=0;i<10;i++) {
if (i==5)
continue;
printf("%d",i);
if (i==8)
break;
}

This code will print 1 to 8 except 5.

184 © 2021 UCEN


goto statement
 C supports goto statement to branch unconditionally
from one point to another in a program.

 The goto requires a label in order to identify the place


where the branch is to be made.

 A label is any valid variable name , and must be


followed by a colon.
goto label;
... ..
... .
.. ..
...
label:
statement;
185 © 2021 UCEN
Example

#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?“
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

186 © 2021 UCEN


C Statements

 Expression
 Conditional
 if (expr) { … } else {…}
 switch (expr) { case c1: case c2: … }

 Iteration
 while (expr) { … } zero or more iterations
 do … while (expr) at least one iteration
 for ( init ; valid ; next ) { … }

 Jump
 goto label
 continue; go to start of loop
 break; exit loop or switch
 return expr; return from function

187 © 2021 UCEN


Storage Classes
 A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program.
 They precede the type that they modify.
 The storage class of a function or a variable determines the part of memory
where storage space will be allocated for that variable or function
 It specifies how long the storage allocation will continue to exist for that
function
 It specifies scope of variable or function
 It specifies whether the variable or function has internal or external or no
linkage
 It specifies whether the variable will be automatically initialized to 0 or any
other value.
 4 different storage classes in a C program
 auto
 register
 static
 Extern
 General Syntax: <storage_class_specifier> <data type> <variable name>

188 © 2021 UCEN


auto
 This is the default storage class for all the variables
declared inside a function or a block.
 Hence, the keyword auto is rarely used while writing
programs in C language.
 Auto variables can be only accessed within the
block/function they have been declared and not outside
them (which defines their scope).
 Of course, these can be accessed within nested blocks
within the parent block/function in which the auto variable
was declared.
 However, they can be accessed outside their scope as well
using the concept of pointers given here by pointing to the
very exact memory location where the variables resides.
 They are assigned a garbage value by default whenever
they are declared.

189 © 2021 UCEN


Storage Memory
Default value Garbage value
Local to the block in which
Scope the variable is defined
Till the control remains
Life time within the block in which
variable is defined

190 © 2021 UCEN


#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of
automatic variables a, b, and c.
return 0;
}
Output:
Garbage value

191 © 2021 UCEN


#include<stdio.h>
int main(){
int a=10;
{
int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}

 Output:
 20 10

192 © 2021 UCEN


#include<stdio.h>
int main(){
{
int a=20;
printf("%d",a);
}
printf(" %d",a); //a is not visible here
return 0;
}

 Output: Compilation error

193 © 2021 UCEN


register
 The register storage class is used to define local variables that should
be stored in a register instead of RAM.
 This makes the use of register variables to be much faster than that of
the variables stored in the memory during the runtime of the program.
 This means that the variable has a maximum size equal to the register
size (usually one word) and can't have the unary '&' operator applied to
it (as it does not have a memory location).
 The register should only be used for variables that require quick access
such as counters.
 It should also be noted that defining 'register' does not mean that the
variable will be stored in a register.
 It means that it MIGHT be stored in a register depending on hardware
and implementation restrictions.
 An important and interesting point to be noted here is that we cannot
obtain the address of a register variable using pointers.
 Static variables can not be stored into the register since we can not use
more than one storage specifier for the same variable.
 storage_class var_data_type var_name;

194 © 2021 UCEN


Storage Register
Default value Garbage value
Local to the block in which
Scope
the variable is defined
Till the control remains
Life time within the block in which
variable is defined

195 © 2021 UCEN


#include <stdio.h>
int main()
{
register int a;
/* variable a is allocated memory in the CPU registe
r. The initial default value of a is 0. */
printf("%d",a);
}

O/P: 0

196 © 2021 UCEN


#include <stdio.h>
int main()
{
register int a = 0;
printf("%u",&a); // This will give a compile time error
since we can not access the address of a registe
r variable.
}

O/p: main.c:5:5: error: address of register variable


?a? requested printf("%u",&a); ^~~~~~

197 © 2021 UCEN


Extern
 The external storage class is used to tell the compiler that
the variable defined as extern is declared with an external
linkage elsewhere in the program.
 The variables declared as extern are not allocated any
memory. It is only declaration and intended to specify that
the variable is declared elsewhere in the program.
 The default initial value of external integral type is 0
otherwise null.
 We can only initialize the extern variable globally, i.e., we
can not initialize the external variable within any block or
method.
 An external variable can be declared many times but can be
initialized at only once.
 If a variable is declared as external then the compiler
searches for that variable to be initialized somewhere in the
program which may be extern or static. If it is not, then the
compiler will show an error.
198 © 2021 UCEN
In short….
 A declaration can be done any number of times but
definition only once.
 the extern keyword is used to extend the visibility of
variables/functions.
 Since functions are visible throughout the program by
default, the use of extern is not needed in function
declarations or definitions. Its use is implicit.
 When extern is used with a variable, it’s only declared,
not defined.
 As an exception, when an extern variable is declared
with initialization, it is taken as the definition of the
variable as well.

199 © 2021 UCEN


Storage Memory

Default value Zero


Global
Scope (i.e., Throughout the program
)
As long as the program’s
Life time execution does not comes to
end

200 © 2021 UCEN


#include <stdio.h>
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}
Output: 0

201 © 2021 UCEN


#include <stdio.h>
extern int i; //extern variable
int main(){
printf("%d",i);
return 0;
}
Output: Compilation error, undefined symbol i.

202 © 2021 UCEN


#include <stdio.h>
extern int i=10; //extern variable
int main(){
printf("%d",i);
return 0;
}
Output: 10

203 © 2021 UCEN


static
 The static storage class instructs the compiler to keep
a local variable in existence during the life-time of the
program instead of creating and destroying it each
time it comes into and goes out of scope.
 Therefore, making local variables static allows them to
maintain their values between function calls.
 The static modifier may also be applied to global
variables.
 When this is done, it causes that variable's scope to
be restricted to the file in which it is declared.
 In C programming, when static is used on a global
variable, it causes only one copy of that member to be
shared by all the objects of its class.

204 © 2021 UCEN


In short

 The variables defined as static specifier can hold their


value between the multiple function calls.
 Static local variables are visible only to the function or
the block in which they are defined.
 A same static variable can be declared many times
but can be assigned at only one time.
 Default initial value of the static integral variable is 0
otherwise null.
 The visibility of the static global variable is limited to
the file in which it has declared.
 The keyword used to define static variable is static.

205 © 2021 UCEN


Storage Memory
Default value Zero
Local to the block in which
Scope
the variable is defined
The value of the persists
between different function
Life time
calls (i.e., Initialization is
done only once)

206 © 2021 UCEN


#include<stdio.h>
int a;
int main(){
printf("%d",a);
return 0;
}
 O/p: 0

207 © 2021 UCEN


#include <stdio.h>
static char c;
static int i;
static float f;
int main(){
printf("%d %d %f",c,i,f);
return 0;
}
Output: 0 0 0.000000

208 © 2021 UCEN


#include <stdio.h>
static int i=10;
int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}
Output: 25

209 © 2021 UCEN


#include<stdio.h>
int main(){
{
static int a=5;
printf("%d",a);
}
//printf("%d",a); variable a is not visible here.
return 0;
}
Output: 5

210 © 2021 UCEN


#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}
 Output:
10 24
11 25
12 26

211 © 2021 UCEN


Preprocessor Directives

212 © 2021 UCEN


Preprocessor Directives
 As the name suggests Preprocessors are programs
that process our source code before compilation.

213 © 2021 UCEN


Preprocessor Directives
 preprocessors directives which tell the compiler to
preprocess the source code before compiling.
 All of these preprocessor directives begin with a ‘#’
(hash) symbol.
 The ‘#’ symbol indicates that, whatever statement
starts with #, is going to the preprocessor program,
and preprocessor program will execute this
statement.
 To extent preprocessor directives to multiple lines use
\ as last character of line

214 © 2021 UCEN


Advantage

 Developing easy to develop, easy to read and


easy to modify programs.
 Transporting the code between different
machines.
 Makes program efficient to use

215 © 2021 UCEN


Preprocessor
Types Directives

Unconditional Conditional

Define If

Line Else

undef Elif

Include Ifdef

Error Ifndef

pragma endif

216 © 2021 UCEN


#define Preprocessor Directive:
 It is known as macro definition
 It use #define
 Two Types
 Object Like Macro
 Function Like Macro
 Object Like Macro
 The #define directive creates symbolic constants
 It do not take any arguments
 The #define directive format is
 #define identifier string
 When this line appears in a file, all subsequent occurrences of
identifier that do not appear in string literals will be replaced by
string automatically before the program is compiled.
#define Preprocessor Directive:
 For example,
 #define PI 3.14159
replaces all subsequent occurrences of the symbolic constant
PI with the numeric constant 3.14159.
Example :
area = PI * radius * radius;
 It will recognize as area = 3.14159* radius * radius;
 Symbolic constants enable you to create a name for a constant
and use the name throughout the program.
 If the constant needs to be modified throughout the program, it
can be modified once in the #define directive.
 When the program is recompiled, all occurrences of the
constant in the program will be modified accordingly.
#define Preprocessor Directive:
 Everything to the right of the symbolic constant name replaces
the symbolic constant.] For example, #define PI =
3.14159 causes the preprocessor to replace every occurrence
of the identifier PI with = 3.14159.
 This is the cause of many subtle logic and syntax errors.
 Redefining a symbolic constant with a new value is also an
error.
Example
#include <stdio.h>
#define PI 3.1415

int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);

// Notice, the use of PI


area = PI*radius*radius;

printf("Area=%.2f",area);
return 0;
}
#define Preprocessor Directive:
 A macro definition also include an expression
 EX1
#define ROWS 3
#define COLUMNS 3
#define SIZE (ROWS * COLUMNS)
 EX2
#include<stdio.h>
#include<conio.h>
#define INPUT printf(“\n Enter a number”); scanf(“%d”,&num);
define EQUALS ==
#define PRINT1 printf(“Great”);
#define PRINT2 printf(“Try Again”);
#define START main()
#define END getch(); \
return 0; }
START
int num;
INPUT
if(num EQUALS )
PRINT1;
else
PRINT2;
END
#define Preprocessor Directive:
Function Like Macros
 More complex than object like macros
 They stimulates functions
 It includes list of parameters
 Syntax:
 #define identifier(arg1,arg2,….argn)
 String
 Consider the following macro definition with one argument
for the area of a circle:
 #define CIRCLE_AREA( x ) ( ( PI ) * ( x ) * ( x ) )
 Wherever CIRCLE_AREA(y) appears in the file, the value of
y is substituted for x in the replacement-text, the symbolic
constant PI is replaced by its value (defined previously) and
the macro is expanded in the program.
#define Preprocessor Directive:
 For example, the statement
 area = CIRCLE_AREA( 4 );

is expanded to
 area = ( ( 3.14159 ) * ( 4 ) * ( 4 ) );

and the value of the expression is evaluated and assigned to


variable area.
 The parentheses around each x in the replacement text force
the proper order of evaluation when the macro argument is an
expression.
Example
#include <stdio.h>
#define PI 3.1415
#define circleArea(r) (PI*r*r)

int main() {
float radius, area;

printf("Enter the radius: ");


scanf("%f", &radius);
area = circleArea(radius);
printf("Area = %.2f", area);

return 0;
}
#define Preprocessor Directive:
 Macro CIRCLE_AREA could be defined as a function.
 Function circleArea
 double circleArea( double x )
{
return 3.14159 * x * x;
}
performs the same calculation as macro CIRCLE_AREA, but
the overhead of a function call is associated with function
circleArea.
#define Preprocessor Directive:
 The advantages of macro CIRCLE_AREA are that macros
insert code directly in the program—avoiding function call
overhead—and the program remains readable because the
CIRCLE_AREA calculation is defined separately and named
meaningfully.
 A disadvantage is that its argument is evaluated twice.
#define Preprocessor Directive:
 The following is a macro definition with two arguments for
the area of a rectangle:
 #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) )
 Wherever RECTANGLE_AREA(x, y) appears in the
program, the values of x and y are substituted in the macro
replacement text and the macro is expanded in place of the
macro name.
 For example, the statement
 rectArea = RECTANGLE_AREA( a + 4, b + 7 );

 is expanded to
 rectArea = ( ( a + 4 ) * ( b + 7 ) );
#define Preprocessor Directive:
 The value of the expression is evaluated and assigned to
variable rectArea.
 The replacement text for a macro or symbolic constant is
normally any text on the line after the identifier in the
#define directive.
 If the replacement text for a macro or symbolic constant is
longer than the remainder of the line, a backslash (\) must be
placed at the end of the line, indicating that the replacement
text continues on the next line.
#define Preprocessor Directive: Nesting
of Macros
 #define SQUARE(X) ((X)*(X))
 #define CUBE(X) (SQUARE(X)*(X))
 #define FOURTH_POWER(X) (CUBE(X)*(X))
 Nested Upto 31 levels
Rules
 Macro Name and formal arguments must follow identifier
rules
 Space, tabs and comments are allowed within #define
directive
 White space in between the identifier and the left
parentheses that introduces the parameter list is not
allowed
 Number of arguments must match
#operator to convert to string literals
#include <stdio.h>
#define PRINT(num) printf(#num”=%d”, num)
main()
{
PRINT(20);
}
PRINT(20); is replaced as printf(num”=%d”, num)
Anoterh Example
#define MAC(x) #x
MAC(“10”) gives string literal “10”
MAC(“HI”) gives string literal “HI”
Rules of using #operator I function like macro
definition
 A parameter following # operator in a function-like macro is converted into
a string literal containing the argument passed to the macro.
 Leading and trailing white-space characters (those that appear before or
after) in the argument passed to the macro are deleted.
 If the argument passed to the macro has multiple white space characters,
then they are replaced by a single space character.
 If the argument passed to the macro contains a string literal and if a
\(backslash) character appears within the literal, then on expansion of the
macro, a second\ character is inserted before the original \.
 If the argument passed to the macro contains a " (double quotation mark)
character, then on expansion of the macro, a character is inserted before
the ".
 The conversion of an argument into a string literal occurs before macro
expansion on that argument.
 If there is more than one # operator in the replacement list of a macro
definition, the order of evaluation of the operators is not defined.
 If the result of the macro expansion is not a valid character string literal,
the behaviour is undefined.
# and ## Operators
 The # and ## preprocessor operators are available in Standard
C.
 The # operator causes a replacement text token to be converted
to a string surrounded by quotes.
 Consider the following macro definition:
 #define HELLO(x) printf( "Hello, " #x "\n" );

 When HELLO(John) appears in a program file, it is expanded


to
 printf( "Hello, " "John" "\n" );

 The string "John" replaces #x in the replacement text.


13.7 # and ## Operators (Cont.)
 Strings separated by white space are concatenated during
preprocessing, so the preceding statement is equivalent to
 printf( "Hello, John\n" );

 The # operator must be used in a macro with arguments


because the operand of # refers to an argument of the macro.
 The ## operator concatenates two tokens.
13.7 # and ## Operators (Cont.)
 Consider the following macro definition:
 #define TOKENCONCAT(x, y) x ## y
 When TOKENCONCAT appears in the program, its arguments
are concatenated and used to replace the macro.
 For example, TOKENCONCAT(O, K) is replaced by OK in the
program.
 The ## operator must have two operands.
Merge Operator ##
#include<stdio.h>
#define JOIN(A,B) A##B
main()
{
int I;
for (i=1;i<=5,i++)
printf(“\n HI JOIN(USER,i):”);
}
O/p:
HI USER1
HI USER2
HI USER3
HI USER4
HI USER5
#include Preprocessor Directive
 The #include preprocessor directive has been used throughout
this text.
 The #include directive causes a copy of a specified file to be
included in place of the directive.
 The two forms of the #include directive are:
 #include <filename>
 #include "filename"
 The difference between these is the location the preprocessor
begins searches for the file to be included.
 If the file name is enclosed in quotes, the preprocessor starts
searches in the same directory as the file being compiled for the
file to be included (and may search other locations, too).
#include Preprocessor Directive
 This method is normally used to include programmer-defined
headers.
 If the file name is enclosed in angle brackets (< and >)—used
for standard library headers—the search is performed in an
implementation-dependent manner, normally through
predesignated compiler and system directories.
#include Preprocessor Directive
 The #include directive is used to include standard library
headers such as stdio.h and stdlib.h and with
programs consisting of several source files that are to be
compiled together.
 A header containing declarations common to the separate
program files is often created and included in the file.
 Examples of such declarations are structure and union
declarations, enumerations and function prototypes.
#undef Preprocessor Directive:
 Symbolic constants and macros can be discarded by using the
#undef preprocessor directive.
 Directive #undef “undefines” a symbolic constant or macro
name.
 The scope of a symbolic constant or macro is from its
definition until it is undefined with #undef, or until the end
of the file.
 Once undefined, a name can be redefined with #define.
 Functions in the standard library sometimes are defined as
macros based on other library functions.
Example
#define MAX 10
#define MIN (X, Y) (((X) < (Y)) ? ( (X) : (Y) )
.
.
.
.
#undef MAX
#undef MIN
#define Preprocessor Directive:
 A macro commonly defined in the stdio.h header is
 #define getchar() getc( stdin )

 The macro definition of getchar uses function getc to get


one character from the standard input stream.
 Function putchar of the stdio.h header and the character
handling functions of the ctype.h header often are
implemented as macros as well.
 Expressions with side effects (i.e., variable values are
modified) should not be passed to a macro because macro
arguments may be evaluated more than once.
Line Numbers
 The #line preprocessor directive causes the subsequent
source code lines to be renumbered starting with the specified
constant integer value.
 The directive
 #line 100

starts line numbering from 100 beginning with the next


source code line.
 A file name can be included in the #line directive.
13.8 Line Numbers (Cont.)
 The directive
 #line 100 "file1.c"

indicates that lines are numbered from 100 beginning with the
next source code line and that the name of the file for the
purpose of any compiler messages is "file1.c".
 The directive normally is used to help make the messages
produced by syntax errors and compiler warnings more
meaningful.
 The line numbers do not appear in the source file.
EXAMPLE
#include<stdio.h>
main()
{
#line 10 “Error.c”
Int a=10:
#line 20
printf(“%d”,a);
}
Pragma Directives
 #pragma directive is used to control the actions of the
compiler in a particular portion of a program without affecting
the program as a whole.
 You can include the pragma directive in your C program from
the point where you want them to take effect.
 The effect of pragma will be applied from the point where it is
included to the end of the compilation unit or until another
pragma changes its status.
 A #pragma directive is an instruction to the compiler and is
usually ignored during preprocessing.
 The syntax of using a pragma directive can be given as
 #pragma string
 Here, string can be one of the instructions given to the
compiler with any required parameters.
Instruction Description

COPYRIGHT To specify a copyright string

COPYRIGHT DATE To specify a copyright date for the


copyright string

HP SHLIB VERSION To create versions of a shared


library routine

LOCALITY To name a code subspace

OPTIMIZE To turn the optimization feature on


or off

OPT LEVEL To set the level of optimization

VERSIONID To specify a version string


Pragma Copyright
 The syntax of pragma copyright can be given as
 #pragma COPYRIGHT "string“
 Here, string specifies the set of characters included in the
copyright message in the object file. If no date is specified
using pragma COPYRIGHT DATE, then the current year is
used in the copyright message.
 For example, if we write
 #pragma COPYRIGHT "JRT Software Ltd“
 Then the following string is placed in the object code
(assuming the current year is 2011):
 © Copyright JRT Software Ltd, 2011. All rights reserved. No
part of this program may be photocopied, reproduced, or
transmitted without prior written consent of JRT Software Ltd.
Pragma Copyright_date
 The syntax of pragma COPYRIGHT DATE can be given as
 #pragma COPYRIGHT DATE "string“
 Here, the string is a date which will be used by the
COPYRIGHT pragma.
 For example, consider the pragma given below
 #pragma COPYRIGHT_DATE "1999-2011“
 #pragma COPYRIGHT "JRT Software Ltd.“
 The above pragma will place the following string in the object
code:
 © Copyright JRT Software Ltd, 1999-2011. All rights reserved.
No part of this program may be photocopied, reproduced, or
transmitted without prior written consent of JRT Software Ltd.
Pragma Optimize
 The syntax of using the pragma optimize can be given
as
 #pragma OPTIMIZE ON
 #pragma OPTIMIZE OFF
 The pragma optimize is basically used to turn on/off
optimization in sections of a source program.
 However, when using this pragma you must specify one
of the optimization options on the aCC command
 Also remember that the pragma optimize cannot be used
within a function.
 For example,
 acC +02 Prog.C
 // Set optimization to level 2 for Prog.C
#pragma OPTIMIZE OFF
void Funcl ()
{
// Turn off optimization for this function
}
#pragma OPTIMIZE ON
void Func2()
{
// Restore optimization to level 2
}
 Pragma OPT_LEVEL
The syntax for pragma OPT LEVEL which is used to set the optimization level to 1,2,3, or 4 can be given as
 #pragma OPT LEVEL 1
 #pragma OPT LEVEL 2
 #pragma OPT_LEVEL 3
 #pragma OPT LEVEL 4
 Like the optimization pragma, even this pragma cannot be used within a function. Finally, OPT_LEVEL 3 and 4 are allowed only at the beginning of a
file.
 For example,
acc -0 prog.C
#pragma OPT_LEVEL 1
void Funcl()
{
// Optimize Func() at level 1.
}
#pragma OPT_LEVEL 2
void Func2()
{
// Optimize Func() at level 2
}
Pragma HP_SHLIB_VERSION
 HP_SHLIB_VERSION pragma which is used to create
different versions of a shared library routine
 The syntax for
 #pragma HP_SHLIB_VERSION ["] date["]
 Here, the date argument is of the form month/year,
optionally enclosed in quotes. The month must be
specified using any number from 1 to 12. The year can
be specified as either the last two digits of the year (99
for 1999) or a full year specification(1999)
Pragma LOCALITY
 which is used to specify a name to be associated with
the code that is written to a re-locatable object module
 The syntax of pragma locality can be given as
 #pragma LOCALITY "string"
 Here, string specifies a name to be used for a code
subspace.
 After this directive, all codes following the directive are
associated with the name specified in string.
 The smallest scope of a unique LOCALITY pragma is a
function.
Pragma VERSIONID
 The syntax of pragma VERSIONID can be given as
 #pragma VERSIONID "string"
 Here, string is a string of characters that is placed in the
object file.
 For example
 #pragma VERSIONID "JRT Software Ltd., Version
12345.A.01.10"
 Then this pragma places the characters JRT Software
Ltd., Version 12345.A.01.10 into the object file.
Pragma once
 The pragma once specifies that the file, in which this
pragma directive is specified will be included (opened)
only once by the compiler in a building of a particular file.
Its syntax can be given as
 #pragma once
Conditional Directives
 Conditional compilation enables you to control the execution
of preprocessor directives and the compilation of program
code.
 Each of the conditional preprocessor directives evaluates a
constant integer expression.
 Cast expressions, sizeof expressions and enumeration
constants cannot be evaluated in preprocessor directives.
 The conditional preprocessor construct is much like the if
selection statement.
When to use
 A program need to be different code depending on the
machine or operating system it is to be done
 Useful when same source file into two different
programs.
#ifdef
 #ifdef is the simplest sort of conditional preprocessor directive
 It is used to check for the existence of macro definitions.
 Its syntax can be given as
#ifdef MACRO
controlled text
endif
 This block is called a conditional group.
 The controlled text will be included in the output of the preprocessor if and
only if MACRO is defined.
 The #ifdef is said to be successful if the MACRO is defined.
 The controlled text will be executed only if the #ifdef succeeds.
 Even if the #ifdef directive fails, the controlled text inside it is still run
through initial transformations and tokenization.
 So, the programmer must ensure that the controlled text is lexically valid.
 For example, all comments and string literals inside a failing conditional
group must still end properly.
Example
 The following example defines a stack array if MAX is
defined for the preprocessor.
#ifdef MAX
int STACK [MAX];
#endif
 In the above example, the stack array will not be created
if MAX had not been initially defined.
#ifndef
 The #ifndef directive is the opposite of #ifdef directive.
 It checks whether the MACRO has not been defined or if its
definition has been removed with #undef.
 #ifndef is successful and returns a non-zero value if the
MACRO has not been defined.
 Otherwise in case of failure, that is when the MACRO has
already been defined, #ifndef returns false (0).
 Therefore, #ifndef directive is used to define code that is to
be executed when a particular macro name is not defined.
 The general format to use #ifndef is the same as for #ifdef:
#ifndef MACRO
controlled text
#endif
#ifndef (Contf.,)
 You can also use #else directive with #ifdef and #ifndef
#ifdef MACRO
controlled text1
#else
controlled text2
#endif
#if Directive
 The #if directive is used control the compilation of
portions of a source file.
 If the specified condition (after the #if) has a non-zero
value, the controlled text immediately following the #if
directive is retained in the translation unit.
 The #if directive in its simplest form consists of
 #if condition
 controlled text
 #endif
#else directive
 #if condition
 Conditional text1
 #else
 Conditional text2
 #endif
#elif directive
 #if condition
 Conditional text1
 #elif new_condition
 Conditional text2
 #else
 Conditional text3
 #endif
example
 #define MAX 10
 #if OPTION==1
 Int STACK[MAX];
 #elif OPTION==2
 float STACK[MAX];
 #elif OPTION==3
 charSTACK[MAX];
 #else
 printf(“\n INVALID Option”);
 #endif
#Error Directive
#error string
Used to produce error message
Example
#ifndf SQUARE
#error MACRO not defined
#endif
#ifndf VERSION
#error VERSION NUMBER is not defined
#endif
#ifndf WINDOWS
/*-------Windows Specific Code ----*/
#else
#error “This code works only in Windows OS”
#endif
Predefined Macro Name
 _LINE_
 _FILE_
 _DATE_
 _TIME_
 _STDC_
 _TIMESTAMP_

You might also like