MH State Board All Notes Free5th to 12th & BA, BSc, B.Com 🔍

Programming in 'C' CBCCA3T03

RTMNU B.Com Semester 3 · Major: Computer Applications · 4 units · notes for every unit

UniversityRTMNU – Rashtrasant Tukadoji Maharaj Nagpur University, Nagpur
CourseB.Com (Four Year UG Programme, NEP 2020)
SemesterSemester III
Paper codeCBCCA3T03
Paper titleProgramming in 'C'
CategoryMajor – Computer Applications
Credits4 credits (60 hours theory)
MarksTheory exam: 80 marks + 20 marks internal (CIE) = 100; minimum 40 to pass
Syllabusas per official RTMNU NEP 2020 B.Com syllabus (Direction No. 21 of 2024), session 2025-26

Unit topics below follow the official RTMNU syllabus. The practical paper CBCCA3P01 is separate. RTMNU official website · All RTMNU B.Com papers

Units

  1. 1Unit I: Introduction to C, Data Types, I/O and OperatorsNotes
  2. 2Unit II: Storage Classes, Control Statements and FunctionsNotes
  3. 3Unit III: Arrays, Strings, Pointers and Dynamic Memory AllocationNotes
  4. 4Unit IV: Structures, Unions and FilesNotes

RTMNU B.Com Sem 3 · CBCCA3T03 · Unit I

Unit I: Introduction to C, Data Types, I/O and Operators

Syllabus topics (RTMNU)

  • Design methods
  • Programming language
  • Translators
  • Introduction to C
  • C character set and keywords
  • Escape sequence
  • Constants and variables
  • Data types
  • Conversion specification
  • Input and output statements in C
  • Operators and expressions (Arithmetic, Relational, Logical, Assignment, Ternary, Bit Wise and Increment & Decrement Operator)

Design Methods

Definition: A design method is a planned way of solving a problem before writing the program. It breaks the problem into clear steps so that coding becomes easy and errors are fewer.

  • Top-down design: start with the main problem and divide it into smaller sub-problems (modules) until each part is simple. Example: a billing program is divided into input, calculation of GST and printing of bill.
  • Bottom-up design: first build small, basic modules (like a function to add tax) and then join them to make the full program.
  • Modular design: the program is made of independent modules (functions in C). Each module does one job and can be tested separately.
  • Structured programming: uses only three control structures – sequence, selection (if/switch) and iteration (loops) – and avoids goto. C supports this style.

Tools of design: (1) Algorithm – step-by-step solution written in simple language; (2) Flowchart – diagram of the algorithm using symbols (oval = start/stop, parallelogram = input/output, rectangle = process, diamond = decision, arrows = flow); (3) Pseudocode – English-like code.

Programming Language and Translators

Programming language: a set of words, symbols and rules used to give instructions to a computer.

  • Machine language (low level): only 0s and 1s; directly understood by the CPU; very fast but hard to write.
  • Assembly language: uses short codes called mnemonics (ADD, MOV, SUB); needs an assembler.
  • High level language: English-like words (C, C++, Java, Python); easy to write and portable; needs a compiler or interpreter.

Translator: a program that converts a program written in assembly or high level language (source code) into machine language (object code).

PointCompilerInterpreter
WorkingTranslates the whole program at onceTranslates and runs line by line
Speed of executionFast (object file is created once)Slow (translation every time)
ErrorsShows all errors after compilingStops at the first error
Object fileCreates an executable fileNo separate file
ExamplesC, C++BASIC, Python

Assembler converts assembly language into machine code. Other helpers: the linker joins object code with library code, and the loader loads the program into memory for running.

Introduction to C

C was developed by Dennis Ritchie at AT&T Bell Laboratories, USA, in 1972. It came from the earlier languages BCPL and B. The UNIX operating system was written mainly in C. It is called a middle level language because it has high level features and can also work close to hardware.

Features of C:

  1. Simple and structured – program is divided into functions.
  2. Portable – a C program can run on different machines with little change.
  3. Fast and efficient – compiled code runs quickly.
  4. Rich library – many built-in functions (printf, sqrt, strlen).
  5. Pointers – direct access to memory.
  6. Extensible – users can add their own functions.
Structure of a simple C program
#include <stdio.h> /* header file */
int main() /* execution starts here */
{
    printf("Welcome to C\n");
    return 0;
}

Basic structure: documentation (comments), link section (#include), definition section (#define), global declarations, main() function, user-defined functions.

C Character Set and Keywords

Character set: the characters allowed in C – letters (A–Z, a–z), digits (0–9), special symbols (+ - * / % = ; , { } ( ) & # etc.) and white spaces (blank, tab, newline).

Keywords: reserved words with a fixed meaning; they cannot be used as variable names. ANSI C has 32 keywords, all in lowercase, e.g. auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while.

Identifiers are names given by the programmer to variables and functions. Rules: start with a letter or underscore, no spaces or special symbols, not a keyword, case-sensitive (total and Total are different).

Escape Sequence

An escape sequence is a backslash (\) followed by a character, used inside strings to represent special (non-printing) characters.

Escape sequenceMeaning
\nNew line
\tHorizontal tab
\bBackspace
\rCarriage return
\aAlert (beep)
\\Backslash
\"Double quote
\'Single quote
\0Null character (end of string)

Constants and Variables

Constant: a fixed value that does not change while the program runs. Types: integer constant (25, -100), real/float constant (3.14), character constant ('A'), string constant ("RTMNU"). Symbolic constants are made with #define PI 3.14 or const float rate = 18.0;

Variable: a named memory location whose value can change during execution. It must be declared before use: int qty; float price = 99.50;

Data Types

A data type tells the compiler what kind of value a variable will store and how much memory it needs.

Data typeStoresTypical size*Format specifier
charSingle character1 byte%c
intWhole number4 bytes (2 on old 16-bit compilers)%d
floatDecimal number (6 digit precision)4 bytes%f
doubleLarge decimal number (15 digit precision)8 bytes%lf
voidNo value––

*Size depends on the compiler; use sizeof() to check. Modifiers short, long, signed and unsigned change the range. Derived types: arrays, pointers, functions. User-defined: struct, union, enum, typedef.

Conversion Specification and Input/Output Statements

A conversion specification (format specifier) starts with % and tells printf/scanf the type of data: %d int, %f float, %c char, %s string, %lf double, %ld long, %u unsigned, %o octal, %x hexadecimal, %e exponent form. Width and precision can be given: %8.2f prints a float in 8 places with 2 decimals.

  • printf() – formatted output: printf("Total = %d", t);
  • scanf() – formatted input; the address operator & is used before variable names: scanf("%d", &t);
  • getchar() / putchar() – read/write one character.
  • gets() / puts() – read/write a string (gets is unsafe; fgets is preferred).
Example: input and output
#include <stdio.h>
int main() {
    int roll;
    float marks;
    char grade;
    printf("Enter roll, marks, grade: ");
    scanf("%d %f %c", &roll, &marks, &grade);
    printf("\nRoll: %d\tMarks: %.2f\tGrade: %c\n", roll, marks, grade);
    return 0;
}

Operators and Expressions

An operator is a symbol that performs an operation on data (operands). An expression is a combination of operands and operators that gives a value, e.g. a + b * 2.

TypeOperatorsExample (a=10, b=3)
Arithmetic+ - * / %a/b = 3 (integer division), a%b = 1
Relational< <= > >= == !=a>b gives 1 (true)
Logical&& (AND), || (OR), ! (NOT)(a>5 && b>5) gives 0
Assignment= += -= *= /= %=a += 5 means a = a + 5
Ternary (conditional)? :big = (a>b) ? a : b; gives 10
Bitwise& | ^ ~ << >>a&b = 2, a|b = 11, a^b = 9, a<<1 = 20
Increment / Decrement++ --x = a++ (x=10, a=11); x = ++a (a first increases)

Pre vs post increment: in ++a the value is increased first and then used; in a++ the old value is used first and then increased. Precedence: * / % are done before + -; brackets have the highest priority.

Exam tip: For an 8-mark question on operators, write the definition, a table of all seven types with symbols, and one small example for each. Always mention that relational and logical operators give 1 for true and 0 for false.

Likely exam questions

  1. (Long, 8/16 marks) What is a translator? Explain compiler, interpreter and assembler. Differentiate between compiler and interpreter.
  2. (Long, 8/16 marks) What is an operator? Explain arithmetic, relational, logical, ternary, bitwise and increment/decrement operators in C with examples.
  3. (Short, 4 marks) Explain any four escape sequences used in C.
  4. (Short, 4 marks) What are data types? List the basic data types of C with their format specifiers.
  5. (Short, 4 marks) Differentiate between a constant and a variable with examples.

RTMNU B.Com Sem 3 · CBCCA3T03 · Unit II

Unit II: Storage Classes, Control Statements and Functions

Syllabus topics (RTMNU)

  • Storage class: Automatic, Static, External, Register
  • Control statement: If-else
  • Looping statements (while, do-while and for loop)
  • Switch
  • Use of break and continue statements
  • Function: Arithmetic and string library function
  • User defined functions
  • Function definition & declaration
  • Function call
  • Return statement
  • Function arguments
  • Use of void
  • Types of function
  • Function with call by value and call by reference
  • Recursion

Storage Class: Automatic, Static, External, Register

Definition: A storage class tells four things about a variable – where it is stored (memory or CPU register), its default initial value, its scope (where it can be used) and its lifetime (how long it stays in memory).

Storage classKeywordStorageDefault valueScopeLifetime
AutomaticautoMemoryGarbage (unknown)Local to the blockTill the block ends
StaticstaticMemoryZeroLocal to the blockWhole program (value is kept between calls)
ExternalexternMemoryZeroGlobal (all functions, even other files)Whole program
RegisterregisterCPU registerGarbageLocal to the blockTill the block ends
  • auto – default for local variables; created when the function starts and destroyed when it ends.
  • static – keeps its last value between function calls; useful for counters.
  • extern – declares a global variable defined elsewhere (outside all functions or in another file).
  • register – requests the compiler to keep the variable in a CPU register for fast access (used for loop counters); the address operator & cannot be used on it.
Example: auto vs static
#include <stdio.h>
void counter() {
    auto int a = 0; /* created fresh on every call */
    static int s = 0; /* keeps value between calls */
    a++; s++;
    printf("auto a=%d static s=%d\n", a, s);
}
int main() {
    counter(); counter(); counter();
    return 0;
}

Output: a is always 1, while s becomes 1, 2, 3.

Control Statement: If-else

Control statements decide the order in which statements run. Decision making statements run a block only when a condition is true.

  • Simple if: if (marks >= 40) printf("Pass");
  • if-else: one block when true, another when false.
  • Nested if: an if inside another if.
  • else-if ladder: many conditions checked one after another, e.g. grade A/B/C by marks.
if (sales > 100000)
    bonus = sales * 0.05;
else
    bonus = 0;

Looping Statements (while, do-while and for loop)

A loop repeats a block of statements until a condition becomes false. Every loop has initialisation, condition and update.

  • while loop (entry controlled): condition is checked first; body may run zero times. while (i <= 10) { ...; i++; }
  • do-while loop (exit controlled): body runs first, condition is checked at the end; body runs at least once. do { ...; i++; } while (i <= 10); – note the semicolon.
  • for loop: initialisation, condition and update in one line: for (i = 1; i <= 10; i++). Best when the number of repetitions is known.
whiledo-while
Entry controlled loopExit controlled loop
Condition checked before the bodyCondition checked after the body
Body may not run even onceBody runs at least once
No semicolon after while( )Semicolon after while( ) is compulsory

Switch Statement

switch is a multi-way decision statement. It compares the value of an integer or character expression with many case labels and runs the matching case. default runs when no case matches. break is needed after each case, otherwise control "falls through" to the next case. Case labels must be constants; float and strings are not allowed.

Example: switch
#include <stdio.h>
int main() {
    int day = 3;
    switch (day) {
        case 1: printf("Monday\n"); break;
        case 2: printf("Tuesday\n"); break;
        case 3: printf("Wednesday\n"); break;
        default: printf("Invalid day\n");
    }
    return 0;
}

Use of break and continue Statements

  • break – ends the loop or switch immediately; control goes to the statement after the loop.
  • continue – skips the remaining statements of the current pass and goes to the next pass of the loop.
Example: break and continue
#include <stdio.h>
int main() {
    int i, sum = 0;
    for (i = 1; i <= 10; i++) {
        if (i == 5) continue; /* skip 5 */
        if (i == 9) break; /* stop at 9 */
        sum = sum + i;
    }
    printf("Sum = %d\n", sum); /* 1+2+3+4+6+7+8 */
    return 0;
}

Output: Sum = 31 (5 is skipped and the loop stops at 9).

Function: Arithmetic and String Library Functions

A function is a self-contained block of code that does a specific task. Library (built-in) functions are ready-made functions given with the compiler; we only include the header file.

HeaderFunctionUse
math.hsqrt(x)Square root: sqrt(49) = 7
math.hpow(x,y)x to the power y: pow(2,5) = 32
stdlib.habs(x)Absolute value: abs(-7) = 7
math.hceil(x), floor(x)Round up / round down
string.hstrlen(s)Length of string
string.hstrcpy(d,s)Copy string s into d
string.hstrcat(d,s)Join s at the end of d
string.hstrcmp(a,b)Compare; gives 0 if equal
string.hstrrev(s), strupr(s), strlwr(s)Reverse / upper / lower case (Turbo C, not standard)

User Defined Functions: Definition, Declaration, Call and Return Statement

A user defined function is written by the programmer. Advantages: avoids repeating code, makes the program modular, easy to test and debug, and functions can be reused.

  • Function declaration (prototype): tells the compiler the name, return type and arguments before use: int add(int, int);
  • Function definition: the actual body: int add(int a, int b) { return a + b; }
  • Function call: uses the function: s = add(10, 20);
  • return statement: sends a value back to the calling function and ends the function. A function can return only one value.

Function Arguments, Use of void and Types of Function

Arguments are values passed to a function. Actual arguments are written in the call; formal arguments are written in the definition and receive the values. void means "nothing": void show() returns no value, and int read(void) takes no argument.

TypeExample prototype
1. No arguments, no return valuevoid line(void);
2. Arguments, no return valuevoid show(int n);
3. No arguments, returns a valueint getnum(void);
4. Arguments and returns a valueint add(int a, int b);

Call by Value and Call by Reference

Call by valueCall by reference
A copy of the value is passedThe address of the variable is passed
Changes inside the function do not affect the original variableChanges affect the original variable
Formal arguments are ordinary variablesFormal arguments are pointers
Call: swapv(a, b);Call: swapr(&a, &b);
Example: swapping
#include <stdio.h>
void swapv(int x, int y) { int t = x; x = y; y = t; }
void swapr(int *x, int *y) { int t = *x; *x = *y; *y = t; }
int main() {
    int a = 5, b = 9;
    swapv(a, b);
    printf("After call by value: a=%d b=%d\n", a, b);
    swapr(&a, &b);
    printf("After call by reference: a=%d b=%d\n", a, b);
    return 0;
}

Output: after call by value a=5 b=9 (no change); after call by reference a=9 b=5.

Recursion

Recursion is a process in which a function calls itself. Every recursive function must have a base condition to stop, otherwise it runs forever (stack overflow). Uses: factorial, Fibonacci series, sum of digits.

Example: factorial using recursion
#include <stdio.h>
long fact(int n) {
    if (n <= 1) return 1; /* base condition */
    return n * fact(n - 1); /* function calls itself */
}
int main() {
    printf("5! = %ld\n", fact(5));
    return 0;
}

Working: fact(5) = 5 × fact(4) = 5 × 4 × 3 × 2 × fact(1) = 120.

Exam tip: In "call by value vs call by reference", always give the difference table and the swap program with its output. For storage classes, the four-column table (storage, default value, scope, lifetime) earns most of the marks.

Likely exam questions

  1. (Long, 8/16 marks) What is a storage class? Explain automatic, static, external and register storage classes with their storage, default value, scope and lifetime.
  2. (Long, 8/16 marks) What is a function? Explain call by value and call by reference with a suitable program. Also explain recursion with the example of factorial.
  3. (Short, 4 marks) Differentiate between while and do-while loop.
  4. (Short, 4 marks) Explain the switch statement with an example.
  5. (Short, 4 marks) Explain break and continue statements with examples.

RTMNU B.Com Sem 3 · CBCCA3T03 · Unit III

Unit III: Arrays, Strings, Pointers and Dynamic Memory Allocation

Syllabus topics (RTMNU)

  • Arrays: Declaration
  • Referring individual elements
  • Entering data in to an array
  • Reading data from array
  • Array initialization
  • Printing of array
  • Searching, Sorting and merging of array
  • String: String manipulation using string library function
  • Pointer: Introduction to pointer
  • Pointer and function
  • Pointer and structure
  • Pointer and array
  • Pointer and string
  • Dynamic memory allocation: Sizeof(), malloc(), calloc(), realloc(), free()

Arrays: Declaration and Referring Individual Elements

Definition: An array is a collection of elements of the same data type stored in continuous memory locations under one common name. Example: marks of 60 students can be kept in one array instead of 60 variables.

Declaration: data_type array_name[size]; e.g. int marks[5]; reserves space for 5 integers. Each element is referred to by its index (subscript), which starts from 0: marks[0] is the first element and marks[4] the last. Types: one-dimensional (a list) and two-dimensional (a table/matrix, int m[3][4];).

Array Initialization

  • int a[5] = {10, 20, 30, 40, 50}; – all values given.
  • int a[] = {1, 2, 3}; – size is taken as 3 automatically.
  • int a[5] = {1, 2}; – remaining elements become 0.
  • char name[] = "Ram"; – string initialization (4 bytes with \0).

Entering Data into an Array, Reading Data from Array and Printing of Array

A for loop is used to visit each index one by one: scanf with &a[i] enters data, and a[i] inside an expression or printf reads/prints it.

Program: enter, read and print an array
#include <stdio.h>
int main() {
    int a[5], i, sum = 0;
    printf("Enter 5 numbers: ");
    for (i = 0; i < 5; i++)
        scanf("%d", &a[i]); /* entering data */
    for (i = 0; i < 5; i++) {
        printf("%d ", a[i]); /* printing */
        sum += a[i]; /* reading data */
    }
    printf("\nSum = %d\n", sum);
    return 0;
}

Searching

Searching means finding whether a given value (key) is present in an array and at which position.

  • Linear search: compare the key with every element from first to last. Works on unsorted arrays; slow for big arrays.
  • Binary search: works only on a sorted array; compare with the middle element and search only the left or right half each time. Much faster.
Program: linear search
#include <stdio.h>
int main() {
    int a[6] = {12, 45, 7, 30, 18, 9}, key = 30, i, pos = -1;
    for (i = 0; i < 6; i++)
        if (a[i] == key) { pos = i; break; }
    if (pos >= 0) printf("Found at position %d\n", pos + 1);
    else printf("Not found\n");
    return 0;
}

Output: Found at position 4.

Sorting

Sorting means arranging elements in ascending or descending order. In bubble sort, adjacent elements are compared and swapped if they are in the wrong order; after each pass the largest element moves to the end. Other methods: selection sort, insertion sort.

Program: bubble sort (ascending)
#include <stdio.h>
int main() {
    int a[5] = {50, 20, 40, 10, 30}, i, j, t;
    for (i = 0; i < 4; i++)
        for (j = 0; j < 4 - i; j++)
            if (a[j] > a[j + 1]) {
                t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
            }
    for (i = 0; i < 5; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Output: 10 20 30 40 50

Merging of Array

Merging means joining two arrays into a third array. If both arrays are sorted, we compare their elements and copy the smaller one each time, so the result is also sorted.

Program: merging two sorted arrays
#include <stdio.h>
int main() {
    int a[3] = {5, 15, 25}, b[4] = {10, 20, 30, 40}, c[7];
    int i = 0, j = 0, k = 0;
    while (i < 3 && j < 4)
        c[k++] = (a[i] < b[j]) ? a[i++] : b[j++];
    while (i < 3) c[k++] = a[i++];
    while (j < 4) c[k++] = b[j++];
    for (k = 0; k < 7; k++) printf("%d ", c[k]);
    printf("\n");
    return 0;
}

Output: 5 10 15 20 25 30 40

String: String Manipulation Using String Library Functions

A string is an array of characters ending with the null character \0. Declared as char city[20]; Read with scanf("%s", city) (stops at a space) or fgets/gets. The header string.h gives functions: strlen (length), strcpy (copy), strcat (join), strcmp (compare: 0 if equal, positive or negative otherwise), strncpy, strchr (find a character), strstr (find a substring).

Program: string functions
#include <stdio.h>
#include <string.h>
int main() {
    char s1[30] = "Tax", s2[] = "Invoice", s3[30];
    strcpy(s3, s1); /* s3 = "Tax" */
    strcat(s1, s2); /* s1 = "TaxInvoice" */
    printf("%s %zu %d\n", s1, strlen(s1), strcmp(s3, "Tax"));
    return 0;
}

Output: TaxInvoice 10 0

Pointer: Introduction to Pointer

Definition: A pointer is a variable that stores the address of another variable. Declared as int *p; The operator & (address of) gives the address, and * (value at / indirection) gives the value stored at that address.

Program: basic pointer
#include <stdio.h>
int main() {
    int x = 25, *p;
    p = &x;
    printf("x=%d *p=%d\n", x, *p);
    *p = 50; /* changes x through pointer */
    printf("x=%d\n", x);
    return 0;
}

Advantages: call by reference, efficient handling of arrays and strings, dynamic memory allocation, building data structures like linked lists.

Pointer and Function, Pointer and Structure

  • Pointer and function: passing addresses to a function (call by reference) lets the function change the original variables, e.g. swap(&a, &b) with void swap(int *x, int *y). A function can also return a pointer.
  • Pointer and structure: a pointer can hold the address of a structure variable. Members are accessed with the arrow operator ->: struct item it = {101, 250.5}, *p = &it; printf("%d", p->code); Here p->code is the same as (*p).code.

Pointer and Array, Pointer and String

The name of an array is the address of its first element, so p = a; makes p point to a[0]. Then *(p + i) is the same as a[i] (pointer arithmetic: p + 1 moves to the next element, not the next byte). A character pointer can point to a string and move through it until \0.

Program: pointer with array and string
#include <stdio.h>
int main() {
    int a[4] = {10, 20, 30, 40}, *p = a, i;
    char *s = "RTMNU";
    for (i = 0; i < 4; i++) printf("%d ", *(p + i));
    while (*s != '\0') { printf("%c", *s); s++; }
    printf("\n");
    return 0;
}

Output: 10 20 30 40 RTMNU

Dynamic Memory Allocation: sizeof(), malloc(), calloc(), realloc(), free()

Dynamic memory allocation means getting memory while the program is running (run time) instead of fixing it at compile time. It avoids waste of memory. The functions are in stdlib.h; memory comes from the heap.

FunctionUse
sizeof()Operator that gives the size in bytes of a type or variable: sizeof(int)
malloc(size)Allocates one block of given bytes; memory has garbage values; returns NULL if it fails
calloc(n, size)Allocates n blocks and sets all bytes to zero
realloc(ptr, newsize)Changes (increases or decreases) the size of memory already allocated
free(ptr)Releases the memory back to the system
malloc()calloc()
One argument (total bytes)Two arguments (number of blocks, size of each)
Memory has garbage valuesMemory is initialised to zero
Slightly fasterSlightly slower due to zero-filling
Program: malloc, realloc and free
#include <stdio.h>
#include <stdlib.h>
int main() {
    int n = 3, i, *p;
    p = (int *) malloc(n * sizeof(int));
    if (p == NULL) { printf("No memory\n"); return 1; }
    for (i = 0; i < n; i++) p[i] = (i + 1) * 10;
    p = (int *) realloc(p, 5 * sizeof(int)); /* grow to 5 */
    p[3] = 40; p[4] = 50;
    for (i = 0; i < 5; i++) printf("%d ", p[i]);
    printf("\n");
    free(p);
    return 0;
}

Output: 10 20 30 40 50

Exam tip: Always check the pointer returned by malloc/calloc against NULL and call free() at the end – examiners look for these two lines.

Likely exam questions

  1. (Long, 8/16 marks) What is an array? Explain declaration, initialization, entering and printing of a one-dimensional array. Write a C program to sort an array in ascending order using bubble sort.
  2. (Long, 8/16 marks) What is a pointer? Explain pointer and array, pointer and string and pointer and structure with examples.
  3. (Short, 4 marks) Write a C program for linear search in an array.
  4. (Short, 4 marks) Explain any four string library functions with examples.
  5. (Short, 4 marks) Differentiate between malloc() and calloc().

RTMNU B.Com Sem 3 · CBCCA3T03 · Unit IV

Unit IV: Structures, Unions and Files

Syllabus topics (RTMNU)

  • Structure: Declaration structure
  • Initializing structure
  • Structure variables
  • Accessing structure elements
  • Arrays of structure
  • Array within structure
  • Unions: Concept and applications
  • Files: Concept of file
  • Modes of files
  • Open and close
  • Creation and reading of files
  • Character input/output function
  • Formatted input/output function
  • String input and output: sscanf, sprintf, gets, puts
  • File input/output: fprintf, fscanf, getc, putc
  • Block read/write: fread, fwrite
  • Random access to files
  • Other file function
  • Command line argument

Structure: Declaration, Initializing, Structure Variables and Accessing Elements

Definition: A structure is a user-defined data type that groups variables of different data types under one name. Example: a student record has roll number (int), name (char array) and marks (float).

  • Declaration: struct student { int roll; char name[20]; float per; }; – this only creates a template; no memory is given yet.
  • Structure variables: struct student s1, s2; – memory is allocated now (total of all members).
  • Initializing: struct student s1 = {1, "Asha", 82.5}; – values in the same order as members.
  • Accessing elements: with the dot (.) operator – s1.roll, s1.per; with a pointer, the arrow (->) operator.

Arrays of Structure and Array within Structure

An array of structures stores many records of the same type, e.g. struct student s[60]; for a whole class; s[i].roll is the roll of the i-th student. An array within a structure means a member itself is an array, e.g. float marks[3]; inside struct student.

Program: array of structures with array inside
#include <stdio.h>
struct student {
    int roll;
    char name[20];
    float marks[3]; /* array within structure */
};
int main() {
    struct student s[2] = {
        {1, "Asha", {70, 80, 90}},
        {2, "Ravi", {60, 65, 70}}
    }; /* array of structures */
    int i;
    for (i = 0; i < 2; i++)
        printf("%d %s Total=%.0f\n", s[i].roll, s[i].name,
               s[i].marks[0] + s[i].marks[1] + s[i].marks[2]);
    return 0;
}

Output: 1 Asha Total=240 and 2 Ravi Total=195.

Unions: Concept and Applications

Definition: A union is a user-defined data type like a structure, but all its members share the same memory location. Its size equals the size of its largest member, and only one member can hold a value at a time.

Program: union
#include <stdio.h>
union data { int i; float f; char c; };
struct sdata { int i; float f; char c; };
int main() {
    union data u;
    u.i = 65;
    printf("u.i=%d\n", u.i);
    u.f = 2.5; /* overwrites i */
    printf("u.f=%.1f\n", u.f);
    printf("union size=%zu struct size=%zu\n", sizeof(union data), sizeof(struct sdata));
    return 0;
}

Output shows union size 4 bytes and structure size 12 bytes (on a typical compiler, including padding).

StructureUnion
Keyword structKeyword union
Each member has its own memoryAll members share one memory
Size = sum of members (plus padding)Size = size of the largest member
All members can be used at the same timeOnly one member is valid at a time
Changing one member does not affect othersChanging one member overwrites the others

Applications of union: saving memory in embedded systems, storing a value that can be of different types at different times (e.g. a payment that is either cash amount or cheque number), and handling hardware registers.

Files: Concept of File and Modes of Files

File: a named collection of related data stored permanently on a disk. Data in variables is lost when the program ends; a file keeps it. In C a file is handled through a pointer of type FILE * (defined in stdio.h). Types: text files (readable characters) and binary files (data stored as in memory).

ModeMeaning
"r"Open an existing file for reading
"w"Create a new file for writing (old contents are erased)
"a"Open for appending (add at the end)
"r+"Read and write an existing file
"w+"Create a file for read and write
"a+"Read and append
"rb", "wb", "ab"Same modes for binary files

Open and Close, Creation and Reading of Files

fp = fopen("stock.txt", "w"); opens a file and returns a FILE pointer, or NULL if it fails. fclose(fp); closes it and saves the buffered data. A file is created by opening it in "w" mode and writing to it, and read by opening it in "r" mode.

Character, Formatted and String Input/Output Functions

FunctionUse
getc(fp) / fgetc(fp)Read one character from a file; returns EOF at end of file
putc(ch, fp) / fputc(ch, fp)Write one character to a file
fprintf(fp, ...)Formatted output to a file (like printf)
fscanf(fp, ...)Formatted input from a file (like scanf)
fgets(s, n, fp) / fputs(s, fp)Read / write a line of text in a file
gets(s) / puts(s)Read a line from keyboard / print a string with newline (gets is unsafe and removed in C11; use fgets)
sprintf(str, ...)Writes formatted output into a string instead of the screen
sscanf(str, ...)Reads formatted input from a string instead of the keyboard
Program: fprintf and fscanf
#include <stdio.h>
int main() {
    FILE *fp;
    char name[20]; int qty; float rate;
    fp = fopen("stock.txt", "w");
    if (fp == NULL) { printf("Cannot open file\n"); return 1; }
    fprintf(fp, "%s %d %.2f\n", "Pen", 50, 10.5);
    fclose(fp);
    fp = fopen("stock.txt", "r");
    fscanf(fp, "%s %d %f", name, &qty, &rate);
    printf("%s %d %.2f\n", name, qty, rate);
    fclose(fp);
    return 0;
}
Program: sprintf and sscanf
#include <stdio.h>
int main() {
    char buf[40], item[10]; int q;
    sprintf(buf, "Bill No %d Amount %.2f", 15, 1180.0);
    puts(buf);
    sscanf("Soap 12", "%s %d", item, &q);
    printf("%s %d\n", item, q);
    return 0;
}

Output: "Bill No 15 Amount 1180.00" and "Soap 12". (The syllabus writes "sprint" and "facanf"; these mean sprintf and fscanf.)

Block Read/Write: fread, fwrite

fwrite(ptr, size, n, fp) writes n blocks (records) of given size from memory to a binary file; fread(ptr, size, n, fp) reads them back. They are used to store whole structures (records) at once.

Random Access to Files and Other File Functions

Random access means jumping directly to any position in a file without reading from the start. Functions: fseek(fp, offset, origin) moves the file pointer (origin SEEK_SET = beginning, SEEK_CUR = current position, SEEK_END = end); ftell(fp) gives the current position in bytes; rewind(fp) goes back to the start. Other functions: feof(fp) checks end of file, ferror(fp) checks errors, remove("a.txt") deletes a file, rename(old, new) renames it.

Program: fwrite, fseek, fread, ftell
#include <stdio.h>
struct emp { int id; float salary; };
int main() {
    struct emp e[3] = {{1, 25000}, {2, 30000}, {3, 35000}}, x;
    FILE *fp = fopen("emp.dat", "wb");
    fwrite(e, sizeof(struct emp), 3, fp); /* write 3 records */
    fclose(fp);
    fp = fopen("emp.dat", "rb");
    fseek(fp, 2 * sizeof(struct emp), SEEK_SET); /* jump to 3rd record */
    fread(&x, sizeof(struct emp), 1, fp);
    printf("id=%d salary=%.0f pos=%ld\n", x.id, x.salary, ftell(fp));
    fclose(fp);
    return 0;
}

Output: id=3 salary=35000 pos=24 (each record is 8 bytes on a typical compiler).

Command Line Argument

Command line arguments are values given to a program when it is run from the command prompt. main is written as int main(int argc, char *argv[]): argc (argument count) is the number of arguments including the program name, and argv (argument vector) is an array of strings holding them. argv[0] is the program name.

Program: show arguments
#include <stdio.h>
int main(int argc, char *argv[]) {
    int i;
    printf("argc = %d\n", argc);
    for (i = 0; i < argc; i++)
        printf("argv[%d] = %s\n", i, argv[i]);
    return 0;
}

Running show sales 2025 gives argc = 3, argv[1] = sales, argv[2] = 2025. Use: passing file names to a copy program, giving options to a program.

Exam tip: For files, write the steps in order – declare FILE pointer, fopen with a mode, check NULL, read/write, fclose – and support with a short program.

Likely exam questions

  1. (Long, 8/16 marks) What is a structure? Explain declaration, initialization and accessing of structure elements. Write a program using an array of structures to store and print records of students.
  2. (Long, 8/16 marks) What is a file? Explain the modes of opening a file and the functions fopen, fclose, fprintf, fscanf, fread, fwrite and fseek with examples.
  3. (Short, 4 marks) Differentiate between structure and union.
  4. (Short, 4 marks) What are command line arguments? Explain argc and argv.
  5. (Short, 4 marks) Explain sprintf() and sscanf() with examples.