Mangayarkarasi College of Engineering

The Coders Club

Content for Week 1 - Basics and Syntax

Monday Maverick

What Are Header Files?

  • They contain function declarations, macros, constants, and data type definitions.
  • Included in source files using the #include directive to share code across multiple files.
  • Facilitate modularity, code reuse, and separation of interface from implementation.

Techie Tuesday

Variables:

Variables are named locations in memory that are used to hold a value that may be modified by the program.

The syntax for declaring a variable is:

Data_type variableName;

Valid Examples:

int age = 21;
float salary = 4564.50;
int marks;
int acc_type;
char ch = 'y';
char name[20] = "apollo";

Invalid Examples:

int 5marks;
int @host;
int acc no$;

Rules for framing a variable:

  • The first character in the variable name must be an alphabet.
  • Alphabets can be followed by a number of digits or underscores _.
  • No commas or blank spaces are allowed within a variable name.
  • No special characters other than underscore (_) can be used in a variable name.
  • The variable name should not be a keyword.
  • Variable names are case sensitive.
  • It should not be of length more than 31 characters.

Syntax Snapshots Wednesday

Basic Syntax of a C Program:


#include <stdio.h> // Preprocessor directive

// main function - entry point of the program
int main() {
    // Print output to the screen
    printf("Hello, World!\\n");

    return 0; // Exit the program
}

Output:

Hello, World!

Explanation of Each Part:

  1. Every C program must have a main() function.
  2. Statements must end with a semicolon ;
  3. C is case-sensitive.
  4. Code is typically written in .c files and compiled using tools like gcc.

Te Ta Thursday

#include <stdio.h>
#define ADD(a, b) ((a) + (b))
int main() { printf("%d\\n", ADD(5, 7)); return 0; }

Output:

12

Explanation:

  1. #define ADD(a, b) ((a) + (b)) This line defines a macro named ADD that takes two arguments, a and b. The macro expands to the expression ((a) + (b)), which calculates the sum of a and b. The parentheses around a and b are used to ensure that the macro works correctly even if the arguments are expressions themselves.
  2. printf("%d\n", ADD(5, 7)); Here, the ADD macro is used to calculate the sum of 5 and 7. The macro expands to ((5) + (7)), which evaluates to 12. The result is then passed to printf(), which prints the value to the console.

How it works:

  1. The preprocessor expands the ADD macro to ((5) + (7))
  2. The compiler evaluates the expression ((5) + (7)) to 12.
  3. The printf() function prints the result, 12, to the console.

Using macros like ADD can be useful for simple calculations, but be cautious when using complex macros, as they can lead to unexpected behavior.

Function Friday

Functions:

Functions are blocks of code designed to perform specific tasks. They enhance modularity, code reuse, and readability.

Types of Functions:

  1. Library Functions: Predefined in header files (printf(),scanf(),strlen(), etc.).
  2. User-Defined Functions: Created by the programmer for specific tasks.
  3. Recursive Functions: Functions that call themselves.

Basic Function Syntax:

#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
    int result = add(5, 7);
    printf("Sum: %d\\n", result);
    return 0;
}
// Function definition
int add(int a, int b) {
    return a + b;
}

Output:

Sum: 12

Function Components Explained:

  • Function Declaration: Specifies return type, function name, and parameters.
  • Function Definition: Contains the actual implementation.
  • Function Call: Invokes the function with arguments.

Function Advantages:

  • Encourages code reusability.
  • Breaks problems into smaller manageable chunks.
  • Improves readability and maintainability.

Fun Fact: In C, functions must be declared before they are used, unless included in header files.

Mindmash

1. How can a C programmer separate function declarations and avoid multiple inclusions?

  1. Use one .c file for everything.
  2. Use .h files with include guards or #pragma once.
  3. Only use standard headers.
  4. Avoid using headers completely.

2. Which of the following variable names are valid in C?

  1. int 2cool4school;
  2. float _temperature;
  3. char full name[50];
  4. double classAverage;
  5. int break;

3. What is required in every C program to serve as the entry point?

  1. main() function
  2. int main()
  3. char full name[50];
  4. void main()
  5. Return type of main (int)

4. What does the #define directive do in C?

  1. Declares a variable
  2. Defines a macro
  3. Includes a library
  4. Defines a function

5. Which of the following scenarios best demonstrates the advantage of using functions in C?

  1. Writing all logic inside main() without breaking it into smaller tasks.
  2. Using separate functions for repeated calculations to improve modularity.
  3. Avoiding function entirely and using global variables for efficiency
  4. Copy-pasting code snippets multiple times instead of defining reusable functions.

Content for Week 2 - Control Structures

Monday Maverick

Introduction to Control Structures:

Control structures allow you to change the flow of program execution based on conditions.

Types:

  • Decision-making (conditional).
  • Looping (iterative).
  • Jumping (branching).

Explanation:

  • Decision-Making Structures: Used to execute a block of code only if a condition is true.
  • Looping Structures: Used to repeat a block of code multiple times.
  • Jumping Statements: Used to alter the normal flow of a program.

Techie Tuesday

Conditional Statements in C:

Conditional statements are used to make decisions in a program. Based on whether a condition is true or false, different blocks of code will be executed.

Types:

  1. if Statement
  2. if...else Statement
  3. else if Ladder
  4. switch Statement

Detailed Explanation of Types:

  1. if Statement:

    Used when you want to execute a block of code only if a condition is true.

    Syntax:
    if (condition) {
        //code to execute if condition is true
    }
  2. if...else Statement:

    Used when you want to choose between two blocks of code.

    Syntax:
    if (condition) {
        //code to execute if condition is true
    }
    else {
        //code if false
    }
  3. else if Ladder:

    Used when you have multiple conditions to check in sequence.

    Syntax:
    if (condition) {
        //code to execute if condition is true
    }
    else if (condition) {
        //code
    }
    else if (condition n) {
        //code
    }
    else {
        //default code
    }
  4. switch Statement:

    Used to replace multiple else if blocks when comparing a single variable against many values.

    Syntax:
    switch (expression) {
    case value1:
        //code
        break;
    case value2:
        //code
        break;
    default:
        //code
        break;
    }

Syntax Snapshots Wednesday

Syntax of if Statement in C:

if (condition) {
    //Code to execute if condition is true
}

Example C program using if:

#include <stdio.h>

int main() {
    int number;
    printf("Enter an integer: ");
    scanf("%d", &number);
    if (number > 0) {
        printf("%d is a positive number.\n", number);
    }
    return 0;
}

Output:

Enter a number: 8 The number is positive.

Te Ta Thursday

  1. Switch Statement with Enumerations:

    Using switch statements with enumerations to handle different cases.
  2. typedef enum {
        RED,
        GREEN,
        BLUE
    } Color;
    
    void printColor(Color c) {
        switch(c){
            case RED:
                printf("Red\n");
                break;
            //..
        }
    }

    Expected Output:

    Red
  3. Nested Loops with Labels:

    Using labels to control nested loopexecution.
  4. outer:
    for(int i = 0; i < 5; i++) {
        for(int j = 0; j < 5; j++) {
            if (i == 3) break outer;
            printf("%d %d\n",i,j);
        }
    }

    Expected Output:

    0 0 0 1 0 2 0 3 0 4 1 0 1 1 1 2 1 3 1 4 2 0 2 1 2 2 2 3 2 4
  5. Break and Continue Statements:

    Controlling loop execution with break and continue.
  6. for ( int i = 0; i < 5; i++) {
        if (i == 3)
            continue; //Skips 3
        if (i == 4)
            break; //Stop at 4
        printf("%d\n",i);
    }

    Expected Output:

    0 1 2
  7. if-else Statements with Conditional Operators:

    Simplifying if-else with conditional operators.
  8. 
    int x=5;
    int result = (x>10) ? 1 : 0; //result = 0
    printf("%d\n",result);
                    

    Expected Output

    0

Function Friday

do...while Loop:

Executes a block of code at least once, and then continues to repeat the block as long as a specified condition remains true.

Syntax:


do {
    // Code to execute
} while (condition);
            

Example:


#include <stdio.h>
int main() {
    int x = 5;
    do {
        printf("Value: %d\n",x); // Corrected printf format string
        x--;
    } while (x > 0);
    return 0;
}
            

Output:

Value: 5 Value: 4 Value: 3 Value: 2 Value: 1

Simulating for-each Loop in C:

C doesn't have a direct for-each, but arrays can be traversed using a for loop.

Example:


#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40};
int size = sizeof(numbers) / sizeof(numbers[0]);
for(int i = 0; i < size; i++) {
printf("Value: %d\n", numbers[i]);
}
return 0;
}
            

Output:

Value: 10 Value: 20 Value: 30 Value: 40

Code Explanation:

  • Defines an array numbers[]
  • Calculates the array size using sizeof(numbers) / sizeof(numbers[0])
  • Iterates through elements, printing each value dynamically

Mindmash

1.What does a control structure do in programming?

  1. It stores data in memory.
  2. It defines the order in which instructions are executed.
  3. It displays output to the user.
  4. It converts high-level code to machine code.

2. What will be printed when the following program is executed?


#include <stdio.h>
int main() {
    int a = 5, b = 10;

    if (a < b)
        if (a != 5)
            printf("A is not five\n");
        else
            printf("A is five\n");
    else
        printf("A is not greater than B\n");

    return 0;
}
            
  1. A is not five.
  2. A is five.
  3. A is not greater than B.
  4. Compilation Error

3. How can a C program use an if statement to check if a number entered by the user is positive?

Sample code / the answer may differ according to your idea

#include <stdio.h>
int main() {
    int number;
    printf("Enter an integer: ");
    scanf("%d", &number);
    if (number > 0) {
        printf("%d is a positive number.\n", number);
    }
    return 0;
}
            

4. What is the purpose of using enumerations with switch statements in C?

  1. To simplify code readability.
  2. To improve code performance.
  3. To handle different cases based on a specific value.
  4. To reduce memory usage.

5.Imagine you have a vending machine that requires a customer to press a button at least once to check if an item is available. If the item is available, they can continue pressing to get more items. Which loop structure in C works similarly to this vending machine process?

  1. for loop.
  2. while loop.
  3. do...while loop.
  4. switch statement.

Content for Week 3 - Functions and Arrays Control Structure

Monday Maverick

What is a function?

A function is a block of code that performs a specific task. It improves modularity and reusability.

Syntax:

return_type function_name(parameters) {
    // code
}

Example:

#include <stdio.h>

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

int main() {
    int sum = add(5, 10);  // Function call
    printf("Sum is: %d", sum);
    return 0;
}

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

Output:

Sum is: 15

Techie Tuesday

Arrays in C:

An array in C is a collection of elements, all of the same type, stored in contiguous memory locations.

Syntax:


data_type array_name[size];
// Example: int myArray[10];
                

Type: The data type of the array elements (e.g., int, float).
Size: The number of elements the array can store.

Example:


#include <stdio.h>
int main() {
    int arr[5] = {1, 2, 3, 4, 5};  // Declaration and initialization
    printf("Element at index 2: %d\n", arr[2]);
    return 0;
}

Output:

Element at index 2: 3

Control Structures for Arrays in C:

Control structures like loops are used to traverse and manipulate arrays in C.

Example with for loop:

#include <stdio.h>
int main() {
    int arr[5] = {1, 2, 3, 4, 5};    
    // Loop through array and print each element
    for (int i = 0; i < 5; i++) {
        printf("Element at index %d: %d\n", i, arr[i]);
    }
    return 0;
}
                

This code prints all the elements of the array arr.

Output:

Element at index 0: 1 Element at index 1: 2 Element at index 2: 3 Element at index 3: 4 Element at index 4: 5

Syntax Snapshots Wednesday

Let see about pointers in C program:

A pointer is a variable that stores the address of another variable. Pointers are powerful tools that enable efficient memory access, dynamic memory management, and are essential in data structures like linked lists and trees.

Example program:


#include <stdio.h>

int main() {
    int a = 10;          // Declare an integer variable
    int *ptr;            // Declare a pointer to int

    ptr = &a;            // Store address of variable 'a' in pointer 'ptr'

    // Print the value and address
    printf("Value of a: %d\n", a);
    printf("Address of a: %p\n", &a);
    printf("Value stored in ptr (address of a): %p\n", ptr);
    printf("Value pointed to by ptr (value of a): %d\n", *ptr);

    return 0;
}
            

Output:

Value of a: 10 Address of a: 0x7ffee0b01234 (This will be a hexadecimal address) Value stored in ptr (address of a): 0x7ffee0b01234 (This will be the same as Address of a) Value pointed to by ptr (value of a): 10

Te Ta Thursday

Passing Arrays to Functions:

One lesser-known aspect is how arrays are passed to functions in C. When an array is passed to a function, it decays into a pointer to the first element. This means the function receives a pointer, not the entire array.

Example program:

#include <stdio.h>

// Function to print array elements
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    printArray(numbers, 5);
    return 0;
}

In this example, arr in the printArray function is essentially a pointer to the first element of the numbers array. The size parameter is necessary because the function doesn't know the size of the array otherwise.

Output:

1 2 3 4 5

Function Friday

Function Pointers in C:

A function pointer stores the address of a function and allows dynamic invocation.

Syntax:


// Function pointer declaration
void (*funcPtr)();

// Assign function address to pointer
funcPtr = &greet;

// Call function using pointer
funcPtr();

            

Example:


#include <stdio.h>
// Function to display a message
void greet() {
    printf("Hello, Function Pointers!\n");
}
int main() {
    void (*funcPtr)(); // Declare function pointer
    funcPtr = &greet;  // Assign function address
    funcPtr();         // Call function using pointer
    return 0;
}

            

Output:

Hello, Function Pointers!

Why use function pointers?

  • Enables callback functions in programs like sorting algorithms.
  • Used in event-driven programming and function abstraction.

Deeper Dive:

  • Function pointers allow runtime function selection, making programs more flexible.
  • They are essential for implementing state machines, commonly used in embedded systems.

Variable-Length Arrays (VLA):

Unlike fixed-size arrays, VLAs allow defining arrays with dynamic sizes at runtime (supported in modern C versions).

Syntax:


int n;
scanf("%d", &n);  // Get array size from user
int arr[n];       // Declare a variable-length array
            

Example:


int main() {
    int n;
    printf("Enter array size: ");
    scanf("%d", &n);
    int arr[n];  // Variable-length array
    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }
    printf("Array contents:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

            

Expected Output:

Enter array size: 5 Array contents: 1 2 3 4 5 --- Enter array size: 3 Array contents: 1 2 3 --- Enter array size: 10 Array contents: 1 2 3 4 5 6 7 8 9 10

Why use VLAs?

  • Allows dynamic array sizing at runtime.
  • Useful when the required array size is unknown before execution.

Deeper Dive:

  • Simpler Syntax Compared to malloc.
  • Eliminates the need for manual memory allocation & deallocation.

When Should You Use VLAs?

  • When you need simple runtime array sizing for small arrays.
  • When writing temporary arrays that won’t persist beyond function scope

Mindmash

1. Define what a "function" is in C programming, and explain how its use contributes to better code quality.

Expected answer

A function in C is a block of code that performs a specific task. It promotes modularity and code reuse, making programs easier to debug, read, and maintain by breaking complex problems into smaller parts.

2. Which of the following statements about arrays in C is TRUE, considering pointer behavior, memory allocation, and function interactions?

  1. The name of an array can be incremented like a pointer, because it points to the base address of the array.
  2. When an array is passed to a function, the entire array is copied and operated on as a separate entity.
  3. Arrays in C can have dynamic lengths declared using variables in standard C90.
  4. The expression *(arr + i) is equivalent to arr[i] in terms of accessing array elements.

3. What concept is primarily demonstrated by the output of the following C program involving a variable and a pointer?


#include <stdio.h>
int main() {
    int a = 10; 
    int *ptr;            
    ptr = &a;           
    printf("Value of a: %d\n", a);
    printf("Address of a: %p\n", &a);
    printf("Value stored in ptr (address of a): %p\n", ptr);
    printf("Value pointed to by ptr (value of a): %d\n", *ptr);
    return 0;
}
            
  1. The program shows how to use a pointer to access the address and value of a variable.
  2. The program swaps two integers using pointers.
  3. The program performs dynamic memory allocation using malloc.
  4. The program uses arrays to store multiple integer values.
  5. The program demonstrates pointer arithmetic with arrays.

4. Why is the size parameter typically necessary when an array is passed to a function in C, as shown in the printArray example?


#include <stdio.h>
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    printArray(numbers, 5);
    return 0;
}
            
  1. The program shows how to use a pointer to access the address and value of a variable.
  2. To ensure the array elements are passed by value instead of by reference.
  3. Because when an array decays to a pointer, the function loses information about its original size.
  4. To allow the function to modify the array's dimensions dynamically.

5. What is the primary advantage of using function pointers in C?

  1. They allow defining arrays with dynamic sizes at runtime.
  2. They enable runtime function selection and dynamic invocation.
  3. They eliminate the need for manual memory allocation.
  4. They are used to declare fixed-size arrays.

Content for Week 4 - Pointers and Strings

Monday Maverick

What is a Pointer?

A pointer is a variable that stores the memory address of another variable.

Syntax:


data_type *pointer_name;
            

Examples:


int *ptr;        // pointer to an int
float *fptr;     // pointer to a float
char *cptr;      // pointer to a char
double *dptr;    // pointer to a double          

Note: Even though * is used in the declaration, the pointer itself just stores an address.

Example:


int a = 10;
int *ptr = &a;   // ptr now holds the address of a
        

Techie Tuesday

What is a String in C?

A string is a sequence of characters terminated by a null character '\0'. In C, strings are represented as arrays of characters. Think of a string as a sentence or word stored in memory.

Example:

#include <stdio.h>
int main() {
    char name[] = "Welcome";
    printf("Hello, %s!\n", name);
    return 0;
}

Output:

Hello, Welcome!

"Welcome" is a string stored in a character array.

Pointers with Strings in C:

A pointer to a string is a pointer that stores the address of the first character of the string. It’s a more memory-efficient and flexible way to handle strings than using character arrays.

Example:

#include <stdio.h>
int main() {
    char *greet = "Welcome!";
    printf("%s\n", greet);
    return 0;
}

Output:

Welcome!

Explanation:

  • char *greet ➡ Pointer to the string "Welcome!"
  • %s in printf prints the full string starting from the pointer.

Syntax Snapshots Wednesday

C Program using String Function (strlen):


#include <stdio.h>
#include <string.h>
int main() {
    char str[100];
    
    printf("Enter a string: ");
    gets(str);  // Note: gets() is unsafe, use fgets() in real programs

    int length = strlen(str);  // Using string function

    printf("Length of the string is: %d\n", length);
    
    return 0;
}

Output:

Hello, Welcome!Enter a string: Hello Length of the string is: 5 --- Enter a string: C Programming Length of the string is: 13 --- Enter a string: Length of the string is: 0

Explanation: strlen() is a string function that returns the length of the string.

C Program using String Pointer:

#include <stdio.h>
int main() {
    char str[] = "Hello, World!";
    char *ptr = str;

    printf("String using pointer:\n");
    while (*ptr != '\0') {
        printf("%c", *ptr);
        ptr++;
    }

    return 0;
}

Output:

String using pointer: Hello, World!

Explanation:

  • char *ptr = str; assigns a pointer to the beginning of the string.
  • while (*ptr != '\0') traverses the string using the pointer.

Te Ta Thursday

Pointer Arithmetic with Strings:

You can use pointer arithmetic to traverse strings.

Example:


char str[] = "Hello";
char *ptr = str;
while (*ptr != '\0') {
    printf("%c", *ptr);
    ptr++;
}

Expected Output:

Hello

This concept is powerful, but it requires careful handling to avoid buffer overflows and other issues.

String Literal vs. Character Array:

In C, string literals and character arrays are not exactly the same.

Example:


char *str1 = "Hello"; // string literal (read-only)
char str2[] = "Hello"; // character array (modifiable)

// str1[0] = 'h'; // would cause a segmentation fault
str2[0] = 'h'; // okay

What may be in the output:

str1: Hello str2: hello

This distinction is important to understand when working with strings in C.

Function Friday

Finding a Character in a String - using Pointers:

This program shows how to write a simple function to search for a character in a string using pointers.

Example:


#include <stdio.h>
int findChar(char *text, char target) {
    int index = 0;
    while (*text != '\0') {
        if (*text == target) {
            return index; // Found it!
        }
        text++;
        index++;
    }
    return -1; // Not found
}

int main() {
    char myWord[] = "apple";
    char charToFind = 'p';

    int position = findChar(myWord, charToFind);

    if (position != -1) {
        printf("'%c' is at index %d\n", charToFind, position);
    } else {
        printf("'%c' not found\n", charToFind);
    }
    return 0;
}

Output:

'p' is at index 1

Finding a Character in a String - using strchr():

This program demonstrates using the built-in strchr() function for the same task, showing its simplicity.

Example:


#include <stdio.h>
#include <string.h>
int main() {
    char mySentence[] = "orange";
    char searchFor = 'a';

    // strchr returns a pointer to the char if found, or NULL
    char *found = strchr(mySentence, searchFor);

    if (found != NULL) {
        // Calculate index by subtracting pointers
        int index = found - mySentence;
        printf("'%c' is at index %d\n", searchFor, index);
    } else {
        printf("'%c' not found\n", searchFor);
    }
    return 0;
}

Output:

'a' is at index 3

Mindmash

1. What is the output of the following code?

int a = 10;
int *p = &a;
printf("%d", *p);
  1. 10
  2. Address of a.
  3. Garbage value.
  4. Compile-time error.

2. What will be the output of the following C code?

#include <stdio.h>
int main() {
    char str1[] = "Hello";
    char *str2 = "Hello";

    str1[0] = 'H';
    str2[0] = 'H';

    printf("str1: %s\n", str1);
    printf("str2: %s\n", str2);

    return 0;
}
  1. str1: Hello
    str2: Hello
  2. str1: Hello
    Segmentation Fault
  3. str1: Hello
    str2: hello
  4. Compile-time error.

3. In this C program, what technique is used to display the string on screen?

#include <stdio.h>
int main() {
    char str[] = "Hello, World!";
    char *ptr = str;

    printf("String using pointer:\n");
    while (*ptr != '\0') {
        printf("%c", *ptr);
        ptr++;
    }

    return 0;
}
  1. It prints the string using a string pointer and while loop.
  2. It uses strlen() function to display the string.
  3. It copies the string using strcpy() before printing.
  4. It sorts the string characters alphabetically before printing.

4. What happens when an array is passed to a function in C?

  1. The entire array is copied and passed to the function.
  2. The array decays into a pointer to the first element.
  3. To allow the function to modify the array's dimensions dynamically.
  4. The function receives a reference to the original array.
  5. The array is not passed at all, and the function uses a default value.

5. Given char word[] = "grape"; and char target = 'e'; what index would findChar(word, target) return?

  1. 4
  2. 3
  3. 0
  4. -1

Content for Week 5 - Structures and File Handling

Monday Maverick

Structures in C:

A structure in C is a user-defined data type that allows you to combine variables of different types under one name.

Syntax:

struct Student {
    int id;
    char name[50];
    float marks;
};

How to Declare and Use:

struct Student s1;

s1.id = 101;
strcpy(s1.name, "John");
s1.marks = 89.5;

printf("%d %s %.2f", s1.id, s1.name, s1.marks);

Expected Output:

101 John 89.50

Techie Tuesday

File Handling in C Programming:

File handling in C allows you to create, open, read, write, and close files — making your programs more powerful by storing and retrieving data from files instead of just using memory!

Header File Required:

#include <stdio.h>

This must be included to use file functions like fopen(), fclose(), fprintf(), fscanf(), etc.

How to Declare and Use:

Operation Function
Create/Open fopen()
Close fclose()
Read fscanf(), fgets()
Write fprintf(), fputs()
Move cursor fseek(), ftell()

File Modes in fopen()

Mode Description
"r" Read
"w" Write (overwrite)
"a" Append (add at end)
"r+" Read & Write
"w+" Write & Read (overwrite)
"a+" Append & Read

Always Remember:

  • Check if the file opened successfully (if (fp == NULL))
  • Always fclose(fp) to avoid memory leaks.

Syntax Snapshots Wednesday

C Program for File Handling (Write + Read):

#include <stdio.h>
int main() {
    FILE *fptr;
    char data[100];

    // Writing to the file
    fptr = fopen("myfile.txt", "w"); // open in write mode
    if (fptr == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    printf("Enter some text to write into the file: ");
    fgets(data, sizeof(data), stdin);
    fprintf(fptr, "%s", data);
    fclose(fptr);
    printf("Data written to file successfully.\n");

    // Reading from the file
    fptr = fopen("myfile.txt", "r"); // open in read mode
    if (fptr == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    printf("Reading from the file:\n");
    while (fgets(data, sizeof(data), fptr) != NULL) {
        printf("%s", data);
    }
    fclose(fptr);

    return 0;
}

Output:

Enter some text to write into the file: Hello, C programming! Data written to file successfully. Reading from the file: Hello, C programming!

Content in myfile.txt :

Hello, C programming!

Te Ta Thursday

Structures in C:

Imagine you have a collection of data that you want to store together, like a person's details. You can create a struct to hold this data:

struct Person {
    int age;
    char name[20];
};

Some cool things about structures:

  • Structure Padding: When you define a structure, the compiler might add some extra space (padding) between members to ensure they're aligned properly in memory.

    For example:

    struct Example {
        char a; // 1 byte
        int b;  // 4 bytes
    }; // The total size might be 8 bytes due to padding
  • Bit Fields: You can specify the number of bits for a structure member, which is useful when working with limited memory:
    struct PackedData {
        unsigned int flag: 1;
        unsigned int mode: 2;
    };
  • Nested Structures: You can define a structure within another structure:
    struct Address {
        char street[20];
        char city[10];
    };
    
    struct Person {
        int age;
        char name[20];
        struct Address address;
    };

File Handling in C:

File handling allows you to read and write data to files. Here are some key functions:

  • fopen(): Opens a file.
  • fread() and fwrite(): Read and write data to files.
  • fclose(): Closes a file.

Example:

FILE *file = fopen("example.txt", "w");
if (file != NULL) {
    fprintf(file, "Hello, world!");
    fclose(file);
}

Expected Output in example.txt :

Hello, world!

Function Friday

Store and Retrieve Structured Data Using File Handling:

This program helps you save a student's info—like their name, ID, and marks—into a file. Then it opens the file and shows you what was saved, kind of like writing something down and reading it later.

Example:

#include <stdio.h>
struct Student {
    int id;
    char name[50];
    float marks;
};

// Function to get user input and write to file
void writeStudentToFile() {
    struct Student s;
    
    printf("Enter Student ID: ");
    scanf("%d", &s.id);
    
    printf("Enter Student Name: ");
    scanf(" %[^\n]", s.name);  // reads string with spaces
    
    printf("Enter Marks: ");
    scanf("%f", &s.marks);

    FILE *fp = fopen("student.txt", "w");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return;
    }

    fprintf(fp, "%d\n%s\n%.2f\n", s.id, s.name, s.marks);
    fclose(fp);
    printf("Student data saved successfully.\n\n");
}

// Function to read from file and display
void readStudentFromFile() {
    struct Student s;
    FILE *fp = fopen("student.txt", "r");

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

    fscanf(fp, "%d\n", &s.id);
    fgets(s.name, sizeof(s.name), fp);
    fscanf(fp, "%f", &s.marks);

    // Remove trailing newline from name (if any)
    if (s.name[strlen(s.name) - 1] == '\n') {
        s.name[strlen(s.name) - 1] = '\0';
    }

    fclose(fp);

    printf("Student Data from File:\n");
    printf("ID: %d\n", s.id);
    printf("Name: %s\n", s.name);
    printf("Marks: %.2f\n", s.marks);
}

int main() {
    writeStudentToFile();
    readStudentFromFile();
    return 0;
}

Output:

Enter Student ID: 105 Enter Student Name: Dave Enter Marks: 92.5 Student data saved successfully. Student Data from File: ID: 105 Name: Dave Marks: 92.50

Mindmash

Quiz goes live on 28/6/25 at 6.00 PM IST!