ICP Module 1 PDF
ICP Module 1 PDF
Subject Code:”B24ESCK245”
“Module-1”
Semester: I
BRANCH: ECE
                                              Semester II
                                   Introduction to C Programming
                                           Category: ESC-II
                            Common to All Branches except CSE allied branches
                                              (Integrated)
Course Code                   : B24ESCK245                    CIE                  :   50 Marks
Teaching Hours L : T : P      : 2:0:2                         SEE                  :   50 Marks
Total Hours                   : 50                            Total                :   100 Marks
Credits                         3                             SEE Duration         :   3 Hrs
Module - 1                                                                                         No.   of
                                                                                                   Hrs
Introduction to Computing: Computer Systems-Hardware and Software, Computer Languages,
Algorithm, Flowchart, Representation of Algorithm and Flowchart with examples. Introduction to 08
C–History of C, Features of C, Structure of C Program, Character Set, C Tokens-Keywords,
Identifiers, Constants, Variables, Data types, Input/output statements in C, Types of errors.
                                                                                                          1
Introduction to C programming                                            B24ESCK245
1. Introduction to Computing
Computing involves using computer systems to process data, perform calculations, and execute
programs. The essential components of a computer system are:
A. Hardware
Hardware refers to all the physical components that make up a computer system. Key hardware
components include:
                                                                                                     2
Introduction to C programming                                            B24ESCK245
B. Software
Software is a collection of programs and data that instruct the hardware on how to operate and perform
specific tasks. There are two primary types of software:
i. System Software
      Device Drivers:
       Software programs that allow the operating system to communicate with hardware devices
       (e.g., printer drivers, graphics card drivers).
      System Calls:
       Mechanisms for programs to interact with the operating system to request services like memory
       allocation, file manipulation, or hardware access.
                                                                                                    3
Introduction to C programming                                            B24ESCK245
Computer languages are used to write software programs. They can be classified based on their level of
abstraction from machine code.
Low-Level Language:
      Definition: Low-level languages communicate directly with the hardware using machine code,
       consisting of binary digits (0 and 1).
      Purpose: Operates, manages, and manipulates hardware and system components.
      Types:
          o Machine Language: The first generation language written in binary (0s and 1s). Directly
               understood by the computer. No need for a translator or interpreter.
               Disadvantages: Hard to remember operation codes, machine-dependent, difficult to
               debug.
          o Assembly Language: Uses words, names, and symbols instead of binary. Translated into
               machine code by an Assembler.
          o Disadvantages: Machine-dependent (specific to one CPU type), but faster and more
               efficient than higher-level languages.
High-Level Language:
      Definition: High-level languages are closer to human language and are easier for programmers
       to write, read, and maintain.
      Purpose: Programs are translated into machine language by compilers or interpreters to run on
       computers. Less machine-dependent.
      Types:
           o Common examples include C, FORTRAN, Pascal, COBOL, Java, LISP, C++,
               BASIC, Prolog, and Ada.
      Advantages: Easier to write and debug. User-friendly, as the language uses English-like words,
       symbols, and characters. Programs are portable across different computers.
      Compiler: Converts high-level code to machine code, also checks for errors before execution.
                                                                                                    4
  Introduction to C programming                                               B24ESCK245
  Key Characteristics:
        Procedural Languages: Focus on the sequence of instructions for the computer to follow (e.g.,
         C, Pascal).
        Object-Oriented Languages: Focus on objects and data encapsulation (e.g., C++, Java).
        Functional Languages: Focus on mathematical functions and immutable data (e.g., Haskell,
         Lisp).
        Markup Languages: Used to define the structure and presentation of content (e.g., HTML,
         XML).
        Scripting Languages: Used to automate tasks or add functionality to websites or programs (e.g.,
         Python, JavaScript).
                                                                                                      5
  Introduction to C programming                                                  B24ESCK245
  For Reference:
             Compiler:
              A compiler translates the entire high-level program into machine code before execution.
              Examples: C, C++.
             Interpreter:
              An interpreter translates and executes the program line by line. Examples: Python, JavaScript.
Interpreter Vs Compiler:
Interpreter Compiler
Interpreters usually take less amount of time to           Compilers usually take a large amount of time to
analyze the source code. However, the overall              analyze the source code. However, the overall
execution time is comparatively slower than                execution time is comparatively faster than
compilers.                                                 interpreters.
No Object Code is generated, hence are memory              Generates Object Code which further requires
efficient.                                                 linking, hence requires more memory.
Programming languages like JavaScript, Python,             Programming languages like C, C++, Java use
Ruby use interpreters.                                     compilers.
                                                                                                               6
Introduction to C programming                                                       B24ESCK245
1.2.3. Evolution of Computer Languages
       First Generation:
        Machine Language (binary code).
       Second Generation:
        Assembly Language (mnemonics).
       Third Generation:
        High-Level Languages (FORTRAN, C, COBOL).
       Fourth Generation:
        High-level languages designed for specific tasks, such as SQL for databases or MATLAB for
        mathematical computations.
        Algorithms are step-by-step procedures designed to solve specific problems and perform
        tasks efficiently in the realm of computer science and mathematics. These powerful sets of
        instructions form the backbone of modern technology and govern everything from web
        searches to artificial intelligence. Here's how algorithms work:
           Input: Algorithms take input data, which can be in various formats, such as numbers, text,
            or images.
           Processing: The algorithm processes the input data through a series of logical and
            mathematical operations, manipulating and transforming it as needed.
           Output: After the processing is complete, the algorithm produces an output, which could
            be a result, a decision, or some other meaningful information.
           Efficiency: A key aspect of algorithms is their efficiency, aiming to accomplish tasks
            quickly and with minimal resources.
           Optimization: Algorithm designers          constantly seek       ways    to   optimize   their
            algorithms, making them faster and more reliable.
           Implementation: Algorithms are implemented in various programming languages,
        enabling         computers   to   execute     them     and     produce      desired   outcomes.
                                                                                                             7
           Introduction to C programming                                                  B24ESCK245
Example:
Example: A simple algorithm to calculate the sum of the first 5 natural numbers would look like this:
           Steps:
           1. Start
           2. Initialize sum as 0
           3. For each number from 1 to 5:
                    Add the number to sum.
           4. End
           (Return sum as the output)
                 1.3.2. FLOWCHARTS
                 A flowchart is a pictorial (graphical) representation of an algorithm. A flowchart is drawn
                 using different kinds of symbols. A symbol is used for a specific purpose. Each symbol has
                 name.
                                                                                                                      8
Introduction to C programming                                                B24ESCK245
       Flowcharts use different shapes of boxes to denote different type of instructions. ANSI
       recommended a number of different rules and guidelines to help standardize the
       flowcharting process.
        Algorithms are represented using flowcharts
        Flowchart symbols are standardized by ANSI
        Flowchart helps to divide a large complex problem into small manageable ones
        Generally, algorithm is first represented as a flowchart and then expressed in a
         programming language.
        While preparing a flowchart, the sequence, selection and iterative structures may be used
         wherever required.
                                                                                                     9
Introduction to C programming   B24ESCK245
                                             10
Introduction to C programming   B24ESCK245
                                             11
Introduction to C programming                                           B24ESCK245
 2.1 INTRODUCTION TO C
C is one of the most influential and widely-used programming languages, developed in the early 1970s.
It is a general-purpose, procedural, and powerful language that has formed the foundation for many
modern programming languages, such as C++, C#, and even operating systems like Unix. C has been
praised for its efficiency and flexibility, making it suitable for system programming and application
development.
2.1.1 History of C
   1. Origins:
         o The C programming language was created by Dennis Ritchie at Bell Labs in the early
            1970s.
         o It was developed as an enhancement of the B language (which was influenced by BCPL)
            and aimed to be more powerful and efficient.
         o C was originally designed for system programming—specifically, to write operating
            systems (like Unix).
   2. Development:
         o 1972: C was first used for writing the Unix operating system.
         o 1978: The first edition of the "K&R C" (named after Brian Kernighan and Dennis
            Ritchie) was published in the book "The C Programming Language". This version of
            C became widely used and is considered the foundation for modern C programming.
         o 1983: The ANSI C standard (American National Standards Institute) was created to
            standardize C across platforms.
         o 1989: The ANSI C standard was revised and became the C89 standard.
         o 1999: A major update, known as C99, was released, which introduced several new
            features (e.g., inline functions, new data types).
         o 2011: The C11 standard was introduced, focusing on features like multi-threading and
            improved Unicode support.
                                                                                                  12
Introduction to C programming                                            B24ESCK245
   3. C's Influence:
         o The C language influenced a wide variety of programming languages and is still relevant
             today, forming the basis for many others.
         o Modern languages such as C++, C#, Objective-C, Java, and Python owe much of their
             structure and syntax to C.
2.1.2. Features of C
C is known for its simplicity and versatility. Some of the most important features of the C programming
language include:
   2. Efficient:
          o C allows direct manipulation of hardware and memory, which gives it a high degree of
             control over system resources.
          o It is considered a highly efficient language because it generates minimal machine code,
             making programs faster.
   3. Portable:
          o C programs can run on different types of systems with minimal modification.
          o The ANSI C standard allows C programs to be compiled and executed on virtually any
             computer or operating system.
          o C is not tied to any particular hardware or operating system. A C program written on one
             machine can often be compiled and run on another with little or no modification.
   4. Low-Level Access:
          o C provides low-level access to memory via pointers, enabling developers to manipulate
             memory addresses and directly interact with hardware.
          o This low-level feature makes C particularly suitable for system programming (e.g.,
             operating systems, drivers).
   5. Rich Library Support:
          o C comes with a comprehensive set of built-in functions and libraries for performing a
             wide variety of operations like mathematical calculations, file handling, memory
             management, and more.
   6. Memory Management:
          o C provides manual memory management using functions like malloc() (for memory
             allocation) and free() (for deallocating memory).
          o This gives developers complete control over memory usage and optimization but requires
             more attention to detail to avoid issues like memory leaks.
   7. Modularity:
          o C allows programs to be divided into smaller functions (modular programming), making
             them easier to develop and maintain.
          o Functions in C can be reused in different parts of a program or even in different programs.
   8. Support for Pointers:
          o Pointers are a powerful feature of C, allowing variables to store memory addresses. This
             makes it possible to dynamically allocate memory and directly manipulate data structures.
                                                                                                    13
Introduction to C programming                                              B24ESCK245
   9. Recursion:
          o C supports recursion, allowing a function to call itself. This is useful for solving problems
              that can be broken down into smaller, similar problems (like tree traversals, factorial
              calculation, etc.).
   10. Efficient Performance
          o C is fast and efficient because it is a compiled language and gives the programmer
              direct control over the hardware. It is one of the best languages for performance-critical
              applications like operating systems and game development.
          o Unlike interpreted languages, C programs can be compiled into highly optimized
              machine code.
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.
   • There are 6 basic sections responsible for the proper execution of a program. Sections are
      mentioned below:
   • 1. Documentation
   • 2. Link/Preprocessor Section
   • 3.Definition Section
                                                                                                      14
Introduction to C programming                                            B24ESCK245
  • 4.Global Declaration Section
  • 5.Main() Function Section
  • 6.Sub Programs Section
     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.
    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. Link/ 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 section:
     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.
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.
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
                                                                                                     15
Introduction to C programming                                            B24ESCK245
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:
return x+y;
// Documentation
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
// Main() Function
int main(void)
int y = 55;
return 0;
    }
                                                                                                16
Introduction to C programming   B24ESCK245
// Subprogram
int sum(int y)
return y + X;
Output: sum : 75
                                             17
Introduction to C programming                                                  B24ESCK245
Output
                                                                                                              18
Introduction to C programming                                                 B24ESCK245
2.6 C TOKENS
         Tokens are the basic building blocks in C language. You may think of a token as the smallest
 individual unit in a C program. This means that a program is constructed using a combination of
 these tokens. There are six main types of tokens in C. They are shown in Figure 2.6.
 2.6.1. KEYWORDS
         Like every computer language, C has a set of reserved words often known as keywords that cannot
 be used as an identifier. All keywords are basically a sequence of characters that have a fixed meaning. By
 convention al1 keywords must be written in lowercase (small) letters. Table 2.2 shows the list of keywords
 in C.
 2.6.2. IDENTIFIERS
         Identifiers, as the name suggests, help us to identify data and other objects in the program. Identifiers
 are basically the names given to program elements such as variables, arrays, and functions. Identifiers may
 consist of sequence of letters, numerals, or underscores.
                                                                                                                19
Introduction to C programming                                              B24ESCK245
Some rules have to be followed while forming identifier names. They are as follows:
i.          Identifiers cannot include any special characters or punctuation marks (like #,s, ^, ?, ., etc.)
            except the underscore_.
ii.         There cannot be two successive underscores.
iii.        Keywords cannot be used as identifiers.
iv.         The case of alphabetic characters that form the identifier name is significant.For example,
            "FIRST' is different from 'first' and 'First'.
     2.6.3. VARIABLES
          A variable is defined as a meaningful name given to a data storage location incomputer memory.
 When using a variable, we actually refer to address of the memory where the data is stored. C language
 supports two basic kinds of variables numeric and character.
i. Declaring variables
          Each variable to be used in the program must be declared. To declare a variable, specify the data
 type of the variable followed by its name. The data type indicates the kind of values that the variable will
 store.
          Variable names should always be meaningful and must reflect the purpose of their usage in the
 program. The memory location of the variable is of importance to the compiler only and not to the
 programmer. Programmers must only be concerned with accessing data through their symbolic names. In
 C, variable declaration always ends with a semicolon, for example:
int emp_num;
                                                                                                           20
Introduction to C programming                                                B24ESCK245
While declaring variables, we can also initialize them with some value. For example:
int emp_num = 7;
         Table 9.4 shows the variants of basic data types. As can be seen from the table, we have unsigned
 char and signed char. Do we have negative characters? No, then why do we have such data types? The
 answer is that we use signed and unsigned char to ensure portability of programs that store non-character
 data as char.
         While the smaller data types take less memory, the larger types incur a performance penalty.
 Although the data type we use for our variables does not have a big impact on the speed or memory usage
 of the application, we should always try to use int unless there is a special need to use any other data type.
                                                                                                             21
Introduction to C programming   B24ESCK245
                                             22
Introduction to C programming                                              B24ESCK245
     2.6.5. CONSTANTS
         Constants are identifiers whose values do not change. While values of variables can be changed at
 any time, values of constants can never be changed. Constants are used to define fixed values like
 mathematical constant pie or the charge on an electron so that their value does not get changed in the
 program even by mistake.
         A constant is an explicit data value specified by the programmer. The value of the constant is known
 to the compiler at the compile time. C allows the programmer to specify constants of integer type, floating
 point type, character type, and string type (Figure 2.8).
i. Declaring Constants
         To declare a constant, precede the normal variable declaration with const keyword and assign it a
 value. For example,
         The const keyword specifies that the value of pi cannot change. However, another way to designate
 a constant is to use the pre-processor command define. Like other pre- processor commands, define is
 preceded with a # symbol. Although #define statements can be placed anywhere in a C program, it is always
 recommended that these statements be placed at the beginning of the program to make them easy to find
 and modify at a later stage. Look at the example given below which defines the value of pi using define.
#define pi 3.14159
                                                                                                            23
Introduction to C programming                                                 B24ESCK245
2.6.2. printf()
The printf function (stands for print formatting) is used to display information required by the user and also
prints the values of the variables. For this, the print function takes data values, converts them to a text stream
using formatting specifications in the controlstring and passes the resulting text stream to the standard output.
The control string may contain zero or more conversion specifications, textual data, and control characters to
be displayed.
          The function accepts two parameters-control string and variable list. The control string may also
 contain the text to be printed like instructions to the user, captions, identifiers,or any other text to make the
 output readable.
 Examples:
printf("\n The number is %6d", 12);
2.6.3. scanf():
          The scanf() function stands for scan formatting and is used to read formatted data from the
 keyboard. The scanf function takes a text stream from the keyboard, extracts and formats data from the
 stream according to a format control string and then stores the data in specified program variables. The
 syntax of the scanf() function can be given as:
                                                                                                                24
Introduction to C programming                                                 B24ESCK245
           The control string specifies the type and format of the data that has to be obtained from the keyboard
 and stored in the memory locations pointed by arguments arg1, arg2,, argn, i.e., the arguments are actually
 the variable addresses where each piece of data is to be stored.
scanf("%d", &num);
 The scanf function reads an integer value (because the type specifier is %d) into the address
 or the memory location pointed by num.
float salary;
scanf("%f ", &salary) ;
           The scanf function reads a floating point number (because the type specifier is %f) into the address
 or the memory location pointed by salary.
char ch;
scanf("%c ", &ch);
           The scanf function reads a single character (because the type specifier is %c) into the address or the
 memory location pointed by ch.
char str[10];
scanf("%s ", str);
           The scanf function reads a string or a sequence of characters (because the type specifier is %s) into
 the address or the memory location pointed by str. Note that in case of reading strings, we do not use the &
 sign in the scanf() function.
Example program:
 Write a program to demonstrate the use of printf and scanf statements to read and print values of
 variables of different data types.
#include <stdio.h>
int main()
{
int num;
float amt;
char code;
                                                                                                               25
Introduction to C programming                               B24ESCK245
double pi;
char msg[10];
printf("\n Enter the value of num ");
scanf("%d", &num)
printf("\n Enter the value of amt: ");
scanf("%f", &amt) ;
printf("\n Enter the value of pi : ");
scanf("%ld", &pi);
printf("\n Enter the value of code: ");
scanf("%c", &code);
printf("\n Enter the message :");
scanf("%s", msg);
printf("\n NUM = %d \n AMT = %f \n PI %e \n POPULATION OF INDIA = %ld \nCODE = %c \n MESSAGE =
%s", num, amt, pi, population_of_india, code, msg);
return 0;
}
    OUTPUT:
NUM = 5
AMT         =   123.450000PI        =     3.141590e+00
POPULATION OF INDIA = 12345CODE = c
MESSAGE = Hello
                                                                                     26
Introduction to C programming                                         B24ESCK245
27