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

cs3251-notes-unit-1

The document provides an overview of the basics of C programming, including programming paradigms, applications of C, and the structure of a C program. It covers fundamental concepts such as data types, constants, operators, and the compilation process. Additionally, it details the components of a C program, including documentation, preprocessor directives, and the main function.

Uploaded by

kanimozhi
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)
4 views

cs3251-notes-unit-1

The document provides an overview of the basics of C programming, including programming paradigms, applications of C, and the structure of a C program. It covers fundamental concepts such as data types, constants, operators, and the compilation process. Additionally, it details the components of a C program, including documentation, preprocessor directives, and the main function.

Uploaded by

kanimozhi
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/ 44

lOMoARcPSD|41379181

Cs3251-notes-unit 1

programming in c (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Kanimozhi .D ([email protected])
lOMoARcPSD|41379181

Unit I 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
1.1Introduction to programming paradigms:
Programming paradigm is an approach to solve problem using some programming
language or also we can say it is a method to solve a problem using tools and techniques
that are available to us following some approach. There are lots for programming
language that are known but all of them need to follow some strategy when they are
implemented and this methodology/strategy is paradigms. Apart from varieties of
programming language there are lots of paradigms to fulfill each and every demand.
 Imperative Programming
Imperative programming consists of sets of detailed instructions that are given to the
computer to execute in a given order. It's called "imperative" because as programmers
we dictate exactly what the computer has to do, in a very specific way.
Imperative programming focuses on describing how a program operates, step by step.
 Procedural Programming
Procedural programming is a derivation of imperative programming, adding to it the
feature of functions (also known as "procedures" or "subroutines").
In procedural programming, the user is encouraged to subdivide the program execution
into functions, as a way of improving modularity and organization.
 Functional Programming
Functional programming takes the concept of functions a little bit further.
In functional programming, functions are treated as first-class citizens, meaning that
they can be assigned to variables, passed as arguments, and returned from other
functions.
 Declarative Programming
Declarative programming is all about hiding away complexity and bringing
programming languages closer to human language and thinking. It's the direct opposite
of imperative programming in the sense that the programmer doesn't give instructions
about how the computer should execute the task, but rather on what result is needed.
 Object-Oriented Programming
One of the most popular programming paradigms is object-oriented programming
(OOP).

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

The core concept of OOP is to separate concerns into entities which are coded as
objects. Each entity will group a given set of information (properties) and actions
(methods) that can be performed by the entity.
1.2.Applications of C Language:
o Development of video games
o Applications using graphical user interfaces
o Databases and computer operating systems
o Browsers on the internet
o Computational and graphical methods
o Banking
o Cloud computing and distributed systems
o Compilers
o Embedded systems are systems that are integrated into a larger system.
o Integrated software libraries for enterprises
o Server applications on a large scale
o Compilers of code
Top 10 applications developed in C
1. Adobe Systems
2. Google
3. Mozilla
4. Mysql
5. Winamp media player
1.3.1Structure of C program :
The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format. C program must follow the
below-mentioned outline in order to successfully compile and execute. Debugging is
easier in a well-structured C program.
Sections of the C Program: There are 6 basic sections responsible for the proper
execution of a program. Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program, and
the creation date and time of the program. It is specified at the start of the program in
the form of comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Or
/* description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and
this will not interfere with the given code. Basically, it gives an overview to the reader of
the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the
program. Header files help us to access other’s improved code into our code. A copy of
these multiple files is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
#include<conio.h>
3. Definition
Preprocessors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and execution of
the program. Preprocessor directives start with the ‘#’ symbol. The #define
preprocessor is used to create a constant throughout the program. Whenever this name
is encountered by the compiler, it is replaced by the actual piece of defined code.
Example:
#define pi=3.14;
4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used
anywhere in the program.
Example:
int num = 18;
5. Main() Function
Every C program must have a main function. The main() function of the program is
written in this section. Operations like declaration and execution are performed inside
the curly braces of the main program. The return type of the main() function can be int
as well as void too. void() main tells the compiler that the program will not return any
value. The int main() tells the compiler that the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

User-defined functions are called in this section of the program. The control of the
program is shifted to the called function whenever they are called from the main or
outside the main() function. These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
Example program:
// Documentation
/**
* file: sum.c
* description: program to find sum.
*/
#include <stdio.h> // Link
#define X 20 // Definition
int sum(int y); // Global Declaration
int main(void) // Main() Function
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
int sum(int y) // Subprogram
{
return y + X;
}
Output
Sum: 75
1.3.2 Data Types in C:
 .Each variable in C has an associated data type. It specifies the type of data that
the variable can store like integer, character, floating, double, etc.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 Each data type requires different amounts of memory and has some specific
operations which can be performed over it.
 The data type is a collection of data with values having fixed values, meaning as
well as its characteristics.
The data types in C can be classified as follows:
1. Primitive Data Types --- Primitive data types are the most basic data types
that are used for representing simple values such as integers, float, characters,
etc.
2. User Defined Data Types --- The user-defined data types are defined by the
user himself.
3. Derived Types--- The data types that are derived from the primitive or built-in
datatypes are referred to as Derived Data Types.
Primitive Data Types : 1. Integer Data Type
The integer datatype in C is used to store the integer numbers(any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values, and
decimal values can be stored in int data type in C.
Range: -2,147,483,648 to 2,147,483,647
Size: 4 bytes
Format Specifier: %d
Syntax of Integer
We use int keyword to declare the integer variable: int var_name;
Example: int a;
The integer data type can also be used as
unsigned int: Unsigned int data type in C is used to store the data values from zero to
positive numbers but it can’t store negative values like signed int.
short int: It is lesser in size than the int by 2 bytes so can only store values from -
32,768 to 32,767.
long int: Larger version of the int datatype so can store values greater than int.
unsigned short int: Similar in relationship with short int as unsigned int with int.
EX: // C program to print Integer data types.
#include <stdio.h>

int main()
{
// Integer value with positive data.
int a = 9;

// integer value with negative data.


int b = -9;

// U or u is Used for Unsigned int in C.


int c = 89U;

// L or l is used for long int in C.


long int d = 99998L;

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

printf("Integer value with positive data: %d\n", a);


printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n",
c);
printf("Integer value with an long int data: %ld", d);

return 0;
}
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Character Data Type:
Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.
Range: (-128 to 127) or (0 to 255)
Size: 1 byte
Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;
Example of char
// C program to print Integer data types.
#include <stdio.h>
void main()
{
char a = 'a';
char c;
printf("Value of a: %c\n", a);
}
Output
Value of a: a
Float Data Type
In C programming float data type is used to store floating-point values. Float in C is used
to store decimal and exponential values. It is used to store decimal numbers (numbers
with floating point values) with single precision.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes
Format Specifier: %f
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
Example of Float

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

#include <stdio.h>
int main()
{
float a = 9.0f;
printf("%f\n", a);
return 0;
}
Output
9.000000
Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers
with decimal values in C.

The double data type is basically a precision sort of data type that is capable of holding
64 bits of decimal numbers or floating points. Since double has more precision as
compared to that float then it is much more obvious that it occupies twice the memory
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits
after or before a decimal point.

Range: 1.7E-308 to 1.7E+308


Size: 8 bytes
Format Specifier: %lf
Syntax of Double
The variable can be declared as double precision floating point using the double
keyword:
double var_name;
Example of Double
// C Program to demonstrate
#include <stdio.h>
int main()
{
double a = 123123123.00
printf("%lf\n", a);
return 0;
}
Output
123123123.000000
Void Data Type:
The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller. It has no values and no operations. It is used to represent
nothing. Void is used in multiple ways as function return type, function arguments as
void, and pointers to void.
Syntax:
// function return type void

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

void exit(int check);


// Function without any parameter can accept void.
int print(void);
// memory allocation function which
// returns a pointer to void.
void *malloc (size_t size);
Example of Void
// C program to demonstrate
// use of void pointers
#include <stdio.h>
int main()
{
int val = 30;
void* ptr = &val;
printf("%d", *(int*)ptr);
return 0;
}
Output:
30
Size of Data Types in C:
The size of the data types in C is dependent on the size of the architecture, so we cannot
define the universal size of the data types. For that, the C language provides the sizeof()
operator to check the size of the data types.
Example
// C Program to print size of
// different data type in C
#include <stdio.h>
int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);
printf("The size of int data type : %d\n", size_of_int);
printf("The size of char data type : %d\n" size_of_char);
printf("The size of float data type : %d\n", size_of_float);
printf("The size of double data type : %d", size_of_double);
return 0;
}
Output
The size of int data type : 4
The size of char data type : 1
The size of float data type : 4
The size of double data type : 8
Literals in C:

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

In C, Literals are the constant values that are assigned to the variables. Literals represent
fixed values that cannot be modified. Literals contain memory but they do not have
references as variables. Generally, both terms, constants, and literals are used
interchangeably.
For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a
constant integer literal.
Types of C Literals
There are 4 types of literal in C:
 Integer Literal
 Float Literal
 Character Literal
String Literal 1. Integer Literals
Integer literals are used to represent and store the integer values only. Integer literals
are expressed in two types i.e.
A) Prefixes: The Prefix of the integer literal indicates the base in which it is to be read.
For Example:
0x10 = 16
Because 0x prefix represents a HexaDecimal base. So 10 in HexaDecimal is 16 in Decimal.
Hence the value 16.
There are basically represented into 4 types:
a. Decimal-literal(base 10): A non-zero decimal digit followed by zero or more
decimal digits(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
Example:
56, 78

b. Octal-literal(base 8): a 0 followed by zero or more octal digits(0, 1, 2, 3, 4, 5, 6, 7).


Example:
045, 076, 06210

c. Hex-literal(base 16): 0x or 0X followed by one or more hexadecimal digits(0, 1, 2,


3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).
Example:
0x23A, 0Xb4C, 0xFEA

d. Binary-literal(base 2): 0b or 0B followed by one or more binary digits(0, 1).


Example:
0b101, 0B111

B) Suffixes: The Prefix of the integer literal indicates the type in which it is to be read.
For example:
12345678901234LL
indicates a long long integer value 12345678901234 because of the suffix LL
These are represented in many ways according to their data types.
 int: No suffix is required because integer constant is by default assigned as an int
2. Floating-Point Literals
These are used to represent and store real numbers. The real number has an integer
part, real part, fractional part, and exponential part. The floating-point literals can be
stored either in decimal form or exponential form. While representing the floating-
point decimals one must keep two things in mind to produce valid literal:

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 In the decimal form, one must include the integer part, or fractional part, or both,
otherwise, it will lead to an error.
 In the exponential form, one must include both the significand and exponent part,
otherwise, it will lead to an error.
A few floating-point literal representations are shown below:
Valid Floating Literals:
10.125
1.215e-10L
10.5E-3

Invalid Floating Literals:


123E
1250f
0.e879

3. Character Literals
This refers to the literal that is used to store a single character within a single quote.
To store multiple characters, one needs to use a character array. Storing more than
one character within a single quote will throw a warning and display just the last
character of the literal. It gives rise to the following two representations:
 char type: This is used to store normal character literal or narrow-character
literals.
Example:
char chr = 'G';

CONSTANTS IN C:
The constants in C are the read-only variables whose values cannot be modified once
they are declared in the C program. The type of constant can be an integer constant, a
floating pointer constant, a string constant, or a character constant. In C language, the
const keyword is used to define the constants.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the
list of the types of constants
 Integer Constant
 Character Constant
 Floating Point Constant
 Double Precision Floating Point Constant
 Array Constant
 Structure Constant
Difference Between Constants and Literals
Constant :
 Constants are variables that cannot be modified once declared.
 Constants are defined by using the const keyword in C. They store literal
values in themselves.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 We can determine the address of constants.


Literals:
 Literals are the fixed values that define themselves.
 They themselves are the values that are assigned to the variables or
constants.
 We cannot determine the address of a literal except string literal.
Keywords:
In C Programming language, there are many rules so to avoid different types of errors.
One of such rule is not able to declare variable names with auto, long, etc. This is all
because these are keywords. Let us check all keywords in C language.
Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers in the program. A list of
keywords in C or reserved words in the C programming language are mentioned below:
Auto break case char const continue
default do double else enum extern
Float for goto if int long
register return short signed sizeof static
Struct switch typedef union unsigned void
volatile while

These keywords have specific purposes within the C programming language and cannot
be used as identifiers for variables, functions, or any other user-defined names.
Operators: Precedence and Associativity
In C language, operators are symbols that represent operations to be performed on one
or more operands. They are the basic components of the C programming. In this article,
we will learn about at all the built-in operators in C with examples.
What is a C Operator?
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables. The values and variables used with operators are called operands. So we can
say that the operators are the symbols that perform operations on operands.
Precedence:
If there is more than one operator in an expression, which operation we need to
perform first is specified by precedence.
Associativity:
If more than one operator has the same precedence which operation we need to
perform is specified by associativity.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Example:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands.
The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
'C' operators can be classified into 8 categories.
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Special operators.
Arithmetic operators:
'C' provides all the basic arithmetic operators.

Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo division
Unary minus example: -2, 2*-1
Note: Modulo division operator (%) is used only for integral values and cannot be
used on floating point data.

*, /, %----------highest precedence
+,----------------lowest precedence

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Arithmetic operator’s associativity is from Left to Right.


i. In integer arithmetic, all operands are integer.
Example: 15/4=3
ii. In real arithmetic, all operands are real.
Example: 15.0/4.0=3.75
iii. In mixed mode arithmetic, one operand is real and another operand is
integer then that expression is called mixed mode arithmetic.
If either operand is of the real type, then only the real operation is performed and
the result is always a real number.
Example: 15.0/4=3.75 or
15/4.0=3.75
Example program:
#include<stdio.h> main()
{
int a,b; floatc,d;
printf("enter 2 integer values\n");
scanf("%d%d",&a,&b); printf("enter 2 float values\n"); scanf("%f%f",&c,&d);
printf("Integer Arithmetic %d/%d=%d\n",a,b,a/b); printf("real Arithmetic %f/%f=%f\
n",c,d,c/d); printf("Mixed mode Arithmetic %f/%d=%f\n",c,b,c/b);
}
Relational operators:

 These operators are used to compare the quantities.


 These operators are used to identify the relation between quantities.

Operator Meaning
< is less than
<= is less than or equal
> is greater than
>= is greater than or equal
== is equal to
!= is not equal to

Form:

ae-1 rela琀椀onal operator ae-2

Where ae-1 and ae-2 are arithmetic expressions, which may be simple constants,
variables, or combination of them.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

The expression containing a relational operator is termed as relational expression. The


value of the relational expression is either one or zero.
It is one if the specified relation is true and zero if the relation is false.
Examples:
Relational Expression Result
10<20 1(true)
20<=10 0(false)
10>5 1(true)
10>=4 1(true)
10==10 1(true)
10!=10 0(false)
<, <=, >, >=--------------highest precedence
==,!=-------------------lowest precedence
Relational expressions are used in decision statements such as, if and while to decide
the course of a running program.
Arithmetic operators have a higher priority than relational operators.
Associativity is from Left to Right.
Example program:
#include<stdio.h> main()
{
int a,b;
printf("enter a,b\n"); scanf("%d%d",&a,&b); printf("%d<%d=%d\n",a,b,a<b);
printf("%d<=%d=%d\n",a,b,a<=b); printf("%d>%d=%d\n",a,b,a>b); printf("%d>=%d=
%d\n",a,b,a>=b); printf("%d==%d=%d\n",a,b,a==b); printf("%d!=%d=%d\n",a,b,a!=b);
}
Logical operators:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

The logical operators && and || are used when we want to test more than one condition
and make decisions.
The logical expression:
An expression which combines 2 or more relational expressions is termed as a logical or
compound relational expression.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Logical expression yields a value of one or zero, according to the truth


table. Truth Table:

op1 op2 op1 && op2 op1 || op2


Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0

Example program:
#inclu
de<std
io.h>
main()
{
int marks,a,b;
printf("enter
marks\n");
scanf("%d",&
marks);
printf("enter 2 int
values\n");
scanf("%d
%d",&a,&b);
printf("marks>=90 && marks<=100: %d\
n",marks>=90 && marks<=100);
printf("a>=b || b>=a=%d\n",a>=b ||
b>=a); printf("!a=%d\n",!a);
}
Local NOT------------highest precedence, Associativity from Right-> Left
Logical AND----------------next highest precedence, Associativity from Left -> Right
Logical OR----------------lowest precedence, Associativity from Left -> Right

Assignment operators:
Assignment operators are used to assign the result of an expression to a variable.
Assignment operator is '='.

Example:
a=10;
Left hand side must be a variable; Right hand side may be a variable/constant
or combination of these two.
'C' has a set of 'shorthand' assignment operators of the form

v op=exp;

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Where v is a variable, exp is an expression and op is C binary arithmetic operator.

Associativity is from Right to Left. v = v op (exp);


Operator op=is known as the shorthand assignment operator. The assignment
statement vop=exp;

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Statement with simple Statement with shorthand


assignment operator operator
a =a + 100 a += 100
a = a - 20 a -= 20
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b

The use of shorthand assignment operators has three advantages:


1. What appears on the left hand side need not be repeated and therefore it becomes easier
to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.

Example program:
#include<stdio.h>
main()
{
int a,n;
printf("enter a,n values\n");
scanf("%d%d",&a,&n);
a += 100;
printf("a=%d\n",a);
a -= 20;
printf("a=%d\n",a);
a *= (n+1); printf("a=
%d\n",a);
a /= (n+1); printf("a=
%d\n",a); a %= n;
printf("a=%d\n",a);
}
Increment and Decrement operators:
 'C' has two very useful operators not generally found in other languages.
 These are increment and decrement operators:
++ and --
 The operator ++ adds 1 to the operand.
 The operator -- subtracts 1 from the operand.
 Both are unary operators.
 We use the increment and decrement statements in for and while loops extensively.

Statement with
Meaning
Operator

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

++a Pre increment


a++ Post increment
--a Pre decrement
a-- Post decrement
 Both ++a and a++ mean the same thing when they
form statements
independently.
 They behave differently when they are used in expressions on the R.H.S. of an
assignment statement.

Statement with Operator used in Meaning Explanation


assignment
First adds1 to a and then the
b = ++a Pre increment
result is assigned value of a to b
First assigns the value of a to b
b = a++ Post increment
and then add 1 to a
b = --a Pre decrement First subtracts 1 to a and then the result
is assigned value of a to b
First assigns the value of a to b
b = a-- Post decrement
and then subtract 1 to a

Associativity is from Right -> Left.

Example Program:
#include<stdio.h>
main()

{
int a,n;
printf("enter a value\n");
scanf("%d",&a);
n=a++; printf("a=%d\tn=%d\
n",a,n); n=++a; printf("a=%d\
tn=%d\n",a,n); n=a--;
printf("a=%d\tn=%d\n",a,n);
n=--a; printf("a=%d\tn=%d\
n",a,n);
}
Output:
enter a value
4
a=5 n=4
a=6 n=6
a=5 n=6

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

a=4 n=4

Conditional operator:

A ternary operator pair "?:"is available in C to construct conditional expressions. Form is


exp1 ? exp2 : exp3;

Where exp1, exp2, exp3 are expressions.


Working of conditional operator "?:" :
i. exp1 is evaluated first. If it is non-zero (true), then the expression exp2 is evaluated and
that is the value of the expression.
ii. If exp1 is zero (false), exp3 is evaluated and it is the value of the expression
iii. Note that only one of the expressions (either exp2 or exp3) is evaluated.
Example:
int a=10, b=15, x;
x=(a<b) ? a : b;
Here, (10<15) evaluates to True, then x=a=10
Result:
x=10
Associativity is from Right -> Left.
//Program to find whether the given number is even or odd using conditional operator
#include<stdio.h>
main()
{
int n;
printf("enter n value\n");
scanf("%d",&n);
(n%2==0)?printf("%d is even number\n",n):printf("%d is odd number\n",n);
}

Output 1:
enter n value
4
4 is even number

Output 2:
enter n value
5
5 is odd number

Example:
#include<stdio.h>

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

main()
{
float a,b,c,d;
printf("enter a,b,c,d values\n"); scanf("%f%f%f
%f",&a,&b,&c,&d);
(c-d!=0)?printf("%f",(a+b)/(c-d)):printf("c-d is 0");
}
Output 1:
entera,b,c,d values 3
4
5
2
2.333333
Output 2:
entera,b,c,d values 3
4
5
5
c-d is 0

Bitwise operators:
 For manipulation of data at bit level, a special operators known as bitwise operators are
introduced.
 These operators are used for testing the bits or shifting them right or left.
 Bitwise operators may not be applied to float or double.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
~ One’s Complement

Truth table for Bitwise AND, Bitwise OR and Bitwise Exclusive OR:

op1 op2 op1 & op2 op1 | op2 op1 ^ op2


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

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Truth table for Bitwise NOT:


op1 ! op1
1 0
0 1
Bitwise AND (&):

Example 1:
x=9
y=7
First convert given decimal number to binary number and then perform bitwise operation.

x=1001
y=0111

z= 0001

Next convert the binary number to decimal number to get final result z = 9 &

7=1

Example2:

x=4
y=14

x=0100
y=1110

z=0100 = 4

z = 4 & 14=4
Bitwise OR (|):

Example 1:
x=8
y=7
First convert given decimal number to binary number and then perform bitwise operation.

x=1000
y=0111

z=1111
Next convert the binary number to decimal number to get final result z = 8|
7=15

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Example2:

x=4
y=14

x=0100
y=1110

z=1110 = 14
z = 4 | 14=4

Bitwise Exclusive-OR (^):

Example 1:
x=5
y=7
First convert given decimal number to binary number and then perform bitwise operation.
x=101
y=111

z=010
Next convert the binary number to decimal number to get final result z = 5 ^
7=2
Example2:

x=4
y=14

x=0100
y=1110

z=1010 = 10

z = 4 ^ 14=4

Bitwise Complement Operator (~):

Example 1:
Find complement of 5 (~5)

Step1:
Convert decimal 5 into binary and take 8 bits.
0000 0101
First perform bits complement means change 1’s as 0’s and 0’s as 1’s (1’s complement).

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

1111 1010
MSB LSB

Step2:
If the MSB bit of result of bits complement is 1, then the final result contains –ve sign. Always
negative numbers in the system are represented using 2’s complement form.
Finding 2’s complement means 1’s complement + 1. 0000
0101---------------------------1’s complement
+1 (in binary addition 1+1 = 10 means 1 as carry and 0 as sum)

0000 0110 ------------- 6


Therefore final result is -6

Note:
(In binary addition 1+1 = 10 means 1 as carry and 0 as sum, 1+0=1, 0+0=0)

Example 2:
Find complement of -5 (~-5)

Step1:
Always negative numbers in the system are represented using 2’s complement form. First take +5
in binary form, find 2’s complement of that number.
0000 0101
1111 1010
+1

1111 1011---------------------5 binary equivalent

Step2:
Perform bits complement (1’s complement) on step1 result. 0000
0100-----------------------4
If the MSB bit of the result contains 0, then the resulting number have the + sign. (~-
5)=+4

Bitwise Shift operators:


The shift operators are used to move bit patterns either to the left or to the right. Left shift:
v << n
Right shift: v >> n

Where v is the integer expression (value) that is to be shifted and n is the number of bit positions
to be shifted.

Left shift:
Left shift means given number multiply by 2 per each shift.
Example:
6<<1 or x=6, x<<1

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

First convert decimal 6 to binary and take 8 bits.


MSB LSB
87654321
0000 0110

00000 110
87654321

Here, 12345678 are bit positions for understanding purpose.


 First move 1stbit as 2ndbit, 2nd bit as 3rdbit, 3rd bit as 4th bit, 4th bit as 5th bit, 5th bit as 6thbit,
6th bit as 7th bit, 7th bit as 8th bit.
 Here, 1st bit is empty, make it as 0. Remove 8th bit because it position exceeds 8 bit
positions.

00001110
87654321

This is the final bit result. Convert binary to decimal and it is equal to decimal 12. 6 << 1 =
12

Special operators:
C supports some special operators of interest such as:
i. Comma operator (,)
ii. sizeof operator
iii. pointer operators (&, *)
iv. member selection operators (., ->)
v. function call symbol ()
vi. array subscript operator []
Comma operator:
 This can be used to link the related expressions together.
 Comma liked lists of expressions are evaluated from left to right. And the value of right
most expression is the value of the combined expression.
 Comma operator has the lowest precedence of all operators, the parenthesis are
necessary.
Example:

value=(x=10, y=5, x+y)


Therefore value=15.

The sizeof operator:


 The sizeof operator is a compile time operator.
 When used with an operand, it returns the number of bytes the operand occupies.
 The operand may be a variable, a constant or a data type qualifier.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 This is normally used to determine the lengths of arrays and structures.

&---------address operator or reference operator, it is unary operator.


* dereference operator or pointer reference or indirection operator.

Expressions:
Arithmetic expressions:
An arithmetic expression is a combination of variables, constants, and operators arranged as per
the syntax of the language.
Examples:
Algebraic expression C expression
a×b–c a*b-c
(m + n)(x + y) (m+n)*(x+y)
ab a*b/c

c
3x2+2x+1 3*x*x+2*x+1
x x/y+c
+c
y
Evaluation of expressions:
Expressions are evaluated using an assignment statement.
Where variable is any valid 'C' variable name.
variable = expression
Example:
a=9, b=12, c=3
x=a–b/3+c*2–1
x = 9 – 12 / 3 + 3 * 2 – 1

Finally x = 10
Type conversion:
char
shortint
int
longint
float
double
long double
Conversion of small data type to big is broadening. Conversion of big data type to small is narrowing.
(small and big in terms of number of bytes)
Conversions are of two types:
1. Implicit type conversion
2. Explicit type conversion
Implicit type conversion:
 Computer considers one operator at a time, involving 2 operands.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 If the operands are of different types, the ‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds.
 The result is of the ‘higher’ type.
 The final result of an expression is converted to the type of the variable on the left of the
assignment sign before assigning the value to it.
 The following rules are followed:
i. float to int causes truncation of the fractional part.
ii. double to float causes rounding of digits.
iii. longint to int causes dropping of the excess higher order bits.

Example:
#include<stdio.h>
main()
{
int a;
floatb,c;
printf("enter a,b values\n");
scanf("%d%f",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output: entera,b
values 4
5
c=0.800000
Explicit type conversion or casting a value:
For example,
#include<stdio.h>
main()
{
int a,b;
float c;
printf("enter a,b values\n");
scanf("%d%d",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output:
entera,b values 4
5
c=0.000000
Consider the statement c=a/b;
 Here a, b are integer data type, so integer division is performed. The result of this division
is 0. So, the decimal part of the division would be lost and the result is not correct.
 This problem can be solved by converting locally one of the variables to the floating point.
c=(float)a/b;
 The operator (float) converts the 'a' to floating point for the purpose of evaluation of
the expression.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 Then automatically conversion is done and then the division is performed in floating point
mode.
 This process of such a local conversion is known as casting a value.
 Form is
(type name) expression

Where type name is one of the valid ‘C’ data types and the expression may be a constant,
variable or an expression.
Usage of type conversion:

Example Action
x = (int) 4.78 4.78 is converted to integer by
truncation and result would be 4
a=(int)13.4/4 Evaluated as 13/4 and the result
would be 3
d=(double)12/5 Division is done in floating point
mode and result would be 2.400000

Operators Precedence and Associativity Table:


Operator Description Associativity Rank
() Function call Left to Right 1
[] Array element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical NOT Right to Left 2
~ Ones complement Pointer
* reference (indirection)
& Address Size
sizeof of an object
(type) Type cast (conversion)

* Multiplication
/ Division Left to Right 3
% Modulo division (modulus)
+ Addition Left to Right 4
- Subtraction
<< Left Shift Left to Right 5
>> Right Shift

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

< Less than


<= Less than or equal to Greater Left to Right 6
> than
>= Greater than or equal to
== Is equal to Left to Right 7
!= Not equal to
& Bitwise AND Left to Right 8
^ Bitwise XOR (Exclusive OR) Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: 13
=
*=, /=, %=
+=, -= Assignment operators Right to Left 14
&=, ^=, |=
<<=, >>=

, Comma operator Left to Right 15

Input/ Output Functions and statements:


C language has a collection of functions that can be used in a program with required number of
arguments written in parantheses. Input /Output functions are also included in the user program by
using the header file <stdio.h> which stands for standard input-output header.
Formatted Input/ Output Functions :
scanf( ) Function:
 scanf() function is used to read/input values of variables using the standared input device
(keyboard).
 It has the following form scanf (“format string”, &v1, &v2, . . . , &vn); where v1, v2, . . . , vn are
variables whose values are to be read from the keyboard.
 “format string” is the control string which represents the format specification.
 The symbol & (ampersand) represents the memory address where the variable value is to be
stored.
 For eg. scanf(“%d%d”, &a, &b); to read value of int variables a and b.
printf( ) Function:
 printf() function is used to print/display values of variables using the standared output
device (monitor).
 It has the following form printf (“format string”, v1, v2, . . . , vn); where v1, v2, . . . , vn are
variables whose values are to be display in the monitor.
 “format string” is the control string which represents the format specification.
 For example : printf(“%d”,a);
FORMAT SPECIFIER:
A format specifier is a special character sequence that begins with a percent sign (%) and indicates how to
write a single data item. The format specifier in printf() determines the interpretation of a variable ‟s type,

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

the width of the field, the number of decimal places printed and the justification. Format specification
determines how the variables to be output should be displaed on the screen, is provided in the control string.
Example Program:
#include <stdio.h>
int main() {
char name[20];
int age;
printf("Enter your name: ");
scanf("%s", name);

printf("Enter your age: ");


scanf("%d", &age);

printf("Your name is %s and your age is %d\n", name, age);

return 0;
}
Output:
Enter your name: Avi
Enter your age: 22
Your name is Avi and your age is 22
Explanation:
We first declare the variables name and age in the above example. After that, the user is prompted for their
name and age using the printf() function. We utilize the scanf() function to read user input and assign it to the
appropriate variables. To format the input, we finally employ the printf() function once more.

Unformatted input/output functions:


Unformatted console input/output functions are used to read a single input from the user at console
and it also allows us to display the value in the output to the user at the console.
Some of the most important formatted console input/output functions are –
1. getch()  function reads a single character from the keyboard by the user but doesn’t
display that character on the console screen and immediately returned without pressing
enter key. This function is declared in conio.h(header file). getch() is also used for hold the
screen.
Syntax: getch();
or
variable-name = getch();
2. getche()  function reads a single character from the keyboard by the user and displays it
on the console screen and immediately returns without pressing the enter key. This function
is declared in conio.h(header file).Reads a single character from the user at the console, and
echoing it.
Syntax:
getche();
or
variable_name = getche();

3. getchar()The getchar() function is used to read only a first single character from the
keyboard whether multiple characters is typed by the user and this function reads one

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

character at one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)
Syntax:
Variable-name = getchar();
4. gets()gets() function reads a group of characters or strings from the keyboard by the user
and these characters get stored in a character array. This function allows us to write space-
separated texts or strings. This function is declared in stdio.h(header file).
Syntax:
char str[length of string in number];
gets(str);
5. puts()I n C programming puts() function is used to display a group of characters or
strings which is already stored in a character array. This function is declared in
stdio.h(header file).
Syntax:
puts(identifier_name );
6. putch() This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name); .
7.putchar()  It is used to display one character at a time on the monitor.

Syntax: putchar (ch);

DECISION MAKING STATEMENTS IN C:


 The conditional statements (also known as decision control structures) such as if, if else,
switch, etc. are used for decision making purpose in 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.

TYPES OF DECISION MAKING STATEMENTS:

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Following are the decision-making statements available in C:


1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
IF STATEMENT:
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:

// 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
As the condition present in the if statement is false. So, the block
below the if statement is not executed.
2. if-else in 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.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 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
// condition is false
}

Example Program:
#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;
}

OUTPUT: i is greater than 15


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, C allow us to nested if statements within if
statements, i.e, we can place an if statement inside another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition2)

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}
Flowchart of Nested if-else Example of Nested if-else:
#include <stdio.h>
void main()
{
int i = 10;
if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");

}
}
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 Flowchart of if-else-if Ladder

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example Program:

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

#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 Flowchart of switch
switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}
EXAMPLE PROGRAM:
#include <stdio.h>
void main()
{ int var = 2;
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;
}
}
Output:

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Case 2 is executed
JUMP STATEMENTS IN C:
These statements are used in C for the unconditional flow of control throughout the functions in a program.
They support four types of jump statements:
 break
 continue
 goto
 return
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.
Syntax of continue
continue;
C) goto
The goto statement in C also referred to as the unconditional jump statement can be used to jump from one
point to another within a function.
D) return
The return in 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.

LOOP STATEMENTS IN C:
Loops in programming are used to repeat a block of code until the specified condition is met. A loop
statement allows programmers to execute a statement or group of statements multiple times without
repetition of code.
There are mainly two types of loops in C Programming:
 Entry Controlled loops: In Entry controlled loops the test condition is checked before entering the
main body of the loop. For Loop and While Loop is Entry-controlled loops.
 Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the loop
body. The loop body will execute at least once, irrespective of whether the condition is true or false.
do-while Loop is Exit Controlled loop.
for Loop:
for loop in C programming is a repetition control structure that allows programmers to write a loop that will
be executed a specific number of times. for loop enables programmers to perform n number of steps together
in a single line.
Syntax:
for (initialize expression; test expression; update expression)

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

{
//
// body of for loop
//
}
Example:
for(int i = 0; i < n; ++i)
{
printf("Body of for loop which will execute till n");
}
FLOW CHART: EXAMPLE
PROGRAM:

#include <stdio.h>
void main()
{
int i = 0;
for (i = 1; i <= 5; i++)
{
printf( "Hello World\n");
}
}
OUTPUT:
Hello World
Hello World
Hello World
Hello World
Hello World

While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations was
previously known to us but in the While loop, the execution is terminated on the basis of the test condition. If
the test condition will become false then it will break from the while loop else body will be executed.
Syntax:
initialization_expression;
while (test_expression)
{
// body of the while loop
update_expression;

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

FLOWCHART: EXAMPLE
PROGRAM:
#include <stdio.h>
void main()
{
int i = 2;
while(i < 5)
{
printf( "Hello World\n");
i++;
}
}
OUTPUT: Hello World
Hello World
Hello World

do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition
which is tested at the end of the body. In the do-while loop, the loop body will execute at least once
irrespective of the test condition.
Syntax:
initialization_expression;
do
{
// body of do-while loop
update_expression;

} while (test_expression);
Example Program:
#include <stdio.h>
int main()
{
int i = 2;
do
{
printf( "Hello World\n");
i++;
} while (i < 1);
}
Output:
Hello World
Above program will evaluate (i<1) as false since i = 2. But still, as it is a do-while loop the body will be
executed once..
PREPROCESSOR DIRECTIVES IN C :

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Preprocessors are programs that process the source code before compilation. Several steps are involved
between writing a program and executing a program in C. Let us have a look at these steps before we actually
start learning about Preprocessors.
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. We can place
these preprocessor directives anywhere in our program.
Types of C Preprocessors
There are 4 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
Let us now learn about each of these directives in detail.

1. Macros
In C, 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.
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program. The
#include preprocessor directive is used to include the header files in the C program.

There are two types of files that can be included by the user in the program:
Standard Header Files
The standard header 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 header file to be included. The ‘<‘ and ‘>’ brackets tell the compiler to look
for the file in the standard directory.
User-defined Header 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 header files.
Syntax
#include "filename"
3. Conditional Compilation
Conditional Compilation in C directives is 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. There are
the following preprocessor directives that are used to insert conditional code:

 #if Directive
 #ifdef Directive
 #ifndef Directive
 #else Directive
 #elif Directive

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 #endif Directive
4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These are:

#undef Directive
#pragma Directive
1. #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.
2. #pragma Directive
This directive is a special purpose directive and is used to turn on or off some features. These types of
directives are compiler-specific, i.e., they vary from compiler to compiler.
Syntax
#pragma directive
COMPILATION PROCESS:
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:

o Preprocessor
o Compiler
o Assembler
o Linker

Preprocessor

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

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'.
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;
}

In the above flow diagram, the following steps are taken to execute a program:

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

o 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.
o 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.
o This assembly code is then sent to the assembler, which converts the
assembly code into object code.
o After the creation of an object code, the linker creates the executable file.
The loader will then load the executable file for the execution.

STORAGE CLASSES IN C:
In the C programming language, storage classes define the scope, visibility, and
lifetime of variables. There are four primary storage classes in C:
1.Automatic Storage Class (auto):
 Variables declared inside a function without any storage class specifier are
by default of auto storage class.
 They are created when the function is called and destroyed when the
function exits.
 Their scope is limited to the block in which they are defined.
2. Static Storage Class (static):
 Variables declared with the static keyword inside a function retain their
value between function calls.
 They are initialized only once at the beginning of the program execution and
retain their value until the program terminates.
 Their scope is limited to the block in which they are defined, but they have
file scope if declared outside any function.
3.Register Storage Class (register):
 Variables declared with the register keyword are stored in CPU registers instead of RAM,
allowing faster access.
 The compiler decides whether to store the variable in a register based on factors such as
availability and usage pattern.
 Their scope is limited to the block in which they are defined.
4.External Storage Class (extern):
 Variables declared with the extern keyword have global visibility across multiple files.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

 They are defined outside of any function or block and can be accessed by any function within
the same program or in other files if properly declared.
 They are not allocated storage space when declared with extern, but rather refer to the
memory space allocated for the variable elsewhere in the program.
 Additionally, there is a fifth storage class in C, known as Thread Storage Class (thread_local),
which specifies that the declared variable has a separate instance for each thread. It was
introduced in C11 to support multithreading environments.

Downloaded by Kanimozhi .D ([email protected])


lOMoARcPSD|41379181

Unit 1 – important programs


Part A
1. What are the various types of operators?
2. Write a for loop to print from 10 to 1?
3. Write any two preprocessor directives in C?
4. List different datatypes available in C?
5. Write a C program to find factorial of a given number using Iteration?
6. What is the use of preprocessor directive?
7. What is the variable? Illustrate with an example?
8. Define static storage class?
9. What is the importance of keywords in C?
10.List out various Input & output statements in c?
Part-B
1. Explain the storage classes in c with example programs?
2. Explain the decision making statement in c with example programs?
3. Explain the looping statement in c with example programs?
4. classified into following types of C operators?
5. Explain the table will show you various directives that we have studied in this
chapter?
6. Write Some of the predefined macros which are readily available?
7. What are the preprocessor directives are divided into four different categories?
8. Explain about the details in preprocessor directive?
9. Write a note on (i) Conditional operator (ii) Assignment Operators (iii) Bitwise
operators?
10.Explain about the Logical operators and relational operators?
11.Illustrate about the various data types in ‘C’ and write a C program to find the sum
of 10 non-negative numbers entered by the user?
12.Explain the purpose of decision making and looping statement Explain in detail the
operation of various looping statements in C with suitable examples?
13.Write short notes on the following (i). ‘for’ loop (ii). ‘while’ loop (iii). ‘do...while’ loop?
14.Illustrate a program for adding two numbers with the help of flowchart?
15.Write a C program to generate Armstrong number between 100 and 999?

Downloaded by Kanimozhi .D ([email protected])

You might also like