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

संगणकशास्त्र Computer Science

बी.एससी. सत्र २ · ९ पाठ · ९ पाठांच्या नोट्स तयार

पाठ

  1. 10C Programming Basicsनोट्स
  2. 11Operators, Expressions and Type Conversion in Cनोट्स
  3. 12Control Statements in Cनोट्स
  4. 13Arrays and Stringsनोट्स
  5. 14Functions in Cनोट्स
  6. 15Pointers and Structuresनोट्स
  7. 16Dynamic Memory Allocation in Cनोट्स
  8. 17Preprocessor Directives and Command-Line Argumentsनोट्स
  9. 18File Handling in Cनोट्स

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 10

C Programming Basics

थोडक्यात सारांश

C is a general-purpose, structured programming language developed by Dennis Ritchie at Bell Laboratories in 1972. It is fast, portable and close to the hardware, so it is used for operating systems and embedded systems. This topic covers the structure of a C program, character set, tokens, data types, variables, constants, operators, and input/output functions.

महत्त्वाचे मुद्दे

  • C was developed to write the UNIX operating system. It is called a middle-level language (has high-level features and low-level access).
  • Structure of a C program: documentation (comments) → preprocessor directives (#include) → global declarations → main() function → user-defined functions.
  • Every C program starts execution from main(). Statements end with a semicolon (;).
  • Tokens are the smallest units: keywords, identifiers, constants, strings, operators and special symbols.
  • C has 32 keywords in C89 (int, float, if, else, while, return, etc.). Keywords cannot be used as variable names.
  • Identifier rules: letters, digits and underscore only; must not start with a digit; case-sensitive; no keywords.
  • Basic data types: int, float, double, char, void. Sizes depend on the compiler; on common 32/64-bit systems int is 4 bytes, char 1 byte, float 4 bytes, double 8 bytes.
  • Format specifiers: %d (int), %f (float), %lf (double), %c (char), %s (string).
  • Operators: arithmetic (+ − * / %), relational (< > <= >= == !=), logical (&& || !), assignment (= += −=), increment/decrement (++ −−), conditional (?:), bitwise (& | ^ ~ << >>), sizeof.
  • Integer division drops the fraction: 7/2 gives 3, and 7 % 2 gives 1.
  • Type conversion: implicit (automatic, smaller to larger type) and explicit (type casting), e.g. (float)7/2 gives 3.5.
  • Input/output: printf() and scanf() (in stdio.h); getchar() and putchar() for single characters. scanf needs & before ordinary variables.

महत्त्वाच्या संज्ञा

  • Preprocessor directive – line starting with # processed before compilation, e.g. #include, #define.
  • Variable (चल) – named memory location whose value can change.
  • Constant – value that does not change; e.g. #define PI 3.14 or const int N = 10;
  • Header file – file with declarations of library functions, e.g. stdio.h, math.h.
  • Operator precedence – order in which operators are evaluated (*, /, % before +, −).

सूत्रे

A simple C program:

#include <stdio.h> int main() { int a, b, sum; printf("Enter two numbers: "); scanf("%d %d", &a, &b); sum = a + b; printf("Sum = %d", sum); return 0; }
Note: on this site < > is shown in #include lines; in real code type the normal less-than and greater-than keys.
  • Precedence (high to low, main ones): () → ++ −− ! (unary) → * / % → + − → < <= > >= → == != → && → || → ?: → = += −=
  • Pre-increment ++a increases first, then uses; post-increment a++ uses first, then increases.

५ महत्त्वाचे प्रश्न

Q1. What are tokens in C? Name the types.

Tokens are the smallest individual units of a C program. Types: keywords, identifiers, constants, strings, operators and special symbols (like { } ; ,).

Q2. Is the statement b = a++ + ++a; safe to use in C? Explain.

This expression modifies a twice without a sequence point, so the C standard calls it undefined behaviour; different compilers can give different answers. Good programs never write such expressions. Use separate statements instead.

Q3. Evaluate: int x = 10, y = 3; find x / y, x % y, (float)x / y and x > y && y > 5.

  • x / y = 3 (integer division)
  • x % y = 1 (remainder)
  • (float)x / y = 3.333333 (x converted to float first)
  • x > y is 1 (true), y > 5 is 0 (false); 1 && 0 = 0
  • Result of logical expression = 0

Q4. Evaluate step by step: int r = 2 + 3 * 4 - 8 / 2 % 3;

  • * , / and % have the same precedence, evaluated left to right: 3 * 4 = 12
  • 8 / 2 = 4, then 4 % 3 = 1
  • Expression becomes 2 + 12 − 1
  • r = 13

Q5. Explain the structure of a C program with an example.

  • Documentation section: comments /* … */ about the program.
  • Link section: #include <stdio.h> (header file in angle brackets).
  • Definition section: #define PI 3.14.
  • Global declaration section.
  • main() function: declarations and executable statements inside { }.
  • Subprogram section: user-defined functions.
  • Give the sum-of-two-numbers program as an example.

परीक्षेसाठी टीप

Practise operator precedence questions and write output carefully, including spaces and newlines (\n). Remember scanf needs & for int, float and char variables.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 11

Operators, Expressions and Type Conversion in C

थोडक्यात सारांश

An operator is a symbol that tells the compiler to do a calculation or comparison, and an expression is a combination of operands and operators that gives a value. This topic goes deeper into C's operators — arithmetic, relational, logical, bitwise, assignment, increment/decrement, conditional and special operators — along with precedence and associativity, and implicit and explicit type conversion, with step-by-step evaluations.

महत्त्वाचे मुद्दे

  • Arithmetic: + - * / %. Integer division drops the fraction: 7 / 2 is 3. % works only on integers; the sign of the result follows the first operand (-17 % 5 is −2).
  • Relational: < <= > >= == !=. Result is 1 (true) or 0 (false).
  • Logical: && (AND), || (OR), ! (NOT). They use short-circuit evaluation: in a || b, if a is true, b is not evaluated.
  • Bitwise: & AND, | OR, ^ XOR, ~ NOT (1's complement), << left shift, >> right shift. They work on each bit.
  • Left shift by n multiplies by 2ⁿ; right shift by n divides by 2ⁿ (for positive numbers).
  • Assignment: = and shorthand += -= *= /= %= (e.g. s += 5 means s = s + 5).
  • Increment/decrement: ++x (pre: change then use), x++ (post: use then change).
  • Conditional (ternary): condition ? value1 : value2.
  • Special: comma ,, sizeof, address &, pointer *, member . and ->.
  • Precedence decides which operator acts first; associativity decides the order among operators of equal precedence (most are left to right; unary, ternary and assignment are right to left).
  • Implicit conversion (automatic): the smaller type is promoted to the bigger one, e.g. int + float gives float. A char used in arithmetic becomes its ASCII value.
  • Explicit conversion (type casting): (type) expression, e.g. (float) x / y.

महत्त्वाच्या संज्ञा

  • Operand – the value an operator works on.
  • Unary / binary / ternary – operator with one / two / three operands.
  • Short-circuit – skipping the second operand when the answer is already known.
  • Type promotion – automatic conversion to a higher type.
  • Typecast – forced conversion written by the programmer.

सूत्रे

Precedence (high → low)OperatorsAssociativity
1() [] -> .Left to right
2! ~ ++ -- sizeof (type) unary -Right to left
3* / %Left to right
4+ -Left to right
5<< >>Left to right
6< <= > >=Left to right
7== !=Left to right
8bitwise AND, then XOR, then ORLeft to right
9logical AND, then logical ORLeft to right
10?:Right to left
11= += -= *= /= %=Right to left
12,Left to right
  • x << n = x × 2ⁿ; x >> n = x ÷ 2ⁿ (integer part, x ≥ 0)
  • ~x = −(x + 1) in 2's complement

५ महत्त्वाचे प्रश्न

Q1. Differentiate & and && in C.

& is the bitwise AND: it works on every bit, e.g. 12 & 10 is 8. && is the logical AND: it treats the whole value as true/false, gives 1 or 0, and short-circuits (if the left side is 0 the right side is not evaluated).

Q2. Find the output: int x = 5, y = 2; float f = x / y; float g = (float) x / y;

  • x / y is integer division = 2, then stored as 2.000000 in f.
  • (float) x = 5.0; 5.0 / 2 = 2.5, so g = 2.500000.
  • Output: f = 2.000000, g = 2.500000. This shows why casting must be done before dividing.

Q3. For int a = 12, b = 10; find a & b, a | b, a ^ b, ~a, a << 2, a >> 2.

  • a = 1100, b = 1010 (4-bit view)
  • a & b = 1000 = 8; a | b = 1110 = 14; a ^ b = 0110 = 6
  • ~a = −(12 + 1) = −13
  • a << 2 = 12 × 4 = 48; a >> 2 = 12 ÷ 4 = 3

Q4. Evaluate step by step: int r = 10 + 20 * 3 % 7 - 4 / 2; and int s = 10; s += 5; s *= 2; s %= 7;

  • *, %, / have the same precedence, left to right: 20 × 3 = 60; 60 % 7 = 4; 4 / 2 = 2
  • Then + and - left to right: 10 + 4 = 14; 14 − 2 = 12. So r = 12.
  • s: 10 + 5 = 15; 15 × 2 = 30; 30 % 7 = 2. So s = 2.

Q5. Explain the types of operators in C with examples, and explain type conversion.

Outline: list each class (arithmetic, relational, logical, bitwise, assignment, increment/decrement, conditional, special) with one example each; show max = (a > b) ? a : b;; then implicit conversion (int + float → float, char + int → int, e.g. 'A' + 2 = 67 = 'C') and explicit casting (float) sum / n for average; mention possible data loss when converting float to int.

परीक्षेसाठी टीप

In expression questions, underline the operator being evaluated at each step and write the intermediate value. Never write two ++ on the same variable in one expression — the result is undefined.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 12

Control Statements in C

थोडक्यात सारांश

Control statements decide the order in which statements are executed. C has decision-making (selection) statements, looping (iteration) statements and jump statements. This topic covers if, if–else, nested if, else-if ladder, switch, while, do–while, for, break, continue and goto with examples.

महत्त्वाचे मुद्दे

  • if: runs a block only when the condition is true (non-zero).
  • if–else: chooses between two blocks.
  • Nested if and else-if ladder: test several conditions one after another.
  • switch: selects one case from many using an integer or character expression. Each case usually ends with break; otherwise control falls through to the next case. default runs when no case matches.
  • while loop: entry-controlled; condition is checked before each iteration. May run zero times.
  • do–while loop: exit-controlled; body runs at least once; ends with a semicolon after while(condition).
  • for loop: for(initialisation; condition; update) — best when the number of repetitions is known.
  • break exits the nearest loop or switch immediately.
  • continue skips the rest of the current iteration and goes to the next one.
  • goto jumps to a label; it is avoided because it makes programs hard to follow.
  • An infinite loop is one whose condition never becomes false, e.g. for(;;) or while(1).
  • Nested loops are used for patterns and matrices; the inner loop finishes fully for each outer iteration.

महत्त्वाच्या संज्ञा

  • Condition – expression that gives true (non-zero) or false (0).
  • Entry-controlled loop – condition tested before the body (while, for).
  • Exit-controlled loop – condition tested after the body (do–while).
  • Iteration (पुनरावृत्ती) – one execution of the loop body.
  • Fall-through – in switch, running into the next case when break is missing.

सूत्रे

Syntax summary:

  • if (condition) { … } else { … }
  • switch (expr) { case 1: …; break; default: …; }
  • while (condition) { … }
  • do { … } while (condition);
  • for (i = 1; i <= n; i++) { … }

Sum of first n natural numbers:

int i, n = 10, sum = 0; for (i = 1; i <= n; i++) sum = sum + i; printf("%d", sum); /* prints 55 */

५ महत्त्वाचे प्रश्न

Q1. Differentiate between while and do–while loops.

while is entry-controlled; the condition is checked first, so the body may not run at all. do–while is exit-controlled; the body runs at least once. do–while ends with a semicolon.

Q2. What is the difference between break and continue?

break ends the loop (or switch) completely and moves control after it. continue skips only the remaining statements of the current iteration and moves to the next iteration.

Q3. Find the output: for (i = 1; i <= 10; i++) { if (i % 3 == 0) continue; if (i == 8) break; printf("%d ", i); }

  • i = 1, 2 → printed.
  • i = 3 → divisible by 3, skipped.
  • i = 4, 5 → printed; i = 6 skipped; i = 7 printed.
  • i = 8 → break, loop ends.
  • Output: 1 2 4 5 7

Q4. Write a program to reverse a number and find the sum of its digits.

int n = 1234, rev = 0, sum = 0, d; while (n > 0) { d = n % 10; rev = rev * 10 + d; sum = sum + d; n = n / 10; } printf("%d %d", rev, sum);
  • Trace: digits taken 4, 3, 2, 1 → rev = 4321, sum = 10.

Q5. Explain the switch statement with an example of a simple calculator.

  • switch(op) where op is a char like '+'.
  • case '+': result = a + b; break;
  • case '-': result = a - b; break;
  • case '': result = a b; break;
  • case '/': check b != 0, then divide; break;
  • default: printf("Invalid operator");
  • Rules: case labels must be constant and unique; break prevents fall-through; switch works with int and char, not float or strings.

परीक्षेसाठी टीप

Output-tracing questions are common. Make a small table with the loop variable and print value for each iteration — it avoids silly mistakes.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 13

Arrays and Strings

थोडक्यात सारांश

An array is a collection of elements of the same data type stored in continuous memory locations under one name. A string in C is an array of characters ending with the null character '\0'. This topic covers one-dimensional and two-dimensional arrays, initialisation, common array programs, strings and the string library functions.

महत्त्वाचे मुद्दे

  • Declaration: int marks[5]; creates 5 integers marks[0] to marks[4]. Index starts at 0; the last index is size − 1.
  • Initialisation: int a[5] = {10, 20, 30, 40, 50}; If fewer values are given, the rest become 0.
  • Elements are stored in contiguous memory. Address of a[i] = base address + i × size of one element.
  • C does not check array bounds; using a[5] in a 5-element array is a bug (undefined behaviour).
  • 2-D array: int m[3][4]; has 3 rows and 4 columns (12 elements). C stores it in row-major order.
  • Arrays are processed with loops: input, output, sum, average, largest/smallest, searching, sorting, matrix addition and multiplication.
  • String: char name[20] = "Pune"; stores 'P', 'u', 'n', 'e', '\0'. Size needed = characters + 1.
  • scanf("%s", name) reads only one word (stops at space); no & is needed because the array name is already an address. fgets(name, 20, stdin) reads a full line safely.
  • String functions (header string.h): strlen, strcpy, strcat, strcmp, and (non-standard but common) strrev, strupr, strlwr.
  • strcmp(s1, s2) returns 0 if equal, a negative value if s1 comes first in dictionary order, a positive value otherwise.
  • Strings cannot be copied or compared with = or ==; use strcpy and strcmp.

महत्त्वाच्या संज्ञा

  • Array (सरणी) – group of same-type elements under one name.
  • Index (subscript) – position number of an element, starting from 0.
  • Base address – address of the first element.
  • Null character – '\0', marks the end of a string.
  • Row-major order – storing a 2-D array row after row.

सूत्रे

  • 1-D address: Address of a[i] = B + i × w (B = base address, w = bytes per element)
  • 2-D row-major: Address of a[i][j] = B + (i × N + j) × w (N = number of columns)
  • Total bytes = number of elements × size of type

Finding the largest element:

int a[5] = {12, 45, 7, 89, 23}, i, max = a[0]; for (i = 1; i < 5; i++) if (a[i] > max) max = a[i]; printf("Largest = %d", max); /* 89 */

५ महत्त्वाचे प्रश्न

Q1. What is the difference between a character array and a string?

A character array is any array of char values. A string is a character array that ends with the null character '\0'. String functions like strlen depend on this '\0' to know where the string ends.

Q2. Explain any four string functions.

strlen(s) returns the length without '\0'. strcpy(d, s) copies s into d. strcat(d, s) joins s at the end of d. strcmp(a, b) compares two strings and returns 0 if they are equal.

Q3. An int array a[10] starts at address 2000 and an int takes 4 bytes. Find the address of a[6].

  • Address = B + i × w
  • = 2000 + 6 × 4
  • = 2000 + 24
  • = 2024

Q4. A 2-D array int m[4][5] is stored in row-major order from address 1000, int = 4 bytes. Find the address of m[2][3].

  • Number of columns N = 5
  • Address = B + (i × N + j) × w
  • = 1000 + (2 × 5 + 3) × 4
  • = 1000 + 13 × 4 = 1000 + 52
  • = 1052

Q5. Write a program to add two 3 × 3 matrices.

int a[3][3], b[3][3], c[3][3], i, j; /* read a and b using nested loops */ for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) c[i][j] = a[i][j] + b[i][j];
  • Print c with nested loops, using printf("\n") after each row.
  • Explain: outer loop selects row, inner loop selects column.

परीक्षेसाठी टीप

Array programs (largest, sum, reverse, matrix addition/multiplication) and address calculations are the most asked. Remember index starts at 0 in every answer.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 14

Functions in C

थोडक्यात सारांश

A function is a self-contained block of code that does a specific task. Functions make programs modular, shorter and easier to debug. This topic covers library and user-defined functions, function declaration (prototype), definition and call, call by value and call by reference, recursion, and storage classes.

महत्त्वाचे मुद्दे

  • Library functions are built in: printf(), sqrt(), strlen(). User-defined functions are written by the programmer.
  • Three parts of a user-defined function: prototype (declaration), definition, and call.
  • Prototype: int add(int, int); tells the compiler the return type and parameter types.
  • Actual arguments are the values in the call; formal parameters are the variables in the definition.
  • return sends a value back to the caller; a void function returns nothing.
  • Four categories: no arguments no return; arguments but no return; no arguments but return; arguments and return.
  • Call by value: a copy of the value is passed; changes inside the function do not affect the original variable.
  • Call by reference (using pointers): the address is passed; the function can change the original variable. Example: swap(&x, &y).
  • Recursion: a function calling itself. It needs a base case to stop, otherwise it recurses until the stack overflows.
  • Each function call uses a stack frame for its local variables.
  • Storage classes decide scope, lifetime and default value: auto, register, static, extern.
  • A static local variable keeps its value between calls; it is initialised only once (default 0).

महत्त्वाच्या संज्ञा

  • Modular programming (मॉड्यूलर) – dividing a program into small functions.
  • Function prototype – declaration before use, giving return type and parameter types.
  • Scope – part of the program where a variable can be used.
  • Lifetime – how long a variable exists in memory.
  • Base case – condition that ends recursion.

सूत्रे

Storage classes:

ClassStorageDefault valueScopeLifetime
automemory (stack)garbagelocal blocktill block ends
registerCPU register (request)garbagelocal blocktill block ends
staticmemory0local block (or file)whole program
externmemory0globalwhole program

Recursive factorial:

long fact(int n) { if (n == 0) return 1; /* base case / return n fact(n - 1); }

५ महत्त्वाचे प्रश्न

Q1. Differentiate call by value and call by reference.

In call by value a copy of the actual argument is passed, so the original is not changed. In call by reference the address is passed using pointers, so the function can change the original. Swapping two numbers works only by reference.

Q2. What is recursion? State one advantage and one disadvantage.

Recursion is when a function calls itself, directly or indirectly. Advantage: short, natural code for problems like factorial, Fibonacci and tree traversal. Disadvantage: uses more memory (stack) and may be slower than a loop.

Q3. Trace fact(4) for the recursive factorial function.

  • fact(4) = 4 × fact(3)
  • fact(3) = 3 × fact(2)
  • fact(2) = 2 × fact(1)
  • fact(1) = 1 × fact(0); fact(0) = 1 (base case)
  • Returning: fact(1) = 1, fact(2) = 2, fact(3) = 6, fact(4) = 24

Q4. Find the output and explain:

void f() { static int c = 0; c++; printf("%d ", c); } int main() { f(); f(); f(); return 0; }
  • c is static, so it is created once and keeps its value.
  • First call: c becomes 1 → prints 1.
  • Second call: 2; third call: 3.
  • Output: 1 2 3. (If c were auto, output would be 1 1 1.)

Q5. Write a function to swap two numbers using call by reference.

void swap(int p, int q) { int t = p; p = q; q = t; }
  • Call: swap(&x, &y);
  • p and q receive the addresses of x and y.
  • p and q change the original variables.
  • With x = 5, y = 9 before, after the call x = 9, y = 5.

परीक्षेसाठी टीप

Always show the function prototype, definition and call separately in long answers. For recursion questions, draw the chain of calls and returns.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 15

Pointers and Structures

थोडक्यात सारांश

A pointer is a variable that stores the memory address of another variable. A structure is a user-defined data type that groups variables of different types under one name. This topic covers pointer declaration, the & and * operators, pointer arithmetic, pointers with arrays and functions, dynamic memory allocation, structures, unions, and file handling basics.

महत्त्वाचे मुद्दे

  • Declaration: int *p; means p can hold the address of an int.
  • The address-of operator (&) gives the address of a variable. The value-at (dereference) operator, an asterisk written before the pointer as in *p, gives the value stored at that address.
  • After p = &x; both x and *p refer to the same value.
  • Pointer arithmetic: p + 1 moves to the next element, i.e. adds the size of the pointed type (4 bytes for a 4-byte int).
  • The array name is the address of its first element: a is the same as &a[0], and a[i] is the same as *(a + i).
  • NULL pointer points to nothing; a pointer that is not initialised is a wild pointer; a pointer to freed memory is a dangling pointer.
  • Pointer to pointer: int **q = &p;
  • Dynamic memory allocation (stdlib.h): malloc (allocates, contents garbage), calloc (allocates and sets to 0), realloc (changes size), free (releases memory).
  • Structure: struct student { int roll; char name[20]; float marks; }; Members are accessed with the dot operator: s.roll. With a pointer, use the arrow operator: ptr->roll.
  • Structure size is at least the sum of its members (the compiler may add padding).
  • Union: like a structure, but all members share the same memory; size = size of the largest member. Only one member holds a valid value at a time.
  • typedef gives a new name to a type: typedef struct student STU;
  • Files: FILE *fp = fopen("data.txt", "w"); modes "r", "w", "a"; functions fprintf, fscanf, fgetc, fputc, fclose.

महत्त्वाच्या संज्ञा

  • Pointer (निर्देशक) – variable that stores an address.
  • Dereferencing – getting the value at the address held by a pointer.
  • Heap – memory area used for dynamic allocation.
  • Memory leak – memory allocated but never freed.
  • Self-referential structure – structure that has a pointer to its own type (used in linked lists).

सूत्रे

  • New address after p + n = address in p + n × sizeof(type)
  • a[i] ≡ *(a + i); &a[i] ≡ a + i
  • Structure size (without padding) = sum of member sizes; Union size = largest member size
PointStructureUnion
Keywordstructunion
Memoryseparate for each membershared by all
Sizesum of members (+ padding)largest member
Values at a timeall membersonly one member

Dynamic array:

int a = (int ) malloc(n * sizeof(int)); if (a == NULL) printf("No memory"); /* use a[0] … a[n-1] */ free(a);

५ महत्त्वाचे प्रश्न

Q1. What is a pointer? How is it declared and initialised?

A pointer is a variable that stores the address of another variable. Declaration: int p; Initialisation: p = &x; Now p gives the value of x.

Q2. Differentiate malloc() and calloc().

malloc(size) allocates one block and leaves garbage values. calloc(n, size) allocates n blocks and sets every byte to zero. Both return NULL if memory is not available.

Q3. int a[5] = {10, 20, 30, 40, 50}; int p = a; Assume a starts at address 1000 and int is 4 bytes. Find p + 2, (p + 2) and *p + 2.

  • p = 1000
  • p + 2 = 1000 + 2 × 4 = 1008 (address of a[2])
  • *(p + 2) = a[2] = 30
  • *p + 2 = 10 + 2 = 12 (value first, then add)

Q4. Find the size of struct s { int a; char b[10]; float c; } and of union u with the same members (int = 4, float = 4, ignore padding).

  • Structure: 4 + 10 + 4 = 18 bytes (a real compiler often pads it to 20)
  • Union: largest member = char b[10] = 10 bytes (often padded to 12 for alignment)
  • Explain that union members overlap in memory.

Q5. Write a program using a structure to store and display data of 3 students.

struct student { int roll; char name[20]; float marks; }; struct student s[3]; int i; for (i = 0; i < 3; i++) scanf("%d %s %f", &s[i].roll, s[i].name, &s[i].marks); for (i = 0; i < 3; i++) printf("%d %s %.2f\n", s[i].roll, s[i].name, s[i].marks);
  • Explain: array of structures, dot operator, no & before name (array).

परीक्षेसाठी टीप

For pointer output questions, write the address and value of every variable in a small table before answering. Learn the structure vs union table — it is a sure question.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 16

Dynamic Memory Allocation in C

थोडक्यात सारांश

Dynamic memory allocation (DMA) means getting memory while the program is running, instead of fixing the size at compile time. C does this with four library functions in <stdlib.h>: malloc(), calloc(), realloc() and free(). This topic covers static versus dynamic allocation, the heap, each function with examples, dynamic arrays, memory leaks and dangling pointers.

महत्त्वाचे मुद्दे

  • Static allocation: size fixed at compile time (e.g. int a[100];); memory may be wasted or may fall short.
  • Dynamic allocation: size decided at run time; memory comes from the heap and stays until it is freed.
  • Local variables live on the stack and are removed automatically when the function ends; heap memory is not.
  • malloc(size) allocates size bytes and returns a void* to the first byte. The memory has garbage values.
  • calloc(n, size) allocates memory for n elements of size bytes each and sets every byte to zero.
  • realloc(ptr, newsize) changes the size of an earlier block; old data is kept (the block may move to a new address).
  • free(ptr) returns the block to the heap.
  • All allocation functions return NULL if memory is not available, so always check before using the pointer.
  • The void* result is usually type-cast, e.g. (int*) malloc(n * sizeof(int)).
  • Use sizeof instead of fixed numbers, because the size of int differs between systems.
  • Memory leak: allocated memory that is never freed; long-running programs slowly use up memory.
  • Dangling pointer: a pointer that still holds the address of freed memory. Set it to NULL after free().
  • DMA is the base of linked lists, trees and other dynamic data structures.

महत्त्वाच्या संज्ञा

  • Heap – area of memory used for dynamic allocation.
  • Stack – area used for function calls and local variables.
  • NULL pointer – a pointer that points to nothing (address 0).
  • void pointer – generic pointer that can hold the address of any type.
  • Memory leak – memory allocated but never released.

सूत्रे

  • Bytes requested by malloc(n * sizeof(int)) = n × size of int (n × 4 when int is 4 bytes)
  • Bytes given by calloc(n, s) = n × s
Pointmalloc()calloc()
ArgumentsOne: total bytesTwo: number of elements, size of each
Initial valueGarbageAll zero
SpeedSlightly fasterSlightly slower (clears memory)
Examplemalloc(5 * sizeof(int))calloc(5, sizeof(int))

५ महत्त्वाचे प्रश्न

Q1. What is the difference between static and dynamic memory allocation?

Static allocation fixes the memory size at compile time on the stack or data area, and it cannot change; unused space is wasted. Dynamic allocation requests memory from the heap at run time with malloc/calloc, can be resized with realloc, and must be released with free.

Q2. What is a dangling pointer? How can it be avoided?

A dangling pointer points to memory that has already been freed (or a local variable that no longer exists). Using it gives wrong results or a crash. Avoid it by writing p = NULL; right after free(p); and by not returning addresses of local variables from functions.

Q3. Write a program to read n numbers into a dynamically allocated array and print their sum.

int n, i, sum = 0; int *p; scanf("%d", &n); p = (int*) malloc(n * sizeof(int)); if (p == NULL) { printf("No memory"); return 1; } for (i = 0; i < n; i++) { scanf("%d", &p[i]); sum += p[i]; } printf("Sum = %d", sum); free(p); p = NULL;
  • For n = 5 and inputs 10, 20, 30, 40, 50 the output is Sum = 150.
  • With 4-byte int, malloc requests 5 × 4 = 20 bytes.

Q4. Explain malloc(), calloc(), realloc() and free() with syntax and examples.

Outline: header <stdlib.h> → malloc syntax and garbage values → calloc syntax and zero values (show calloc(3, sizeof(int)) gives 0 0 0) → realloc(p, 8 * sizeof(int)) to grow an array from 5 to 8 elements, old values kept → free(p) → NULL check after each call → finish with the malloc vs calloc table.

Q5. What is a memory leak? Give an example and explain how to prevent it.

Example: inside a loop, p = malloc(100); is called again and again without free(p). Each time the old address is lost, so that block can never be freed. Prevention: free every block when it is no longer needed, free before reassigning the pointer, keep one owner for each block, and use tools like Valgrind to detect leaks.

परीक्षेसाठी टीप

Always show the NULL check and the free() call in DMA programs — examiners look for both. Learn the malloc vs calloc table.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 17

Preprocessor Directives and Command-Line Arguments

थोडक्यात सारांश

The C preprocessor is a program that processes the source code before the actual compilation. Lines that start with # are preprocessor directives. This topic covers file inclusion (#include), macro substitution (#define, macros with arguments), conditional compilation (#if, #ifdef, #ifndef), and how command-line arguments are passed to main() through argc and argv.

महत्त्वाचे मुद्दे

  • Preprocessing is the first stage of compiling: preprocessor → compiler → assembler → linker.
  • Directives begin with #, need no semicolon, and are usually written at the top of the file.
  • File inclusion: #include <stdio.h> searches the standard library folders; #include "myfile.h" searches the current folder first.
  • Macro (symbolic constant): #define PI 3.14159 — every PI is replaced by the value before compiling.
  • Macro with arguments: #define SQR(x) ((x) * (x)). Macros do simple text replacement, so always put brackets around each argument and the whole body.
  • #undef NAME removes a macro definition.
  • Conditional compilation: #if, #elif, #else, #endif, #ifdef, #ifndef include or skip code — used for debugging code and for different platforms.
  • Header guard: #ifndef MYFILE_H / #define MYFILE_H / … / #endif stops a header being included twice.
  • Predefined macros: __DATE__, __TIME__, __FILE__, __LINE__.
  • Command-line arguments: int main(int argc, char *argv[]). argc = number of arguments including the program name; argv = array of strings; argv[0] is the program name.
  • Arguments arrive as strings; convert numbers with atoi() or atof() from <stdlib.h>.

महत्त्वाच्या संज्ञा

  • Directive – instruction to the preprocessor, starting with #.
  • Macro expansion – replacing a macro name with its body.
  • Header file – file with declarations, ending in .h.
  • argc – argument count.
  • argv – argument vector (array of strings).

सूत्रे

PointMacroFunction
Processed byPreprocessor (text replace)Compiler (real call)
SpeedFaster, no call overheadSlower, call overhead
Code sizeGrows with each useOne copy only
Type checkingNoneYes
Example#define SQR(x) ((x)*(x))int sqr(int x) { return x * x; }

५ महत्त्वाचे प्रश्न

Q1. What is the difference between #include <file> and #include "file"?

With angle brackets the preprocessor searches only the system include folders, so it is used for standard headers like <stdio.h>. With double quotes it searches the current project folder first and then the system folders, so it is used for user-made headers.

Q2. What are argc and argv? If a program is run as ./add 10 20, what are their values?

argc counts the words on the command line and argv stores them as strings. Here argc = 3, argv[0] = "./add", argv[1] = "10", argv[2] = "20". The sum is found with atoi(argv[1]) + atoi(argv[2]) = 30.

Q3. Find the output and explain:

#define SQUARE(x) x * x #define SQR(x) ((x) * (x)) printf("%d %d", SQUARE(2 + 3), SQR(2 + 3)); printf("%d %d", 100 / SQUARE(5), 100 / SQR(5));
  • SQUARE(2 + 3) becomes 2 + 3 * 2 + 3 = 2 + 6 + 3 = 11 (not 25)
  • SQR(2 + 3) becomes ((2 + 3) * (2 + 3)) = 25
  • 100 / SQUARE(5) becomes 100 / 5 * 5 = 20 * 5 = 100
  • 100 / SQR(5) becomes 100 / ((5) * (5)) = 4
  • Output: 11 25 then 100 4. Lesson: bracket every macro argument and the whole body.

Q4. Explain the types of preprocessor directives with examples.

Outline: (1) file inclusion #include; (2) macro substitution — simple #define MAX 100, with arguments #define MAX(a, b) ((a) > (b) ? (a) : (b)), and #undef; (3) conditional compilation — #ifdef DEBUG printf(...) #endif, #if/#elif/#else; (4) other directives — #pragma, #error, #line. Give one use for each.

Q5. Write a program that prints all command-line arguments and the total of the numbers given.

#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i, total = 0; for (i = 1; i < argc; i++) { printf("%s\n", argv[i]); total += atoi(argv[i]); } printf("Total = %d\n", total); return 0; }
  • Run as ./sum 5 7 8 → prints 5, 7, 8 and Total = 20. The loop starts at 1 to skip the program name.

परीक्षेसाठी टीप

For macro output questions, write the expanded expression first, then apply precedence. In argc questions, remember the program name is counted.

बी.एससी. सत्र २ · संगणकशास्त्र · पाठ 18

File Handling in C

थोडक्यात सारांश

A file stores data permanently on disk, so it is not lost when the program ends. C handles files through a FILE pointer and library functions in <stdio.h>. This topic covers text and binary files, opening modes, reading and writing functions (character, string, formatted and block I/O), random access with fseek(), ftell() and rewind(), end-of-file checking and error handling.

महत्त्वाचे मुद्दे

  • Data in variables is lost when a program ends; files give permanent storage.
  • Text file: stores characters, readable in Notepad. Binary file: stores data in the same bytes as in memory; smaller and faster.
  • Steps: declare FILE *fp; → open with fopen() → read/write → close with fclose().
  • fopen() returns NULL if the file cannot be opened (e.g. it does not exist in "r" mode). Always check.
  • Modes: "r" read, "w" write (creates new or erases old), "a" append (adds at the end), "r+" read and write, "w+" write and read, "a+" append and read. Add "b" for binary: "rb", "wb", "ab".
  • Character I/O: fgetc(), fputc(). String I/O: fgets(), fputs(). Formatted I/O: fprintf(), fscanf().
  • Block (record) I/O for binary files: fwrite(&rec, sizeof(rec), 1, fp) and fread(&rec, sizeof(rec), 1, fp) — ideal for structures.
  • EOF (usually −1) marks the end of a file; feof(fp) returns non-zero at the end.
  • Store the result of fgetc() in an int, not a char, so EOF is detected correctly.
  • Random access: fseek(fp, offset, origin) moves the file position; origin is SEEK_SET (start), SEEK_CUR (current) or SEEK_END (end). ftell(fp) gives the current position in bytes. rewind(fp) goes back to the start.
  • Other functions: remove("a.txt") deletes a file; rename(old, new) renames it; ferror(fp) checks for errors.

महत्त्वाच्या संज्ञा

  • File pointer – pointer of type FILE * that keeps track of an open file.
  • Stream – flow of data between a program and a device or file.
  • Buffer – temporary memory area used during file I/O; fclose or fflush writes it out.
  • Sequential access – reading from start to end in order.
  • Random access – jumping directly to any position.

सूत्रे

ModeIf file existsIf file does not exist
"r"Opens for readingReturns NULL
"w"Old contents erasedNew file created
"a"Writes added at the endNew file created
"r+"Read and write, no eraseReturns NULL
  • Position of record k (k = 0, 1, 2 …) in a binary file = k × sizeof(record)
  • fseek(fp, k * sizeof(struct student), SEEK_SET); jumps to record k

५ महत्त्वाचे प्रश्न

Q1. Differentiate text files and binary files.

A text file stores data as readable characters, with line endings, and numbers take as many bytes as their digits. A binary file stores the exact memory bytes, so an int always takes sizeof(int) bytes; it is compact and fast but cannot be read in a text editor. Text uses fprintf/fscanf; binary uses fwrite/fread.

Q2. Explain fseek(), ftell() and rewind().

fseek(fp, offset, origin) moves the file position by offset bytes from SEEK_SET, SEEK_CUR or SEEK_END. ftell(fp) returns the current byte position as a long. rewind(fp) moves to the start of the file. Example: fseek(fp, 0, SEEK_END); size = ftell(fp); gives the file size.

Q3. Write a program to count characters and lines in a text file.

FILE *fp; int ch, chars = 0, lines = 0; fp = fopen("a.txt", "r"); if (fp == NULL) { printf("Cannot open"); return 1; } while ((ch = fgetc(fp)) != EOF) { chars++; if (ch == '\n') lines++; } fclose(fp); printf("Chars = %d, Lines = %d", chars, lines);
  • If a.txt contains "Hello" and "Padhai" on two lines (each ending with a newline), the output is Chars = 13, Lines = 2 (5 + 1 + 6 + 1 = 13).

Q4. Write a program to store records of students in a binary file and read them back.

Outline: define struct student { int roll; char name[20]; float marks; }; → open "wb" → loop: read data, fwrite(&s, sizeof(s), 1, fp) → close → open "rb" → while (fread(&s, sizeof(s), 1, fp) == 1) printf(...) → close. Mention checking NULL after each fopen, and that fread returns the number of records read.

Q5. Explain the file opening modes and the steps of file handling in C.

Outline: need for files → steps (declare, open, process, close) → syntax of fopen → each mode with what happens when the file exists or not (table above) → binary modes with "b" → importance of fclose (flushes the buffer, frees the file) → error checking with NULL and ferror.

परीक्षेसाठी टीप

Every file program must show FILE *fp, a NULL check after fopen, and fclose at the end. Use int ch with fgetc — examiners notice it.