0% found this document useful (0 votes)
32 views47 pages

New UNIT-II

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

New UNIT-II

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

lOMoARcPSD|188 724 01

UNIT-II
BASICS OF C PROGRAMMING

Introduction to programming paradigms – Applications of C Language - Structure of C program - C


programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence
and Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Preprocessor directives - Compilation process.

INTRODUCTION TO PROGRAMMING PARADIGMS


Paradigm
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigms are a way to classify programming languages based on their features.

Programming paradigm
Programming paradigm is an approach to solve problem using some programming language.
It is a method to solve a problem using tools and techniques that are available to us following some approach.
There are lots for programming language that are known but all of them need to follow some strategy when
they are implemented and this methodology/strategy is paradigms.
Apart from varieties of programming language there are lots of paradigms to fulfill each and every demand.

Types of programming paradigms


 Imperative paradigm
 Functional paradigm
 Logic paradigm
 Object-oriented paradigm
lOMoARcPSD|188 724 01

Imperative programming paradigm:


 It is one of the oldest programming paradigm.
 It features close relation to machine architecture.
 It is based on Von Neumann architecture. It works by changing the program state through assignment
statements.
 It performs step by step task by changing state.
 The main focus is on how to achieve the goal.
 The paradigm consists of several statements and after execution of all the result is stored.
 Language representatives (FORTRAN, ALGOL, Pascal, Basic, C).
Advantage:
 Very simple to implement
 It contains loops, variables etc.
Disadvantage:
 Complex problem cannot be solved
 Less efficient and less productive
 Parallel programming is not possible

Procedural programming paradigm


 This paradigm emphasizes on procedure in terms of under lying machine model.
 There is no difference in between procedural and imperative approach.
 It has the ability to reuse the code and it was boon at that time when it was in use because of its
reusability.

Object oriented programming


 The program is written as a collection of classes and object which are meant for communication.
 The smallest and basic entity is object and all kind of computation is performed on the objects only.
 More emphasis is on data rather procedure.
 It can handle almost all kind of real life problems which are today in scenario.
Advantages:
 Data security
 Inheritance
 Code reusability
 Flexible and abstraction is also present
Parallel processing approach –
 Parallel processing is the processing of program instructions by dividing them among multiple
processors.
 A parallel processing system posses many numbers of processor with the objective of running a
program in less time by dividing them.
 This approach seems to be like divide and conquer.
 Examples are NESL (one of the oldest one) and C/C++ also supports because of some library
function.

Declarative programming paradigm:


 It is divided as Logic, Functional, and Database.
 In computer science the declarative programming is a style of building programs that expresses logic
of computation without talking about its control flow.
 It often considers programs as theories of some logic.
 It may simplify writing parallel programs. The focus is on what needs to be done rather how it should
be done basically emphasizing on what code is actually doing.
 It just declares the result we want rather how it has be produced.
 This is the only difference between imperative (how to do) and declarative (what to do) programming
paradigms.
 Getting into deeper we would see logic, functional and database.
lOMoARcPSD|188 724 01

Logic programming paradigms


 It can be termed as abstract model of computation.
 It would solve logical problems like puzzles, series etc.
 In logic programming we have a knowledge base which we know before and along with the question
and knowledge base which is given to machine, it produces result.
 In normal programming languages, such concept of knowledge base is not available but while using
the concept of artificial intelligence, machine learning we have some models like Perception model
which is using the same mechanism.
 In logical programming the main emphasize is on knowledge base and the problem.
 The execution of the program is very much like proof of mathematical statement, e.g., Prolog

Functional programming paradigms


 The functional programming paradigms have its roots in mathematics and it is language independent.
 The key principal of this paradigms is the execution of series of mathematical functions.
 The central model for the abstraction is the function which are meant for some specific computation
and not the data structure. Data are loosely coupled to functions.
 The function hide their implementation.
 Function can be replaced with their values without changing the meaning of the program.
 Some of the languages like perl, javascript mostly uses this paradigm.

Database/Data driven programming approach


 This programming methodology is based on data and its movement.
 Program statements are defined by data rather than hard-coding a series of steps.
 A database program is the heart of a business information system and provides file creation, data
entry, update, query and reporting functions.
 There are several programming languages that are developed mostly for database application. For
example SQL.
 It is applied to streams of structured data, for filtering, transforming, aggregating (such as computing
statistics), or calling other programs. So it has its own wide application.

HISTORY OF C LANGUAGE
 All modern computer languages are started through the ALGOL language in 1960.
 After, the COBOL was being used for commercial applications.
 FORTRAN was developed for scientific applications.
 A committee was formed to develop a new language called Combined Programming Language (CPL)
at Cambridge University.
 Basic CPL was derived by BCPL. BCPL was developed by Martin Richards at Cambridge University
by 1967.
 At the same time a language called ‘B’ was developed by Ken Thomson at AT & T’s Bell labs in
1970.
 Then C language is developed by Dennis Ritchie in 1972 with some additional features of BCPL and
B which is very simple.
 ANSI C (American National Standard Institute) has begun to work on a standardized definition of the
‘C’ language that makes it still powerful
lOMoARcPSD|188 724 01

Types of Languages
Low Level Language (Or) Machine Language
Binary language (0’s & 1’s). It is understandable by computer machine.
High Level Language
Normal English, Human Understandable Language, Machine Independent, C, C++, etc…
Middle Level Language
C Language is also called as Middle Level Language because ‘C’ stands in between Low Level Language
(nor) High Level Language (i.e) it performs task of low level languages as well as high level language.

Application of C Language

Operating Systems. The first operating system to be developed using a high-level programming language was
UNIX, which was designed in the C programming language.

Embedded Systems
The C programming language is considered an optimum choice when it comes to scripting applications and
drivers of embedded systems, as it is closely related to machine hardware.

GUI
GUI stands for Graphical User Interface. Adobe Photoshop, one of the most popularly used photo editors
since olden times, was created with the help of C. Later on, Adobe Premiere and Illustrator were also created
using C.

New Programming Platforms


Not only has C given birth to C++, a programming language including all the features of C in addition to the
concept of object-oriented programming but, various other programming languages that are extensively used
in today’s world like MATLAB and Mathematica. It facilitates the faster computation of programs.

Google
Google file system and Google chromium browser were developed using C/C++. Not only this, the Google
Open Source community has a large number of projects being handled using C/C+
+.

Mozilla Firefox and Thunderbird


Since Mozilla Firefox and Thunderbird were open-source email client projects, they were written in C/C++.

MySQL
MySQL, again being an open-source project, used in Database Management Systems was written in C/C++.

Compiler Design.
Since the C programming language is relatively faster than Java or Python, as it is compiler- based, it finds
several applications in the gaming sector.
lOMoARcPSD|188 724 01

STRUCTURE OF C PROGRAM
Discuss about the structure of C program in detail.[NOV/DEC 2019]

Documentation Section
It consists of set of comment lines used to specify the name of the program, the author and other details, etc.
Comments
Comments are very helpful in identifying the program features and underlying logic of the program.
The lines begins with ‘/*’ and ending with ‘*/’ are known as comments lines.
These lines are not executable. There are two types of comment lines,
Single Comment Line eg., //ABCD….
Nested Comment Line (or) Multiple Comment Line
e.g, /*……..
……..*/

Preprocessor Section
It is used to link system library files for defining the macros and for defining the conditional inclusion.
C program depends upon some header file for function definition that is used in program.
Header file is extended with ‘.h’.
This file should be included using #.
Eg., #include<stdio.h>, #define A 10, #if def, #endif…

Global Declaration Section


This section declares some variables that are used in more than one function throughout the program.
These variables must be declared outside of the main function. So these variables are known as global
variables.

Main Function
 Every C program must contain main function.
 Without main function that is not a C program.
 After main function empty parenthesis are necessary.
 Main () is the starting point of every ‘C’ program.
 The execution always begin with the main function
 The execution starts with opening brace ‘{’ & closing brace ‘}’
 In between these braces the programmer should write executable and declaration part.
Executable part - It contains a set of statements or a single statement. These statements are enclosed
between the braces.
Declaration part - It declares the entire variables that are used in executable part. Variable initialization is
done in declaration section.
lOMoARcPSD|188 724 01

Sub Program Section (Or) User Defined Function- These section defined by user are called user defined
functions. These functions are defined after the main function (Or) before the main function.
Programming Rules
 While writing a program, a programmer should follow the following rules.
 All statements should be written in lowercase letters.
 Uppercase letters are only used for symbolic constants.
 Blank space may be inserted between the words. But blank space is not used while declaring a
variable, keyword, constant and function.
 The programmers can write the statement anywhere between the two braces.
 We can write one or more statements in a same line by separating each statement in a same line with
semicolon (:).
 The opening and closing braces should be balanced.

CONSTANTS, VARIABLES AND DATA TYPES


C Character Set
Character set are the set of alphabets, letters and some special characters that are valid in C language.
It is used to represent information.
Two types of Character Set
 Source Character Set
 Executable Character Set
Source Character Set
It is used to construct the statements in the source program.
Source character set is classified into,
Alphabets - A to Z and a to z
Digits - 0 to 9
o Special Characters - +, -, ?, /, (, ), *, &, ^, $, #, @, !, <, >, :, ;, ’, ”, _, =
White Spaces - Blank Space, Horizontal Tabs, Vertical Tab, New Line, Form Feed.

Executable Character Set


It is used at the time of execution.
Execution character set is also called as non-graphic character (or) Escape sequence.
Escape sequence are invisible and cannot be printed (or) displayed on the output screen.
Escape sequence are always represented by a back slash (\) followed by a character.
Character Escape Sequence Result
Bell (Alert) \a Beep Sound
Back Space \b Moves Previous Position
lOMoARcPSD|188 724 01

Horizontal Tab \t Moves next horizontal tab


Vertical Tab \v Moves next vertical tab
Newline (line feed) \n Moves next line
Form feed \f Moves initial position next page
Carriage return \r Moves beginning of the next line
Question mark \? Present Question mark
Backslash \\ \\ Present Back slash mark
NULL \0 NULL

C Tokens
Token is defined as the collection of entities such as identifiers, keywords, constants, strings, operators and
special symbols.
A token is source-program text that the compiler does not break down into component elements.

Identifiers
Identifier is a combination of alphanumeric characters.
An identifier is used for any variable, function, data definition, etc.
Eg., STDNAME, _SUB, TOT_MARKS – Valid Identifiers
Eg., Return, STD NAME - Invalid Identifiers
Rules for Naming an Identifier
 It consists of letters (uppercase & lowercase), digits and underscore ( _ ) only.
 The first letter of an identifier should be either a letter or an underscore.
 No space and special symbols are allowed between the identifier.
 The identifier cannot be a keyword.

DATA TYPES
DIFFERENT DATA TYPES IN C
Explain the various data types available in C with example. (Or) Discuss the basic data types in
C. (May/June 2016)[Nov/Dec2021] Data types
Data types are the keywords, which are used for assigning a type to a variable.
Allows the programmers to select the appropriate data type as per the need of the application.
Data types are used to specify the types of data that are going to process within the program.
lOMoARcPSD|188 724 01

C supports different types of data types. They are,


 Primary Data Type (or) Primitive data type
 User Defined Data Type
 Derived Data Type
 Empty Data Type

Primary Data Type (or) Primitive data type


The primary data types are divided into the following,
1. Integer Data Type
 Integer data type allows a variable to store numeric values.
 The keyword is used to define integer data type is “int”.
 The storage size of integer data type is 2 or 4 or 8 byte.
Eg., int a;
Signed Integer Unsigned Integer

long int b=2; unsigned short int c;

2. Character Data Type


Character data type allows a variable to store only one character.
Storage size of character data type is 1 byte. We can store only one character using character data type.
The keyword is used to define character data type is “char”.
Eg: char a;
Signed Char Unsigned Char
⟶It occupies 1 byte in memory. ⟶It occupies 1 byte in memory.
⟶It ranges from -128 to 127. ⟶It ranges from 0 to 255.
⟶Control String used is %c. ⟶Control String used is %c.
3. Floating Point Data Type
Floating point data type consists of 2 types. They are,
Float and double
float
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4 byte.
 These are numbers which contain fractional parts, both positive and negative.
 The keyword used to define float data type is, float.
 It ranges from (3.42-38) to (3.42+38).
 Control String used is %f.
Eg: float a;
double
 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The keyword used to define double variables is double.
 The range for double data type is from 1E–37 to 1E+37.
 It also occupies 2 bytes in memory.
Eg: double a;

User Defined Data Type


 The keyword used to define user defined data type is “typedef”.
 It allows users to define the identifier which would represent an existing data type.
 The main advantage is it increases the program’s readability.
lOMoARcPSD|188 724 01

Derived Data Type


 Derived data types are created by using predefined data types (int, char, float, double) only.
 Array, pointer, structure and union are called as derived data types in C language.

Empty Data Type


 Void is an empty data type that has no value.
 This can be used in functions and pointers.

Example Program
#include<stdio.h>
main()
{
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21;
/* assign float value */ letter = 'A';
/* assign character value */ pi = 2.01E6;
/* assign a double value */ printf("value of sum = %d\n", sum );
printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
printf("value of pi = %e\n", pi );
}

Output
value of sum = 10
value of money = 2.210000 value of letter = A
value of pi = 2.010000e+06

CONSTANTS
What are Constants? Explain the various types of constants in C. (April/May 2015)
Constants are the entity whose values can't be changed during the execution of a program.
Eg: x=3, Here 3 is a constant.
Constants are classified into two types. They are,
 Numerical Constant
 Character Constant
 Numerical Constant
It is divided into two types,
 Integer Constant
 Real Constant

Integer constants are the numeric constants formed with the sequence of digits without any fractional part or
exponential part.
There are three types of integer constants in C language: decimal constant (base 10), octal constant (base 8)
and hexadecimal constant (base 16).
Decimal Digits: 0 1 2 3 4 5 6 7 8 9
Octal Digits: 0 1 2 3 4 5 6 7
Hexadecimal Digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.

Example
Decimal Constants: 0, 9, 22, etc.
Octal Constants: 021, 077, 033, etc.
Hexadecimal Constants: 0x7f, 0x2a, 0x521, etc.
lOMoARcPSD|188 724 01

Floating Point Constant


Floating point constants are the numeric constant that has either fractional part or exponent part.
Example
2.0 0.0000234
0.22E5

Character Constant
Character constants are the constant which use single quotation around characters.

Single Character Constant


It contains a single character enclosed within a pair of single inverted commas both pointing to the left.
Eg: ‘s’, ‘M’, ‘3’, etc.

String Constant
A string constant is a sequence of characters enclosed in double quotes, the characters may be letters,
numbers, special characters and blank spaces, etc.
Eg: “Hello”, ”23”, “a”, etc.

Rules for Defining Constants


 It must have at least one digit.
 It can be either positive or negative.
 No commas or blank spaces are allowed.
 Decimal points are not allowed in integer constants, but allowed in real constants.

VARIABLE
 Variables are memory location in computer's memory to store data.
 To indicate the memory location, each variable should be given a unique name called identifier.
 A variable is an identifier that is used to represent some specified type of information within a
designated portion of the program.
Rules for naming the variables
 Variable name can be composed of letters (both uppercase and lowercase letters), digits and
underscore '_' only.
 The first letter of a variable should be either a letter or an underscore.
 No commas or blank spaces are allowed within a variable name.
 There is no rule for the length of length of a variable. However, the first 31 characters of a variable
are discriminated by the compiler.
Variable Declaration
Declaration of variable can be done in the declaration part of the program.
The variables must be declared before they are used in the program.
Syntax
Data_type variable name;
Example
int a; char m; float s;
Initializing Variables
Value can be initialized in the valuable name using an assignment operator = .
Syntax
Data_type variable name = value; (or) variable name=value;
Example
Eg: int x=2;
x=2;
Scope of the Variable
Scope of the variable implies the availability of variables within the program.
Variables have 2 types of scope.
 Local variables
 Global variables
lOMoARcPSD|188 724 01

Local Variables
Local variables are defined inside a main function block (Or) inside a compound statement of a function
subprogram are called local variables.
Example
function() { int i, j;
}
Global / External Variables
The variables that are declared before the function main() are called the global / external variables.
Eg:
int a, b; // here a,ball is a global variables.
main() {
…… function()
}
function() {
…….}

Enumerated constants
 Enumerated data types are a special form of integers, with the following constraints:
 Only certain pre-determined values are allowed.
 Each valid value is assigned a name, which is then normally used instead of integer values when
working with this data type.
 Enumerated types, variables, and typedefs, operate similarly to structs:
 enum suits { CLUBS, HEARTS, SPADES, DIAMONDS, NOTRUMP } trump;
 enum suits ew_bid, ns_bid;
 typedef enum Direction{ NORTH, SOUTH, EAST, WEST } Direction; Direction nextMove =
NORTH;
 Values may be assigned to specific enum value names.
 Any names without assigned values will get one higher than the previous entry.
 If the first name does not have an assigned value, it gets the value of zero.
 It is even legal to assign the same value to more than one name.

Example:
enum Errors{ NONE=0, // Redundant. The first one would be zero anyway
MINOR1=100, MINOR2, MINOR3, // 100, 101, and 102
MAJOR1=1000, MAJOR2, DIVIDE_BY_ZERO=1000 }; // 1000, 1001, and 1000
again.
Because enumerated data types are integers, they can be used anywhere integers are allowed.
One of the best places in in switch statements:
switch( nextMove ) {
case NORTH: y++;
break;

// etc.
The compiler will allow the use of ordinary integers with enumerated variables, e.g. trump = 2; , but it is bad
practice.

KEYWORDS
 Keywords are the reserved words used by the compiler that have standard and fixed (or) predefined
meaning in ‘C’ Language.
 Those words cannot be changed by the user and they are the basic building blocks for program
statements.
 All the keywords must be written in lower case.
 There are 32 keywords in C language. Some of the keywords are,
lOMoARcPSD|188 724 01

Keywords in C Language
auto double int struct do
break else Long switch default
case enum register typedef const
char extern return union if
continue for Signed, void goto
unsigned
float static sizeof short while

OPERATORS AND EXPRESSION


Precedence of operators
 If more than one operators are involved in an expression, C language has a predefined rule of priority
for the operators. This rule of priority of operators is called operator precedence.
 In C, precedence
arithmetic operators( *, %, /, +, -) relational operators(==, !=, >, <, >=, <=) logical operators(&&, || and
!).

Example of precedence
(1 > 2 + 3 && 4)
This expression is equivalent to:
((1 > (2 + 3)) && 4)
e, (2 + 3) executes first resulting into 5
then, first part of the expression (1 > 5) executes resulting into 0 (false) then, (0 && 4) executes resulting
into 0 (false)
Output
0

Associativity of operators
If two operators of same precedence (priority) is present in an expression, Associativity of operators
indicate the order in which they execute.

Example of Associativity
1 == 2 != 3
Here, operators == and != have same precedence.
The Associativity of both == and != is left to right, i.e, the expression on the left is executed first and moves
towards the right.
Thus, the expression above is equivalent to : ((1 == 2) != 3)
i.e, (1 == 2) executes first resulting into 0 (false) then, (0 != 3) executes resulting into 1 (true)
lOMoARcPSD|188 724 01

The table below shows all the operators in C with precedence and Associativity.

Operator Meaning of operator Associativity


() Functional call
[] Array element reference Left to right
-> Indirect member selection
. Direct member selection
! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment Right to left
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply
/ Divide Left to right
% Remainder
+ Binary plus(Addition) Left to right
- Binary minus(subtraction)
<< Left shift Left to right
>> Right shift

< Less than


<= Less than or equal Left to right
> Greater than
>= Greater than or equal
== Equal to Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Right to left
= Simple assignment Assign product
Assign quotient Assign remainder
*= Assign sum Assign difference
/= Assign bitwise AND Assign
%= bitwise XOR Assign bitwise OR
-= Assign left shift Right to left
&= Assign right shift
^=
|=
<<=
>>=
, Separator of expressions Left to right
lOMoARcPSD|188 724 01

TYPES OF OPERATORS IN C LANGUAGE

What are the various operators available in C? Discuss each one of them with suitable illustrations.
(Nov/Dec 2014) (Or) Explain the different types of operators available in C. (April/May 2015)
(Nov/Dec 2015) (May/June 2016) (Or) Explain various operators in C language in detail. (April / May
2017)[APR/MAY 2018][NOV/DEC 2019] [NOV/DEC 2020][APR/MAY 2021][Nov/Dec2021]

Operators
An operator is a symbol that specifies an operation to be performed on the operands.

Operand
It is a data item on which operators perform operation.
Eg: a+b
Here, a, b Operands + = Operator
Various Types of Operator
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and Decrement Operators
 Conditional Operators
 Bitwise Operators
 Special Operators

Arithmetic Operators
C allows basic arithmetic operations like addition, subtraction, multiplication and division.
Arithmetic Operators are,
+ , - , * , / , %.
Arithmetic operators are classified as
Unary Arithmetic: It requires only one operand.
Eg: +x, -y
Binary Arithmetic: It requires two operands.
Eg: a+b, a%b, etc.
Integer Arithmetic: It requires both operands are integer values for arithmetic operation.
Eg: a+b a=5, b=2
a+b = 5+2=7
Floating Point Arithmetic: It requires both operands are float type for arithmetic operation.
Eg: a+b, a=6.5 b=3.5
a+b, 6.5+3.5 = 10

Sample Program 1:
#include<stdio.h> // Header File
#include<conio.h>
int a=5, b=10; //Global Declaration
void main( ) /* main is the starting of every c program */
{
int c; //Local Declaration
clrscr( );
printf(“ \n The sum of the two values:”);
c = a+b;
printf(“%d”,c);
getch( );
}
Output: The sum of the two values: 15
lOMoARcPSD|188 724 01

Sample Program 2:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=10, b=4, c;
float d=3, e;
clrscr( );
c = a/b;
printf(" \n Value of a/b is:%d",c);
e = a/d;
printf("\n Value of a/d is:%f",e);
getch( );
}

Output
Value of a/b is: 2
Value of a/d is: 3.333333

Relational Operator
 Relational operators are used to compare two or more operands. Operands may be variables,
constants or expression.
 If the relation is true, it returns value 1 and if the relation is false, it returns value 0.
 Relational operators are, <, >, <=, >=, ==, !=
Example Program
#include<stdio.h> #include<conio.h> void main()
{
int a,b; clrscr();
printf(“\n Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(“\n The Result is”);
printf(“%d”, a<b);
printf(“%d”, a>b);
printf(“%d”, a<=b);
printf(“%d”, a>=b);
printf(“%d”, a==b);
printf(“%d”, a!=b); getch();
}
Output
Enter the Values of a and b: 4 2
The Result is

0
1
0
1
0
1
Logical Operators
Logical operators are used to combine the results of two or more conditions.
Operator Meaning Example
&& Logical AND If c=5 and d=2 then,((c==5) &&
(d>5)) Returns false.
|| Logical OR If c=5 and d=2
Then, ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.
lOMoARcPSD|188 724 01

Logical AND – This operator is used where a set of statements are to be executed, if two or more expressions
are true.
Logical OR – This is used, if either of them is true from two or more condition, then set of statements are
executed.
Logical NOT – This operator reverses the value of the expression it operates on.

Sample Program
#include<stdio.h> #include<conio.h> void main()
{
int c1.c2,c3; clrscr();
printf(“Enter the values c1, c2, c3:”);
scanf(“%d%d%d”, &c1,&c2&c3);
if((c1<c2)&&(c1<c3))
printf(“c1 is less than c2 and c3”);
if(!(c1<c2))
printf(“\n c1 is greater than c2”);
if((c1<c2)||((c1<c3))
printf(“c1 is less than c2 or c3 both”);
getch();
}
Output
Enter the values c1, c2, c3: 9 6 3
C1 is greater than c2

Assignment Operator
Assignment operators are used to assign a value or an expression or a value of a variable to another
variable.
Syntax: variable=expression (or) value ;
Example : x=10; x=a+b; x=y;
Two types of assignment operator are,
 Compound Assignment
 Nested Assignment (or) Multiple Assignment

Compound Assignment
Assign a value to a variable in order to assign a new value to a variable after performing a specified
operation.
Operator Example Same As
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Multiple Assignments
It is used to assign a single value or an expression to multiple variables.
Syntax: var1=var2= varn=single variable or expression;
Sample Program
#include<stdio.h>
#include<conio.h>
int b=10;
void main( )
{
int a=3, b=5;
clrscr( );
a+=b; // a= a+b
printf(" \n The sum of the two values:%d",a);
getch( );
lOMoARcPSD|188 724 01

}
Output:
The sum of the two values: 8

Increment and Decrement Operators


These are the increment (++) and decrement (--) operators. Both of these are unary operators.
The ++ adds 1 to the operand and – subtracts 1 from the operand.
++x - Pre Increment (First increment and then return the value)
--x - Pre Decrement (First decrement and then return the value)
x++ - Post Increment (First return the value and then increment)
x Post Decrement (First return the value and then decrement)

Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a=5;
clrscr();
printf(“Post Increment Value a++=%d\n”,a++);
printf(“Pre Increment Value ++a=%d\n”,++a);
printf(“Pre Decrement Value -- a=%d\n”,--a);
printf(“Post Decrement Value a--=%d\n”,a--);
getch();
}
Output:
Post Increment Value a++=5
Pre Increment Value ++a=7
Pre Decrement Value --a=6
Post Decrement Value a--=6

Conditional Operator (Or) Ternary Operator


Conditional operator itself checks the condition and executes the statement depending on the condition.
Syntax: condition?exp1:exp2

Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a=5, b=2, big;
clrscr();
big=(a>b)?a:b;
printf(“Largest number is %d”,big);
getch();
}
Output: Largest number is 5

Bitwise Operators
It is used to manipulate the data at bit level. It operates on integers only.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s Complement
lOMoARcPSD|188 724 01

Operations of above operators are,


a b a|b a&b a^b ~a
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0

Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a, b, c;
clrscr(); a=12; b=25;
c=a&b;
printf(“Bitwise AND=%d”,c);
c=a/b;
printf(“Bitwise OR=%d”,c);
c=a^b;
printf(“Bitwise XOR=%d”,c);
c=~a;
printf(“One’s Complement=%d”,c);
getch();
}
Output:
Bitwise AND=8 Bitwise OR=29 Bitwise XOR=21
One’s Complement= 220

Special Operators
It consists of the following,
Operators Meaning
, Comma Operator
sizeof() Size of Operator
& and * Address Operator / Indirection Operator
. and Member Selection Operator
Comma Operator
 It is used to separate the statement elements such as variables, constants or expression, etc.
sizeof() Operator
 It is a unary operator which is used in finding the size of data type, constant, arrays, structureetc.
Address Operator / Indirection Operator
Address Operator (&) - This symbol is used to specify the address of the variable.
Indirection Operator (*) - It is used to specify the value of the variable.
Member Selection Operator
These symbols are used to access the elements from a structure.
Sample Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int c;
clrscr( );
printf(" \n Size of Int is:%d",sizeof(c));
getch( );
}
Output
Size of Int is: 2
lOMoARcPSD|188 724 01

EXPRESSIONS
 An expression represents data item such as variables, constants and are interconnected
withoperators as per the syntax of the language.
 Syntax: variable=expression;
 An expression is a formula in which operands are linked to each other by the use of operators
to compute a value. An operand can be a function reference, a variable, an array element or a
constant.
Let's see an example:
a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.

There are four types of expressions exist in C:

 Arithmetic expressions
 Relational expressions
 Logical expressions
 Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.

For example:

x = 9/2 + a-b;
The entire above line is a statement, not an expression.
The portion after the equal is an expression.
lOMoARcPSD|188 724 01

Input and Output


 Input and output are covered in some detail. C allows quite precise control of these.
 This section discusses input and output from keyboard and screen.
 The same mechanisms can be used to read or write data from and to files.
 It is also possible to treat character strings in a similar way, constructing or analysing them
and storing results in variables.
The Standard Input Output File
Character Input / Output
getchar
putchar
Formatted Input / Output
printf
scanf
Whole Lines of Input and Output
gets
puts

printf
This offers more structured output than putchar. Its arguments are, in order; a control string,
which controls what gets printed, followed by a list of values to be substituted for entries in the
control string.
Example: int a,b;
printf(“ a = %d,b=%d”,a,b);.

 It is also possible to insert numbers into the control string to control field widths for values to
be displayed.
 For example %6d would print a decimal value in a field 6 spaces wide, %8.2f would print a
real value in a field
 8 spaces wide with room to show 2 decimal places. Display is left justified by default, but
can be right justified
 by putting a - before the format information, for example %-6d, a decimal integer right
justified in a 6 space
 field.

scanf
 scanf allows formatted reading of data from the keyboard.
 Like printf it has a control string, followed by the list of items to be read.
 However scanf wants to know the address of the items to be read, since it is a function which
will change that value.
 Therefore the names of variables are preceded by the & sign.
 Character strings are an exception to this.
 Since a string is already a character pointer, we give the names of string variables unmodified
by a leading &. Control string entries which match values to be read are preceeded by the
percentage sign in a similar way to their printf equivalents.
Example: int a,b;
scan f(“%d%d”,& a,& b);
lOMoARcPSD|188 724 01

getchar
 getchar returns the next character of keyboard input as an int. If there is an error then EOF
(end of file) is returned instead.
 It is therefore usual to compare this value against EOF before using it. If the return value is
stored in a char, it will never be equal to EOF, so error conditions will not be handled
correctly.
 As an example, here is a program to count the number of characters read until an EOF is
encountered.
 EOF can be generated by typing Control - d.

#include <stdio.h>

main()
{ int ch, i = 0;

while((ch = getchar()) != EOF)


i ++;

printf("%d\n", i);
}

putchar
 putchar puts its character argument on the standard output (usually the screen).
 The following example program converts any typed input into capital letters. To do this it
applies the function to upper from the character conversion library c type .h to each character
in turn.

#include <ctype.h> /* For definition of toupper */


#include <stdio.h> /* For definition of getchar, putchar, EOF */
main()
{ char ch;

while((ch = getchar()) != EOF)


putchar (toupper(ch));
}
gets
gets reads a whole line of input into a string until a new line or EOF is encountered. It is critical
to ensure that the string is large enough to hold any expected input lines.
When all input is finished, NULL as defined in studio is returned.
#include <stdio.h>
main()
{ char ch[20];

gets(x);
puts(x);
}
lOMoARcPSD|188 724 01

puts
puts writes a string to the output, and follows it with a new line character.
Example: Program which uses gets and puts to double space typed input.

#include <stdio.h>

main()
{ char line[256]; /* Define string sufficiently large to
store a line of input */

while(gets(line) != NULL) /* Read line */


{ puts(line); /* Print line */
printf("\n"); /* Print blank line */
}
}
Note that putchar, printf and puts can be freely used together.

Decision Making
The conditional statements (also known as decision control structures) such as if, if else, switch, etc.
are used for decision-making purposes in C/C++ programs.

They are also known as Decision-Making Statements and are used to evaluate one or more
conditions and make the decision whether to execute a set of statements or not. These decision-
making statements in programming languages decide the direction of the flow of program execution.

Need of Conditional Statements


There come situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next. Similar situations arise in programming also where we
need to make some decisions and based on these decisions we will execute the next block of code.
For example, in C if x occurs then execute y else execute z. There can also be multiple conditions
like in C if x occurs then execute p, else if condition y occurs execute q, else execute r. This
condition of C else-if is one of the many ways of importing multiple conditions.
lOMoARcPSD|188 724 01

Types of Conditional Statements in C

1. if in C/C++
The if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block
of statements is executed otherwise not.
Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement accepts boolean values
– if the value is true then it will execute the block of statements below it otherwise not. If we do not
provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement will consider the
first immediately below statement to be inside its block.
Flowchart of if Statement
lOMoARcPSD|188 724 01

Flow Diagram of if Statement


Example of if in C

// C program to illustrate If statement


#include <stdio.h>
int main()
{
int i = 10;

if (i > 15) {
printf("10 is greater than 15");
}
printf("I am Not in if");
}

Output
I am Not in if

2. if-else in C/C++
The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won’t. But what if we want to do something else when the condition is false?
Here comes the C else statement. We can use the else statement with the if statement to execute a
block of code when the condition is false. The if-else statement consists of two blocks, one for false
expression and one for true expression.
Syntax of if else in C
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
lOMoARcPSD|188 724 01

// condition is false
}

Flowchart of if-else Statement

Flow Diagram of if else

Example of if-else

// C program to illustrate If statement


#include <stdio.h>

int main()
{
int i = 20;

if (i < 15) {

printf("i is smaller than 15");


}
else {

printf("i is greater than 15");


}
return 0;}
lOMoARcPSD|188 724 01

Output
i is greater than 15
The block of code following the else statement is executed as the condition present in
the if statement is false.

3. Nested if-else in C
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean
an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements
within if statements, i.e, we can place an if statement inside another if statement.

Flow Diagram of Nested if-else


Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}

Example of Nested if-else

// C program to illustrate nested-if statement


#include <stdio.h>

int main()
{
lOMoARcPSD|188 724 01

int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}

return 0;
}

Output
i is smaller than 15
i is smaller than 12 too

4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed. if-else-if ladder is
similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.

else
statement;
lOMoARcPSD|188 724 01

Flowchart of if-else-if Ladder

Example of if-else-if Ladder

// C program to illustrate nested-if statement


#include <stdio.h>
int main()
{
int i = 20;

if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}

Output
i is 20
5. switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement. The switch
block consists of cases to be executed based on the value of the switch variable.
Syntax of switch
switch (expression) {
case value1:
statements;
case value2:
lOMoARcPSD|188 724 01

statements;
....

default:
statements;
}
Note: The switch expression should evaluate to either integer or character. It cannot evaluate any
other data type.
Flowchart of switch

Example of switch Statement

// C Program to illustrate the use of switch statement


#include <stdio.h>

int main()
{
// variable to be used in switch statement
int var = 2;
lOMoARcPSD|188 724 01

// declaring switch cases


switch (var) {
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}

return 0;
}

Output
Case 2 is executed

6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-else
statement. It is also known as the ternary operator as it works on three operands.
Syntax of Conditional Operator
(condition) ? [true_statements] : [flase_statements];

Flowchart of Conditional Operator


lOMoARcPSD|188 724 01

Example of Conditional Operator

// C Program to illustrate the use of conditional operator


#include <stdio.h>

// driver code
int main()
{
int var;
int flag = 0;
// using conditional operator to assign the value to var
// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);
// changing the value of flag
flag = 1;
// again assigning the value to var using same statement
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is NOT 0: %d", var);

return 0;
}

Output
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25

7. Jump Statements in C
These statements are used in C or C++ for the unconditional flow of control throughout the functions
in a program. They support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is
encountered from within a loop, the loop iterations stop there, and control returns from the loop
immediately to the first statement after the loop.
Syntax of break
break;
Basically, break statements are used in situations when we are not sure about the actual number of
iterations for the loop or we want to terminate the loop based on some condition.
lOMoARcPSD|188 724 01

Example of break

// C program to illustrate
// to show usage of break
// statement
#include <stdio.h>

void findElement(int arr[], int size, int key)


{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d",
(i + 1));
break;
}
}
}

int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };

// no of elements
int n = 6;
lOMoARcPSD|188 724 01

// key to be searched
int key = 3;

// Calling function to find the key


findElement(arr, n, key);

return 0;
}

Output
Element found at position: 3
B) continue
This loop control statement is just like the break statement. The continue statement is opposite to
that of the break statement, instead of terminating the loop, it forces to execute the next iteration of
the loop.
As the name suggests the continue statement forces the loop to continue or execute the next iteration.
When the continue statement is executed in the loop, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.
Syntax of continue
continue;

Flowchart of Continue
lOMoARcPSD|188 724 01

Example of continue

// C program to explain the use


// of continue statement
#include <stdio.h>

int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {

// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;

else
// otherwise print the value of i
printf("%d ", i);
}

return 0;
}

Output
1 2 3 4 5 7 8 9 10
If you create a variable in if-else in C/C++, it will be local to that if/else block only. You can use
global variables inside the if/else block. If the name of the variable you created in if/else is as same
as any global variable then priority will be given to the `local variable`.

#include <stdio.h>

int main()
{

int gfg = 0; // local variable for main


printf("Before if-else block %d\n", gfg);
if (1) {
int gfg = 100; // new local variable of if block
printf("if block %d\n", gfg);
}
printf("After if block %d", gfg);
return 0;
}
lOMoARcPSD|188 724 01

Output
Before if-else block 0
if block 100
After if block 0
C) goto
The goto statement in C/C++ also referred to as the unconditional jump statement can be used to
jump from one point to another within a function.
Syntax of goto
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a
label. Here, a label is a user-defined identifier that indicates the target statement. The statement
immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also appear before
the ‘goto label;’ statement in the above syntax.

Flowchart of goto Statement


Examples of goto

// C program to print numbers


// from 1 to 10 using goto
// statement
#include <stdio.h>
lOMoARcPSD|188 724 01

// function to print numbers from 1 to 10


void printNumbers()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
}

// Driver program to test above function


int main()
{
printNumbers();
return 0;
}

Output
1 2 3 4 5 6 7 8 9 10
D) return
The return in C or C++ returns the flow of the execution to the function from where it is called. This
statement does not mandatorily need any conditional statements. As soon as the statement is
executed, the flow of the program stops immediately and returns the control from where it was
called. The return statement may or may not return anything for a void function, but for a non-void
function, a return value must be returned.
Flowchart of return

Flow Diagram of return


Syntax of return
return [expression];
lOMoARcPSD|188 724 01

// C code to illustrate return


// statement
#include <stdio.h>

// non-void return type


// function to calculate sum
int SUM(int a, int b)
{
int s1 = a + b;
return s1;
}

// returns void
// function to print
void Print(int s2)
{
printf("The sum is %d", s2);
return;
}

int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}

Output
The sum is 20
Switch Case
This is another form of the multi way decision. It is well structured, but can only be used in certain
cases where;
• Only one variable is tested, all branches must depend on the value of that variable. The
variable must be an integral type. (int, long, short or char).
• Each possible value of the variable can control a single branch. A final, catch all, default
branch may optionally be used to trap all unspecified cases.
Hopefully an example will clarify things. This is a function which converts an integer into a vague
description. It is useful where we are only concerned in measuring a quantity when it is quite small.

estimate(number)
int number;
/* Estimate a number as none, one, two, several, many */
{ switch(number) {
case 0 :
printf("None\n");
break;
lOMoARcPSD|188 724 01

case 1 :
printf("One\n");
break;
case 2 :
printf("Two\n");
break;
case 3 :
case 4 :
case 5 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
}
Each interesting case is listed with a corresponding action. The break statement prevents any further
statements from being executed by leaving the switch. Since case 3 and case 4 have no following
break, they continue on allowing the same action for several values of number.
Both if and switch constructs allow the programmer to make a selection from a number of possible
actions.

Loops
Looping is a way by which we can execute any some set of statements more than one times
continuously .In c there are mainly three types of loops are use :
• while Loop
• do while Loop
• For Loop
While Loop
Loops generally consist of two parts: one or more control expressions which (not surprisingly)
control the execution of the loop, and the body, which is the statement or set of statements which is
executed over and over.
The general syntax of a while loop is
Initialization
while( expression )
{
Statement1
Statement2
Statement3

The most basic loop in C is the while loop. A while loop has one control expression, and executes as
long as that expression is true. This example repeatedly doubles the number 2 (2, 4, 8, 16, ...) and
prints the resulting numbers as long as they are less than 1000:
int x = 2;

while(x < 1000)


lOMoARcPSD|188 724 01

{
printf("%d\n", x);
x = x * 2;
}
(Once again, we've used braces {} to enclose the group of statements which are to be executed
together as the body of the loop.)

For Loop
Our second loop, which we've seen at least one example of already, is the for loop. The general
syntax of a while loop is

for( Initialization;expression;Increments/decrements )
{
Statement1
Statement2
Statement3

The first one we saw was:


for (i = 0; i < 10; i = i + 1)
printf ("i is %d\n", i);
(Here we see that the for loop has three control expressions. As always, the statement can be a
brace-enclosed block.)
Do while Loop
This is very similar to the while loop except that the test occurs at the end of the loop body. This
guarantees that the loop is executed at least once before continuing. Such a setup is frequently used
where data is to be read. The test then verifies the data, and loops back to read again if it was
unacceptable.

do
{
printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value != 1 && input_value != 0)

C Preprocessors
Preprocessors are programs that process our source code before compilation. There are a number of
steps involved between writing a program and executing a program in C / C++. Let us have a look at
these steps before we actually start learning about Preprocessors.
lOMoARcPSD|188 724 01

You can see the intermediate steps in the above diagram. The source code written by programmers is
first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an
expanded source code file is generated named “program.i”. This expanded file is compiled by the
compiler and an object code file is generated named “program.obj”. Finally, the linker links this
object code file to the object code of the library functions to generate the executable file
“program.exe”.

Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source
code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’
symbol indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get
executed. Examples of some preprocessor directives are: #include, #define, #ifndef etc. Remember
that the # symbol only provides a path to the preprocessor, and a command such as include is
processed by the preprocessor program. For example, #include will include extra code in your
program. We can place these preprocessor directives anywhere in our program.

There are 4 Main Types of Preprocessor Directives:


Macros
File Inclusion
Conditional Compilation
Other directives

1. Macros
Macros are pieces of code in a program that is given some name. Whenever this name is encountered
by the compiler, the compiler replaces the name with the actual piece of code. The ‘#define’
directive is used to define a macro. Let us now understand the macro definition with the help of a
program:

#include <stdio.h>

// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++) {
lOMoARcPSD|188 724 01

printf("%d \n",i);
}

return 0;
}
Output:

0
1
2
3
4
In the above program, when the compiler executes the word LIMIT, it replaces it with 5. The word
‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.

Note: There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a
semi-colon to end.

Macros With Arguments: We can also pass arguments to macros. Macros defined with arguments
work similarly to functions. Let us understand this with a program:

#include <stdio.h>
// macro with parameter
#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5, area;

area = AREA(l1, l2);

printf("Area of rectangle is: %d", area);

return 0;
}
Output
Area of rectangle is: 50
Output:
Area of rectangle is: 50

We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it
replaces it with the statement (l*b). Not only this, but the values passed to the macro template
AREA(l, b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to
10*5.

2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program.
There are two types of files that can be included by the user in the program:
lOMoARcPSD|188 724 01

Header files or Standard files: These files contain definitions of pre-defined functions like printf(),
scanf(), etc. These files must be included to work with these functions. Different functions are
declared in different header files. For example, standard I/O functions are in the ‘iostream’ file
whereas functions that perform string operations are in the ‘string’ file.
Syntax:
#include< file_name >
where file_name is the name of the file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to
look for the file in the standard directory.

User-defined files: When a program becomes very large, it is a good practice to divide it into smaller
files and include them whenever needed. These types of files are user-defined files. These files can
be included as:

#include"filename"
3. Conditional Compilation
Conditional Compilation directives are a type of directive that helps to compile a specific portion of
the program or to skip the compilation of some specific part of the program based on some
conditions. This can be done with the help of the two preprocessing commands ‘ifdef‘ and ‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute
normally, but if it is not defined, the compiler will simply skip this block of statements.

4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These
are:
#undef Directive: The #undef directive is used to undefine an existing macro. This directive works
as:

#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef
LIMIT” statement will evaluate as false.

#pragma Directive: This directive is a special purpose directive and is used to turn on or off some
features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler.
Some of the #pragma directives are discussed below:

#pragma startup and #pragma exit: These directives help us to specify the functions that are needed
to run before program startup (before the control passes to main()) and just before program exit (just
before the control returns from main()).
lOMoARcPSD|188 724 01

Note: Below program will not work with GCC compilers.

#include <stdio.h>

void func1();
void func2();

#pragma startup func1


#pragma exit func2

void func1()
{
printf("Inside func1()\n");
}

void func2()
{
printf("Inside func2()\n");
}

int main()
{
void func1();
void func2();
printf("Inside main()\n");

return 0;
}Output
Inside main()
Output:
Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:

Inside main()
This happens because GCC does not support #pragma startup or exit. However, you can use the
below code for a similar output on GCC compilers.
#include <stdio.h>
void func1();
void func2();

void __attribute__((constructor)) func1();


void __attribute__((destructor)) func2();

void func1()
{
printf("Inside func1()\n");
lOMoARcPSD|188 724 01

void func2()
{
printf("Inside func2()\n");
}

int main()
{
printf("Inside main()\n");

return 0;
}
Output
Inside func1()
Inside main()
Inside func2()
#pragma warn Directive: This directive is used to hide the warning message which is displayed
during compilation. We can hide the warnings as shown below:

#pragma warn -rvl: This directive hides those warnings which are raised when a function that is
supposed to return a value does not return a value.
#pragma warn -par: This directive hides those warnings which are raised when a function does not
use the parameters passed to it.
#pragma warn -rch: This directive hides those warnings which are raised when a code is
unreachable. For example, any code written after the return statement in a function is unreachable.

Compilation process in c

The compilation is a process of converting the source code into object code. It is done with
the help of the compiler. The compiler checks the source code for the syntactical or structural errors,
and if the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or machine
code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments from the source
code. The preprocessor takes the preprocessor directive and interprets it. For example, if <stdio.h>,
the directive is available in the program, then the preprocessor interprets the directive and replace
this directive with the content of the 'stdio.h' file.

The following are the phases through which our program passes before being transformed into an
executable form:
 Preprocessor
 Compiler
 Assembler
 Linker
lOMoARcPSD|188 724 01

Preprocessor
The source code is the code which is written in a text editor and the source code file is given an
extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.

Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler converts
this code into assembly code. Or we can say that the C compiler converts the pre-processed code into
assembly code.

Assembler
The assembly code is converted into object code by using an assembler. The name of the object file
generated by the assembler is the same as the source file. The extension of the object file in DOS is
'.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the name of the
object file would be 'hello.obj'.

Linker
Mainly, all the programs written in C use library functions. These library functions are pre-compiled,
and the object code of these library files is stored with '.lib' (or '.a') extension. The main working of
the linker is to combine the object code of library files with the object code of our program.
Sometimes the situation arises when our program refers to the functions defined in other files; then
linker plays a very important role in this. It links the object code of these files to our program.
Therefore, we conclude that the job of the linker is to link the object code of our program with the
object code of the library files and other files. The output of the linker is the executable file. The
name of the executable file is the same as the source file but differs only in their extensions. In DOS,
the extension of the executable file is '.exe', and in UNIX, the executable file can be named as 'a.out'.
lOMoARcPSD|188 724 01

For example, if we are using printf() function in a program, then the linker adds its associated code
in an output file.

Let's understand through an example.

hello.c

#include <stdio.h>
int main()
{
printf("Hello javaTpoint");
return 0;
}

Now, we will create a flow diagram of the above program:


lOMoARcPSD|188 724 01

In the above flow diagram, the following steps are taken to execute a program:
Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor converts the
source code into expanded source code. The extension of the expanded source code would be hello.i.
The expanded source code is passed to the compiler, and the compiler converts this expanded source
code into assembly code. The extension of the assembly code would be hello.s.
This assembly code is then sent to the assembler, which converts the assembly code into object code.
After the creation of an object code, the linker creates the executable file. The loader will then load
the executable file for the execution.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy