0% found this document useful (0 votes)
8 views62 pages

Unit 2

C is a procedural programming language developed by Dennis Ritchie in 1972, primarily for system programming and writing the UNIX operating system. Key features include its efficiency, modularity, portability, and a rich set of built-in operators and libraries. The document also outlines the structure of a C program, the compilation process, and the various types of tokens used in C programming.

Uploaded by

saniyaammm
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)
8 views62 pages

Unit 2

C is a procedural programming language developed by Dennis Ritchie in 1972, primarily for system programming and writing the UNIX operating system. Key features include its efficiency, modularity, portability, and a rich set of built-in operators and libraries. The document also outlines the structure of a C program, the compilation process, and the various types of tokens used in C programming.

Uploaded by

saniyaammm
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

UNIT-2

CHAPTER -1: INTRODUCTION TO C

C Language Introduction

C is a procedural programming language initially developed by Dennis Ritchie in
the year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a
system programming language to write the UNIX operating system.

What are the Most Important Features of C Language?


Here are some of the most important features of the C language:
1. Procedural Language
2. Fast and Efficient
3. Modularity
4. Statically Type
5. General-Purpose Language
6. Rich set of built-in Operators
7. Libraries with Rich Functions
8. Middle-Level Language
9. Portability
10. Easy to Extend
1. Procedural Language

 In a procedural language like C step by step, predefined instructions are


carried out.
 C program may contain more than one function to perform a particular task.
New people to programming will think that this is the only way a particular
programming language works.
 There are other programming paradigms as well in the programming world.
Most of the commonly used paradigm is an object-oriented programming
language.

2. Fast and Efficient

 Newer languages like Java, python offer more features than c programming
language but due to additional processing in these languages, their
performance rate gets down effectively.
 C programming language as the middle-level language provides
programmers access to direct manipulation with the computer hardware but
higher-level languages do not allow this.
 That’s one of the reasons C language is considered the first choice to start
learning programming languages. It’s fast because statically typed languages
are faster than dynamically typed languages.

3. Modularity

 The concept of storing C programming language code in the form of libraries


for further future uses is known as modularity.
 This programming language can do very little on its own most of its power is
held by its libraries. C language has its own library to solve common
problems.

4. Statically Type

 C programming language is a statically typed language.


 Meaning the type of variable is checked at the time of compilation but not at
run time. This means each time a programmer types a program they have to
mention the type of variables used.

5. General-Purpose Language

 From system programming to photo editing software, the C programming


language is used in various applications.
 Some of the common applications where it’s used are as follows:
 Operating systems: Windows, Linux, iOS, Android, OXS
 Databases: PostgreSQL, Oracle, MySQL, MS SQL Server, etc.

6. Rich set of built-in Operators

 It is a diversified language with a rich set of built-in operators which are


used in writing complex or simplified C programs.

7. Libraries with Rich Functions

 Robust libraries and functions in C help even a beginner coder to code with
ease.

8. Middle-Level Language

 As it is a middle-level language so it has the combined form of both


capabilities of assembly language and features of the high-level language.

9. Portability

 C language is lavishly portable as programs that are written in C language


can run and compile on any system with either no or small changes.

10. Easy to Extend

 Programs written in C language can be extended means when a program is


already written in it then some more features and operations can be added to
it.
Structure of the C Program

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.
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<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.142

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

 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;
}

Creating and Executing a C Program



 Whenever a C program file is compiled and executed, the compiler
generates some files with the same name as that of the C program file but
with different extensions.
 So, what are these files and how are they created?
Below image shows the compilation process with the files created at each step of
the compilation process:

 Every file that contains a C program must be saved with ‘.c’ extension.
 This is necessary for the compiler to understand that this is a C program file.
Suppose a program file is named, first.c. The file first.c is called the source
file which keeps the code of the program.
 Now, when we compile the file, the C compiler looks for errors. If the C
compiler reports no error, then it stores the file as a .obj file of the same name,
called the object file. So, here it will create the [Link]. This .obj file is not
executable.
 The process is continued by the Linker which finally gives a .exe file which is
executable.
Linker:
 First of all, let us know that library functions are not a part of any C program
but of the C software.
 Thus, the compiler doesn’t know the operation of any function, whether it be
printf or scanf.
 The definitions of these functions are stored in their respective library which
the compiler should be able to link.
 This is what the Linker does. So, when we write #include, it includes stdio.h
library which gives access to Standard Input and Output. The linker links the
object files to the library functions and the program becomes a .exe file. Here,
[Link] will be created which is in an executable format.

Loader:
 Whenever we give the command to execute a particular program, the loader
comes into work.
 The loader will load the .exe file in RAM and inform the CPU with the
starting point of the address where this program is loaded.

CPU Registers

Instruction Register: It holds the current instructions to be executed by the CPU.


Program Counter: It contains the address of the next instructions to be executed
by the CPU.
Accumulator: It stores the information related to calculations.
The loader informs Program Counter about the first instruction and initiates the
execution. Then onwards, Program Counter handles the task.

Block diagram of execution of C program


Tokens in C

Definition:
A token in C can be defined as the smallest individual element of the C
programming language that is meaningful to the compiler. It is the basic component
of a C program.

Types of Tokens in C
The tokens of C language can be classified into six types based on the functions
they are used to perform. The types of C tokens are as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. Keywords
Definition:
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program.

 Since keywords are referred names for a compiler, they can’t be used as
variable names because by doing so, we are trying to assign a new meaning to
the keyword which is not allowed.
 You cannot redefine keywords. However, you can specify the text to be
substituted for keywords before compilation by using C preprocessor
directives. C language supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Note: The number of keywords may change depending on the version of C you are
using. For example, keywords present in ANSI C are 32 while in C11, it was
increased to 44. Moreover, in the latest c23, it is increased to around 54.

[Link]

Definition:
Identifiers are used as the general terminology for the naming of variables,
functions, and arrays.
 These are user-defined names consisting of an arbitrarily long sequence of
letters and digits with either a letter or the underscore(_) as a first character.
 Identifier names must differ in spelling and case from any keywords.
 You cannot use keywords as identifiers; they are reserved for special use.
 Once declared, you can use the identifier in later program statements to refer
to the associated value.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special
character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are
significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be
treated as different.
For example,
 main: method name.
 a: variable name.

3. Constants
Definition:
The constants refer to the variables with fixed values. They are like normal
variables but with the difference that their values cannot be modified in the
program once they are defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
float x=567;

4. Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in
double quotes. Whereas, a character is enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;

5. Special Symbols
The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose. Some of these are listed below:
 Brackets[]: Opening and closing brackets are used as array element references.
These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and
function parameters.
 Braces{}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
 Comma (, ): It is used to separate more than one statement like for separating
parameters in function calls.
 Colon(:): It is an operator that essentially invokes something called an
initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end of one
logical entity. That’s why each individual statement must be ended with a
semicolon.
 Asterisk (*): It is used to create a pointer variable and for the multiplication of
variables.
 Assignment operator(=): It is used to assign values and for logical operation
validation.
 Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
 Period (.): Used to access members of a structure or union.
 Tilde(~): Bitwise One’s Complement Operator.

[Link]:
Definition:
Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can
be classified as follows:
 Unary Operators: Those operators that require only a single operand to act
upon are known as unary operators.
For Example increment and decrement operators
 Binary Operators: Those operators that require two operands to act upon are
called binary operators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator

1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations
on operands. There are 9 arithmetic operators in C language:
Operator Description
S. No. Symbol Syntax

Adds two numeric


+ Plus values. a+b
1

Subtracts right
– Minus operand from left a–b
operand.
2

Multiply two
* Multiply numeric values. a*b
3

/ Divide Divide two a/b


4
Operator Description
S. No. Symbol Syntax

numeric values.

Returns the
remainder after
% Modulus diving the left a%b
operand with the
right operand.
5

Used to specify
+ Unary Plus the positive +a
values.
6

Flips the sign of


– Unary Minus the value. -a
7

Increases the
++ Increment value of the a++
operand by 1.
8

Decreases the
— Decrement value of the a–
operand by 1.
9
Example of C Arithmetic Operators
C
// C program to illustrate the arithmatic operators
#include <stdio.h>
#include<conio.h>
void main()
{

int a = 25, b = 5;
clrscr();

// using operators and printing results


printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
printf("+a = %d\n", +a);
printf("-a = %d\n", -a);
printf("a++ = %d\n", a++);
printf("a-- = %d\n", a--);

getch0;
}

Output
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26

2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All
these operators are binary operators that return true or false values as the result of
comparison.
These are a total of 6 relational operators in C:
Operator Description
S. No. Symbol Syntax
Operator Description
S. No. Symbol Syntax

Returns true if
the left
operand is less
< Less than a<b
than the right
operand. Else
false
1

Returns true if
the left
operand is
> Greater than greater than a>b
the right
operand. Else
false
2

Returns true if
the left
operand is less
Less than or
<= than or equal a <= b
equal to
to the right
operand. Else
false
3

Returns true if
the left
operand is
Greater than
>= greater than or a >= b
or equal to
equal to right
operand. Else
false
4
Operator Description
S. No. Symbol Syntax

Returns true if
both the
== Equal to a == b
operands are
equal.
5

Returns true if
both the
!= Not equal to a != b
operands are
NOT equal.
6
Example of C Relational Operators
C
// C program to illustrate the relational operators
#include <stdio.h>
#include<conio.h>
void main()
{

int a = 25, b = 5;
clrscr();
// using operators and printing results
printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);

getch();
}

Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1

Here, 0 means false and 1 means true.

3. Logical Operator in C
Logical Operators are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition in consideration. The result of
the operation of a logical operator is a Boolean value either true or false.
Operator Description
S. No. Symbol Syntax

Returns true if
both the
&& Logical AND a && b
operands are
true.
1

Returns true if
both or any of
|| Logical OR a || b
the operand is
true.
2

Returns true if
! Logical NOT the operand is !a
false.
3
Example of Logical Operators in C
C
// C program to illustrate the logical operators
#include <stdio.h>
#include<conio.h>
void main()
{
int a = 25, b = 5;
clrscr();
// using operators and printing results
printf("a && b : %d\n", a && b);
printf("a || b : %d\n", a || b);
printf("!a: %d\n", !a);

getch();
}

Output
a && b : 1
a || b : 1
!a: 0

4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is performed
on the operands. Mathematical operations such as addition, subtraction,
multiplication, etc. can be performed at the bit level for faster processing.
There are 6 bitwise operators in C:
Operator Description
S. No. Symbol Syntax

Performs bit-
by-bit AND
& Bitwise AND operation and a&b
returns the
result.
1

Performs bit-
by-bit OR
| Bitwise OR operation and a|b
returns the
result.
2
Operator Description
S. No. Symbol Syntax

Performs bit-
by-bit XOR
^ Bitwise XOR operation and a^b
returns the
result.
3

Flips all the


Bitwise First set and unset
~ ~a
Complement bits on the
number.
4

Shifts the
number in
binary form
Bitwise by one place
<< a << b
Leftshift in the
operation and
returns the
result.
5

Shifts the
number in
binary form
Bitwise by one place
>> a >> b
Rightshilft in the
operation and
returns the
result.
6
Example of Bitwise Operators
C
// C program to illustrate the bitwise operators
#include <stdio.h>

void main()
{

int a = 25, b = 5,c=10;


clrscr();
// using operators and printing results
printf("a & b: %d\n", a & b);
printf("a | b: %d\n", a | b);
printf("a ^ b: %d\n", a ^ b);
printf("~a: %d\n", ~a);
printf("c >> 2: %d\n", c >> 2);
printf("c << 2: %d\n", c << 2);

getch();
}

Output
a & b: 1
a | b: 29
a ^ b: 28
~a: -26
c >> : 2
c << b: 40

5. Assignment Operators in C
Assignment operators are used to assign value to a variable.
 The left side operand of the assignment operator is a variable and the right
side operand of the assignment operator is a value.
 The value on the right side must be of the same data type as the variable on
the left side otherwise the compiler will raise an error.
 The assignment operators can be combined with some other operators in C to
provide multiple operations using single operator. These operators are called
compound operators.
In C, there are 11 assignment operators :
Operator Description
S. No. Symbol Syntax

Assign the
value of the
Simple
= right operand a=b
Assignment
to the left
operand.
1

Add the right


operand and
Plus and left operand
+= assign and assign this a += b
value to the
left operand.
2

Subtract the
right operand
and left
Minus and
-= operand and a -= b
assign
assign this
value to the
left operand.
3

Multiply the
right operand
and left
Multiply and
*= operand and a *= b
assign
assign this
value to the
left operand.
4

Divide and Divide the left


/= assign a /= b
5 operand with
Operator Description
S. No. Symbol Syntax

the right
operand and
assign this
value to the
left operand.

Assign the
remainder in
the division of
Modulus and
%= left operand a %= b
assign
with the right
operand to the
left operand.
6

Performs
bitwise AND
AND and and assigns
&= assign this value to a &= b
the left
operand.
7

Performs
bitwise OR
OR and and assigns
|= assign this value to a |= b
the left
operand.
8

XOR and Performs


^= assign bitwise XOR a ^= b
9 and assigns
Operator Description
S. No. Symbol Syntax

this value to
the left
operand.

Example of C Assignment Operators


C
// C program to illustrate the assignment operators
#include <stdio.h>
#include<conio.h>
void main()
{
int a = 25, b = 5;
clrscr();
// using operators and printing results
printf("a = b: %d\n", a = b);
printf("a += b: %d\n", a += b);
printf("a -= b: %d\n", a -= b);
printf("a *= b: %d\n", a *= b);
printf("a /= b: %d\n", a /= b);
printf("a %= b: %d\n", a %= b);
printf("a &= b: %d\n", a &= b);
printf("a |= b: %d\n", a |= b);

getch();
}

Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5

6. Other Operators
Apart from the above operators, there are some other operators available in C used
to perform some specific tasks. Some of them are discussed here:

i. sizeof Operator
 sizeof is much used in the C programming language.
 It is a compile-time unary operator which can be used to compute the size of its
operand.
 The result of sizeof is of the unsigned integral type which is usually denoted by
size_t.
 Basically, the sizeof the operator is used to compute the size of the variable or
datatype.
Syntax
sizeof (operand)

ii. Comma Operator ( , )


 The comma operator (represented by the token) is a binary operator that
evaluates its first operand and discards the result, it then evaluates the second
operand and returns this value (and type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.
Syntax
operand1 , operand2

iii. Conditional Operator ( ? : )


 The conditional operator is the only ternary operator in C++.
 Here, Expression1 is the condition to be evaluated. If the
condition(Expression1) is True then we will execute and return the result of
Expression2 otherwise if the condition(Expression1) is false then we will
execute and return the result of Expression3.
 We may replace the use of if..else statements with conditional operators.
Syntax
operand1 ? operand2 : operand3;
 Ternary Operator: The operator that requires three operands to act upon is
called the ternary operator. Conditional Operator(?) is also called the ternary
operator.

7. Variables

Definition:
A variable in C language is the name associated with some memory location
to store data of different types.
 There are many types of variables in C depending on the scope, storage class,
lifetime, type of data they store, etc.
 A variable is the basic building block of a C program that can be used in
expressions as a substitute in place of the value it stores.

Syntax
The syntax to declare a variable in C specifies the name and the type of the
variable.
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable
Here,
 data_type: Type of data that a variable can store.
 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.
Example
int var; // integer variable
char a; // character variable
float fff; // float variables
Note: C is a strongly typed language so all the variables types must be specified
before using them.

There are 3 aspects of defining a variable:


1. Variable Declaration
2. Variable Definition
3. Variable Initialization\

1. Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with
the given name and data [Link] the variable is declared, an entry in symbol
table is created and memory will be allocated at the time of initialization of the
variable.

2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some
value to it. A defined variable will contain some random garbage value till it is not
initialized.
Example
int var;
char var2;
Note: Most of the modern C compilers declare and define the variable in single
step. Although we can declare a variable in C by using extern keyword, it is not
required in most of the cases. To know more about variable declaration and
definition, click here.

3. Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful
value to the variable when creating the variable.
Example
int var = 10; // variable declaration and definition (i.e. Vairable Initialization)

Rules for Naming Variables in C


You can assign any name to the variable as long as it follows the following
rules:
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot
start with a digit.
3. No white space is allowed within the variable name.
4. A variable name must not be any reserved word or keyword.
// C program to demonstrate the declaration, definition and initialization of
variable.
#include <stdio.h>
#include<conio.h>
void main()
{
// declaration with definition
int defined_var;
clrscr();

printf("Defined_var: %d\n", defined_var);

// assignment
defined_var = 12;

// declaration + definition + initialization


int ini_var = 25;

printf("Value of defined_var after assignment: %d\n", defined_var);


printf("Value of ini_var: %d", ini_var);

getch();
}

Output
Defined_var: 0
Value of defined_var after assignment: 12
Value of ini_var: 25
Variable Types
The C variables can be classified into the following types:
1. Local Variables
2. Global Variables

1. Local Variables in C:
 A Local variable in C is a variable that is declared inside a function or a
block of code.
 Its scope is limited to the block or function in which it is declared.
Example of Local Variable in C
C
// C program to declare and print local variable inside a function.
#include <stdio.h>
#include<conio.h>
void demo()
{
int x = 10; // local variable
printf("%d", x);
}

void main()
{
demo();
getch();
}

Output
10
In the above code, x can be used only in the scope of function(). Using it in the
main function will give an error.

2. Global Variables in C
 A Global variable in C is a variable that is declared outside the function or a
block of code.
 Its scope is the whole program i.e. we can access the global variable anywhere
in the C program after it is declared.
Example of Global Variable in C
C
// C program to demonstrate use of global variable
#include <stdio.h>
#include<conio.h>
int x = 20; // global variable

void function1()
{
printf("Function 1: %d\n", x);
}
void function2()
{
printf("Function 2: %d\n", x);
}

void main()
{
clrscr();
function1();
function2();
getch();
}

Output
Function 1: 20
Function 2: 20

Data Types in C
A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.

There are the following data types in C language.

Types Data Types


Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types


 The basic data types are integer-based and floating-point based. C language
supports both signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit
operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767


unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

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

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte -3.4*10^38 to +3.4*10^38 or


1.2E-38 to 3.4E+38

double 8 byte 1.7E-308 to 1.7E+308

long double 10 byte 3.4E-4932 to 1.1E+4932

Int:

 Integers are entire numbers without any fractional or decimal parts, and
the int data type is used to represent them.
 It is frequently applied to variables that include values, such as counts,
indices, or other numerical numbers.
 The int data type may represent both positive and negative numbers because
it is signed by default.
 An int takes up 4 bytes of memory on most devices, allowing it to store values
between around -2 billion and +2 billion.

Char:

 Individual characters are represented by the char data type.


 Typically used to hold ASCII or UTF-8 encoding scheme characters, such
as letters, numbers, symbols, or commas.
 There are 256 characters that can be represented by a single char, which takes
up one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in
single quotes.

Float:
 To represent integers, use the floating data type.
 Floating numbers can be used to represent fractional units or numbers with
decimal places.
 The float type is usually used for variables that require very good precision
but may not be very precise.
 It can store values with an accuracy of about 6 decimal places and a range of
about 3.4 x 1038 in 4 bytes of memory.

Double:

 Use two data types to represent two floating integers. When additional
precision is needed, such as in scientific calculations or financial applications,
it provides greater accuracy compared to float.
 Double type, which uses 8 bytes of memory and has an accuracy of about 15
decimal places, yields larger values. C treats floating point numbers as
doubles by default if no explicit type is supplied.

int age = 25;


char grade = 'A';
float temperature = 98.6;
double pi = 3.14159265359;

In the example above, we declare four variables: an int variable for the person's
age, a char variable for the student's grade, a float variable for the temperature
reading, and two variables for the number pi.

Derived Data Type

Beyond the fundamental data types, C also supports derived data


types, including arrays, pointers, structures, and unions. These data types give
programmers the ability to handle heterogeneous data, directly modify memory,
and build complicated data structures.

Array:
Definition:

An array is a collection of homogeneous elements.


 An array, a derived data type, lets you store a sequence of fixed-size
elements of the same type. It provides a mechanism for joining multiple
targets of the same data under the same name.
 The index is used to access the elements of the array, with a 0 index for the
first entry.
 The size of the array is fixed at declaration time and cannot be changed during
program execution. The array components are placed in adjacent memory
regions.

Syntax:

Data_type var[size];

Here is an example of declaring and utilizing an array:

#include <stdio.h>
#include<conio.h>
void main()
{
int numbers[5]; // Declares an integer array with a size of 5 elements

// Assign values to the array elements


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Display the values stored in the array


printf("Values in the array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

getch();
}
Output:
Values in the array: 10 20 30 40 50
Pointer:

 A pointer is a derived data type that keeps track of another data type's
memory address.
 When a pointer is declared, the data type it refers to is stated first, and then
the variable name is preceded by an asterisk (*).

Syntax:
Data_type *ptr_var;
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,*ptr;
a=20;
clrscr();
ptr=&a;
printf(“Values of ptr=%d\n”,*ptr);
getch();
}

Structure:
A structure is a derived data type that enables the creation of composite data types
by allowing the grouping of many data types under a single name. It gives you the
ability to create your own unique data structures by fusing together variables of
various sorts.

1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
3. A structure's members can be accessed by using the dot (.) operator.\
Syntax:

struct Structure_name

Data_type var1,var2;

}structure_variable;

Example:
#include<stdio.h>
#include<conio.h>
struct add
{
int a,b;
}s;
void main()
{
int sum;
s.a=10;
s.b=20;
clrscr();
sum=s.a+s.b;
printf("Addition of two number=%d\n",sum);
getch();
}

Union:
 A derived data type called a union enables you to store various data types in
the same memory address.
 In contrast to structures, where each member has a separate memory space,
members of a union all share a single memory space.
 A value can only be held by one member of a union at any given moment.
When you need to represent many data types interchangeably, unions come in
handy.
 Like structures, you can access the members of a union by using the dot
(.) operator.
Syntax:

union Union_name

Data_type var1,var2…..varn;

}union_variable;

Example:
#include<stdio.h>
#include<conio.h>
unio add
{
int a,b;
}u;
void main()
{
int sum;
u.a=10;
u.b=20;
clrscr();
sum=u.a+u.b;
printf("Addition of two number=%d\n",sum);
getch();
}

Enumeration Data Type


 A set of named constants or enumerators that represent a collection of
connected values can be defined in C using the enumeration data type
(enum).
 Enumerations give you the means to give names that make sense to a group
of integral values, which makes your code easier to read and maintain.
Syntax:

enum Enum_name

Values;

};
Here is an example of how to define and use an enumeration in C:

#include <stdio.h>
#include<conio.h>
// Define an enumeration for days of the week
enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};

void main()
{
// Declare a variable of type enum DaysOfWeek
enum DaysOfWeek today;

// Assign a value from the enumeration


today = Wednesday;

// Accessing the enumeration value


printf("Today is %d\n", today);

getch();
}

Output:
Today is 2
void Data Type:

 The void data type in the C language is used to denote the lack of a particular
type.
 Function return types, function parameters, and pointers are three situations
where it is frequently utilized.

Function Return Type:

A void return type function does not produce a value.

A void function executes a task or action and ends rather than returning a value.

void printHello() { printf("Hello, world!\n"); }


Function Parameters:

The parameter void can be used to indicate that a function accepts no arguments.

Example:

void processInput(void) { /* Function logic */ }

Defining Constant using #define Preprocessor /Symbolic constant:


We can also define a constant in C using #define preprocessor. The constants
defined using #define are macros that behave like a constant. These constants are
not handled by the compiler, they are handled by the preprocessor and are
replaced by their value before compilation.

Syntax:
#define const_name value

Example:
// C Program to define a constant using #define
#include <stdio.h>
#define pi 3.142

void main()
{

printf("The value of pi: %.2f", pi);


getch();
}
Output
The value of pi: 3.14

Formatted I/O Functions:

 Formatted I/O functions are used to take various inputs from the user and
display multiple outputs to the user.
 These types of I/O functions can help to display the output to the user in
different formats using the format specifiers.
 These I/O supports all data types like int, float, char, and many more.

Why they are called formatted I/O?


These functions are called formatted I/O functions because we can use format
specifiers in these functions and hence, we can format these functions according to
our needs.
List of some format specifiers-
S Format
Type Description
NO. Specifier

int/signed
1 %d used for I/O signed integer value
int

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

Used for I/O string/group of


4 %s string
characters

5 %ld long int Used for I/O long signed integer value
unsigned
6 %u Used for I/O unsigned integer value
int

7 %i signed int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

The following formatted I/O functions will be discussed in this section-


1. printf()
2. scanf()

1. printf():
printf() function is used in a C program to display any value like float, integer,
character, string, etc on the console screen. It is a pre-defined function that is
already declared in the stdio.h(header file).

Syntax 1:
printf(“Format Specifier”, var1, var2, …., varn);
Example:
// C program to implement printf() function

#include <stdio.h>

#include<conio.h>

void main()

// Declaring an int type variable

int a;

// Assigning a value in a variable

a = 20;

// Printing the value of a variable

printf("%d", a);

getch();

Output
20

2. scanf():
 scanf() function is used in the C program for reading or taking any value
from the keyboard by the user, these values can be of any data type like
integer, float, character, string, and many more.
 This function is declared in stdio.h(header file), that’s why it is also a pre-
defined function.
 In scanf() function we use &(address-of operator) which is used to store the
variable value on the memory location of that variable.
Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);
Example:

// C program to implement scanf() function

#include <stdio.h>

#include<conio.h>

void main()

int num1;

// Printing a message on the output screen

printf("Enter a integer number: ");

// Taking an integer value from keyboard

scanf("%d", &num1);

// Displaying the entered value

printf("You have entered %d", num1);

getch();

Output
Enter a integer number: You have entered 0
Output:
Enter a integer number: 56
You have entered 56

Unformatted Input/Output functions


 Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype.
 These functions are used to read single input from the user at the console and
it allows to display the value at the console.
Why they are called unformatted I/O?
These functions are called unformatted I/O functions because we cannot use
format specifiers in these functions and hence, cannot format these functions
according to our needs.
The following unformatted I/O functions will be discussed in this section-
1. getch()
2. getchar()
3. putchar()
4. gets()
5. puts()

1. getch():
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
Example:
 C

// C program to implement getch() function

#include <conio.h>

#include <stdio.h>
void main()

printf("Enter any character: ");

// Reads a character but not displays

getch();

Output:
Enter any character:

2. 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 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();
Example:
 C

// C program to implement the getchar() function

#include <conio.h>

#include <stdio.h>

void main()

{
// Declaring a char type variable

char ch;

clrscr();

printf("Enter the character: ");

// Taking a character from keyboard

ch = getchar();

// Displays the value of ch

printf("%c", ch);

getch();

Output:
Enter the character: a
a
3. putchar():
The putchar() function is used to display a single character at a time by passing
that character directly to it or by passing a variable that has already stored a
character. This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example:
 C

// C program to implement the putchar() function

#include <conio.h>
#include <stdio.h>

void main()

char ch;

printf("Enter any character: ");

// Reads a character

ch = getchar();

// Displays that character

putchar(ch);

getch();

Output:
Enter any character: Z
Z
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]; //Declare a char type variable of any
length
gets(str);
Example:
// C program to implement the gets() function

#include <conio.h>

#include <stdio.h>

void main()

// Declaring a char type array of length 50 characters

char name[50];

printf("Please enter some texts: ");

// Reading a line of character or a string

gets(name);

// Displaying this line of character or a string

printf("You have entered: %s",name);

getch();

Output:
Please enter some texts: Welcome to the class
You have entered: Welcome to the class
5. puts():
 In 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 );
Example:

// C program to implement the puts() function

#include <stdio.h>

#include<conio.h>

void main()

char name[50];

printf("Enter your text: ");

// Reads string from user

gets(name);

printf("Your text is: ");

// Displays string

puts(name);

getch();

Output:
Enter your text: Welcome to the class
Your text is: Welcome to the class

Escape Sequence in C

 The escape sequence in C is the characters or the sequence of characters
that can be used inside the string literal.
 The purpose of the escape sequence is to represent the characters that
cannot be used normally using the keyboard. Some escape sequence
characters are the part of ASCII charset but some are not.
Different escape sequences represent different characters but the output is
dependent on the compiler you are using.
Escape Sequence List
The table below lists some common escape sequences in C language.
Escape
Sequence Name Description

It is used to generate a bell sound in the C


\a Alarm or Beep
program.

It is used to move the cursor one place


\b Backspace
backward.

It is used to move the cursor to the start of the


\f Form Feed
next logical page.

\n New Line It moves the cursor to the start of the next line.

It moves the cursor to the start of the current


\r Carriage Return
line.

It inserts some whitespace to the left of the


\t Horizontal Tab
cursor and moves the cursor accordingly.

\v Vertical Tab It is used to insert vertical space.

\\ Backlash Use to insert backslash character.


Escape
Sequence Name Description

\’ Single Quote It is used to display a single quotation mark.

\” Double Quote It is used to display double quotation marks.

\? Question Mark It is used to display a question mark.

\ooo Octal Number It is used to represent an octal number.

Hexadecimal
\xhh It represents the hexadecimal number.
Number

\0 NULL It represents the NULL character.

\e Escape sequence It represents the ASCII escape character.

\s Space Character It represents the ASCII space character.

\d Delete Character It represents the ASCII DEL character.

Out of all these escape sequences, \n and \0 are used the most. In fact, escape
sequences like \f, \a, are not even used by programmers nowadays.
Escape Sequence in C Examples
The following are the escape sequence examples that demonstrate how to use
different escape sequences in C language.
1. Example to demonstrate how to use \a escape sequence in C
// C program to illustrate \a escape sequence
#include <stdio.h>

void main()
{
clrscr();
// output may depend upon the compiler
printf("My mobile number "
"is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");
getch();
}

Output
My mobile number is 7873923408
2. Example to demonstrate how to use \b escape sequence in C
C
// C program to illustrate \b escape sequence
#include <stdio.h>
#include<conio.h>

void main()
{
clrscr();
// \b - backspace character transfers the cursor one character back with or
without //deleting on different compilers.
printf("Hello \b\b\b\b\b\bHi Hello");
getch();
}

Output
Hello Hi Hello
3. Example to demonstrate how to use \n escape sequence in C

// C program to illustrate \n escape sequence


#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
// Here we are using \n, which is a new line character.
printf("Hello\n");
printf("Welcome to the class");
getch ();
}
Output
Hello
Welcome to the class
4. Example to demonstrate how to use \t escape sequence in C

// C program to illustrate \t escape sequence


#include <stdio.h>
#include<conio.h>
void main()
{
Clrscr();
// Here we are using \t, which is a horizontal tab [Link] will provide a tab
space //between two words.
printf("Hello\t Hi\tJSS");
getch ();
}

Output
Hello Hiiii
The escape sequence “\t” is very frequently used in loop-based pattern printing
programs.

5. Example to demonstrate how to use \v escape sequence in C


// C program to illustrate \v escape sequence
#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
// Here we are using \v, which is vertical tab character.
printf("Hello friends\v");

printf("Welcome to class");

getch ();
}
Output
Hello friends
Welcome to GFG
6. Example to demonstrate how to use \r escape sequence in C

// C program to illustrate \r escape sequence


#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
// Here we are using \r, which is carriage return character.
printf("Hello Hii \rWelcome");
getch ();
}

Output
WelcomeHello Hii
7. Example to demonstrate how to use \\ escape sequence in C
// C program to illustrate \\(Backslash)
// escape sequence to print backslash.
#include <stdio.h>
#include<conio.h>

void main()
{
// Here we are using \,It contains two escape sequence means \ and \n.
printf("Hello\\Hi");
getch ();
}

Output
Hello\Hi
Explanation: It contains two ‘\’ which means we want print ‘\’ as output.

8. Example to demonstrate how to use \’ and \” escape sequence in C


// C program to illustrate \' escape sequence/ and \" escape sequence to print single
//quote and double quote.
#include <stdio.h>
int main(void)
{
printf("\' Hello Hi\n");
printf("\" Hello Hi");
return 0;
}

Output
' Hello Hi
" Hello Hi
9. Example to demonstrate how to use \? escape sequence in C
// C program to illustrate
// \? escape sequence
#include <stdio.h>

int main(void)
{
// Here we are using \?, which is
// used for the presentation of trigraph
// in the early of C programming. But
// now we don't have any use of it.
printf("\?\?!\n");
return 0;
}

Output
??!
10. Example to demonstrate how to use \ooo escape sequence in C
// C program to illustrate \OOO escape sequence
#include <stdio.h>

int main(void)
{
// we are using \OOO escape sequence, here
// each O in "OOO" is one to three octal
// digits(0....7).
char* s = "A\072\065";
printf("%s", s);
return 0;
}

Output
A:5
Explanation: Here 000 is one to three octal digits(0….7) means there must be at
least one octal digit after \ and a maximum of three. Here 072 is the octal notation,
first, it is converted to decimal notation which is the ASCII value of char ‘:’. At the
place of \072, there is: and the output is A:5.

11. Example to demonstrate how to use \xhh escape sequence in C


// C program to illustrate \XHH escape
// sequence
#include <stdio.h>
int main(void)
{
// We are using \xhh escape sequence.
// Here hh is one or more hexadecimal
// digits(0....9, a...f, A...F).
char* s = "B\x4a";
printf("%s", s);
return 0;
}

Output
BJ

computational problems :

While arithmetic expressions in C are generally straight forward to evaluate, there


are some computational problems that can arise. Here are a few examples:
1. Integer division:
When dividing two integers, C uses integer division, which truncates the
result to an integer value. For example, the expression 5 / 2 will
result in 2, not 2.5. To get a floating-point result, one or both operands must
be cast to a float or double type.
2. Division by 0:
Dividing any number by zero is undefined in C and will result in a runtime
error. Programmers should ensure that their code does not attempt
to divide by zero.
3. Overflow and Underflow:
When performing arithmetic with integers, the result must fit within the range
of the data type being used. If the result is too large, it will
overflow the range and produce an incorrect result. If the result is too small, it
will underflow and also produce an incorrect result.
4. Order of evaluation:
As mentioned earlier, the order of evaluation for arithmetic operators in C is
determined by operator precedence and associativity. If programmers
do not understand these rules, they may write expressions that produce
unexpected results.
5. Floating-point precision:
Due to the way that floating-point numbers are represented in memory, some
arithmetic expressions may produce slightly different results than expected
due to rounding errors. Programmers should be aware of this issue and use
appropriate rounding functions to ensure accurate results.

Operator Precedence and Associativity in C and Evaluating the expression.


The concept of operator precedence and associativity in C helps in determining


which operators will be given priority when there are multiple operators in the
expression. It is very common to have multiple operators in C language and the
compiler first evaluates the operator with higher precedence. It helps to maintain
the ambiguity of the expression and helps us in avoiding unnecessary use of
parenthesis.
In this article, we will discuss operator precedence, operator associativity, and
precedence table according to which the priority of the operators in expression is
decided in C language.

Operator Precedence and Associativity Table


The following tables list the C operator precedence from highest to lowest and the
associativity for each of the operators:

Operator
Precedence Description Associativity

1 () Parentheses (function call) Left-to-Right


Operator
Precedence Description Associativity

Array Subscript (Square


[]
Brackets)

. Dot Operator

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

Logical NOT, Bitwise


!,~
complement
2 Right-to-Left
(type) Cast Operator

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

Bitwise shift left, Bitwise shift


5 << , >> Left-to-Right
right

Relational less than, less than or


< , <=
equal to
6 Left-to-Right
> , >= Relational greater than, greater
Operator
Precedence Description Associativity

than or equal to

Relational is equal to, is not


7 == , != Left-to-Right
equal to

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

Multiplication, division
*= , /=
assignment

14 Modulus, bitwise AND Right-to-Left


%= , &=
assignment

Bitwise exclusive, inclusive OR


^= , |=
assignment

Bitwise shift left, right


<<=, >>=
assignment

15 , comma (expression separator) Left-to-Right


Example:
// C Program to illustrate operator Associativity
#include <stdio.h>
#include<conio.h>

void main()
{
// Verifying the result of the same expression
Clrscr();
printf("100 / 5 % 2 = %d", 100 / 5 % 2);

getch();
}

Output
100 / 5 % 2 = 0

Type Conversion in

Definition:
Type conversion in C is the process of converting one data type to another.
 The type conversion is only performed to those data types where conversion
is possible. Type conversion is performed by a compiler.
 In type conversion, the destination data type can’t be smaller than the source
data type.
 Type conversion is done at compile time and it is also called widening
conversion because the destination data type can’t be smaller than the source
data type.
There are two types of Conversion:
1. Implicit Type Conversion/Widening type casting:
Also known as ‘automatic type conversion’.
A. Done by the compiler on its own, without any external trigger from the user.
B. Generally takes place when in an expression more than one data type is present.
In such conditions type conversion (type promotion) takes place to avoid loss of
data.
C. All the data types of the variables are upgraded to the data type of the variable
with the largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
D. It is possible for implicit conversions to lose information, signs can be lost
(when signed is implicitly converted to unsigned), and overflow can occur (when
long is implicitly converted to float).

Example of Type Implicit Conversion


Example no
 C

// An example of implicit conversion

#include <stdio.h>

#include<conio.h>

void main()

int x = 10; // integer x

char y = 'a'; // character c

// y implicitly converted to int. ASCII value of 'a' is 97


clrscr();

x = x + y;

printf("x = %d", x);

getch();

Output
x = 107

2. Explicit Type Conversion/Narrowing type casting:

This process is also called type casting and it is user-defined. Here the user can
typecast the result to make it of a particular data type.
The syntax in C Programming:
(type) expression
Type indicated the data type to which the final result is converted.
Example no 2

 C

// C program to demonstrate explicit type casting

#include<stdio.h>

#include<conio.h>

void main()

double x = 1.2;

clrscr();

// Explicit conversion from double to int

int sum = (int)x + 1;

printf("sum = %d", sum);

getch();

Output
sum = 2

You might also like