Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Unit I - Basics of C Programming

Uploaded by

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

Unit I - Basics of C Programming

Uploaded by

jankar123
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 147

CS8251 - Programming in C

Unit I - Basics of C Programming

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Basics of C Programming
Introduction to programming paradigms - Structure of C
program - C programming: Data Types – Storage classes -
Constants – Enumeration Constants - Keywords –
Operators: Precedence and Associativity - Expressions -
Input/output statements, Assignment statements – Decision
making statements - Switch statement - Looping statements
– Pre-processor directives - Compilation process.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Introduction to C

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

An Introduction
⮚ C was developed in the early 1970s by “Dennis Ritchie” at Bell
Laboratories
⮚ C was initially developed for writing system software
⮚ Today, C has become a popular language and various software
programs are written using this language.
⮚ Many other commonly used programming languages such as C++
and Java are also based on C

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Characteristics of C
⮚ A high level programming language
⮚ C is a Stable language, Core language, Portable language and
Extensible language
⮚ Small size. C has only 32 keywords. This makes it relatively easy to
learn
⮚ Makes extensive use of function calls
⮚ C is well suited for structured programming.
⮚ Unlike PASCAL it supports loose typing (as a character can be
treated as an integer and vice versa)
⮚ Facilitates low level (bitwise) programming
⮚ Supports pointers to refer computer memory, array, structures and
functions.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Programming Paradigms

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Programming Paradigms
⮚ It defines how the Structure and Basic elements of a computer program
will be built.
⮚ It also describes the Style of writing programs and set of capabilities and
limitations that a particular programming language supports.
⮚ Some programming language supports single paradigm while some others
may draw the concepts from more than one.
⮚ Paradigms can be classified as follows,
⮚ Monolithic Programming
⮚ Procedural Programming
⮚ Structured Programming
⮚ Object Oriented Programming
⮚ Each of these paradigms has its own strength and weakness.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

1. Monolithic Programming
⮚ Monolithic Program have just one program module as such programming
language do not support the concept of subroutines.
⮚ It consist of Global Data and Sequential Code.
⮚ Global Data can be accessed and modified from any part of the program.
⮚ Sequential Code is the one in which all the instructions are executed in the
specified sequence.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Monolithic Programming Cont…


⮚ Jump and goto statements are used to change the sequence of instructions.

DISADVANTAGE:
⮚ Size of the Program is large
⮚ Difficult to debug and maintain
⮚ Can be used only for small and simple applications.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

2. Procedural Programming
⮚ Here, program is divided into sub routines that can access Global Data.
⮚ Each subroutine performs a well-defined task
⮚ Any subroutine can call any other subroutine to receive its service
⮚ ‘Jump’, ‘goto’ and ‘call’ instruction are used to control the flow of
execution of the program.

Global Data

subroutine
Program

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Procedural Programming Contd…


Advantage:
⮚ Programs are easier to write as compared to monolithic programming.

Disadvantage:
⮚ No reusability
⮚ Requires more time to write programs
⮚ Programs are difficult to maintain
⮚ Global data is shared and therefore may get altered mistakenly

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

3. Structured Programming
⮚ It specifically designed to enforce a logical structure on the program.
⮚ Structured Programming employs a top-down approach in which the
overall program structure is broken down in to separate modules.
⮚ Modules are coded separately and once a module is written and tested
individually, it is then integrated with other modules to form a overall
program structure.

Global Data

Modules that
have local
data and code
Program
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

3. Structured Programming Contd…


⮚ Modularization makes a program easier to write, debug and
understand.
⮚ It is always easy to understand 10-single page module instead single 10-
page program.
⮚ In a structured programming the program flow follows a simple sequence
and usually avoids the use of ‘goto’ statements.
⮚ Besides sequential flow structured programming also supports selection
and repetition as mentioned below,
⮚ Selection statement contains the keywords such as ‘if’, ‘then’, ‘end if’ or
‘switch’ that help to identify the order as a logical executable.
⮚ Repetition statement include such as ‘repeat’, ‘for’ or ‘do….until’
which instructs the program as how long it needs to continue.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

3. Structured Programming Contd…


Advantage:
⮚ Very easy to understand and change.
⮚ With module, many programmers instead of working on a single, large
program, they will work on a different separate module.
⮚ Each module performs a specific task.
⮚ Each module has its own local data.
⮚ Easy to debug because each Procedure(Module) is specialized to perform
just one task.
Disadvantage:
⮚ Not data centered.
⮚ Global data is shared and therefore may get modified by mistake.
⮚ Main focus on Functions (Procudures/ Modules/ Methods).

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Structure of C Program
⮚ A C program contains one or more functions
⮚ The statements in a C program are written in a logical sequence to perform
a specific task.
⮚ Execution of a C program begins at the main() function
⮚ We can choose any name for the functions.
⮚ Every program must contain one function that has its name as main().

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Structure of C Program

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

First C Program
// This is my first program in C

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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Data Types

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

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

long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295

signed long int 4 -2147483648 to 2147483647


float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Integer
• Integers are whole numbers that can have both zero, positive and
negative values but no decimal values. For example, 0, -5, 10
• We can use int for declaring an integer variable.
Example :int id;
• Here, id is a variable of type integer.
• You can declare multiple variables at once in C programming. For
example,
int id, age;

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Example 2
#include <stdio.h>
#include <stdio.h>
int main()
int main()
{ {
int a=10; int a=10,b=20,c;
int b=20; c=a+b;
printf("answer:%d",c);
int c; return 0;
c=a+b; }
printf("answer:%d",c);
return 0;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

character

• Keyword char is used for declaring character type variables.


• For example,
• char test = 'h';
• The size of the character variable is 1 byte.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Example 3
• #include <stdio.h>
• int main()
• {
• char test = 'h';
• printf("answer:%c",test);
• return 0;
• }

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

float and double

• float and double are used to hold real numbers.


Example: float salary;
double price;

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Example 4
#include <stdio.h>
int main()
{
float a, b, product;
printf("Enter two numbers: ");
scanf("%f %f", &a, &b);
// Calculating product
product = a * b;
// %.2lf displays number up to 2
decimal point
printf("Product = %.2lf",
product);
return 0;
}
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Variables

• A variable is defined as a meaningful name given to the data storage location in


computer memory.
• When using a variable, we actually refer to address of the memory where the data is
stored.
Declaring Variable
• To declare a variable specify data type of the variable followed by its name.
• Variable names should always be meaningful and must reflect the purpose of their usage
in the program.
• Variable declaration always ends with a semicolon.
• Example,
int emp_num;
float salary;
char grade;
double balance_amount;
–Reema
unsigned
Thareja short int acc_no;
―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

Example 1
#include<stdio.h>
int main() A. 2
{ B. 25
int 1_one = 25;
printf("%d",1_one); C. Runtime error
return 0; D. Compilation error
}

J Press, Second Edition, 2016


Reema Thareja ―Programming in C, Oxford University
CS8251 - Programming in C

Option: D
Explanation
Invalid variable name. Variable name must begins with either
alphabet or underscore( _ ).

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

What will be the output of the C program?

#include<stdio.h> A. Compilation error


B. Runtime error
int main() C. 5
D. 3
{
int default = 5, a = 3;
if(a > 2)
printf("%d",default);
return 0;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

• Option: A
• Explanation
• default is a C reserved keyword and hence it
cannot be used.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

What will be the output of the C program?


#include<stdio.h>
int main()
A. garbage value
{ B. Compilation error
C. Runtime error
int class; D. 30

int public = 5;
int private = 10;
int protected = 15;
class = public + private + protected;
printf("%d",class);
return 0;
}

Jansons Institute of
Reema Thareja ―Programming in Technology,Karumathampatti
C, Oxford University Press, Second ,Edition, 2016
Coimbatore -641659
CS8251 - Programming in C

• Option: D
• Explanation
• C programming don't have any access
specifier. Thus it is possible to
use class, Public, Private and Protected as a
variable name.

Jansons Institute of
Reema Thareja ―Programming in Technology,Karumathampatti
C, Oxford University Press, Second ,Edition, 2016
Coimbatore -641659
CS8251 - Programming in C

What will be the output of the C program?

#include<stdio.h>
int main() A. Runtime error
B. 5
{ C. Garbage value
D. Compilation error
int _int = 5;
printf("%d",_int);
return 0;
}

Jansons Institute of
Reema Thareja ―Programming in Technology,Karumathampatti
C, Oxford University Press, Second ,Edition, 2016
Coimbatore -641659
CS8251 - Programming in C

• Option: B
• Explanation
• Though int is a keyword, it is prefixed with
underscore, this makes it possible to
use _int as a variable.

Jansons Institute of
Reema Thareja ―Programming in Technology,Karumathampatti
C, Oxford University Press, Second ,Edition, 2016
Coimbatore -641659
CS8251 - Programming in C

#include<stdio.h>
What will be the output of the C program?
int main()
{
int _ = 5; A. Runtime error
B. Compilation error
C. 10

int __=5; D. Some Garbage value

int ___ = _ + __;


printf("%d",___);
return 0;
}
Jansons Institute of
Reema Thareja ―Programming in Technology,Karumathampatti
C, Oxford University Press, Second ,Edition, 2016
Coimbatore -641659
CS8251 - Programming in C

• Option: C
• Explanation
• Using underscore ( _ ) alone as a variable
name is too possible in C programming.

Jansons Institute of
Reema Thareja ―Programming in Technology,Karumathampatti
C, Oxford University Press, Second ,Edition, 2016
Coimbatore -641659
CS8251 - Programming in C

Local Vs Global Variable

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

What will be the output of the C program?


#include<stdio.h>
int main()
{
int xyz = 20;
A. garbage value
B. Compilation error
C. 40

{
D. 20

int xyz = 40;


}
printf("%d",xyz);
return 0;
}
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

• Option: D
• Explanation
• int xyz = 20; is a global variable, and int xyz
= 40 is a local variable, Here we are calling
xyz outside the scope of xyz = 40. Thus it
outputted 20.

Jansons Institute of
Reema Thareja ―Programming in Technology,Karumathampatti
C, Oxford University Press, Second ,Edition, 2016
Coimbatore -641659
CS8251 - Programming in C

Storage Classes

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Storage Classes
⮚ The storage class of a variable defines the scope (visibility) and life time
of variables and/or functions declared within a C Program.
⮚ In addition to this, the storage class gives the following information about
the variable or the function,
⮚ It is used to determine the part of memory where storage space will be
allocated for that variable or function (whether the variable/function will be
stored in a register or in RAM)
⮚ it specifies how long the storage allocation will continue to exist for that
function or variable.
⮚ It specifies the scope of the variable or function. That is, the part of the C
program in which the variable name is visible, or accessible.
⮚ It specifies whether the variable or function has internal, external, or no linkage
⮚ It specifies whether the variable will be automatically initialized to zero or
to any indeterminate value

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Storage Classes Types


⮚ C Supports four storage classes,
⮚ automatic
⮚ register
⮚ external
⮚ static

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Storage Classes Types


STORAGE CLASS
FEATURE
Auto Extern Register Static

Local: Accessible
within the function
Accessible within Accessible within Accessible within or block in which it
the function or all program files the function or is declared
Accessibility
block in which it is that are a part of block in which it is Global: Accessible
declared the program declared within the program
in which it is
declared

Storage Main Memory Main Memory CPU Register Main Memory

Exists when the Exists when the


function or block in function or block in Local: Retains
which it is declared which it is declared value between
Exists
is entered. Ceases to is entered. Ceases to function calls or
throughout the
Existence exist when the exist when the block entries
execution of the
control returns from control returns from Global: Preserves
program
the function or the the function or the value in program
block in which it block in which it files
was declared was declared

Default value Garbage Zero Garbage Zero

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Storage Classes Types Contd…


⮚ Example: ‘auto’ Storage Class
#include<stdio.h>

void func1() //function 1 definition


{
int a=10; Output:
printf(“\n a = %d”, a); // auto integer local to func1()
} a = 10
void func2() //function 2 definition a = 20
{ a = 30
int a=20;
printf(“\n a = %d”, a); // auto integer local to func1()
}

void main()
{
int a=30;
func1(); //function 1 call
func2(); //function 2 call
printf(“\n a = %d”, a);
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Storage Classes Types Contd…


⮚ Example: ‘extern’ Storage Class

// FILE 1.C // FILE2.C


#include<stdio.h> #include<stdio.h>
#include<FILE2.C> extern int x;
int x; void print()
void print(void); {
int main() printf("\n X in File2= %d", x);
{ }
x = 10; main()
print(“X in File1=%d”, x); {
print(); // Statements
return 0; }
} // END OF FILE2.C
// END OF FILE1.C

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Storage Classes Types Contd…


⮚ Example: ‘register’ Storage Class
#include<stdio.h>
int exp(int a, int b); //function declaration

int main()
{ Output:
int a=3, b=5, res;
res=exp(a,b); 3 to the power of 5 = 243
printf(“\n %d to the power of %d=%d”, a, b, res);
return 0;
}

int exp(int a, int b) //function definition


{
register int res=1; //using register as storage class because res is
frequently accessed in all iterations of ‘for’ loop
int i;
for(i-0; i<=b; i++)
res=res*a;
return res;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Storage Classes Types Contd…


⮚ Example: ‘static’ Storage Class
#include<stdio.h>
void print(void);
int main()
{
printf("\n First call of print()"); Output:
print();
printf("\n\n Second call of print()"); First call of print()
print(); Static integer variable, x = 0
printf("\n\n Third call of print()"); Integer variable, y = 0
print();
return 0; Second call of print()
} Static integer variable, x = 1
Integer variable, y = 0
void print()
{ Third call of print()
static int x; Static integer variable, x = 2
int y = 0; Integer variable, y = 0
printf("\n Static integer variable, x = %d", x);
printf("\n Integer variable, y = %d", y);
x++;
y++;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Constants

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Constants
⮚ Constants are identifiers whose value does not change.
⮚ Constants are used to define fixed values like PI, so that their value
does not get changed in the program even by mistake.
⮚ To declare a constant, precede the normal variable declaration with
const keyword and assign it a value. For example,
const float pi = 3.14;
⮚ Another way to designate a constant is to use the pre-processor
command define.
#define PI 3.14159
⮚ When the preprocessor reformats the program to be compiled by the
compiler, it replaces each defined name with its corresponding value
wherever it is found in the source program. Hence, it just works like
the Find and Replace command available in a text editor.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Constants Contd…
Different types of Constants in C Program,
⮚ Integer Type (example: 123, 456, etc.,)
⮚ Floating Point Type (example: 0.02, -0.23, 123.456, etc.,)
⮚ Character Type (example: ‘a’, ‘A’, ‘b’, ‘B’, etc.,)
⮚ String Type (example: “hi”, “hello”, etc.,)

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Enumeration Constants

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Enumeration Constants
⮚ The enumerated data type is a user defined type based on the
standard integer type.
⮚ An enumeration consists of a set of named integer constants.
That is, in an enumerated type, each integer value is assigned
an identifier. This identifier (also known as an enumeration
constant) can be used as symbolic names to make the program
more readable.
⮚ To define enumerated data types, enum keyword is used.
⮚ Enumerations create new data types to contain values that are
not limited to the values fundamental data types may take.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Enumeration Constants Contd…


⮚ The syntax of creating an enumerated data type can be given
as below.
enum enumeration_name { identifier1, identifier2, …...,
identifiern };
⮚ Consider the example given below which creates a new type
of variable called COLORS to store colors constants.
enum COLORS {RED, BLUE, BLACK, GREEN,
YELLOW, PURPLE, WHITE};
⮚ In case if we do not assign any value to a constant, the default
value in our example,
RED = 0, BLUE = 1, BLACK = 2, GREEN = 3,
YELLOW = 4, PURPLE = 5, WHITE =6
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

Enumeration Constants Contd…


⮚ If we want to explicitly assign values to these integer constants
then we should specifically mention those values as shown
below.
enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN = 7,
YELLOW, PURPLE , WHITE = 15};
⮚ As a result of the above statement, now
RED = 2, BLUE = 3, BLACK = 5, GREEN = 7, YELLOW = 8,
PURPLE = 9, WHITE = 15

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Enumeration Constants Example


#include<stdio.h>

int main()
{

enum {RED=2, BLUE, BLACK=5, GREEN=7, YELLOW, Output:


PURPLE, WHITE=15};
RED = 2
printf(“\n RED = %d”, RED); BLUE = 3
printf(“\n BLUE = %d”, BLUE); BLACK = 5
printf(“\n BLACK = %d”, BLACK); GREEN = 7
YELLOW = 8
printf(“\n GREEN = %d”, GREEN); PURPLE = 9
printf(“\n YELLOW = %d”, YELLOW); WHITE = 15
printf(“\n PURPLE = %d”, PURPLE);
printf(“\n WHITE = %d”, WHITE);

return 0;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Keywords

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Operators in C

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Operators in C
C language supports a lot of operators to be used in expressions. These
operators can be categorized into the following major groups:
⮚ Arithmetic operators
⮚ Relational Operators
⮚ Equality Operators
⮚ Logical Operators
⮚ Unary Operators
⮚ Conditional Operators
⮚ Bitwise Operators
⮚ Assignment operators
⮚ Comma Operator
⮚ Sizeof Operator

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Arithmetic Operator

OPERATION OPERATOR SYNTAX COMMENT RESULT


result = a *
Multiply * a * b
b
27

result = a /
Divide / a / b
b
3

result = a +
Addition + a + b
b
12

Subtracti - a - b
result = a –
6
on b

result = a %
Modulus % a % b
b
0

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Relational Operator
⮚ Also known as a comparison operator, that compares two
values.
⮚ Expressions that contain relational operators are called
relational expressions.
⮚ Relational operators return true or false value, depending on
whether the conditional relationship between the two operands
holds or not.
OPERATOR MEANING EXAMPLE
< LESS THAN 3 < 5 GIVES 1

> GREATER THAN 7 > 9 GIVES 0

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

GREATER THAN EQUAL


<= 50 >=100 GIVES 0
TO

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Equality Operator
⮚ C language supports two kinds of equality operators to
compare their operands for strict equality or inequality.
⮚ They are equal to (==) and not equal to (!=) operator.
⮚ The equality operators have lower precedence than the
relational operators.

OPERATOR MEANING

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

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


!=
OTHERWISE

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Logical Operator
⮚ C language supports three logical operators.
⮚ They are- Logical AND (&&), Logical OR (||) and Logical
NOT (!).
⮚ Logical expressions are evaluated from left to right.

A B A &&B A B A || B
A !A

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

1 0 0 1 0
1 0 1

1 1 1 1 1 1

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Unary Operator
⮚ Unary operators act on single operands.
⮚ C language supports three unary operators. They are unary minus,
increment and decrement operators.
⮚ When an operand is preceded by a minus sign, the unary operator negates
its value.
⮚ The increment operator is a unary operator that increases the value of its
operand by 1. Similarly, the decrement operator decreases the value of its
operand by 1. For example,
int x = 10, y; y = ++x;
y = x++;

is equivalent to writing is equivalent to writing


y = x; x = x + 1;
x = x + 1; y = x;

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Conditional Operator
⮚ The conditional operator operator (?:) is just like an if .. else statement that
can be written within expressions.
⮚ The syntax of the conditional operator is
exp1 ? exp2 : exp3
⮚ Here, exp1 is evaluated first. If it is true then exp2 is evaluated and
becomes the result of the expression, otherwise exp3 is evaluated and
becomes the result of the expression.
⮚ For example, large = ( a > b) ? a : b
⮚ Conditional operators make the program code more compact, more
readable, and safer to use.
⮚ Conditional operator is also known as ternary operator as it is neither a
unary nor a binary operator; it takes three operands.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Bitwise Operator
⮚ Bitwise operators perform operations at bit level. These operators include: bitwise
AND, bitwise OR, bitwise XOR and shift operators.
⮚ The bitwise AND operator (&) is a small version of the boolean AND (&&) as it
performs operation on bits instead of bytes, chars, integers, etc.
⮚ The bitwise OR operator ( | ) is a small version of the boolean OR (||) as it performs
operation on bits instead of bytes, chars, integers, etc.
⮚ The bitwise NOT ( ~ ), or complement, is a unary operation that performs logical
negation on each bit of the operand. By performing negation of each bit, it actually
produces the ones' complement of the given binary value.
⮚ The bitwise XOR operator ( ^ ) performs operation on individual bits of the
operands. The result of XOR operation is shown in the table
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Bitwise Shift Operator


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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Assignment Operator
⮚ The assignment operator is responsible for assigning values to the variables.
⮚ While the equal sign (=) is the fundamental assignment operator, C also supports
other assignment operators that provide shorthand ways to represent common
variable assignments.
⮚ They are shown in the table.

OPERATOR SYNTAX EQUIVALENT TO

/= variable /= expression variable = variable / expression

\= variable \= expression variable = variable \ expression


*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Comma Operator
⮚ The comma operator in C takes two operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the
result of the expression.
⮚ Comma separated operands when chained together are evaluated in left-to-right
sequence with the right-most value yielding the result of the expression.
⮚ Among all the operators, the comma operator has the lowest precedence.
⮚ For example,
int a=2, b=3, x=0;
x = (++a, b+=a);
// here it will evaluate first expression now a=3,
then second expression b+=a i.e., [b=a+b]
= 3 +3
Now, the value of x = 6.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Sizeof Operator
⮚ ‘sizeof’ is a unary operator used to calculate the sizes of Data Types.
⮚ It can be applied to all data types.
⮚ The operator returns the size of the variable, data type or expression in bytes.
⮚ 'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take.
⮚ For example,
‘sizeof(char)’ returns 1, that is the size of a character data type.
⮚ Example
int a = 10;
unsigned int result;
result = sizeof(a); // now ‘a’ is of the type integer
then result = 2,

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Operator Precedence and Associativity

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Operator Precedence & Associativity

Operator Description Associativity


() Parentheses (function call)
[] Brackets (array subscript)
. Member selection via object name left-to-right
-> Member selection via pointer
++ -- Prefix increment/decrement
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value
of type) right-to-left
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this
implementation

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Operator Precedence & Associativity

Operator Description Associativity


* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

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

< <= Relational less than/less than or equal


to left-to-right
> >= Relational greater than/greater than or
equal to
== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Operator Precedence & Associativity

Operator Description Associativity


^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

, Comma (separate expressions) left-to-right

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Operator Precedence & Associativity

Operator Description Associativity


= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment right-to-left
^= |= Bitwise exclusive/inclusive OR
assignment
<<= >>= Bitwise shift left/right assignment

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Input/ Output Statements in C

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Input/ Output Statements in C

⮚ streams
⮚ printf()
⮚ Scanf()

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Streams Contd…

Keyboard Data

Streams in a C program

Text Stream Binary Stream

Monitor Data

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf()
⮚ The printf function is used to display information required to
the user and also prints the values of the variables.
⮚ Its syntax can be given as
printf (“control string”, variable list);
⮚ The parameter control string is a C string that contains the text
that has to be written on to the standard output device.
⮚ The prototype of the control string can be given as below
%[flags][width][.precision][length]specifier

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf() Contd…
⮚ FLAGS: Optional Argument which specifies output justification
such as numerical sign, trailing zeros or octal, decimal or
hexadecimal prefixes.

Flags Description
- Left-justify within the data 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 hexa decimal
values respectively for values different than
zero.
0 The number is left-padded with zeroes (0)
instead of spaces

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf() Contd…
⮚ WIDTH: Optional Argument which specifies the minimum
number of positions in the Output.
⮚ If data need more space then specified, then printf() overrides the
width specified by the user.
⮚ If the number of Output character is smaller than the specified
width, then the output would be right justified with Blank Spaces to
the left.
⮚ If the user does not specify any width then the output will take just
enough space for data.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf() Contd…
⮚ PRECISION: Optional Argument which specifies the maximum
number of characters to print.
⮚ For Integer Specifiers (d, I, o, u, x, X): Precision flag specifies
minimum number of digits to be written.
⮚ For Character Strings: Precision flag specifies maximum number
of characters to be printed.
⮚ For Floating Point Numbers: Precision flag specifies the number
of decimal places to be printed.

Example: “%7.3f” – Print a floating point value of maximum 7 digits


where 3 digits are allotted for the digits after the decimal point

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf() Contd…
⮚ LENGTH MODIFIER:

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)

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf() Contd…
⮚ TYPE SPECIFIER:
Used to define the type of the Value

Type Qualifying Input


c For single character
d For decimal 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 number.
s For a sequence of (string of) characters
u For Unsigned decimal value
X, x For Hexadecimal value.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf() Contd…
⮚ 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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Printf() Contd…
⮚ Examples:
printf(“\n Result: %5d \t %x \t %#x”, 234, 234, 234) ;
Result: 234 EA 0xEA

printf(“\n Result: %6d”, 1234) ;


Result: 1234

printf(“\n Result: %06d”, 1234) ;


Result: 001234

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

scanf()

⮚ The scanf() is used to read formatted data from the keyboard.


⮚ The syntax of the scanf() can be given as,
scanf (“control string”, arg1, arg2, ………….argn);
⮚ The control string specifies the type and format of the data that has
to be obtained from the keyboard and stored in the memory
locations pointed by the arguments arg1, arg2,…, argn.
⮚ The prototype of the control string can be give as:
[%[*][width][modifiers]type]

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

scanf()
⮚ * is an optional argument that suppresses assignment of the input
field. That is, it indicates that data should be read from the stream
but ignored (not stored in the memory location).
⮚ width is an optional argument that specifies the maximum number
of characters to be read.
⮚ modifiers is an optional argument that can be h, l or L for the data
pointed by the corresponding additional arguments.
⮚ Type is same as specifier in printf()

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

scanf()
Rules to Use scanf() function in C Program:
⮚ Rule 1:
The scanf() function works until,
1. Maximum number of characters has been processed
2. a white space character is encountered, or
3. an error is detected.
⮚ Rule 2:
Every variable that has to be processed must have a control
string associated with it.
⮚ Rule 3:
There must be a variable address for each control string.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

scanf()
Rules to Use scanf() function in C Program:
⮚ Rule 4:
An error would be generated if the format string is ended with a
white space character.
⮚ Rule 5:
Data entered by the user must match the character specified in the
control string.
⮚ 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.
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

Decision Making Statements

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Decision Control Statements


⮚ Decision control statements are used to alter the flow of a sequence of
instructions.
⮚ These statements help to jump from one part of the program to another
depending on whether a particular condition is satisfied or not.
⮚ These decision control statements include,
If statement
If else statement
If else if statement
Switch statement

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

if Statement
⮚ If statement is the simplest form of decision control statements that is
frequently used in decision making.
⮚ First the test expression is evaluated. If the test expression is true, the
statement of if block (statement 1 to n) are executed otherwise these
statements will be skipped and the execution will jump to statement x.

SYNTAX OF IF STATEMENT FALSE


Test Expression
if (test expression)
{
statement 1;
.............. TRUE
statement n;
} Statement Block 1
statement x;

Statement x
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

if Statement Example

// Program to demonstrate the use of if-statement

#include<stdio.h>
int main()
{
int x=10;
if ( x>0)
x++;
printf("\n x = %d", x);
return 0;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

if else Statement
⮚ In the if-else statement, first the test expression is evaluated. If the
expression is true, statement block 1 is executed and statement block 2 is
skipped.
⮚ Otherwise, if the expression is false, statement block 2 is executed and
statement block 1 is ignored. In any case after the statement block 1 or 2
gets executed the control will pass to statement x. Therefore, statement x is
executed in every case.
FALSE
SYNTAX OF IF STATEMENT
Test
if (test expression) TRUE Expression
{
statement_block 1;
} Statement Block 1 Statement Block 2
else
{
statement_block 2;
}
statement x;
Statement x

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

if else Statement Example

// PROGRAM TO FIND WHETHER A NUMBER IS EVEN OR ODD

#include<stdio.h>
main()
{
int a;
printf("\n Enter the value of a : ");
scanf("%d", &a);
if(a%2==0)
printf("\n %d is even", a);
else
printf("\n %d is odd", a);
return 0;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

if else-if Statement
⮚ C language supports if else-if statements to test additional
conditions apart from the initial test expression.
⮚ The if else-if construct works in the same way as a normal if
statement
SYNTAX OF IF-ELSE STATEMENT
if ( test expression 1)
{
TRUE FALSE
statement block 1;
} Test
else if ( test expression 2) Expression 1
{
statement block 2;
Statement Block 1 FALSE
}
Test
...........................
Expression 2
else if (test expression N)
{ TRUE
statement block N; Statement Block X
} Statement Block 2
else
{
Statement Block X;
Statement Y
}
Statement Y;

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Switch Statement

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Switch Statement
⮚ A switch case statement is a multi-way decision statement.
⮚ Switch statements are used:
When there is only one variable to evaluate in the expression
When many conditions are being tested for
⮚ Switch case statement advantages include:
Easy to debug, read, understand and maintain
Execute faster than its equivalent if-else construct

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Switch Statement Syntax


switch(grade)
{
case 'A':
printf("\n Excellent");
break;
case 'B':
printf("\n Good");
break;
case 'C':
printf("\n Fair");
break;
default:
printf("\n Invalid Grade");
break;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Switch Statement Example


// PROGRAM TO PRINT THE DAY OF THE WEEK
#include<stdio.h>
int main()
{
int day;
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;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Looping/ Iterative Statements

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Looping/ Iterative Statement


⮚ Iterative statements are used to repeat the execution of a list
of statements, depending on the value of an integer expression.
⮚ In this section, we will discuss all these statements.
❖While loop
❖Do-while loop
❖For loop

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

While Loop
⮚ The while loop is used to repeat one or more statements while a
particular condition is true.
⮚ In the while loop, the condition is tested before any of the
statements in the statement block is executed.
⮚ If the condition is true, only then the statements will be executed
otherwise the control will jump to the immediate statement outside
the while loop block.
⮚ We must constantly update the condition of the while loop.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

While Loop

Statement x
while (condition)
{
statement_block;
} Update the
Condition
condition
statement x;
expression

TRUE
Statement Block
FALSE
Statement y

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

While Loop Example

// PROGRAM TO PRINT NUMBERS FROM 0 TO 10 USING WHILE


LOOP

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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Do While Loop
⮚ The do-while loop is similar to the while loop. The only difference is that
in a do-while loop, the test condition is tested at the end of the loop.
⮚ The body of the loop gets executed at least one time (even if the
condition is false).
⮚ The do while loop continues to execute whilst a condition is true. There is
no choice whether to execute the loop or not. Hence, entry in the loop is
automatic there is only a choice to continue it further or not.
⮚ The major disadvantage of using a do while loop is that it always
executes at least once, so even if the user enters some invalid data, the loop
will execute.
⮚ Do-while loops are widely used to print a list of options for a menu driven
program.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Do While Loop

Statement x;
Statement x
do
{
statement_block;
Statement
}
Block

while (condition);
statement y; Update the condition expression

TRUE
Condition

FALSE
Statement y

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Do While Loop Example

// PROGRAM TO PRINT NUMBERS FROM 0-10 USING DO-WHILE


LOOP

#include<stdio.h>
int main()
{
int i = 0;
do
{
printf(“\n %d”, i);
i = i + 1;
} while(i<=10);
return 0;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

For Loop
⮚ For loop is used to repeat a task until a particular condition is true.
⮚ The syntax of a for loop
for (initialization; condition; increment/decrement/update)
{
statement block;
}
Statement Y;

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

For Loop
⮚ When a for loop is used, the loop variable is initialized only once.
⮚ With every iteration of the loop, the value of the loop variable is
updated and the condition is checked.
⮚ If the condition is true, the statement block of the loop is executed
else, the statements comprising the statement block of the for loop
are skipped and the control jumps to the immediate statement
following the for loop body.
⮚ Updating the loop variable may include incrementing the loop
variable, decrementing the loop variable.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

For Loop Example

// code given below which print first n numbers using a for loop.

#include<stdio.h>
int main()
{
int i, n;
printf(“\n Enter the value of n :”);
scanf(“%d”, &n);

for(i=0; i<= n; i++)


printf(“\n %d”, i);

return 0;
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Break Statement

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Break Statement
⮚ The break statement is used to terminate the execution of the
nearest enclosing loop in which it appears.
⮚ When compiler encounters a break statement, the control passes to
the statement that follows the loop in which the break statement
appears.
⮚ Its syntax is quite simple, just type keyword break followed with a
semi-colon.
break;
⮚ In switch statement if the break statement is missing then every
case from the matched case label to the end of the switch,
including the default, is executed.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Continue Statement

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Continue Statement
⮚ The continue statement can only appear in the body of a loop.
⮚ When the compiler encounters a continue statement then.
⮚ Its syntax is quite simple, just type keyword continthe rest of the statements in
the loop are skipped and the control is unconditionally transferred to the loop-
continuation portion of the nearest enclosing loopue followed with a semi-colon.
continue;
⮚ If placed within a for loop, the continue statement causes a branch to the code that
updates the loop variable.
⮚ For example,
int i;
for(i=0; i<= 10; i++)
{ if (i==5)
continue;
printf(“\t %d”, i);
}
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

Preprocessor Directive

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

INTRODUCTION
⮚ The preprocessor is a program that processes the source code before it
passes through the compiler. It operates under the control of preprocessor
directive which is placed in the source program before the main().
⮚ Before the source code is passed through the compiler, it is examined by
the preprocessor for any preprocessor directives. In case, the program has
some preprocessor directives, appropriate actions are taken (and the source
program is handed over to the compiler.
⮚ The preprocessor directives are always preceded by a hash sign (#).
⮚ The preprocessor is executed before the actual compilation of program
code begins. Therefore, the preprocessor expands all the directives and
take the corresponding actions before any code is generated by the
program statements.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

INTRODUCTION

⮚ No semicolon (;) can be placed at the end of a preprocessor directive.


⮚ The advantages of using preprocessor directives in a C program include:
⮚ Program becomes readable and easy to understand
⮚ Program can be easily modified or updated
⮚ Program becomes portable as preprocessor directives makes it easy to
compile the program in different execution environments
⮚ Due to the aforesaid reason the program also becomes more efficient to
use.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

Types of Preprocessor Directive

Preprocessor Directive

Unconditional Conditional

define line undef include error pragma

.
if else elif ifdef ifndef endif

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

1. #define

⮚ To define preprocessor macros we use #define. The #define statement is


also known as macro definition or simply a macro. There are two types of
macros-
1. Object like macro, and
2. Function like macro.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

1. #define Contd…
1. Object like macro
⮚ An object-like macro is a simple identifier which will be replaced by a
code fragment. They are usually used to give symbolic names to numeric
constants. Object like macros do not take ant argument. It is the same what
we have been using to declare constants using #define directive. The
general syntax of defining a macro can be given as:,
Syntax: #define identifier string

⮚ The preprocessor replaces every occurrence of the identifier in the source


code by a string.
Example: #define PI 3.14

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

1. #define Contd…
2. Function-like macros
⮚ They are used to stimulate functions.
⮚ When a function is stimulated using a macro, the macro definition replaces
the function definition.
⮚ The name of the macro serves as the header and the macro body serves as
the function body. The name of the macro will then be used to replace the
function call.
⮚ The function-like macro includes a list of parameters.
⮚ References to such macros look like function calls. However, when a
macro is referenced, source code is inserted into the program at compile
time. The parameters are replaced by the corresponding arguments, and the
text is inserted into the program stream. Therefore, macros are considered
to be much more efficient than functions as they avoid the overhead
involved in calling a function.
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

1. #define Contd…
⮚ The syntax of defining a function like macro can be given as
#define identifier(arg1,arg2,...argn) string
⮚ The following line defines the macro MUL as having two
parameters a and b and the replacement string (a * b):
#define MUL(a,b) (a*b)
⮚ Look how the preprocessor changes the following statement
provided it appears after the macro definition.
int a=2, b=3,c;
c = MUL(a,b);

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

1. #define Contd…
⮚ Example:
#include<stdio.h>
#define MUL(a,b) printf(“%d”,a*b)
void main()
{
int a=2,b=3,c;
clrscr();
c=MUL(a,b);
getch();
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

OPERATORS RELATED TO MACROS


# Operator to Convert to String Literals
⮚ The # preprocessor operator which can be used only in a function like macro
definition is used to convert the argument that follows it to a string literal. For
example:
#include<stdio.h>
#define PRINT(num) printf( #num " = %d", num)
main()
{
PRINT(20);
}
⮚ The macro call expands to
printf( “num" “ = %d", num)
⮚ Finally, the preprocessor will automatically concatenate two string literals into one
string. So the above statement will become
printf( “num = %d", num)

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

OPERATORS RELATED TO MACROS


2. Merge Operator (##)
⮚ At times you need macros to generate new tokens. Using the merge operator you
can concatenate two tokens into a third valid token. For example,
#include<stdio.h>
#define JOIN(A,B) A##B
main()
{
int i;
for(i=1;i<=3;i++)
printf("\n HI JOIN(USER, i) : ");
}
⮚ The above program would print
HI USER1
HI USER2
HI USER3

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

2. #include

⮚ An external file containing function, variables or macro definitions can be


included as a part of our program. This avoids the effort to re-write the
code that is already written.
⮚ The #include directive is used to inform the preprocessor to treat the
contents of a specified file as if those contents had appeared in the source
program at the point where the directive appears.
⮚ The #include directive can be used in two forms. Both forms makes the
preprocessor insert the entire contents of the specified file into the source
code of our program. However, the difference between the two is the way
in which they search for the specified.
#include <filename>

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

2. #include

⮚ This variant is used for system header files. When we include a file using
angular brackets, a search is made for the file named filename in a standard
list of system directories.
#include "filename"
⮚ This variant is used for header files of your own program. When we
include a file using double quotes, the preprocessor searches the file named
filename first in the directory containing the current file, then in the quote
directories and then the same directories used for <filename>.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

3. #undef

⮚ As the name suggests, the #undef directive undefines or removes a macro


name previously created with #define. Undefining a macro means to cancel
its definition. This is done by writing #undef followed by the macro name
that has to be undefined.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

4. #line
⮚ Compile the following C program.
#include<stdio.h>
main()
{
int a=10 :
printf("%d", a);
}
⮚ The above program has a compile time error because instead of a semi-colon
there is a colon that ends line int a = 10. So when you compile this program an
error is generated during the compiling process and the compiler will show an
error message with references to the name of the file where the error happened
and a line number. This makes it easy to detect the erroneous code and rectify it

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

4. #line Contd…
⮚ The #line directive enables the users to control the line numbers within the
code files as well as the file name that we want that appears when an error
takes place.
⮚ The syntax of #line directive is:
#line line_number filename
⮚ Here, line_number is the new line number that will be assigned to the next
code line. The line numbers of successive lines will be increased one by one
from this point on.
⮚ Filename is an optional parameter that redefines the file name that will appear
in case an error occurs. The filename must be enclosed within double quotes. If
no filename is specified then the compiler will show the original file name.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

4. #line Contd…
⮚ For Example,
#include<stdio.h>
main()
{
#line 10 "Error.C"
int a=10:
#line 20
printf("%d, a);
}

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

4. Pragma Directives

⮚ The #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.
⮚ 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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

4. Pragma Directives Contd…

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

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

CONDITIONAL DIRECTIVES
⮚ A conditional directive is used instruct the preprocessor to select whether or not to
include a chunk of code in the final token stream passed to the compiler. The
preprocessor conditional directives can test arithmetic expressions, or whether a
name is defined as a macro, etc.
Conditional preprocessor directives can be used in the following situations:
⮚ A program may need to use different code depending on the machine or
operating system it is to run on.
⮚ The conditional preprocessor directive is very useful when you want to compile
the same source file into two different programs. While one program might
make frequent time-consuming consistency checks on its intermediate data, or print
the values of those data for debugging, the other program, on the other hand can
avoid such checks.
⮚ The conditional preprocessor directives can be used to exclude code from the
program whose condition is always false but is needed to keep it as a sort of
comment for future reference.
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C

1. #ifdef

⮚ #ifdef is the simplest sort of conditional preprocessor directive and is used


to check for the existence of macro definitions.
⮚ Its syntax can be given as:
#ifdef MACRO
controlled text
#endif
Example:
#ifdef MAX
int STACK[MAX];
#endif

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

2. #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).
⮚ The general format to use #ifndef is the same as for #ifdef:
#ifndef MACRO
controlled text
#endif

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

3. The #if Directive


⮚ The #if directive is used to control the compilation of portions of a
source file. If the specified condition (after the #if) has a nonzero 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
⮚ While using #if directive, make sure that each #if directive must be
matched by a closing #endif directive. Any number of #elif directives can
appear between the #if and #endif directives, but at most one #else
directive is allowed. However, the #else directive (if present) must be the
last directive before #endif.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

4. The #else Directive


⮚ The #else directive can be used within the controlled text of an #if
directive to provide alternative text to be used if the condition is false.
⮚ The general format of #else directive can be given as:
#if condition
Controlled text1
#else
Controlled text2
#endif

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

5. The #elif Directive


⮚ The #elif directive is used when there are more than two possible
alternatives. The #elif directive like the #else directive is embedded within
the #if directive.
⮚ It has the following syntax:
#if condition
Controlled text1
#elif new_condition
Controlled text2
#else
Controlled text3
#endif

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

6. The #endif Directive


⮚ The general syntax of #endif preprocessor directive which is used to end
the conditional compilation directive can be given as:
#endif
⮚ The #endif directive ends the scope of the #if , #ifdef , #ifndef , #else , or
#elif directives.

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

The defined operator


⮚ We have seen that we can check the existence of a macro by using #ifdef directive.
However, the alternative to #ifdef directive is to use the defined unary operator.
⮚ The defined operator has one of the following forms:
defined MACRO or defined (MACRO)
⮚ The above expression evaluates to 1 if MACRO is defined and to 0 if it is not. The
defined operator helps you to check for macro definitions in one concise line
without having to use many #ifdef or #ifndef directives.
⮚ For example,
#if defined (MACRO1) && defined (MACRO2)
Controlled text1
#else
printf(“\n MACROS not defined”);
#endif

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016


CS8251 - Programming in C

#error Directive
⮚ The #error directive is used to produce compiler-time error messages.
⮚ The syntax of this directive is:
#error string
⮚ The error messages include the argument string. The #error directive is usually
used to detect programmer inconsistencies and violation of constraints during
preprocessing.
⮚ When #error directive is encountered, the compilation process terminates and the
message specified in string is printed to stderr.
⮚ For example,
#ifndef SQUARE
#error MACRO not defined.
#endif

Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016

You might also like