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

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

BSc First Year · 18 chapters · 18 with notes

Chapters

  1. 1Fundamentals of ComputersNotes
  2. 2Input and Output DevicesNotes
  3. 3Computer Memory and Storage DevicesNotes
  4. 4Number SystemsNotes
  5. 5Boolean Algebra and Logic GatesNotes
  6. 6Computer Software and Programming LanguagesNotes
  7. 7Operating System BasicsNotes
  8. 8Internet and Its ApplicationsNotes
  9. 9Algorithms and FlowchartsNotes
  10. 10C Programming BasicsNotes
  11. 11Operators, Expressions and Type Conversion in CNotes
  12. 12Control Statements in CNotes
  13. 13Arrays and StringsNotes
  14. 14Functions in CNotes
  15. 15Pointers and StructuresNotes
  16. 16Dynamic Memory Allocation in CNotes
  17. 17Preprocessor Directives and Command-Line ArgumentsNotes
  18. 18File Handling in CNotes

BSc First Year · Computer Science · Chapter 1

Fundamentals of Computers

Quick summary

A computer is an electronic device that accepts data, processes it under the control of a program, stores it and gives output. This topic covers characteristics of computers, generations, classification, the block diagram (input, CPU, memory, output), types of memory, and hardware versus software.

Key points

  • A computer works on the IPO cycle: Input → Process → Output, with Storage.
  • Characteristics: speed, accuracy, diligence (no tiredness), versatility, huge storage. A computer has no IQ (cannot think on its own) and no feelings.
  • Generations: 1st – vacuum tubes (ENIAC, UNIVAC); 2nd – transistors; 3rd – integrated circuits (ICs); 4th – microprocessors (VLSI); 5th – artificial intelligence, parallel processing.
  • Classification by size/power: microcomputer (PC, laptop), minicomputer, mainframe, supercomputer. India's PARAM series of supercomputers was built by C-DAC, Pune.
  • Classification by type of data: analog, digital and hybrid computers.
  • Block diagram: Input unit, Central Processing Unit (CPU), Output unit and Memory/Storage unit.
  • The CPU has three parts: ALU (arithmetic and logic operations), CU (control unit, directs all operations) and registers (very fast small storage).
  • Primary memory: RAM (volatile, read/write) and ROM (non-volatile, read-only; PROM, EPROM, EEPROM).
  • Cache memory is a very fast memory between the CPU and RAM.
  • Secondary memory: hard disk, SSD, pen drive, CD/DVD, magnetic tape. It is non-volatile and large.
  • Memory hierarchy (fast and costly → slow and cheap): registers → cache → RAM → secondary storage.
  • Software types: system software (operating system, compilers, utilities) and application software (MS Word, Tally, browsers).
  • Language translators: compiler (translates whole program at once), interpreter (line by line), assembler (assembly to machine language).

Important terms

  • Hardware – physical parts of a computer you can touch.
  • Software (सॉफ्टवेअर / प्रणाली) – set of programs that tell the hardware what to do.
  • Bit – smallest unit of data, 0 or 1. Byte – 8 bits.
  • Volatile memory – loses its data when power goes off (RAM).
  • Firmware – software stored permanently in ROM, like BIOS.
  • Peripheral – external device attached to the computer (printer, scanner).

Formulas

Memory units (binary):

UnitSize
1 Nibble4 bits
1 Byte8 bits
1 KB1024 bytes
1 MB1024 KB
1 GB1024 MB
1 TB1024 GB
  • Input devices: keyboard, mouse, scanner, microphone, webcam, barcode reader, OMR, MICR (used in bank cheques).
  • Output devices: monitor, printer (impact: dot-matrix; non-impact: inkjet, laser), speaker, plotter, projector.

5 important questions

Q1. Differentiate between RAM and ROM.

RAM is volatile, read-write memory used to hold programs currently running. ROM is non-volatile, mostly read-only memory that stores permanent instructions like the BIOS. RAM is larger; ROM is small.

Q2. What is the difference between a compiler and an interpreter?

A compiler translates the whole program into machine code at once and shows all errors together; execution is fast. An interpreter translates and runs one line at a time and stops at the first error; it is slower. C uses a compiler; Python normally uses an interpreter.

Q3. Draw and explain the block diagram of a computer.

  • Input unit: accepts data and converts it into machine form (keyboard, mouse).
  • Memory unit: stores data and instructions (primary and secondary).
  • CPU: ALU does calculations and comparisons; CU fetches, decodes and controls; registers hold data in use.
  • Output unit: converts results into human-readable form (monitor, printer).
  • Arrows show data flow from input to memory to CPU to output, and control signals from CU to all units.

Q4. Explain the generations of computers.

  • First (about 1940s–1950s): vacuum tubes, machine language, very large, much heat.
  • Second: transistors, assembly language, smaller and more reliable.
  • Third: integrated circuits, keyboards and monitors, operating systems.
  • Fourth: microprocessors (VLSI), personal computers, GUIs, networks.
  • Fifth: AI, parallel processing, natural language, ULSI.

Q5. Explain the memory hierarchy.

  • Registers: inside CPU, fastest, smallest.
  • Cache: between CPU and RAM, stores frequently used data.
  • Main memory (RAM): holds running programs.
  • Secondary storage: HDD/SSD, large, permanent, slower.
  • As we go down: speed and cost per bit decrease, capacity increases.

Exam tip

The block diagram question comes almost every year. Draw neat boxes with arrows and label ALU, CU and memory clearly.

BSc First Year · Computer Science · Chapter 2

Input and Output Devices

Quick summary

Input devices send data and instructions into the computer, and output devices show or give the results back to the user. This topic covers common input devices (keyboard, mouse, scanner, MICR, OCR, OMR, barcode reader, touch screen, microphone, webcam), output devices (monitor, printer, plotter, speaker, projector), how they differ, and devices that do both jobs.

Key points

  • Input device: converts data from the human (or the real world) into a binary form the computer understands.
  • Keyboard: most common input device. Keys: alphanumeric, function keys (F1–F12), cursor keys, numeric keypad, modifier keys (Shift, Ctrl, Alt).
  • Mouse: pointing device. Types: mechanical (ball), optical (LED light), wireless. Actions: click, double-click, right-click, drag, scroll.
  • Other pointing devices: trackball, touchpad, joystick, light pen, stylus.
  • Scanner: converts a printed page or photo into a digital image. Flatbed and handheld types.
  • MICR (Magnetic Ink Character Recognition): reads cheque numbers printed in magnetic ink. Used by banks.
  • OCR (Optical Character Recognition): converts scanned text into editable text.
  • OMR (Optical Mark Reader): reads pencil/pen marks in fixed boxes. Used to check MCQ answer sheets.
  • Barcode reader: reads the black-and-white bar pattern on products in shops. A QR code is a 2-D barcode.
  • Output device: converts binary results into a form humans can understand (text, picture, sound, print).
  • Monitor (VDU): soft-copy output. Types: CRT (old), LCD, LED, OLED. Quality depends on resolution, pixel size and refresh rate.
  • Printer: hard-copy output. Impact printers (dot-matrix, line printer) strike the paper; non-impact printers (inkjet, laser, thermal) do not.
  • Plotter: draws large, accurate drawings like maps and building plans.
  • I/O (both) devices: touch screen, modem, network card, headset with mic.

Important terms

  • Soft copy – output seen on screen; it is temporary.
  • Hard copy – output printed on paper; it is permanent.
  • Pixel – the smallest dot of a screen picture.
  • Resolution – number of pixels shown, e.g. 1920 × 1080.
  • DPI – dots per inch; measures printer quality.
  • PPM – pages per minute; measures printer speed.

Formulas

  • Total pixels = horizontal pixels × vertical pixels
  • Memory for one screen image (bytes) = total pixels × bits per pixel ÷ 8
  • Number of colours possible = 2ⁿ, where n = bits per pixel
FeatureImpact printerNon-impact printer
MethodStrikes ribbon on paperInk spray, laser or heat
NoiseNoisyQuiet
QualityLowerHigh
Multiple copies (carbon)PossibleNot possible
ExampleDot-matrixLaser, inkjet

5 important questions

Q1. Differentiate between OCR and OMR.

OCR reads printed or typed letters and converts them into editable text. OMR only detects the presence of a mark in a fixed position, such as a filled circle on an MCQ answer sheet. OCR is used to digitise books; OMR is used in exams and surveys.

Q2. A monitor has a resolution of 1024 × 768 and uses 24 bits per pixel. How much memory is needed for one screen image?

  • Total pixels = 1024 × 768 = 786,432
  • Bits = 786,432 × 24 = 18,874,368 bits
  • Bytes = 18,874,368 ÷ 8 = 2,359,296 bytes = 2304 KB = 2.25 MB
  • Colours possible = 2²⁴ = 16,777,216 (about 16.7 million)

Q3. What is an input device? Explain any five input devices.

Outline: define input device → keyboard (types of keys) → mouse (types, actions) → scanner (flatbed, handheld) → MICR (banks, cheques) → barcode reader (shops, billing). Give one use for each.

Q4. Explain different types of printers.

  • Classify into impact and non-impact.
  • Dot-matrix: pins strike ribbon; cheap, noisy, used for bills.
  • Line printer: prints a whole line at a time; fast, for bulk output.
  • Inkjet: sprays tiny ink drops; good colour quality, home use.
  • Laser: uses a laser, drum and toner powder; fast, sharp, office use.
  • Thermal: uses heat-sensitive paper; ATM slips and receipts.
  • End with the comparison table.

Q5. Compare CRT, LCD and LED monitors.

CRT uses an electron gun and a picture tube; it is bulky and uses more power. LCD uses liquid crystals with a backlight; it is thin and uses less power. LED monitors are LCD panels with an LED backlight; they are brighter, thinner and save more power. OLED pixels give their own light, so there is no backlight and blacks are deeper.

Exam tip

Always give one real-life use for each device (MICR in banks, OMR in exams, barcode in shops). Examiners like a neat comparison table for impact vs non-impact printers.

BSc First Year · Computer Science · Chapter 3

Computer Memory and Storage Devices

Quick summary

Memory is the part of a computer that stores data and programs. Primary memory (RAM, ROM, cache, registers) is fast and directly used by the CPU; secondary storage (hard disk, SSD, pen drive, optical disc) is slower but large and permanent. This topic covers the types of memory, units of storage, how a hard disk works, and how to calculate capacity and access time.

Key points

  • Primary memory is directly accessed by the CPU. Secondary memory is accessed through I/O and must be loaded into RAM first.
  • RAM (Random Access Memory) is volatile: data is lost when power goes off.
  • SRAM uses flip-flops; fast, costly, no refresh needed; used for cache. DRAM uses capacitors; cheaper, needs refreshing; used as main memory.
  • ROM is non-volatile and holds firmware such as the BIOS. Types: PROM (written once), EPROM (erased by UV light), EEPROM (erased electrically), flash memory.
  • Cache memory sits between CPU and RAM and keeps the most-used data. A cache hit means the data was found in cache; a miss means it must come from RAM.
  • Registers are the fastest storage, inside the CPU (accumulator, program counter, instruction register, MAR, MDR).
  • Memory hierarchy (fastest and costliest to slowest and cheapest): registers → cache → RAM → SSD/HDD → optical disc/tape.
  • Hard disk (HDD): magnetic platters divided into tracks and sectors; a read/write head on an arm moves over them. Tracks at the same position on all surfaces form a cylinder.
  • SSD uses flash memory with no moving parts, so it is faster, quieter and more shock-proof than an HDD.
  • Optical discs: CD (about 700 MB), DVD (4.7 GB single layer), Blu-ray (25 GB single layer). Data is read by a laser.
  • Access methods: random (RAM, disk), sequential (magnetic tape).

Important terms

  • Volatile – loses data without power.
  • Bit / Byte – 1 binary digit / 8 bits.
  • Seek time – time to move the head to the correct track.
  • Rotational latency – time for the sector to come under the head.
  • Firmware – permanent software stored in ROM.
  • Virtual memory – disk space used as an extension of RAM.

Formulas

  • 1 KB = 1024 bytes; 1 MB = 1024 KB; 1 GB = 1024 MB; 1 TB = 1024 GB
  • Disk capacity = surfaces × tracks per surface × sectors per track × bytes per sector
  • Average rotational latency = ½ × time for one rotation; one rotation (ms) = 60,000 ÷ RPM
  • Access time = seek time + rotational latency + transfer time
  • Average memory access time = hit ratio × cache time + (1 − hit ratio) × (cache time + RAM time)

5 important questions

Q1. Differentiate SRAM and DRAM.

SRAM stores each bit in a flip-flop, needs no refresh, is faster and costlier, and is used for cache. DRAM stores each bit as charge in a capacitor, must be refreshed thousands of times a second, is slower and cheaper, and is used as main memory.

Q2. What is cache memory? Why is it used?

Cache is a small, very fast memory between the CPU and RAM. It keeps copies of the data and instructions the CPU uses most often, so the CPU waits less. It works because programs tend to reuse nearby and recent data (locality of reference).

Q3. A disk has 4 platters (8 surfaces), 1000 tracks per surface, 50 sectors per track and 512 bytes per sector. Find its capacity.

  • Capacity = 8 × 1000 × 50 × 512
  • = 8 × 1000 = 8000; 8000 × 50 = 400,000 sectors
  • 400,000 × 512 = 204,800,000 bytes
  • In MB = 204,800,000 ÷ (1024 × 1024) ≈ 195.3 MB

Q4. A disk rotates at 6000 RPM and has an average seek time of 5 ms. Find the average access time, ignoring transfer time.

  • One rotation = 60,000 ÷ 6000 = 10 ms
  • Average rotational latency = 10 ÷ 2 = 5 ms
  • Access time = 5 + 5 = 10 ms

Q5. Explain the memory hierarchy with a diagram (in words).

Outline: draw a pyramid with registers at the top, then cache, main memory (RAM), secondary storage (SSD/HDD) and backup storage (optical disc, tape) at the bottom. Moving down, capacity increases, while speed and cost per bit decrease. Explain why a hierarchy gives speed close to the top level at a cost close to the bottom level. Give an example size for each level.

Exam tip

Write the capacity formula first, then substitute values, and always state the unit (bytes, KB, MB). Remember 1 KB = 1024 bytes in memory questions.

BSc First Year · Computer Science · Chapter 4

Number Systems

Quick summary

A number system is a way of representing numbers using a set of symbols. Computers use the binary system because electronic circuits have two states, ON and OFF. This topic covers decimal, binary, octal and hexadecimal systems, conversions between them, binary arithmetic, complements and codes like BCD, ASCII and Gray code.

Key points

  • Base (radix) = number of digits used. Decimal = 10 (0–9), Binary = 2 (0, 1), Octal = 8 (0–7), Hexadecimal = 16 (0–9, A–F where A = 10 … F = 15).
  • Each position has a place value = base raised to the position (starting at 0 from the right of the point).
  • Decimal to any base: divide repeatedly by the base and read the remainders from bottom to top. For a fraction, multiply repeatedly by the base and read the integer parts from top to bottom.
  • Any base to decimal: multiply each digit by its place value and add.
  • Binary to octal: group 3 bits from the right. Binary to hex: group 4 bits.
  • Binary addition: 0+0 = 0, 0+1 = 1, 1+1 = 10 (sum 0, carry 1), 1+1+1 = 11.
  • 1's complement: change every 0 to 1 and 1 to 0.
  • 2's complement = 1's complement + 1. Computers use 2's complement to subtract by adding.
  • In signed 8-bit 2's complement, the range is −128 to +127.
  • BCD (8421 code): each decimal digit is written as a 4-bit binary number. 59 = 0101 1001.
  • ASCII: 7-bit code for characters. 'A' = 65, 'a' = 97, '0' = 48. Unicode covers all world scripts, including Devanagari.
  • Gray code: only one bit changes between two consecutive numbers. Used in encoders.

Important terms

  • Radix – base of a number system.
  • MSB / LSB – most significant bit (leftmost) / least significant bit (rightmost).
  • Nibble – group of 4 bits.
  • Complement – value used to represent negative numbers and to do subtraction.
  • Weighted code – each bit position has a fixed weight (BCD 8421).

Formulas

  • Value = Σ dᵢ × bⁱ (dᵢ = digit, b = base, i = position)
  • r's complement of N (n digits) = rⁿ − N; (r − 1)'s complement = (rⁿ − 1) − N
  • Binary to Gray: G₁ = B₁ (MSB same); Gᵢ = Bᵢ₋₁ XOR Bᵢ
  • Range of n-bit unsigned = 0 to 2ⁿ − 1; signed 2's complement = −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1
DecimalBinaryOctalHex
10101012A
15111117F
16100002010

5 important questions

Q1. Convert (45)₁₀ to binary.

45 ÷ 2 = 22 r 1; 22 ÷ 2 = 11 r 0; 11 ÷ 2 = 5 r 1; 5 ÷ 2 = 2 r 1; 2 ÷ 2 = 1 r 0; 1 ÷ 2 = 0 r 1. Reading bottom to top: (45)₁₀ = (101101)₂.

Q2. Convert (2AF)₁₆ to decimal.

2 × 16² + A(10) × 16¹ + F(15) × 16⁰ = 512 + 160 + 15 = (687)₁₀.

Q3. Convert (110101.101)₂ to decimal.

  • Integer: 1×32 + 1×16 + 0×8 + 1×4 + 0×2 + 1×1 = 53
  • Fraction: 1×½ + 0×¼ + 1×⅛ = 0.5 + 0.125 = 0.625
  • Answer: (53.625)₁₀
  • Check with octal: 110 101 . 101 = (65.5)₈ = 6×8 + 5 + 5/8 = 53.625 ✓

Q4. Subtract 9 from 5 using 8-bit 2's complement (5 − 9).

  • 5 = 00000101; 9 = 00001001
  • 1's complement of 9 = 11110110; 2's complement = 11110111
  • Add: 00000101 + 11110111 = 11111100 (no carry out)
  • No carry → result is negative; take 2's complement of 11111100 = 00000100 = 4
  • Answer = −4 ✓

Q5. Explain BCD, ASCII and Gray code with examples.

  • BCD: each decimal digit in 4 bits; 92 = 1001 0010. Codes 1010–1111 are invalid.
  • ASCII: 7-bit character code (128 characters); 'B' = 66 = 1000010.
  • Gray: unit-distance code; binary 0111 (7) → Gray 0100; 1000 (8) → Gray 1100.
  • Uses: BCD in calculators and digital displays, ASCII in text files, Gray in rotary encoders.

Exam tip

Show every division or multiplication step in conversions. In 2's complement problems, state clearly whether a carry came out and what it means.

BSc First Year · Computer Science · Chapter 5

Boolean Algebra and Logic Gates

Quick summary

Boolean algebra is the algebra of two values, 0 (false) and 1 (true), developed by George Boole. It is the mathematics of digital circuits. This topic covers basic operations, laws and theorems (including De Morgan's), logic gates, universal gates, simplification by K-map, and simple combinational circuits like adders.

Key points

  • Three basic operations: AND (A·B), OR (A + B), NOT (A′ or Ā).
  • Logic gates are electronic circuits that perform Boolean operations: AND, OR, NOT, NAND, NOR, XOR, XNOR.
  • NAND and NOR are universal gates: any other gate can be built using only NAND gates or only NOR gates.
  • XOR gives 1 when the inputs are different; XNOR gives 1 when the inputs are the same.
  • De Morgan's theorems: (A + B)′ = A′·B′ and (A·B)′ = A′ + B′.
  • A truth table lists the output for every input combination. n inputs give 2ⁿ rows.
  • Boolean expressions are written in SOP (sum of products, from minterms) or POS (product of sums, from maxterms) form.
  • Karnaugh map (K-map): a grid method to simplify expressions of 2, 3 or 4 variables. Adjacent cells differ by one variable (Gray code order). Group 1s in pairs, quads, octets.
  • Half adder: adds two bits. Sum = A ⊕ B, Carry = A·B.
  • Full adder: adds three bits (A, B, carry-in). Sum = A ⊕ B ⊕ C, Carry = AB + BC + CA. It can be made from two half adders and an OR gate.
  • Duality principle: interchanging AND ↔ OR and 0 ↔ 1 in a valid identity gives another valid identity.

Important terms

  • Boolean variable – variable that can take only 0 or 1.
  • Minterm – product term containing all variables (gives 1 for one input combination).
  • Maxterm – sum term containing all variables (gives 0 for one combination).
  • Universal gate – gate that can implement any Boolean function alone.
  • Combinational circuit (संयोजी परिपथ) – circuit whose output depends only on present inputs.

Formulas

Laws of Boolean algebra:

  • Identity: A + 0 = A; A·1 = A
  • Null: A + 1 = 1; A·0 = 0
  • Idempotent: A + A = A; A·A = A
  • Complement: A + A′ = 1; A·A′ = 0
  • Involution: (A′)′ = A
  • Commutative, associative and distributive: A(B + C) = AB + AC; A + BC = (A + B)(A + C)
  • Absorption: A + AB = A; A(A + B) = A
  • A + A′B = A + B
  • XOR: A ⊕ B = A′B + AB′
ABANDORNANDNORXOR
0000110
0101101
1001101
1111000

5 important questions

Q1. Why are NAND and NOR called universal gates?

Because every basic gate (NOT, AND, OR) and so every Boolean function can be built using only NAND gates or only NOR gates. Example: NOT A = A NAND A.

Q2. State and prove one of De Morgan's theorems using a truth table.

(A + B)′ = A′·B′. For inputs 00, 01, 10, 11, (A + B)′ gives 1, 0, 0, 0 and A′·B′ gives 1, 0, 0, 0. Both columns match, so the theorem is proved.

Q3. Simplify Y = AB + AB′ + A′B using Boolean laws.

  • Y = A(B + B′) + A′B
  • = A·1 + A′B = A + A′B
  • = (A + A′)(A + B) (distributive law)
  • = 1·(A + B)
  • Y = A + B

Q4. Simplify F(A, B, C) = Σm(1, 3, 5, 7) using a K-map.

  • Minterms 1 (001), 3 (011), 5 (101), 7 (111) all have C = 1.
  • In the 3-variable K-map the four 1s lie in the C = 1 column/row and form one quad.
  • In the quad, A and B change, C stays 1.
  • F = C

Q5. Explain the full adder with truth table and logic diagram.

  • Inputs A, B, Cin; outputs Sum, Cout.
  • Sum = A ⊕ B ⊕ Cin; Cout = AB + Cin(A ⊕ B), which simplifies to AB + BCin + ACin.
  • Truth table has 8 rows; e.g. 1, 1, 1 → Sum 1, Cout 1; 1, 1, 0 → Sum 0, Cout 1.
  • Built using two half adders and one OR gate.
  • Used in ALUs to add multi-bit numbers (ripple carry adder).

Exam tip

Always draw the truth table to check your simplified answer. In K-map, make groups as large as possible and wrap around the edges.

BSc First Year · Computer Science · Chapter 6

Computer Software and Programming Languages

Quick summary

Software is the set of programs that tells the hardware what to do. This topic covers the types of software (system, application, utility), open-source and proprietary software, the generations of programming languages from machine language to 4GL, language translators (assembler, compiler, interpreter), and the linker and loader that prepare a program to run.

Key points

  • System software controls the hardware and gives a platform for other programs: operating system, device drivers, translators, utilities.
  • Application software does a user's task: word processor, spreadsheet, browser, Tally, games.
  • Utility software maintains the computer: antivirus, disk cleanup, backup, compression (zip).
  • Proprietary software is owned by a company; source code is closed (MS Windows, MS Office). Open-source software gives free access to source code (Linux, LibreOffice, Python). Freeware is free to use but may be closed source.
  • 1GL – Machine language: binary 0s and 1s; runs directly, very fast, but hard to write and machine-dependent.
  • 2GL – Assembly language: uses mnemonics like ADD, MOV, SUB; needs an assembler; still machine-dependent.
  • 3GL – High-level languages: English-like (C, C++, Java, Python); portable; need a compiler or interpreter.
  • 4GL: closer to human language, for databases and reports (SQL). 5GL: based on rules and logic, used in AI (Prolog).
  • Compiler translates the whole program at once into object code and lists all errors together (C, C++).
  • Interpreter translates and runs one line at a time and stops at the first error (Python, BASIC).
  • Linker joins object files and library code into one executable file. Loader places the executable into RAM and starts it.
  • Steps to run a C program: source code (.c) → compiler → object code (.obj/.o) → linker → executable (.exe) → loader → RAM → run.

Important terms

  • Source code – the program written by the programmer in a high-level language.
  • Object code – the machine-code output of a compiler or assembler.
  • Mnemonic – a short word for a machine instruction, e.g. MOV.
  • Syntax error – breaking the grammar rules of a language.
  • Logical error – the program runs but gives a wrong result.
  • Debugging – finding and removing errors.

Formulas

PointCompilerInterpreter
TranslationWhole program at onceOne statement at a time
Object fileCreatedNot created
Error reportAll errors after compilingStops at first error
Execution speedFasterSlower
ExampleC, C++Python, BASIC
GenerationExampleTranslator needed
1GL Machine10110000 01100001None
2GL AssemblyMOV AL, 61hAssembler
3GL High levelprintf("Hi");Compiler / interpreter
4GLSELECT * FROM student;DBMS query processor

5 important questions

Q1. Differentiate system software and application software.

System software runs and manages the computer itself and works in the background (OS, drivers, translators). Application software is used by the user for a particular job (MS Word, browser, billing software). Application software cannot run without system software.

Q2. What is the role of a linker and a loader?

The linker combines the object code of the program with object code of library functions (such as printf) and other modules, and resolves addresses, to make one executable file. The loader copies this executable from disk into main memory, sets the starting address and hands control to the program.

Q3. Explain the generations of programming languages with merits and demerits.

Outline: 1GL machine language (fast, no translation; hard, machine-dependent) → 2GL assembly (mnemonics, easier; still machine-dependent, needs assembler) → 3GL high-level (English-like, portable, easy to debug; slower, needs translator) → 4GL (very little code, non-procedural, e.g. SQL) → 5GL (logic programming for AI). Give one example for each.

Q4. Compare compiler, interpreter and assembler.

All three are language translators. An assembler converts assembly language into machine code. A compiler converts a whole high-level program into machine code before running. An interpreter converts and runs a high-level program line by line. Add the comparison table above.

Q5. Explain open-source and proprietary software with examples. Which is better for a college lab?

Open-source: source code available, free to modify and share, community support (Linux, LibreOffice, Python, GIMP). Proprietary: licence fee, closed code, vendor support (Windows, MS Office, Photoshop). For a college lab, open source cuts cost and lets students study the code, but some subjects need specific proprietary tools; many labs use a mix.

Exam tip

Learn the compiler vs interpreter table by heart; it is asked almost every year. In "steps to run a program" draw the flow with arrows and name the file at each stage.

BSc First Year · Computer Science · Chapter 7

Operating System Basics

Quick summary

An operating system (OS) is system software that manages the computer's hardware and provides services to programs and users. It acts as an interface between the user and the hardware. This topic covers OS functions, types of OS, booting, and an introduction to Windows, Linux and common commands.

Key points

  • An OS is the first program loaded at start-up; all other programs run on top of it. Examples: Windows, Linux, macOS, Android, iOS.
  • Functions of OS: process management, memory management, file management, device (I/O) management, security and protection, user interface, error detection.
  • User interface: CLI (command line, e.g. MS-DOS, Linux terminal) or GUI (graphical, icons and windows, e.g. Windows).
  • Types of OS:
  • Batch OS – similar jobs are grouped and run without user interaction.
  • Multiprogramming – several programs in memory; CPU switches when one waits for I/O.
  • Time-sharing (multitasking) – CPU time divided in small slices among users or tasks.
  • Multiprocessing – more than one CPU.
  • Real-time OS – gives response within a fixed time (traffic control, medical devices).
  • Distributed and network OS – manage many connected computers.
  • Mobile OS – Android, iOS.
  • Booting: process of starting the computer. Cold boot (power on) and warm boot (restart). BIOS/UEFI runs POST, then the boot loader loads the OS kernel.
  • Kernel is the core part of the OS that always stays in memory.
  • Linux is open-source and free; it is widely used on servers. Windows is proprietary.
  • File systems organise files into directories (folders) in a tree. Windows uses NTFS; Linux commonly uses ext4.

Important terms

  • Kernel – core of the OS that controls hardware and resources.
  • Shell – program that takes user commands and passes them to the kernel.
  • Process – a program in execution.
  • Booting (संगणक सुरू करणे) – loading the OS into memory at start-up.
  • Device driver – small program that lets the OS talk to a hardware device.
  • Open-source software – software whose source code is freely available (Linux).

Formulas

Common commands (no formulas in this topic):

TaskMS-DOS / WindowsLinux
List filesdirls
Change directorycdcd
Make directorymd / mkdirmkdir
Copy filecopycp
Delete filedelrm
Rename / moverenmv
Show file contenttypecat
Clear screenclsclear

5 important questions

Q1. Define operating system. Give two examples.

An operating system is system software that manages hardware resources and provides an environment for running programs. It is an interface between user and computer. Examples: Windows 11 and Linux (Ubuntu).

Q2. Differentiate CLI and GUI.

In a CLI the user types text commands; it needs memorising commands but uses few resources. In a GUI the user clicks icons, menus and windows with a mouse; it is easy for beginners but needs more memory.

Q3. Explain the functions of an operating system.

  • Process management: creating, scheduling and ending processes.
  • Memory management: allocating and freeing RAM.
  • File management: creating, deleting and organising files and folders.
  • Device management: controlling I/O devices through drivers.
  • Security: passwords, permissions; user interface; error handling.

Q4. Explain different types of operating systems.

  • Batch: jobs grouped, no interaction (old mainframes).
  • Time-sharing: many users share CPU through time slices.
  • Real-time: strict time limits (hard and soft real-time).
  • Distributed: many computers appear as one system.
  • Mobile/embedded: Android, iOS; designed for low power and touch.

Q5. What is booting? Explain the booting process.

  • Booting is loading the OS into main memory when the computer starts.
  • Power on → BIOS/UEFI in ROM runs.
  • POST (power-on self-test) checks hardware.
  • Boot loader is found on the boot device and loaded.
  • Boot loader loads the kernel; OS starts services and shows the login screen.
  • Cold boot vs warm boot.

Exam tip

Learn the list of OS functions and OS types with one example each; these are asked as both short and long questions.

BSc First Year · Computer Science · Chapter 8

Internet and Its Applications

Quick summary

The Internet is a worldwide network of networks that uses the TCP/IP protocols to connect millions of computers. This topic covers its history, how one connects to it, the World Wide Web, URLs and domain names, web browsers and search engines, e-mail, and everyday uses such as e-commerce, net banking and e-learning, with basic safety rules.

Key points

  • The Internet began with ARPANET (1969) in the USA. The World Wide Web was invented by Tim Berners-Lee at CERN (proposed in 1989).
  • The Internet is the hardware network; the WWW is a service on it made of linked web pages.
  • ISP (Internet Service Provider) gives Internet access, e.g. BSNL, Jio, Airtel.
  • Ways to connect: dial-up (old), DSL/broadband, fibre (FTTH), cable, mobile data (4G/5G), Wi-Fi, satellite.
  • Web page is written in HTML; a website is a group of related pages; the first page is the home page.
  • Web browser displays web pages: Chrome, Firefox, Edge, Safari.
  • Search engine finds pages using keywords: Google, Bing, DuckDuckGo.
  • URL (Uniform Resource Locator) is the full address of a resource, e.g. https://www.example.com/notes/index.html.
  • DNS (Domain Name System) converts a domain name into an IP address.
  • E-mail address format: username@domain. Parts of a mail: To, Cc, Bcc, Subject, body, attachment.
  • Protocols: HTTP/HTTPS (web), SMTP (sending mail), POP3/IMAP (receiving mail), FTP (file transfer).
  • Applications: e-commerce, net banking, UPI payments, e-governance (DigiLocker, online forms), e-learning, social media, video calls.
  • Safety: strong passwords, check for HTTPS, avoid unknown links (phishing), never share OTP.

Important terms

  • Hyperlink – clickable text or image that opens another page.
  • IP address – unique number of a device on a network, e.g. 192.168.1.1 (IPv4).
  • Domain name – easy name of a website, e.g. example.com.
  • Bandwidth – amount of data that can be sent per second (Mbps).
  • Cookie – small data file a website stores in the browser.
  • Intranet – private network inside an organisation using Internet technology.

Formulas

Parts of the URL https://www.example.com:443/notes/page.html:

PartMeaning
httpsProtocol (secure HTTP)
www.example.comHost / domain name
443Port number (optional)
/notes/page.htmlPath of the file on the server
Top-level domainUsed for
.comCommercial
.eduEducation
.gov / .gov.inGovernment
.orgOrganisations
.inIndia (country code)
  • Download time (s) = file size (bits) ÷ speed (bits per second)

5 important questions

Q1. Differentiate Internet and WWW.

The Internet is the global network of connected computers, cables and routers. The WWW is one service that runs on the Internet, made of web pages linked by hyperlinks and accessed with HTTP through a browser. E-mail and FTP use the Internet but are not part of the WWW.

Q2. How long will a 40 MB file take to download at 8 Mbps? (Take 1 MB = 8 Mb, decimal units.)

  • File size = 40 × 8 = 320 megabits
  • Time = 320 ÷ 8 = 40 seconds

Q3. Explain e-mail: its parts, working and advantages.

Outline: define e-mail → address format → parts (To, Cc, Bcc, Subject, body, attachment, signature) → working (client sends with SMTP to the mail server, receiver's server stores it, receiver reads with POP3/IMAP) → advantages (fast, cheap, attachments, record kept) → limitations (spam, phishing, needs Internet).

Q4. What is a search engine? Explain how it works.

A search engine is a website that finds information on the WWW. It works in three steps: crawling (programs called spiders visit pages and follow links), indexing (words of each page are stored in a huge index), and ranking (when you type keywords, matching pages are sorted by relevance and shown). Tips: use exact words in quotes and site: to search one website.

Q5. Explain any five applications of the Internet.

E-commerce (Amazon, Flipkart), net banking and UPI, e-learning (SWAYAM, YouTube lectures), e-governance (online scholarship and admission forms, DigiLocker), communication (e-mail, video calls, social media), and entertainment. Write 2 lines on each with one example.

Exam tip

Write a URL and label its parts in Q&A on the Internet; it earns easy marks. Know the full forms: HTTP, HTTPS, URL, DNS, ISP, SMTP, FTP.

BSc First Year · Computer Science · Chapter 9

Algorithms and Flowcharts

Quick summary

Before writing a program, a programmer plans the solution. An algorithm is a step-by-step method to solve a problem, and a flowchart is a diagram of that method. This topic covers characteristics of algorithms, flowchart symbols, pseudocode, and examples like finding the largest number, factorial and prime check.

Key points

  • Algorithm: a finite set of clear, ordered steps that solves a problem. The word comes from the Persian mathematician al-Khwarizmi.
  • Characteristics (by Knuth): input (zero or more), output (at least one), definiteness (each step clear), finiteness (ends after finite steps), effectiveness (each step basic and doable).
  • Flowchart (प्रवाह आकृती): a graphical representation of an algorithm using standard symbols joined by arrows.
  • Pseudocode: algorithm written in simple English-like statements close to program code.
  • Three basic control structures: sequence, selection (decision: if–else) and iteration (repetition: loops).
  • Advantages of flowcharts: easy to understand, good for communication, help in debugging and documentation.
  • Limitations: difficult for large programs; changes need redrawing.
  • Complexity of an algorithm: time complexity (how steps grow with input size n) and space complexity (memory used). Written with Big-O notation, e.g. O(n), O(n²), O(log n).
  • Program development steps: define problem → analyse → design algorithm/flowchart → code → test and debug → document → maintain.

Important terms

  • Terminal – start or end of a flowchart.
  • Decision box – diamond shape with a yes/no question.
  • Connector – small circle to join parts of a flowchart.
  • Dry run – checking an algorithm by hand with sample values.
  • Big-O – upper bound on growth of running time.

Formulas

Flowchart symbols:

SymbolShapeUse
Terminaloval / rounded rectanglestart, stop
Input/Outputparallelogramread, print
Processrectanglecalculation, assignment
Decisiondiamondcondition, yes/no
Flow linearrowdirection of flow
Connectorsmall circlejoin parts

Common complexities: linear search O(n); binary search O(log n); bubble sort O(n²).

5 important questions

Q1. Define algorithm. State its characteristics.

An algorithm is a finite sequence of clear steps for solving a problem. Characteristics: input, output, definiteness, finiteness and effectiveness.

Q2. Differentiate between an algorithm and a flowchart.

An algorithm is written in steps using words; a flowchart is a diagram using symbols and arrows. Algorithms are easier to write for big problems; flowcharts are easier to understand visually.

Q3. Write an algorithm and describe the flowchart to find the largest of three numbers.

  1. Start.
  2. Read A, B, C.
  3. If A > B and A > C, print A is largest.
  4. Else if B > C, print B is largest.
  5. Else print C is largest.
  6. Stop.
  • Flowchart: oval Start → parallelogram Read A, B, C → diamond "A > B and A > C?" → Yes: print A; No: diamond "B > C?" → Yes: print B; No: print C → oval Stop.

Q4. Write an algorithm to find the factorial of a number N and dry-run it for N = 4.

  1. Start. Read N.
  2. Set F = 1, I = 1.
  3. While I ≤ N: F = F × I; I = I + 1.
  4. Print F. Stop.
  • Dry run: I=1, F=1; I=2, F=2; I=3, F=6; I=4, F=24; I=5 stops loop. Output 24.

Q5. Write an algorithm to check whether a number is prime.

  1. Start. Read N.
  2. If N < 2, print "Not prime" and stop.
  3. Set I = 2, flag = 0.
  4. While I × I ≤ N: if N mod I = 0, set flag = 1 and exit loop; else I = I + 1.
  5. If flag = 0 print "Prime", else print "Not prime".
  6. Stop. (Checking up to √N is enough.)

Exam tip

Draw flowcharts with correct shapes — examiners deduct marks for a wrong symbol. Always include Start and Stop.

BSc First Year · Computer Science · Chapter 10

C Programming Basics

Quick summary

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.

Key points

  • 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.

Important terms

  • 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 +, −).

Formulas

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.

5 important questions

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.

Exam tip

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

BSc First Year · Computer Science · Chapter 11

Operators, Expressions and Type Conversion in C

Quick summary

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.

Key points

  • 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.

Important terms

  • 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.

Formulas

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

5 important questions

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.

Exam tip

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.

BSc First Year · Computer Science · Chapter 12

Control Statements in C

Quick summary

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.

Key points

  • 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.

Important terms

  • 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.

Formulas

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 */

5 important questions

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.

Exam tip

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

BSc First Year · Computer Science · Chapter 13

Arrays and Strings

Quick summary

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.

Key points

  • 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.

Important terms

  • 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.

Formulas

  • 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 */

5 important questions

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.

Exam tip

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

BSc First Year · Computer Science · Chapter 14

Functions in C

Quick summary

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.

Key points

  • 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).

Important terms

  • 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.

Formulas

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); }

5 important questions

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.

Exam tip

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

BSc First Year · Computer Science · Chapter 15

Pointers and Structures

Quick summary

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.

Key points

  • 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.

Important terms

  • 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).

Formulas

  • 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);

5 important questions

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).

Exam tip

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.

BSc First Year · Computer Science · Chapter 16

Dynamic Memory Allocation in C

Quick summary

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.

Key points

  • 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.

Important terms

  • 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.

Formulas

  • 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))

5 important questions

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.

Exam tip

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

BSc First Year · Computer Science · Chapter 17

Preprocessor Directives and Command-Line Arguments

Quick summary

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.

Key points

  • 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>.

Important terms

  • 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).

Formulas

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; }

5 important questions

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.

Exam tip

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

BSc First Year · Computer Science · Chapter 18

File Handling in C

Quick summary

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.

Key points

  • 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.

Important terms

  • 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.

Formulas

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

5 important questions

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.

Exam tip

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.