UNIT 1
1. Introduction to C Programming
1.1 Overview of C
C is a general-purpose, high-level language that was originally developed by
Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was
originally first implemented in 1972.
The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C. C has now become a widely used professional
language for various reasons −
  ●   Easy to learn
  ●   Structured language
  ●   It produces efficient programs
  ●   It can handle low-level activities
  ●   It can be compiled on a variety of computer platforms
Facts about C
  ●   C was invented to write an operating system called UNIX.
  ●   C is a successor of B language which was introduced around the early
      1970s.
  ●   The language was formalized in 1988 by the American National Standard
      Institute (ANSI).
  ●   The UNIX OS was totally written in C.
  ●   Today C is the most widely used and popular System Programming
      Language.
  ●   Most of the state-of-the-art software have been implemented using C.
  ●   Today's most popular Linux OS and RDBMS MySQL have been written in
      C.
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.   Structured programming language
   4.   Rich Library
   5.   Memory Management
   6.   Fast Speed
   7.   Pointers
   8.   Recursion
   9.   Extensible
Why use C?
C was initially used for system development work, particularly the programs that
make-up the operating system. C was adopted as a system development language
because it produces code that runs nearly as fast as the code written in assembly
language. Some examples of the use of C might be −
  ●     Operating Systems
  ●     Language Compilers
  ●   Assemblers
  ●   Text Editors
  ●   Print Spoolers(SPOOLING-simultaneous peripheral operations online)
  ●   Network Drivers
  ●   Modern Programs
  ●   Databases
  ●   Language Interpreters
  ●   Utilities
C Programs
A C program can vary from 3 lines to millions of lines and it should be written
into one or more text files with extension ".c"; for example, hello.c.
The C Compiler
The source code written in source file is the human readable source for your
program. It needs to be "compiled", into machine language so that your CPU can
actually execute the program as per the instructions given.
The compiler compiles the source codes into final executable programs. The most
frequently used and free available compiler is the C compiler,
1.2 History of C Programming
   ● C is one of the high-level programming languages developed by Dennis
     Ritchie.
   ● C was originally developed for UNIX operating system to beat the issues
     of previous languages such as B, BCPL, etc.
   ● The UNIX operating system development started in the year 1969, and its
     code was rewritten in C in the year 1972.
   ● The UNIX operating system development started in the year 1969, and its
     code was rewritten in C in the year 1972.
   ● In 1985, Windows 1.0 was released. Even though Windows source code
     isn’t publicly available on the market, it’s been stated that its kernel is
     mostly written in C.
   ● In 1991, Linux kernel development started, and it’s additionally written in
     C.
   ● After a year it was released under the GNU license and was used as part
     of the GNU Operating System.
   ● The GNU operating system was started using C and Lisp programming
     languages. So, many of its components are written in C.
     ● In 1977, Oracle database development started, and in 1983 its code was
       rewritten from assembly to C. It became one in all the foremost
       widespread databases within the world.
     ● Now a days C is exclusively used for building OS, application packages
       and customized software. Because of its power and efficiency, it has
       gained more popularity.
     ● C is increasingly used by system programmers, application developers
       and researchers for a spread of programming tasks.
1.3 The basic structure of a 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
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program,
and the creation date and time of the program. It is specified at the start of the
program in the form of comments. Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
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(LINK)
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
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.
Basic Structure of the C Program
    Section                                   Description
                Consists of the description of the program, programmer's name, and
Documentation
                creation date. These are generally written in the form of comments.
                All header files are included in this section which contains different
Link            functions from the libraries. A copy of these header files is inserted
                into your code before compilation.
                Includes preprocessor directive, which contains symbolic constants.
Definition      E.g.: #define allows us to use constants in our code. It replaces all the
                constants with its value in the code.
Global          Includes declaration of global variables, function declarations, static
Declaration     global variables, and functions.
Main()          For every C program, the execution starts from the main() function. It
Function        is mandatory to include a main() function in every C program.
            Includes all user-defined functions (functions the user provides). They
            can contain the inbuilt functions and the function definitions declared
Subprograms
            in the Global Declaration section. These are called in the main()
            function.
Example
   //Documentation
/ * file: age.c
  author: you
* description: program to find our age.
 */
#include <stdio.h> //Link
#define BORN 2000        //Definition
int age(); //Global Declaration
int main()        //Main() Function
{
  int current = 2021;
  printf("Age: %d", age(current));
  return 0;
}
int age(int current)       //Subprograms
 {
   return current - BORN;
}
1.4 Creating and executing a c program
      The steps for creating and running programs are: writing/editing,
compiling, linking and execution. This can be viewed diagrammatically as shown
below:
Writing/Editing: The first step in creating programs is, writing or editing the
program. A program can be written in any text editor like notepad. After writing
a program, the program must be saved, In C language, the program is saved with
the extension “.c”. This is the source program written in a high-level language.
Compilation: After writing and saving the source program, the next step is
compilation. Here we will use a software called as compiler, which converts a
program written in high-level language into machine language. The resultant file
is known as an object file in C. The extension of that file is “.obj”.
 Linking: After compilation the next step is linking. Here software called linker
is used. The linker links the program with external library files which contains
the code for predefined functions and creates an executable file. The extension of
the executable file is “.exe”.
 Execution: Finally after the executable file is created after linking, the next step
is execution. The operating system executes the executable file which is the
machine code with the help of the CPU and other hardware components.
2. C Programming-Basic Concepts
2.1 C Character Set
As every language contains a set of characters used to construct words,
statements, etc., C language also has a set of characters which include alphabets,
digits, and special symbols. C language supports a total of 256 characters.
Every C program contains statements. These statements are constructed using
words and these words are constructed using characters from C character set. C
language character set contains the following set of characters...
   1. Alphabets
   2. Digits
   3. Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and
upper case letters together support 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C
language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform
mathematical operations, to check conditions, white spaces, backspaces, and
other special symbols.
     Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline
     space NULL bell backspace vertical tab etc.,
     2.2 C Tokens
     In a passage of text, individual words and punctuation marks are called tokens
     or lexical units. Similarly, the smallest individual unit in a c program is known
     as a token or a lexical unit.
     C tokens can be classified as follows:
1.   Keywords
2.   Identifiers
3.   Constants
4.   Strings
5.   Special Symbols
6.   Operators
                1. C Keywords
     C keywords are the words that convey a special meaning to the c compiler. The
     keywords cannot be used as variable names because by doing so, we are trying
     to assign a new meaning to the keyword which is not allowed.
     The list of C keywords is given below:
     auto          break     case       char         const
     continue      default do           double       else
     enum          extern    float      for          goto
     if            int       long       register     return
     short         signed    sizeof     static       struct
     switch        typedef union        unsigned     void
     volatile      while
                2. C Identifiers
     Identifiers are used as the general terminology for the names of variables,
     functions and arrays. These are user-defined names consisting of arbitrarily long
     sequence of letters and digits with either a letter or the underscore(_) as a first
     character.
     There are certain rules that should be followed while naming c identifiers:
●    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 first 31 characters are significant.
    Some examples of c identifiers:
    Name           Remark
    _A9            Valid
    Temp.var       Invalid as it contains special character other than the underscore
    void           Invalid as it is a keyword
           3. C Constants
    C constants refers to the data items that do not change their value during the
    program execution. Several types of C constants that are allowed in C are:
           3.1. Integer Constants
    Integer constants are whole numbers without any fractional part. It must have at
    least one digit and may contain either + or – sign. A number with no sign is
    assumed to be positive.
    There are three types of integer constants:
          3.1.1. Decimal Integer Constants
    Integer constants consisting of a set of digits, 0 through 9, preceded by an
    optional – or + sign.
    Example of valid decimal integer constants
    341, -341, 0, 8972
           3.1.2. Octal Integer Constants
    Integer constants consisting of sequence of digits from the set 0 through 7
    starting with 0 is said to be octal integer constants.
    Example of valid octal integer constants
    010, 0424, 0, 0540
          3.1.3. Hexadecimal Integer Constants
    Hexadecimal integer constants are integer constants having sequence of digits
    preceded by 0x or 0X. They may also include alphabets from A to F
    representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used
in programming.
      3.2. Real Constants
The numbers having fractional parts are called real or floating point constants.
These may be represented in one of the two forms called fractional form or
the exponent form and may also have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Representing a real constant in exponent form
The general format in which a real number may be represented in exponential or
scientific form is
mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal
notation.
The letter e separating the mantissa and the exponent can also be written in
uppercase i.e. E
And, the exponent must be an integer.
Examples of valid real constants in exponent form are:
252E85, 0.15E-10, -3e+8
      3.3. Character Constants
A character constant contains one single character enclosed within single
quotes.
Examples of valid character constants
‘a’ , ‘Z’, ‘5’
It should be noted that character constants have numerical values known as
ASCII values, for example, the value of ‘A’ is 65 which is its ASCII value.
      3.4.Escape Characters/ Escape Sequences
C allows us to have certain non graphic characters in character constants. Non
graphic characters are those characters that cannot be typed directly from
keyboard, for example, tabs, carriage return, etc.
These non graphic characters can be represented by using escape sequences
represented by a backslash() followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a
single character.
Escape Sequence           Description
\a                        Audible alert(bell)
\b                        Backspace
\f                        Form feed
\n                        New line
\r                        Carriage return
\t                        Horizontal tab
\v                        Vertical tab
\                         Backslash
“                         Double quotation mark
‘                         Single quotation mark
?                         Question mark
                          Null
       4.String Constants
String constants are sequence of characters enclosed within double quotes. For
example,
“hello”
“abc”
“hello911”
Every sting constant is automatically terminated with a special
character ” called the null character which represents the end of the string.
For example, “hello” will represent “hello” in the memory.
Thus, the size of the string is the total number of characters plus one for the null
character.
       5.Special Symbols
The following special symbols are used in C having some special meaning and
thus, cannot be used for some other purpose.
[] () {} , ; : * … = #
   Braces{}: These opening and ending curly braces marks the start and end of a
   block of code containing more than one executable statement.
   Parentheses(): These special symbols are used to indicate function calls and
   function parameters.
   Brackets[]: Opening and closing brackets are used as array element reference.
   These indicate single and multidimensional subscripts.
          6. C Operators
   C operators are symbols that triggers an action when applied to C variables and
   other objects. The data items on which operators act upon are called operands.
   Depending on the number of operands that an operator can act upon, operators
   can be classified as follows:
1. Unary Operators: Those operators that require only single operand to act upon
   are known as unary operators.
2. Binary Operators: Those operators that require two operands to act upon are
   called binary operators.
3. Ternary Operators: These operators requires three operands to act upon.
   2.3 Variables in C
   A variable is a name of the memory location. It is used to store data. Its value
   can be changed, and it can be reused many times.
   It is a way to represent memory location through symbol so that it can be easily
   identified.
   Rules for defining variables
      o   A variable can have alphabets, digits, and underscore.
      o   A variable name can start with the alphabet, and underscore only. It can't
          start with a digit.
      o   No whitespace is allowed within the variable name.
      o   A variable name must not be any reserved word or keyword, e.g. int, float,
          etc.
   2.3 Datatypes in C
   Each variable in C has an associated data type. Each data type requires different
   amounts of memory and has some specific operations which can be performed
over it. It specifies the type of data that the variable can store like integer,
character, floating, double, etc. The data type is a collection of data with values
having fixed values, meaning as well as its characteristics.
The data types in C can be classified as follows:
 Types               Description
 Primitive    Data   Arithmetic types can be further classified into integer and
 Types               floating data types.
                     The data type has no value or operator and it does not
                     provide a result to its caller. But void comes under
 Void Types          Primitive data types.
 User   Defined      It is mainly used to assign names to integral constants,
 DataTypes           which make a program easy to read and maintain
                     The data types that are derived from the primitive or built-
 Derived types       in datatypes are referred to as Derived Data Types.
                 Memory                         Format
DataType         (bytes)   Range                Specifier
Short int        2         -32,768 to 32,767    %hd
unsigned short
int              2         0 to 65,535          %hu
unsigned int     4         0 to 4,294,967,295   %u
                   Memory                                      Format
 DataType          (bytes)     Range                           Specifier
                               -2,147,483,648 to
 int               4           2,147,483,647                   %d
                               -2,147,483,648 to
 long int          4           2,147,483,647                   %ld
 unsigned long
 int               4           0 to 4,294,967,295              %lu
 long long int     8           -(2^63) to (2^63)-1             %lld
 unsigned long                 0 to
 long int          8           18,446,744,073,709,551,615      %llu
 signed char       1           -128 to 127                     %c
 unsigned char     1           0 to 255                        %c
 float             4                                           %f
                               1.2E-38 to 3.4E+38
 double            8                                           %lf
                               1.7E-308 to 1.7E+308
 long     double   16                                          %Lf
                               3.4E-4932 to 1.1E+4932
Different data types also have different ranges up to which they can store
numbers. These ranges may vary from compiler to compiler. Below is a list of
ranges along with the memory requirement and format specifiers on the 32-bit
GCC compiler.
Declaration of variable
Variables are containers for storing data values.
In C, there are different types of variables (defined with different keywords), for
example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
Declaring (Creating) Variables
To create a variable, specify the type and assign it a value:
Syntax
type variableName = value
Where type is one of C types (such as int), and variableName is the name of the
variable (such as x or myName). The equal sign is used to assign a value to the
variable.
So, to create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign the value 15 to it:
int myNum = 15;
Operators
The operators are types of symbols that inform a compiler for performing some
specific logical or mathematical functions. The operators serve as the foundations
of the programming languages. Thus, the overall functionalities of the C
programming language remain incomplete if we do not use operators. In simpler
words, the operators are symbols that help users perform specific operations and
computations- both logical and mathematical on the operands. Thus, the operators
operate on the available operands in a program.
Use of Operators in C
The operators basically serve as symbols that operate on any value or variable.
We use it for performing various operations- such as logical, arithmetic,
relational, and many more. A programmer must use various operators for
performing certain types of mathematical operations. Thus, the primary purpose
of the operators is to perform various logical and mathematical calculations.
The programming languages like C come with some built-in functions that are
rich in nature. The use of these operators is vast. These operators act as very
powerful and useful features of all the programming languages, and the
functionality of these languages is pretty much useless without these. These make
it very easy for programmers to write the code very easily and efficiently.
Types of Operators in C
Various types of operators are available in the C language that helps a
programmer in performing different types of operations. We can handle different
operations in a program using these types of operators:
Relational Operators
Arithmetic Operators
Logical Operators
Assignment Operators
Bitwise Operators
Misc Operators
Relational Operators
We use the relational operators in c when we would like to compare the values
available for two given operands. Here is a table that states all the relational
operators available in the C language, along with their individual functions.
Function of Operator       Operator   Example
To check if two operands are equal to each other.(==)
5 == 3 would return to 0
and 4 == 4 would return to 1
To check if two operands are unequal to each other.
(!=   )
8 != 5 would return to 1
6 != 6 would return to 0
To check if the operand value on the left is comparatively greater than that of the
operand value on the right.     >
5 > 8 would return to 0
9 > 7 would return to 1
To check if the operand value on the left is comparatively smaller than that of the
operand value on the right.     <
2 < 0 would return to 0
4 < 8 would return to 1
To check if the operand value on the left is equal to or comparatively greater than
that of the operand value on the right. >=
1 >= 5 would return to be 0
4 >= 2 would return to be 1
9 >= 9 would return to be 1
To check if the operand value on the left is equal to or comparatively smaller than
that of the operand value on the right. <=
3 <= 6 would return to be 1
7 <= 3 would return to be 0
2 <= 2 would return to be 1