Unit 1-C PGM
Unit 1-C PGM
BASICSOFCPROGRAMMING
Problem Solving Methods - Flow Chart, Developing Algorithm - Procedural Programming
(Modular and Structural) - Introduction to programming paradigms – Applications of C
Language - Structure of C program - C programming: Data Types - Constants – Enumeration
Constants - Keywords – Operators: Precedence and Associativity - Expressions – Input / Output
statements, Assignment statements – Decision making statements – Switch statement – Looping
statements – Preprocessor directives - Compilation process.
1. Understanding the Problem: Before you start writing code, make sure you understand the
problem requirements and constraints clearly. Identify the inputs, desired outputs, and any
special conditions to consider.
2. Algorithm Design: Design a step-by-step plan (algorithm) to solve the problem. You can use
techniques like pseudo code or flowcharts to map out the logic before writing the actual code.
3. Decomposition: Break down the problem into smaller sub-problems or tasks. This approach
makes the problem easier to tackle and allows you to focus on one part at a time.
4. Modularization: Divide your C code into smaller, self-contained functions. Each function
should perform a specific task, and you can call these functions whenever needed, making the
code more organized and easier to maintain.
5. Input Validation: Always validate user inputs and handle possible errors or invalid data
gracefully to avoid unexpected behavior or crashes.
6. Looping and Iteration: Use loops (like for, while, do-while) to repeat certain tasks until a
condition is met. They are useful for processing data collections or performing actions multiple
times.
7. Conditional Statements: Employ conditional statements (e.g., if, else if, switch) to make
decisions based on specific conditions, allowing your program to adapt and behave differently
    depending on the situation.
    8. Arrays and Pointers: Use arrays and pointers effectively to store and manipulate data. They
    are particularly useful for managing collections of related elements.
    9. Recursion: In C, you can use recursion to solve problems by calling a function within itself.
    Recursive algorithms can be elegant and powerful when used appropriately.
    10. Data Structures: Choose appropriate data structures (like linked lists, stacks, queues, etc.)
    to efficiently organize and manage data based on the problem requirements.
    11. Error Handling: Implement error handling mechanisms, like returning error codes or using
    exceptions, to deal with unexpected situations and provide meaningful feedback to users.
    12. Debugging: Learn how to use C's debugging tools and techniques, like printing intermediate
    values or using a debugger, to identify and fix issues in your code.
    13. Testing: Always thoroughly test your code with different input scenarios to ensure its
    correctness and robustness.
    14. Optimization: If required, optimize your code for performance and memory usage, but do
    this only after you have a working solution. Premature optimization can make your code harder
    to read and maintain.
    15. Code Documentation: Add comments and documentation to your code to make it easier for
    others (and your future self) to understand the purpose and functionality of different parts of the
    program.
1. Modular Programming:
    Definition: Modular programming focuses on breaking down a program into smaller,
    independent modules or functions, each responsible for performing a specific task or
    functionality.
    Key Concepts:
           Modularity: Encourages dividing a program into smaller, self-contained modules that
            can be developed, tested, and maintained independently.
           Abstraction: Allows hiding the implementation details of a module's functionality,
            providing a clear interface for interacting with the module.
           Code Reusability: Promotes reuse of modules across different parts of the program or in
            different programs, reducing redundancy and improving efficiency.
    Advantages:
           Enhances code readability and maintainability by breaking down complex programs into
            smaller, more manageable components.
           Facilitates collaborative development by allowing multiple developers to work on
            different modules simultaneously.
           Promotes code reuse, leading to faster development cycles and fewer errors.
   Example: In C programming, functions serve as modules, where each function encapsulates a
   specific task or operation. By organizing related functions into separate modules, modular
   programming principles can be applied effectively.
2. Structural Programming:
         Definition: Structural programming emphasizes the use of control structures such as
          sequences, loops, and conditionals to control the flow of program execution in a clear and
          structured manner.
   Key Concepts:
         Sequential Execution: Programs are structured as sequences of instructions that are
          executed sequentially, one after the other.
         Selection (Conditional Statements): Allows executing different code blocks based on
          specified conditions, using constructs like if-else statements.
         Iteration (Loops): Enables repeating a set of instructions multiple times until a certain
          condition is met, using constructs like for, while, and do-while loops.
   Advantages:
         Provides clear and logical control flow, making it easier to understand and maintain the
          program's behavior.
         Offers fine-grained control over program execution through conditional statements and
          loops.
         Facilitates structured error handling and debugging, improving program reliability and
          stability.
   Example: In C programming, structural programming principles are applied when designing
   algorithms using sequences of statements, conditional expressions, and loops to achieve specific
   tasks or solve problems.
   Programming paradigms represent different approaches or styles for writing computer programs.
   Each paradigm provides a set of concepts, principles, and techniques for designing, structuring,
   and organizing code.
Imperative Programming:
      Definition: Imperative programming focuses on describing a sequence of statements that
       change the program's state. Programs are composed of commands that explicitly instruct
       the computer on how to perform tasks.
      Key Features: Mutable state, variables, assignment statements, loops, and conditional
       statements.
      Example Languages: C, Pascal, BASIC.
Declarative Programming:
      Definition: Declarative programming emphasizes describing the desired outcome or
       result without explicitly specifying the steps to achieve it. Programs focus on defining
       what needs to be done rather than how to do it.
      Key Features: Emphasis on expressions, functions, and data transformations. Divided
       into functional and logic programming paradigms.
      Example Languages: Functional - Haskell, Lisp; Logic - Prolog.
Object-Oriented Programming (OOP):
      Definition: Object-oriented programming organizes code around objects, which are
       instances of classes encapsulating data and behavior. It emphasizes concepts like
       inheritance, polymorphism, and encapsulation.
      Key Features: Classes, objects, inheritance, polymorphism, encapsulation.
      Example Languages: Java, C++, Python.
Functional Programming:
      Definition: Functional programming treats computation as the evaluation of
       mathematical functions. It emphasizes immutability, pure functions, and higher-order
       functions.
      Key Features: First-class functions, immutability, recursion, higher-order functions,
       lambda expressions.
      Example Languages: Haskell, Lisp, Scala, Erlang.
Logic Programming:
      Definition: Logic programming focuses on defining relations and rules to model
       problems as logical predicates. Programs specify the desired outcomes, and the
       interpreter infers the steps to achieve them.
      Key Features: Logical inference, pattern matching, unification, backtracking.
      Example Languages: Prolog, Datalog.
Procedural Programming:
      Definition: Procedural programming emphasizes writing procedures or routines that
       perform specific tasks. It focuses on the step-by-step execution of instructions to
       manipulate data.
      Key Features: Procedures, variables, loops, conditional statements.
      Example Languages: C, Pascal, BASIC.
Aspect-Oriented Programming (AOP):
      Definition: Aspect-oriented programming aims to modularize cross-cutting concerns
       such as logging, security, and error handling. It achieves this by separating such concerns
       from the main application logic.
      Key Features: Aspects, pointcuts, advice, weaving.
      Example Languages: AspectJ, Spring AOP.
APPLICATIONS OF C LANGUAGE
C programming language, being one of the oldest and most widely used programming languages,
finds applications in various domains. Here are some common applications of C:
   1. System Programming: C is commonly used for system programming tasks such as
       developing operating systems, device drivers, firmware, and low-level libraries. Its close-
       to-hardware nature and ability to manipulate memory efficiently make it suitable for
       these purposes.
   2. Embedded Systems: C is extensively used in embedded systems programming for
       microcontrollers, sensors, and other embedded devices. Its efficiency in terms of memory
       usage and execution speed makes it well-suited for resource-constrained environments.
   3. Compilers and Interpreters: Many compilers and interpreters for other programming
       languages are written in C. Its portability and ability to generate efficient machine code
       contribute to its popularity in this domain.
   4. Application Software: While C is not as commonly used for developing application
       software compared to higher-level languages like Java or Python, it is still employed in
      performance-critical applications such as gaming engines, graphics software, and real-
      time applications.
   5. Databases: C is used in developing database management systems (DBMS) and database
      engines due to its efficiency in handling data structures and memory management.
      Projects like SQLite, which is a lightweight and self-contained SQL database engine, are
      written in C.
   6. Networking: C is used for developing network-based applications such as web servers,
      network protocols, and communication software. Its ability to interact directly with
      system resources and sockets makes it suitable for implementing networking
      functionalities.
   7. Operating Systems: C has been extensively used in the development of operating
      systems such as Unix, Linux, and Windows. Many parts of these operating systems,
      including the kernel and core utilities, are written in C due to its efficiency and low-level
      control.
   8. Compilers and Tools: C is used for developing compilers, debuggers, code analyzers,
      and other software development tools. Its ability to manipulate memory and perform low-
      level operations makes it suitable for implementing such tools.
   9. High-Performance Computing: C is commonly used in scientific computing and high-
      performance computing (HPC) applications where performance is critical. Libraries such
      as OpenMP and MPI are commonly used with C for parallel computing tasks.
   10. Security Software: C is used for developing security software such as antivirus
      programs, encryption libraries, and network security tools. Its low-level control and
      efficient memory handling are essential for implementing security-related algorithms and
      protocols.
STRUCTURE OF C PROGRAM
There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:
   1. Documentation
   2. Preprocessor Section
   3. Definition
   4. Global Declaration
   5. Main() Function
   6. Sub Programs
1. Documentation
      This section consists of the description of the program, the name of the program, and the
       creation date and time of the program. It is specified at the start of the program in the
       form of comments. Documentation can be represented as:
       // description, name of the program, programmer name, date, time etc.
       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
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:
C
// Documentation
/**
* 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)
{
    return y + X;
}
Output
Sum: 75
DATA TYPES
        // 2x10^-4
        float c = 2E-4f;
        printf("%f\n", a);
        printf("%f\n", b);
        printf("%f", c);
        return 0;
}
Output:
9.000000
2.500000
0.000200
Double Data Type
       A Double data type in C is used to store decimal numbers (numbers with floating point
        values) with double precision. It is used to define numeric values which hold numbers
        with decimal values in C.
       The double data type is basically a precision sort of data type that is capable of holding
        64 bits of decimal numbers or floating points.
       Since double has more precision as compared to that float then it is much more obvious
        that it occupies twice the memory occupied by the floating-point type.
       It can easily accommodate about 16 to 17 digits after or before a decimal point.
       Range: 1.7E-308 to 1.7E+308
       Size: 8 bytes
       Format Specifier: %lf
Syntax of Double
       The variable can be declared as double precision floating point using the double
        keyword: double var_name;
// C Program to demonstrate
// use of double data type
#include <stdio.h>
int main()
{
        double a = 123123123.00;
        double b = 12.293123;
        double c = 2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
        printf("%lf", c);
        return 0;
}
Output:
123123123.000000
12.293123
2312312312.123123
Integer Constants:
    Integer constants represent whole numbers without any fractional part.
      Examples: 10, -5, 1000, etc.
      Integer constants can be represented in decimal, octal, or hexadecimal formats.
           1. Decimal format: 10, -20
           2. Octal format (prefixed with '0'): 077, -010
           3. Hexadecimal format (prefixed with '0x' or '0X'): 0xFF, -0x1A
Floating-Point Constants:
      Floating-point constants represent numbers with fractional parts.
      Examples: 3.14, -0.005, 100.0, etc.
      Floating-point constants are represented in decimal format and may include an exponent
       part.
           1. Decimal format: 3.14, -0.005
           2. Exponential notation: 1.23e-5, 1.5E2
Character Constants:
      Character constants represent individual characters enclosed within single quotes.
      Examples: 'A', 'b', '5', '$', etc.
      A character constant represents an ASCII value of the character.
      char ch = 'A';
String Constants:
      String constants represent sequences of characters enclosed within double quotes.
      Examples: "Hello", "C Programming", "1234", etc.
      String constants are represented as arrays of characters with a null-terminating character
       ('\0') at the end.
      char str[] = "Hello";
Symbolic Constants:
      Symbolic constants are identifiers that represent fixed values and are defined using the
       #define preprocessor directive.
       #define PI 3.14159
       #define MAX_LENGTH 100
                                  ENUMERATION CONSTANTS
Enumeration Declaration:
      Enumeration constants are declared using the enum keyword followed by the name of the
       enumeration.
      Inside the curly braces, you specify a list of named constants separated by commas.
              enum Color {
                   RED,
                   GREEN,
                   BLUE
              };
Enumeration Constants:
      Each constant within an enumeration gets an integer value starting from 0 for the first
       constant and incrementing by 1 for subsequent constants.
      You can also explicitly assign integer values to enumeration constants.
              NO enum Direction {
                   NORTH = 1,
                   SOUTH,
                   EAST,
                   WEST
              };
Using Enumeration Constants:
      Enumeration constants are typically used to declare variables, function parameters, or
       function return types.
              enum Color c = RED;
              enum Direction d = EAST;
Size of Enumeration Constants:
      By default, enumeration constants are of type int, and their size depends on the size of an
       integer on the particular platform.
      You can use the sizeof operator to determine the size of an enumeration constant.
              printf("Size of enum Color: %lu bytes\n", sizeof(enum Color));
      In C++, enumeration constants can be scoped using the enum class keyword to avoid
       naming conflicts.
               enum class Weekday {
                    MONDAY,
                    TUESDAY,
                    WEDNESDAY
               };
Example:
     #include <stdio.h>
     // Define an enumeration for colors
     enum Color {
          RED,
          GREEN,
          BLUE
     };
     int main() {
          enum Color c = RED;
          enum Direction d = EAST;
          printf("Color: %d\n", c); // Output: 0
          printf("Direction: %d\n", d); // Output: 3
          printf("Size of enum Color: %lu bytes\n", sizeof(enum Color)); // Output: 4 bytes
          return 0;
     }
                                             KEYWORDS
Keywords in C are reserved words that have predefined meanings and cannot be used as
identifiers (such as variable names, function names, etc.) in the program. These keywords are an
integral part of the C language syntax and serve specific purposes within the language. Here's a
list of keywords in C:
      auto: Specifies automatic storage duration for variables declared within a block.
      break: Terminates the execution of the nearest enclosing loop or switch statement.
      case: Defines a label within a switch statement.
      char: Declares a character data type.
      const: Specifies that a variable's value cannot be changed.
      continue: Skips the remaining code in the loop and proceeds to the next iteration.
      default: Specifies the default case within a switch statement.
      do: Introduces a do-while loop.
      double: Declares a double-precision floating-point data type.
      else: Introduces the else part of an if-else statement.
      enum: Declares an enumeration data type.
      extern: Declares a variable or function as externally defined.
      float: Declares a single-precision floating-point data type.
      for: Introduces a for loop.
      goto: Transfers control to a labeled statement.
      if: Introduces an if statement.
      int: Declares an integer data type.
          long: Declares a long integer data type.
          register: Suggests that a variable be stored in a CPU register.
          return: Returns a value from a function.
          short: Declares a short integer data type.
          signed: Declares a signed integer data type.
          sizeof: Returns the size of a data type or variable.
          static: Specifies static storage duration for variables.
          struct: Declares a structure data type.
          switch: Introduces a switch statement.
          typedef: Defines a new data type using an existing data type.
          union: Declares a union data type.
          unsigned: Declares an unsigned integer data type.
          void: Specifies that a function does not return a value or declares a pointer to void.
          volatile: Specifies that a variable may be changed externally.
          while: Introduces a while loop.
                       EXPRESSION
 Constant expressions: Constant Expressions consists of only constant values. A constant
   value is one that doesn’t change.
   Examples:
           5, 10 + 5 / 6.0, 'x’
 Integral expressions: Integral Expressions are those which produce integer results after
   implementing all the automatic and explicit type conversions.
   Examples:
           x, x * y, x + int( 5.0)
           where x and y are integer variables.
 Floating expressions: Float Expressions are which produce floating point results after
   implementing all the automatic and explicit type conversions.
   Examples:
           x + y, 10.75
           where x and y are floating point variables.
 Relational expressions: Relational Expressions yield results of type bool which takes a
   value true or false. When arithmetic expressions are used on either side of a relational
   operator, they will be evaluated first and then the results compared.
    Relational expressions are also known as Boolean expressions.
      Examples:
              x <= y, x + y > 2
    Logical expressions: Logical Expressions combine two or more relational expressions
      and roduces bool type results.
      Examples:
               x > y && x == 10, x == 10 || y == 5
    Pointer expressions: Pointer Expressions produce address values.
      Examples:
              &x, ptr, ptr++
              where x is a variable and ptr is a pointer.
    Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They
      are basically used for testing or shifting bits.
      Examples:
              x << 3
                       shifts three bit position to left
              y >> 1
                       shifts one bit position to right.
      Shift operators are often used for multiplication and division by powers of two.