Full C Language Notes – Unit-wise

UNIT 1: Basics of C Programming

1.1 Introduction to C

C is a general-purpose, procedural programming language developed by Dennis Ritchie at Bell Laboratories in 1972. It is designed for system programming and is widely used in operating systems, embedded systems, and application development.

History of C:

  • Developed in 1972 by Dennis Ritchie
  • Based on BCPL and B languages
  • ANSI C standardized in 1989 (C89/C90)
  • Updated standards: C99 (1999), C11 (2011), C17 (2017)

1.2 Features of C

  • Simple: Easy to learn and understand
  • Portable: Code runs on different platforms with minimal changes
  • Efficient: Fast execution speed
  • Low-level Access: Direct memory manipulation
  • Rich Library: Large collection of built-in functions
  • Modular: Supports functions and code reusability
  • Structured: Supports structured programming

1.3 Structure of a C Program

// Preprocessor directives
#include <stdio.h>
#define MAX 100

// Global declarations
int global_var = 10;

// Function prototypes
void function_name();

// Main function
int main() {
    // Local declarations
    int local_var = 20;
    
    // Executable statements
    printf("Hello, World!\n");
    
    return 0;  // Return statement
}

// Function definitions
void function_name() {
    // Function body
}

1.4 Tokens in C

Tokens are the smallest units of a C program.

Types of Tokens:

  1. Keywords: Reserved words (int, char, if, else, for, while, return, etc.)
  2. Identifiers: Names given to variables, functions, arrays (e.g., count, sum, calculate)
  3. Constants: Fixed values (integer, float, character, string)
  4. Strings: Sequence of characters in double quotes ("Hello")
  5. Operators: Symbols for operations (+, -, *, /, %, ==, &&, etc.)
  6. Special Symbols: Punctuation marks (, [], (), ;, ,, etc.)

1.5 Data Types in C

Basic Data Types:

  • int: Integer values (-32768 to 32767 or larger)
  • char: Single character ('A', 'z', '5')
  • float: Single precision floating-point (6 decimal places)
  • double: Double precision floating-point (15 decimal places)
  • void: No value (used with functions, pointers)

Derived Data Types:

  • Array: Collection of similar elements
  • Pointer: Stores memory address
  • Structure: Groups different data types
  • Union: Shares memory for members
  • Enum: User-defined data type for constants

Type Modifiers:

  • signed / unsigned (for int and char)
  • short / long (for int and double)
  • const (constant, cannot be modified)
  • volatile (may change unexpectedly)

1.6 Variables

Variable is a named memory location that stores data value.

Variable Declaration:

int age;
float salary;
char grade;
double pi;

Variable Initialization:

int age = 25;
float salary = 50000.50;
char grade = 'A';
double pi = 3.14159;

Rules for Identifiers:

  • Must start with letter or underscore
  • Can contain letters, digits, underscore
  • Cannot be a keyword
  • Case sensitive
  • No special characters except underscore

1.7 Constants

Types of Constants:

  • Integer: 10, -5, 0
  • Float: 3.14, -2.5, 0.0
  • Character: 'A', 'z', '5'
  • String: "Hello", "C Programming"

Defining Constants:

// Using #define
#define PI 3.14159
#define MAX_SIZE 100

// Using const keyword
const float PI = 3.14159;
const int MAX_SIZE = 100;

1.8 Operators

Arithmetic Operators:

  • + (Addition), - (Subtraction), * (Multiplication)
  • / (Division), % (Modulus - remainder)

Relational Operators:

  • < (Less than), > (Greater than), <= (Less than or equal)
  • >= (Greater than or equal), == (Equal to), != (Not equal)

Logical Operators:

  • && (Logical AND), || (Logical OR), ! (Logical NOT)

Assignment Operators:

  • = (Simple assignment), +=, -=, *=, /=, %= (Compound assignment)

Increment/Decrement Operators:

  • ++ (Increment), -- (Decrement)
  • Pre-increment (++x): Increments before use
  • Post-increment (x++): Increments after use

Bitwise Operators:

  • & (AND), | (OR), ^ (XOR), ~ (NOT)
  • << (Left shift), >> (Right shift)

Special Operators:

  • sizeof: Returns size of data type or variable
  • &: Address of operator
  • *: Pointer/dereference operator
  • ? : : Ternary/conditional operator

UNIT 2: Control Statements & Loops

2.1 Conditional Statements

if Statement:

if (condition) {
    // statements executed if condition is true
}

if-else Statement:

if (condition) {
    // statements if condition is true
} else {
    // statements if condition is false
}

if-else if-else Statement:

if (condition1) {
    // statements
} else if (condition2) {
    // statements
} else if (condition3) {
    // statements
} else {
    // statements
}

Nested if:

if (condition1) {
    if (condition2) {
        // statements
    }
}

Switch Statement:

switch (expression) {
    case constant1:
        // statements
        break;
    case constant2:
        // statements
        break;
    default:
        // statements
}

2.2 Loops

for Loop:

for (initialization; condition; increment/decrement) {
    // statements
}

// Example:
for (int i = 0; i < 10; i++) {
    printf("%d ", i);
}

while Loop:

while (condition) {
    // statements
}

// Example:
int i = 0;
while (i < 10) {
    printf("%d ", i);
    i++;
}

do-while Loop:

do {
    // statements
} while (condition);

// Example:
int i = 0;
do {
    printf("%d ", i);
    i++;
} while (i < 10);

Nested Loops:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        printf("%d %d\n", i, j);
    }
}

2.3 Loop Control Statements

break Statement:

Exits the loop immediately when encountered.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exits loop at i=5
    }
    printf("%d ", i);
}

continue Statement:

Skips current iteration and continues with next iteration.

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue;  // Skips printing 5
    }
    printf("%d ", i);
}

goto Statement:

Jumps to labeled statement (generally avoided).

label:
    // statements
    goto label;

UNIT 3: Arrays, Strings & Functions

3.1 Arrays

Array is a collection of similar data elements stored in contiguous memory locations.

Array Declaration:

data_type array_name[size];

// Examples:
int arr[10];           // Array of 10 integers
float marks[5];        // Array of 5 floats
char name[20];         // Array of 20 characters

Array Initialization:

int arr[5] = {1, 2, 3, 4, 5};
int arr[] = {1, 2, 3};  // Size automatically determined
int arr[5] = {1, 2};    // Remaining elements initialized to 0

Accessing Array Elements:

arr[0] = 10;        // First element
arr[4] = 50;        // Fifth element
printf("%d", arr[2]);  // Print third element

Multi-dimensional Arrays:

// 2D Array (Matrix)
int matrix[3][3];  // 3x3 matrix
matrix[0][0] = 1;  // First row, first column

// Initialization
int matrix[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

3.2 Strings

String is an array of characters terminated by null character '\\0'.

String Declaration:

char str[50];                    // Character array
char str[] = "Hello";           // String literal
char str[10] = {'H', 'e', 'l', 'l', 'o', '\0'};

String Functions:

  • strlen(): Returns length of string
  • strcpy(): Copies one string to another
  • strcat(): Concatenates two strings
  • strcmp(): Compares two strings
  • strstr(): Finds substring in string
  • strrev(): Reverses string (non-standard)
#include <string.h>

char str1[20] = "Hello";
char str2[20] = "World";
int len = strlen(str1);
strcpy(str1, str2);      // Copy
strcat(str1, str2);      // Concatenate
int result = strcmp(str1, str2);  // Compare

3.3 Functions

Function is a block of code performing specific task. Promotes code reusability and modularity.

Function Syntax:

return_type function_name(parameters) {
    // function body
    return value;
}

Types of Functions:

  • Built-in Functions: printf(), scanf(), strlen(), etc.
  • User-defined Functions: Created by programmer
  • Functions with return value
  • Functions without return value (void)

Function Prototype:

// Function declaration (prototype)
int add(int a, int b);

int main() {
    int result = add(5, 3);  // Function call
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}

Function Categories:

  • Functions with arguments and return value
  • Functions with arguments but no return value
  • Functions without arguments but with return value
  • Functions without arguments and return value

Recursion:

Function calling itself. Must have base case to terminate.

// Factorial using recursion
long long factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;  // Base case
    }
    return n * factorial(n - 1);  // Recursive call
}

UNIT 4: Pointers, Structures & Unions

4.1 Pointers

Pointer is a variable that stores memory address of another variable.

Pointer Declaration:

data_type *pointer_name;

// Examples:
int *ptr;        // Pointer to integer
float *fptr;     // Pointer to float
char *cptr;      // Pointer to character

Pointer Operations:

int num = 10;
int *ptr = &num;  // Store address of num

printf("%d", *ptr);  // Dereference: prints 10
printf("%p", ptr);   // Prints address of num
printf("%d", num);   // Prints 10

Pointer Arithmetic:

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;  // Points to first element

ptr++;           // Points to second element
printf("%d", *ptr);  // Prints 2
printf("%d", *(ptr + 2));  // Prints 4

Pointers and Arrays:

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;

// arr[i] is equivalent to *(arr + i)
printf("%d", arr[2]);     // Method 1
printf("%d", *(arr + 2)); // Method 2
printf("%d", ptr[2]);     // Method 3
printf("%d", *(ptr + 2)); // Method 4

Pointers to Pointers:

int num = 10;
int *ptr = &num;
int **pptr = &ptr;  // Pointer to pointer

printf("%d", **pptr);  // Prints 10

NULL Pointer:

int *ptr = NULL;  // Pointer pointing to nothing

if (ptr != NULL) {
    *ptr = 10;  // Safe to use
}

4.2 Structures

Structure groups related data of different types together.

Structure Definition:

struct structure_name {
    data_type member1;
    data_type member2;
    // ...
};

// Example:
struct Student {
    int roll_no;
    char name[50];
    float marks;
};

Structure Variable Declaration:

struct Student s1;  // Variable declaration
s1.roll_no = 101;
s1.marks = 85.5;
strcpy(s1.name, "John");

// Initialization
struct Student s2 = {102, "Jane", 90.0};

Accessing Structure Members:

// Using dot operator
s1.roll_no = 101;
printf("%d", s1.roll_no);

// Using pointer (arrow operator)
struct Student *ptr = &s1;
ptr->roll_no = 101;
printf("%d", ptr->roll_no);  // Arrow operator
printf("%d", (*ptr).roll_no);  // Alternative method

Array of Structures:

struct Student students[10];

for (int i = 0; i < 10; i++) {
    students[i].roll_no = i + 1;
    scanf("%s", students[i].name);
    scanf("%f", &students[i].marks);
}

Nested Structures:

struct Date {
    int day;
    int month;
    int year;
};

struct Employee {
    int id;
    char name[50];
    struct Date dob;  // Nested structure
};

typedef:

typedef struct Student Student;

Student s1;  // Now use Student instead of struct Student

4.3 Unions

Union is similar to structure but shares memory for all members. Only one member active at a time.

Union Definition:

union union_name {
    data_type member1;
    data_type member2;
    // ...
};

// Example:
union Data {
    int i;
    float f;
    char c;
};

Difference between Structure and Union:

  • Memory: Structure allocates separate memory for each member. Union shares memory (size = largest member).
  • Access: All structure members can be accessed. Only one union member active at a time.
  • Size: Structure size = sum of member sizes (with padding). Union size = size of largest member.

UNIT 5: File Handling & Advanced Topics

5.1 File Handling

File handling allows programs to read from and write to files.

File Operations:

  • fopen(): Opens a file
  • fclose(): Closes a file
  • fprintf(): Writes formatted data to file
  • fscanf(): Reads formatted data from file
  • fgets(): Reads string from file
  • fputs(): Writes string to file
  • fread(): Reads binary data
  • fwrite(): Writes binary data

File Modes:

  • "r": Read mode (file must exist)
  • "w": Write mode (creates new file or overwrites existing)
  • "a": Append mode (appends to end of file)
  • "r+": Read and write
  • "rb": Read binary mode
  • "wb": Write binary mode
  • "ab": Append binary mode

Writing to File:

FILE *fp;
fp = fopen("data.txt", "w");

if (fp == NULL) {
    printf("Error opening file!\n");
    return 1;
}

fprintf(fp, "Hello, World!\n");
fprintf(fp, "Number: %d\n", 42);
fclose(fp);

Reading from File:

FILE *fp;
char buffer[100];

fp = fopen("data.txt", "r");
if (fp == NULL) {
    printf("Error opening file!\n");
    return 1;
}

while (fgets(buffer, sizeof(buffer), fp) != NULL) {
    printf("%s", buffer);
}
fclose(fp);

5.2 Dynamic Memory Allocation

Allocating memory at runtime using malloc(), calloc(), realloc(), and freeing with free().

malloc():

int *ptr = (int *)malloc(sizeof(int) * 10);
if (ptr == NULL) {
    printf("Memory allocation failed!\n");
    exit(1);
}
// Use ptr
free(ptr);  // Free memory when done
ptr = NULL;  // Set to NULL

calloc():

int *ptr = (int *)calloc(10, sizeof(int));  // Initialized to 0
// Use ptr
free(ptr);
ptr = NULL;

realloc():

ptr = realloc(ptr, sizeof(int) * 20);  // Resize to 20 elements
// Use ptr
free(ptr);
ptr = NULL;

5.3 Command Line Arguments

Arguments passed to main function from command line.

Syntax:

int main(int argc, char *argv[]) {
    // argc: argument count (number of arguments)
    // argv: argument vector (array of strings)
    
    printf("Number of arguments: %d\n", argc);
    
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    
    return 0;
}

// Execution: ./program arg1 arg2 arg3

5.4 Preprocessor Directives

Instructions processed before compilation.

Common Directives:

  • #include: Includes header files
  • #define: Defines macros
  • #ifdef / #ifndef: Conditional compilation
  • #endif: Ends conditional block
  • #pragma: Implementation-specific directive

Macros:

#define MAX 100
#define SQUARE(x) ((x) * (x))
#define MIN(a, b) ((a) < (b) ? (a) : (b))

📚 Study Guide

Review each unit thoroughly. Practice programs for each topic. Understand concepts before moving to next unit. Use these notes along with practice questions and lab exercises. Regular practice is key to mastering C programming.

Unit Summary

UnitTopics CoveredDifficulty
Unit 1Basics, Tokens, Data Types, Variables, Constants, OperatorsBeginner
Unit 2Control Statements, Loops, Loop ControlBeginner
Unit 3Arrays, Strings, Functions, RecursionIntermediate
Unit 4Pointers, Structures, UnionsIntermediate
Unit 5File Handling, Dynamic Memory, Command Line ArgumentsAdvanced

Frequently Asked Questions

Q1: What is the best way to study C programming?

Start with basics (Unit 1), understand each concept thoroughly before moving forward. Practice coding for each topic. Write programs yourself rather than copying. Review regularly, solve practice questions, and work through lab exercises. Build small projects to apply concepts. Regular practice and hands-on coding are essential.

Q2: Which unit is most important for exams?

All units are important, but Unit 3 (Arrays, Strings, Functions) and Unit 4 (Pointers, Structures) are typically heavily weighted in exams. Pointers and structures are fundamental concepts that appear in many questions. However, don't skip any unit as concepts build upon each other.

Q3: How do I remember all the syntax and functions?

Practice regularly - write code daily. Don't try to memorize everything at once. Focus on understanding concepts first. Syntax becomes natural with practice. Keep a reference handy while learning. Create cheat sheets for commonly used functions. Most importantly, write code yourself rather than just reading.

Q4: What is the difference between structure and union?

Structure allocates separate memory for each member (size = sum of all members). Union shares memory among members (size = largest member). All structure members can be accessed simultaneously, but only one union member is active at a time. Use structures for grouping related data, unions for memory-efficient storage when only one member is needed.

Q5: Why are pointers considered difficult?

Pointers involve indirect memory access, which can be abstract. Understanding address vs value, pointer arithmetic, and memory management requires practice. Start with simple examples, draw memory diagrams, and practice with small programs. Once you understand that pointers store addresses, concepts become clearer. Practice is key to mastering pointers.

Q6: How important is file handling in C?

File handling is essential for real-world applications. It enables data persistence, reading configurations, logging, and data processing. While basic programs may not need files, most practical applications require file I/O. Understanding file operations is crucial for building complete applications. Practice reading and writing both text and binary files.

Q7: What should I focus on for lab exams?

Focus on writing complete, working programs. Practice common programs: array operations, string manipulation, matrix operations, searching/sorting, file handling, and structure programs. Understand algorithms, be able to explain your code, and practice debugging. Time management is important - practice writing code quickly and correctly.

Q8: How do I prepare for viva questions?

Understand concepts deeply, not just syntax. Be able to explain why things work, not just how. Practice explaining with examples. Review common viva questions, understand memory management, pointers, and compilation process. Be ready to write small code snippets and explain your lab programs. Practice explaining concepts in your own words.

Conclusion

C programming is a fundamental language that forms the basis for many other programming languages and systems programming. Mastering C provides a strong foundation for understanding computer systems, memory management, and low-level programming concepts. The concepts covered in these units are essential for any computer science student.

Regular practice, understanding concepts deeply, and building projects are key to mastering C programming. Don't rush through topics - take time to understand each concept thoroughly. Use these notes as a reference, but always practice coding yourself. Combine theoretical knowledge with hands-on practice for the best learning experience.

Related Links

🔹 Author: Dr. J. Siva Ramakrishna

🔹 Institution: Narayana Engineering College, Gudur

🔹 Last Updated: 9 January 2026