Unit I - Basics of C Programming
Unit I - Basics of C Programming
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.
Introduction to 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
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.
Programming Paradigms
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.
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.
DISADVANTAGE:
⮚ Size of the Program is large
⮚ Difficult to debug and maintain
⮚ Can be used only for small and simple applications.
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
Disadvantage:
⮚ No reusability
⮚ Requires more time to write programs
⮚ Programs are difficult to maintain
⮚ Global data is shared and therefore may get altered mistakenly
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
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().
Structure of C Program
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;
}
Data Types
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
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;
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;
}
character
Example 3
• #include <stdio.h>
• int main()
• {
• char test = 'h';
• printf("answer:%c",test);
• return 0;
• }
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
Variables
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
}
Option: D
Explanation
Invalid variable name. Variable name must begins with either
alphabet or underscore( _ ).
• Option: A
• Explanation
• default is a C reserved keyword and hence it
cannot be used.
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
#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
• 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
{
D. 20
• 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
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
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
void main()
{
int a=30;
func1(); //function 1 call
func2(); //function 2 call
printf(“\n a = %d”, a);
}
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;
}
Constants
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.
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.
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.,)
Enumeration Constants
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.
int main()
{
return 0;
}
Keywords
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
Operators 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
Arithmetic Operator
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
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
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
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
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++;
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.
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
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.
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.
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,
+ - Addition/subtraction left-to-right
|| Logical OR left-to-right
⮚ streams
⮚ printf()
⮚ Scanf()
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.
Streams Contd…
Keyboard Data
Streams in a C program
Monitor Data
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
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
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.
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.
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)
Printf() Contd…
⮚ TYPE SPECIFIER:
Used to define the type of the Value
Printf() Contd…
⮚ Examples:
printf(“\n Result: %d%c%f”, 12, ‘a’, 2.3) ;
Result: 12a2.3
Printf() Contd…
⮚ Examples:
printf(“\n Result: %5d \t %x \t %#x”, 234, 234, 234) ;
Result: 234 EA 0xEA
scanf()
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()
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.
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
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.
Statement x
Reema Thareja ―Programming in C, Oxford University Press, Second Edition, 2016
CS8251 - Programming in C
if Statement Example
#include<stdio.h>
int main()
{
int x=10;
if ( x>0)
x++;
printf("\n x = %d", x);
return 0;
}
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
#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;
}
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;
Switch Statement
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
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.
While Loop
Statement x
while (condition)
{
statement_block;
} Update the
Condition
condition
statement x;
expression
TRUE
Statement Block
FALSE
Statement y
#include<stdio.h>
int main()
{
int i = 0;
while(i<=10)
{
printf(“\n %d”, i);
i = i + 1; // condition updated
}
return 0;
}
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.
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
#include<stdio.h>
int main()
{
int i = 0;
do
{
printf(“\n %d”, i);
i = i + 1;
} while(i<=10);
return 0;
}
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;
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.
// 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);
return 0;
}
Break Statement
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.
Continue Statement
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
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.
INTRODUCTION
Preprocessor Directive
Unconditional Conditional
.
if else elif ifdef ifndef endif
1. #define
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
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);
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();
}
2. #include
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>.
3. #undef
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
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.
4. #line Contd…
⮚ For Example,
#include<stdio.h>
main()
{
#line 10 "Error.C"
int a=10:
#line 20
printf("%d, a);
}
4. Pragma Directives
INSTRUCTION DESCRIPTION
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
2. #ifndef
#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