1. C Programming Notes
An algorithm is a sequence of instructions that are carried out in a predetermined
sequence in order to solve a problem or complete a work. A function is a block of code
that can be called and executed from other parts of the program.
A set of instructions for resolving an issue or carrying out a certain activity. In computer
science, algorithms are used for a wide range of operations, from fundamental math to
intricate data processing.
Features of the algorithm
It defines several important features of the algorithm, including:
o Inputs: Algorithms must receive inputs that can be represented as values or data.
o Output: The algorithm should produce some output. It can be a consequence of
a problem or a solution designed to solve it.
o Clarity: Algorithms must be precisely defined, using unambiguous instructions
that a computer or other system can follow unambiguously.
o Finiteness: The algorithm requires a limited steps. It means that it should be
exited after executing a certain number of commands.
o Validity: The algorithm must be valid. In other words, it should be able to
produce a solution to the problem that the algorithm is designed to solve in a
reasonable amount of time.
o Effectiveness: An algorithm must be effective, meaning that it must be able to
produce a solution to the problem it is designed to solve in a reasonable amount
of time.
o Generality: An algorithm must be general, meaning that it can be applied to a
wide range of problems rather than being specific to a single problem.
How to write an algorithm
1. First define the problem you want the algorithm to solve.
2. For example, suppose we want to write an algorithm to find the maximum value from a
list of numbers.
2. Break the problem down into smaller, manageable steps.
o Initialize the 'max' variable to the first value in the list.
o For each subsequent value in the list, compare with "max".
o If the value is greater than "max", set "max" to that value.
o Continue doing this until every value in the list has been compared.
o Returns the final "max" value.
3. Write your algorithm in pseudocode or a programming language.
Algorithm written in pseudo code:
1. MAX (list)
2. max = list[0]
3. For i = 1 the length of the list
4. list IF[i] > max
5. max = list[i]
6. End for
7. Maximum return
8. Maximum end
4. Test your algorithm to make sure it is correct and efficient.
You can test the algorithm by entering different lists of numbers and verifying that it
returns the maximum correct value. You can also analyze the time complexity of your
algorithm to determine how well it scales for larger inputs.
Example:-
Input: [1, 5, 2, 7, 3]
Output: 7.
Explanation: 7 is the maximum value in the list.
5. Optimize the algorithm.
3. Look for ways to optimize algorithms for making them faster and more efficient. This
may involve modifying pseudocode or implementing more efficient data structures or
algorithms.
Basic writing of algorithms
Example: - The sum of two integers.
Step 1:= - Get started
Step 2:= Declare three integers a, b, c
Step 3:= Define the values of a and b
Step 4:= Add the values of a and b
Step 5:= Save the output of step 4 in c
Step 6:= Print c
Step 7 :=Stop
What do you mean by flowchart?
The Flowchart is the most widely used graphical representation of an algorithm and
procedural design workflows. It uses various symbols to show the operations and
decisions to be followed in a program. It flows in sequential order.
Types of Flowchart
The various types of the flowchart are given below.
o Horizontal Flowchart
o Panoramic Flowchart
o Vertical Flowchart
o Architectural Flowchart
4. Rules or guidelines of Flow
o Only conventional flowchart symbols should be used.
o Proper use of names and variables in the flow
o If the flowchart becomes large and complex, use connector symbols.
o Flowcharts should have start and stop points.
Flowchart symbols:
The different flowchart symbols have
The various symbols used in Flowchart Designs are given below.
o Terminal Symbol: In the flowchart, it is represented with the help of a circle for
denoting the start and stop symbol. The symbol given below is used to represe
the terminal symbol.
o Input/output Symbol:
the output symbol is used to display the output operation. The symbol given
below is used for representing the Input/output symbol.
Rules or guidelines of Flow
Only conventional flowchart symbols should be used.
Proper use of names and variables in the flowchart.
If the flowchart becomes large and complex, use connector symbols.
Flowcharts should have start and stop points.
Flowchart symbols:
The different flowchart symbols have different conventional meanings.
The various symbols used in Flowchart Designs are given below.
In the flowchart, it is represented with the help of a circle for
denoting the start and stop symbol. The symbol given below is used to represe
the terminal symbol.
Input/output Symbol: The input symbol is used to represent the input data, a
the output symbol is used to display the output operation. The symbol given
below is used for representing the Input/output symbol.
If the flowchart becomes large and complex, use connector symbols.
In the flowchart, it is represented with the help of a circle for
denoting the start and stop symbol. The symbol given below is used to represent
the terminal symbol.
The input symbol is used to represent the input data, and
the output symbol is used to display the output operation. The symbol given
below is used for representing the Input/output symbol.
5. o Processing Symbol:It is represented in a flowchart with the help of a rectangle
box used to represent the arithmetic and data movement instructions.
symbol given below is used to represent the processing symbol.
o Decision Symbol: Diamond symbol is used for represents decision
statements. The symbol given below is used to represent the decision symbol.
o Connector Symbol:The connector symbol is used if flows discontinued at some
point and continued again at another place. The following symbol is the
It is represented in a flowchart with the help of a rectangle
box used to represent the arithmetic and data movement instructions.
symbol given below is used to represent the processing symbol.
Diamond symbol is used for represents decision
statements. The symbol given below is used to represent the decision symbol.
The connector symbol is used if flows discontinued at some
point and continued again at another place. The following symbol is the
It is represented in a flowchart with the help of a rectangle
box used to represent the arithmetic and data movement instructions. The
symbol given below is used to represent the processing symbol.
Diamond symbol is used for represents decision-making
statements. The symbol given below is used to represent the decision symbol.
The connector symbol is used if flows discontinued at some
point and continued again at another place. The following symbol is the
6. representation of the connector symbol.
o Flow lines: It represents the exact sequence in which instructions are executed.
Arrows are used to represent the flow lines in a flowchart. The symbol given
below is used for representing the flow lines:
o Hexagon symbol (Flat):
loop setting statement. The symbol given below is used for representing the
representation of the connector symbol.
It represents the exact sequence in which instructions are executed.
Arrows are used to represent the flow lines in a flowchart. The symbol given
below is used for representing the flow lines:
Hexagon symbol (Flat): It is used to create a preparation box containing the
loop setting statement. The symbol given below is used for representing the
representation of the connector symbol.
It represents the exact sequence in which instructions are executed.
Arrows are used to represent the flow lines in a flowchart. The symbol given
below is used for representing the flow lines:
It is used to create a preparation box containing the
loop setting statement. The symbol given below is used for representing the
7. Hexagon symbol.
o On-Page Reference Symbol:
the flow continues on a matching symbol containing the same letters so
else on the same page. The symbol given below is used for representing the on
page reference symbol.
o Off-Page Reference: This symbol contains a letter inside indicating that the flow
continues on a matching symbol containing the same letter somewhere else on a
different page. The symbol given below is used to represent
Hexagon symbol.
Page Reference Symbol: This symbol contains a letter inside that indicates
the flow continues on a matching symbol containing the same letters so
else on the same page. The symbol given below is used for representing the on
page reference symbol.
This symbol contains a letter inside indicating that the flow
continues on a matching symbol containing the same letter somewhere else on a
different page. The symbol given below is used to represent
Hexagon symbol.
This symbol contains a letter inside that indicates
the flow continues on a matching symbol containing the same letters somewhere
else on the same page. The symbol given below is used for representing the on-
page reference symbol.
This symbol contains a letter inside indicating that the flow
continues on a matching symbol containing the same letter somewhere else on a
different page. The symbol given below is used to represent the off-page
8. reference symbol.
o Delay or Bottleneck: This symbol is used for identifying a delay in a flowchart.
The alternative name used for the delay is the bottleneck. The symbol given
below is used to represent the delay or bottleneck symbol.
o Document Symbol: This symbol is used in a flowchart to indicate a document or
report.The symbol given below is used to represent the document symbol.
reference symbol.
This symbol is used for identifying a delay in a flowchart.
The alternative name used for the delay is the bottleneck. The symbol given
below is used to represent the delay or bottleneck symbol.
This symbol is used in a flowchart to indicate a document or
report.The symbol given below is used to represent the document symbol.
reference symbol.
This symbol is used for identifying a delay in a flowchart.
The alternative name used for the delay is the bottleneck. The symbol given
below is used to represent the delay or bottleneck symbol.
This symbol is used in a flowchart to indicate a document or
report.The symbol given below is used to represent the document symbol.
9. o Internal storage symbol:
internal storage symbol.
Advantages of Flowchart in C:
Following are the various advantages of flowchart:
o Communication: A flowchart is a better way of communicating the log
program.
o Synthesis: Flowchart is used as working models in designing new programs and
software systems.
o Efficient Coding: Flowcharts act as a guide for a programmer in writing the
actual code in a high-level language.
o Proper Debugging: Flowcharts h
o Effective Analysis: Effective analysis of logical programs can be easily done with
the help of a related flowchart.
o Proper Documentation:
consists of various activities su
maintaining all related program records.
o Testing: A flowchart helps in the testing process.
o Efficient program maintenance:
easy with the help of a flowchart.
Internal storage symbol: The symbol given below is used to represent the
ernal storage symbol.
Advantages of Flowchart in C:
Following are the various advantages of flowchart:
A flowchart is a better way of communicating the log
Flowchart is used as working models in designing new programs and
Flowcharts act as a guide for a programmer in writing the
level language.
Flowcharts help in the debugging process.
Effective analysis of logical programs can be easily done with
the help of a related flowchart.
Proper Documentation: Flowchart provides better and proper documentation. It
consists of various activities such as collecting, organizing, storing, and
maintaining all related program records.
A flowchart helps in the testing process.
Efficient program maintenance: The maintenance of the program becomes
easy with the help of a flowchart.
The symbol given below is used to represent the
ernal storage symbol.
A flowchart is a better way of communicating the logic of a
Flowchart is used as working models in designing new programs and
Flowcharts act as a guide for a programmer in writing the
Effective analysis of logical programs can be easily done with
Flowchart provides better and proper documentation. It
ch as collecting, organizing, storing, and
The maintenance of the program becomes
10. History of C Language
History of C language is interesting to know. Here we are going to discuss a brief
history of the c language.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories
of AT&T (American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits
many features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K & R C 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
11. C99 1999 Standardization Committee
Features of C Language
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
12. 1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.
3) Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop system
applications such as kernel, driver, etc. It also supports the features of a high-level
language. That is why it is known as mid-level language.
4) Structured programming language
C is a structured programming language in the sense that we can break the program
into parts using functions. So, it is easy to understand and modify. Functions also
provide code reusability.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
13. The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
Structure of the 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
14. 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<math.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 long long ll
15. 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;
}
Structure of C Program with example
Example: Below C program to find the sum of 2 numbers:
// Documentation
/**
16. * file: sum.c
* author: you
* description: program to find sum.
*/
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
17. return y + X;
}
Explanation of the above Program
Below is the explanation of the above program. With a description explaining
the program’s meaning and use.
Sections Description
/**
* file: sum.c
* author: you
* description: program
to find sum.
*/
It is the comment section and is part of the description section
of the code.
#include<stdio.h>
Header file which is used for standard input-output. This is the
preprocessor section.
#define X 20
This is the definition section. It allows the use of constant X in
the code.
int sum(int y)
This is the Global declaration section includes the function
declaration that can be used anywhere in the program.
int main() main() is the first function that is executed in the C program.
{…}
These curly braces mark the beginning and end of the main
function.
18. Sections Description
printf(“Sum: %d”,
sum(y));
printf() function is used to print the sum on the screen.
return 0;
We have used int as the return type so we have to return 0
which states that the given program is free from the error and it
can be exited successfully.
int sum(int y)
{
return y + X;
}
This is the subprogram section. It includes the user-defined
functions that are called in the main() function.
Steps involved in the Compilation and execution of a C program:
Program Creation
Compilation of the program
Execution of the program
The output of the program
Compiler
The Compiler is a translator which takes input i.e., High-Level Language, and
produces an output of low-level language i.e. machine or assembly language.
The work of a Compiler is to transform the codes written in the programming
language into machine code (format of 0s and 1s) so that computers can
understand.
A compiler is more intelligent than an assembler it checks all kinds of limits,
ranges, errors, etc.
But its program run time is more and occupies a larger part of memory. It
has a slow speed because a compiler goes through the entire program and
then translates the entire program into machine codes.
19. Role of a Compiler
For Converting the code written in a high
language so that computers can easily understand, we use a compiler.
Converts basically convert high
language by a compiler and then assembled into machine code by an
assembler.
Advantages of Compiler
Compiled code runs faster in comparison to Interpreted code.
Compilers help in improving the security of Applications.
As Compilers give Debugging tools, which help in fixing errors easily.
Disadvantages of Compiler
The compiler can catch only
Compilation can take more time in the case of bulky code.
Interpreter
An Interpreter is a program that translates a programming language into a
comprehensible language. The interpreter converts high
intermediate language. It contains pre
It translates only one statement of the program a
Interpreters, more often than not are smaller than compilers.
For Converting the code written in a high-level language into machine
language so that computers can easily understand, we use a compiler.
Converts basically convert high-level language to intermediate assembly
language by a compiler and then assembled into machine code by an
Compiler
Advantages of Compiler
Compiled code runs faster in comparison to Interpreted code.
Compilers help in improving the security of Applications.
As Compilers give Debugging tools, which help in fixing errors easily.
Disadvantages of Compiler
The compiler can catch only syntax errors and some semantic errors
ilation can take more time in the case of bulky code.
is a program that translates a programming language into a
comprehensible language. The interpreter converts high-level language to an
intermediate language. It contains pre-compiled code, source code, etc.
It translates only one statement of the program at a time.
Interpreters, more often than not are smaller than compilers.
level language into machine-level
language so that computers can easily understand, we use a compiler.
to intermediate assembly
language by a compiler and then assembled into machine code by an
As Compilers give Debugging tools, which help in fixing errors easily.
errors.
is a program that translates a programming language into a
level language to an
compiled code, source code, etc.
20. Role of an Interpreter
The simple role of an interpreter is to translate the material into a target
language. An Interpreter works line by line on a code. It also converts high-level
language to machine language.
Interpreter
Advantages of Interpreter
Programs written in an Interpreted language are easier to debug.
Interpreters allow the management of memory automatically, which reduces
memory error risks.
Interpreted Language is more flexible than a Compiled language.
Disadvantages of Interpreter
The interpreter can run only the corresponding Interpreted program.
Interpreted code runs slower in comparison to Compiled code.
Difference Between Compiler and Interpreter
Compiler Interpreter
Steps of Programming:
Program Creation.
Analysis of language by the compiler
and throws errors in case of any
incorrect statement.
In case of no error, the Compiler
converts the source code to Machine
Steps of Programming:
Program Creation.
Linking of files or generation of Machine
Code is not required by Interpreter.
Execution of source statements one by
one.
21. Compiler Interpreter
Code.
Linking of various code files into a
runnable program.
Finally runs a Program.
The compiler saves the Machine
Language in form of Machine Code on
disks.
The Interpreter does not save the Machine
Language.
Compiled codes run faster than
Interpreter.
Interpreted codes run slower than Compiler.
Linking-Loading Model is the basic
working model of the Compiler.
The Interpretation Model is the basic working
model of the Interpreter.
The compiler generates an output in the
form of (.exe).
The interpreter does not generate any output.
Any change in the source program after
the compilation requires recompiling the
entire code.
Any change in the source program during the
translation does not require retranslation of the
entire code.
Errors are displayed in Compiler after
Compiling together at the current time.
Errors are displayed in every single line.
The compiler can see code upfront which
helps in running the code faster because
of performing Optimization.
The Interpreter works by line working of Code,
that’s why Optimization is a little slower
compared to Compilers.
It does not require source code for later It requires source code for later execution.
22. Compiler Interpreter
execution.
Execution of the program takes place
only after the whole program is compiled.
Execution of the program happens after every
line is checked or evaluated.
Compilers more often take a large
amount of time for analyzing the source
code.
In comparison, Interpreters take less time for
analyzing the source code.
CPU utilization is more in the case of a
Compiler.
CPU utilization is less in the case of a
Interpreter.
The use of Compilers mostly happens in
Production Environment.
The use of Interpreters is mostly in
Programming and Development Environments.
Object code is permanently saved for
future use.
No object code is saved for future use.
C, C++, C#, etc are programming
languages that are compiler-based.
Python, Ruby, Perl, SNOBOL, MATLAB, etc
are programming languages that are
interpreter-based.
Compilation process in c
What is a compilation?
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.
23. 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.
o Preprocessor
o Compiler
o Assembler
o Linker
24. Preprocessor
The source code is the code which is written in a text editor and the source code file is
given an extension ".c". This source code is first passed to the preprocessor, and then
the preprocessor expands this code. After expanding the code, the exp
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 cod
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'.
source file is 'hello.c', then the name of the object file would be 'hello.obj'.
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 exp
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
processed code into assembly code.
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
then the name of the object file would be 'hello.obj'.
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
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
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
If the name of the
then the name of the object file would be 'hello.obj'.
25. 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
1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello javaTpoint");
5. return 0;
6. }
Now, we will create a flow diagram of the above program:
27. In the above flow diagram, the following steps are taken to execute a program:
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.
o Next →← Prev
o Data Types in C
o A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.
o
o There are the following data types in C language.
Types Data Types
Basic Data Type int, char, float, double
28. Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
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
29. double 8 byte
long double 10 byte
Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We
can define the token as the smallest individual element in C. For `example, we cannot
create a sentence without using words; similarly, we cannot create a program in C
without using tokens in C. Therefore, we can say that tokens in C is the building block or
the basic component for creating a program in C language.
Classification of tokens in C
Tokens in C language can be divided into the following categories:
o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
30. o Constant in C
o Special Characters in C
Keywords in C
Keywords in C can be defined as the pre-defined or the reserved words having its own
importance, and each keyword has its own functionality. Since keywords are the pre-
defined words used by the compiler, so they cannot be used as the variable names. If
the keywords are used as the variable names, it means that we are assigning a different
meaning to the keyword, which is not allowed. C language supports 32 keywords 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
Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers
in C are the user-defined words. It can be composed of uppercase letters, lowercase
letters, underscore, or digits, but the starting letter should be either an underscore or an
alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in C
are given below:
o The first character of an identifier should be either an alphabet or an underscore,
and then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
31. o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can
say that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to
read.
For example,
o int student;
o float marks;
Here, student and marks are identifiers
int var1, var2;
float Avg;
function sum();
Here,
int, float, function are all keywords.
var1, var2, Sum, Avg, are the identifiers.
Types of identifiers
o Internal identifier
o External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal
identifier. The internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier.
The external identifiers can be function names, global variables.
32. Strings in C
Strings in C are always represented as an array of characters having null character '0' at
the end of the string. This null character denotes the end of the string. Strings in C are
enclosed within double quotes, while characters are enclosed within single characters.
The size of a string is a number of characters that the string contains.
Now, we describe the strings in different ways:
char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
char a[10] = {'j','a','v','a','t','p','o','i','n','t','0'}; // String is represented in the form of characters.
Operators in C
Operators in C is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the operands.
Depending on the number of operands, operators are classified as follows:
Unary Operator
A unary operator is an operator applied to the single operand. For example: increment operator
(++), decrement operator (--), sizeof, (type)*.
Binary Operator
The binary operator is an operator applied between two operands. The following is the
list of the binary operators:
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator
33. C Operators
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C
language.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right
or right to left.
Let's understand the precedence by the example given below:
The precedence and associativity of C operators is given below:
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
34. Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Constants in C
A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.
There are two ways of declaring constant:
o Using const keyword
o Using #define pre-processor
Types of constants in C
Constant Example
Integer constant 10, 11, 34, etc.
Floating-point constant 45.6, 67.8, 11.2, etc.
35. Octal constant 011, 088, 022, etc.
Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.
Character constant 'a', 'b', 'c', etc.
String constant "java", "c++", ".net", etc.
Special characters in C
Some special characters are used in C, and they have a special meaning which cannot be
used for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in
the opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for
example, separating function parameters in a function call, separating the
variable when printing the value of more than one variable using a single printf
statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.
C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The
format string determines the format of the input and output. The format string always
starts with a '%' character.
36. The commonly used format specifiers in printf() function are:
Format
specifier
Description
%d or %i It is used to print the signed integer value where signed integer means that
the variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer
means that the variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value always
starts with a 0 value.
%x It is used to print the hexadecimal unsigned integer where the hexadecimal
integer value always starts with a 0x value. In this, alphabetical characters are
printed in small letters such as a, b, c, etc.
%X It is used to print the hexadecimal unsigned integer, but %X prints the
alphabetical characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it prints the
6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.
%g It is used to print the decimal floating-point values, and it uses the fixed
precision, i.e., the value after the decimal in input would be exactly the same as
the value in the output.
%p It is used to print the address in a hexadecimal form.
%c It is used to print the unsigned character.
37. %s It is used to print the strings.
%ld It is used to print the long-signed integer value.
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?
List of some format specifiers-
S
NO.
Format Specifier Type
Description
1 %d
int/signed
int
used for I/O signed integer value
2 %c char Used for I/O character value
3 %f float Used for I/O decimal floating-point value
4 %s string
Used for I/O string/group of characters
5 %ld long int Used for I/O long signed integer value
6 %u
unsigned int
Used for I/O unsigned integer value
7 %i unsigned int used for the I/O integer value
8 %lf double Used for I/O fractional or floating data
38. 9 %n prints prints nothing
The following formatted I/O functions will be discussed in this section-
1. printf()
2. scanf()
3. sprintf()
4. sscanf()
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:
To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);
Example:
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
int 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);
39. return 0;
}
Output
20
Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);
Example:
C
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
int main()
{
// Displays the string written
// inside the double quotes
printf("This is a string");
return 0;
}
Output
40. This is a string
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
// C program to implement
// scanf() function
#include <stdio.h>
// Driver code
int main()
{
int num1;
// Printing a message on
// the output screen
printf("Enter a integer number: ");
41. // Taking an integer value
// from keyboard
scanf("%d", &num1);
// Displaying the entered value
printf("You have entered %d", num1);
return 0;
}
Output
Enter a integer number: You have entered 0
Output:
Enter a integer number: 56
You have entered 56
sprintf():
sprintf stands for “string print”. This function is similar to printf() function but
this function prints the string into a character array instead of printing it on the
console screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);
Example:
C
// C program to implement
42. // the sprintf() function
#include <stdio.h>
// Driver code
int main()
{
char str[50];
int a = 2, b = 8;
// The string "2 and 8 are even number"
// is now stored into str
sprintf(str, "%d and %d are even number",
a, b);
// Displays the string
printf("%s", str);
return 0;
}
Output
2 and 8 are even number
sscanf():
43. sscanf stands for “string scanf”. This function is similar to scanf() function but
this function reads data from the string or character array instead of the console
screen.
Syntax:
sscanf(array_name, “format specifier”, &variable_name);
Example:
C
// C program to implement
// sscanf() function
#include <stdio.h>
// Driver code
int main()
{
char str[50];
int a = 2, b = 8, c, d;
// The string "a = 2 and b = 8"
// is now stored into str
// character array
sprintf(str, "a = %d and b = %d",
a, b);
44. // The value of a and b is now in
// c and d
sscanf(str, "a = %d and b = %d",
&c, &d);
// Displays the value of c and d
printf("c = %d and d = %d", c, d);
return 0;
}
Output
c = 2 and d = 8
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. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()
45. 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
variable-name = getch();
Example:
C
// C program to implement
// getch() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
printf("Enter any character: ");
// Reads a character but
// not displays
getch();
46. return 0;
}
Output:
Enter any character:
getche():
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).
Syntax:
getche();
or
variable_name = getche();
Example:
C
// C program to implement
// the getche() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
47. printf("Enter any character: ");
// Reads a character and
// displays immediately
getche();
return 0;
}
Output:
Enter any character: g
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>
48. // Driver code
int main()
{
// Declaring a char type variable
char ch;
printf("Enter the character: ");
// Taking a character from keyboard
ch = getchar();
// Displays the value of ch
printf("%c", ch);
return 0;
}
Output:
Enter the character: a
a
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);
49. Example:
C
// C program to implement
// the putchar() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
char ch;
printf("Enter any character: ");
// Reads a character
ch = getchar();
// Displays that character
putchar(ch);
return 0;
}
50. Output:
Enter any character: Z
Z
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
// C program to implement
// the gets() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
// Declaring a char type array
// of length 50 characters
char name[50];
51. 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);
return 0;
}
Output:
Please enter some texts: geeks for geeks
You have entered: geeks for geeks
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
52. // C program to implement
// the puts() function
#include <stdio.h>
// Driver code
int main()
{
char name[50];
printf("Enter your text: ");
// Reads string from user
gets(name);
printf("Your text is: ");
// Displays string
puts(name);
return 0;
53. }
Output:
Enter your text: GeeksforGeeks
Your text is: GeeksforGeeks
putch():
putch() function is used to display a single character which is given by the user
and that character prints at the current cursor location. This function is declared
in conio.h(header file)
Syntax:
putch(variable_name);
Example:
C
// C program to implement
// the putch() functions
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
char ch;
printf("Enter any character:n ");
54. // Reads a character from the keyboard
ch = getch();
printf("nEntered character is: ");
// Displays that character on the console
putch(ch);
return 0;
}
Output:
Enter any character:
Entered character is: d
Formatted I/O vs Unformatted I/O
S
No.
Formatted I/O functions Unformatted I/O functions
1
These functions allow us to take input or
display output in the user’s desired
format.
These functions do not allow to take
input or display output in user desired
format.
2
These functions support format
specifiers.
These functions do not support format
specifiers.
3
These are used for storing data more
user friendly
These functions are not more user-
friendly.
55. 4 Here, we can use all data types.
Here, we can use only character and
string data types.
5
printf(), scanf, sprintf() and sscanf() are
examples of these functions.
getch(), getche(), gets() and puts(), are
some examples of these functions.