1FY3-06/ 2FY3-06 · RTU · 1st Year
Programming for Problem Solving
Fundamentals of Computer, Number System, and detailed C Programming.
Last time you stopped at card —. ·
- 20cards
- 3units
- 0nailed
- 8diagrams
20/20
-
Stored Program Architecture (Von Neumann Architecture)
The stored-program concept is a fundamental principle of computer design, largely attributed to John von Neumann. Before this concept, early computers (like ENIAC) had to be physically rewired to perform different tasks. The stored-program architecture revolutionized computing by proposing that both the program instructions and the data should be stored in the same electronic memory.
Core Components:
- Central Processing Unit (CPU): The brain of the computer. It consists of the Arithmetic Logic Unit (ALU) which performs mathematical and logical operations, and the Control Unit (CU) which directs the operation of the processor by fetching, decoding, and executing instructions from memory.
- Memory Unit: Also known as Primary Memory or RAM. It holds both the instructions of the program currently being executed and the data those instructions manipulate. This single unified memory is the hallmark of the Von Neumann architecture.
- Input/Output (I/O) Devices: Mechanisms for getting data into the computer (e.g., keyboard, mouse) and getting results out (e.g., monitor, printer).
- System Buses: Communication pathways that connect the CPU, memory, and I/O devices. The Data Bus carries actual data, the Address Bus carries memory addresses, and the Control Bus carries control signals (like read/write commands).
The Fetch-Decode-Execute Cycle
In a stored-program computer, execution happens in a continuous loop:
- 1. Fetch: The Control Unit fetches the next instruction from memory using the Program Counter (PC) which holds the address of the next instruction.
- 2. Decode: The instruction is decoded by the Control Unit to understand what operation is required.
- 3. Execute: The ALU performs the operation on the data, and the result is stored either in a register or back in memory.
Advantages and The Von Neumann Bottleneck
The primary advantage is immense flexibility; changing the program is as simple as loading new instructions into memory, without changing hardware. However, because both data and instructions share the same bus to the CPU, a phenomenon known as the Von Neumann Bottleneck occurs. The CPU is vastly faster than memory, and it must wait idle while instructions or data are fetched one at a time over this shared bus, limiting overall system performance.
-
Primary Memory (Main Memory)
Primary memory is the computer hardware directly accessible by the CPU without the use of computer's input/output channels. It is used to store data and instructions that are currently being processed. It is generally faster but has lower capacity compared to secondary storage.
1. Random Access Memory (RAM)
RAM is the working space of the computer. It is volatile, meaning it loses its contents when the power is turned off. It allows data to be read or written in almost the same amount of time regardless of the physical location of data inside the memory.
- Static RAM (SRAM): Retains data as long as power is supplied without needing to be refreshed. It uses flip-flops to store each bit. SRAM is very fast, expensive, and takes up more space, making it ideal for CPU Cache memory (L1, L2, L3 caches).
- Dynamic RAM (DRAM): Stores each bit of data in a separate tiny capacitor. Because capacitors leak charge, DRAM must be periodically refreshed (thousands of times per second). It is slower than SRAM but much cheaper and denser, making it the standard main system memory in computers.
2. Read-Only Memory (ROM)
ROM is non-volatile memory. Data stored in ROM cannot be easily modified and remains intact even when the computer is powered off. It typically contains essential firmware.
- Mask ROM: Data is written during the manufacturing process and can never be changed.
- PROM (Programmable ROM): Can be programmed only once by a user using a special device. Once written, the data is permanent.
- EPROM (Erasable Programmable ROM): Can be erased by exposing it to strong ultraviolet (UV) light and then rewritten.
- EEPROM (Electrically Erasable Programmable ROM): Can be erased and reprogrammed electrically without removing it from the computer. Flash memory (used in USB drives and SSDs) is a modern, advanced type of EEPROM.
Role in Boot Process
When a computer is turned on, the CPU first reads instructions from the ROM (specifically the BIOS/UEFI). These instructions perform a Power-On Self-Test (POST) and then load the Operating System from the secondary storage into the RAM, where the CPU can then execute it.
-
Secondary Storage Devices
Secondary storage is non-volatile, long-term memory. It is not directly accessible by the CPU; instead, data must be transferred to primary memory (RAM) before the CPU can process it. Secondary storage provides vastly more capacity than primary memory at a much lower cost per byte, but it is significantly slower.
Magnetic Storage
Uses magnetic patterns to represent data.
- Hard Disk Drives (HDD): Consist of spinning magnetic platters and mechanical read/write heads on an actuator arm. They offer massive storage capacities (Terabytes) at low cost. However, the mechanical moving parts make them susceptible to physical damage and relatively slow compared to solid-state memory. Data is organized into concentric circles called tracks, which are divided into sectors.
- Magnetic Tape: One of the oldest storage mediums. It is purely sequential access. While terribly slow for random data retrieval, it is extremely cheap per terabyte and highly durable, making it the gold standard for massive enterprise data archiving and backups.
Optical Storage
Uses lasers to read and write data. The surface of the disc has microscopic pits (depressions) and lands (flat areas). A laser beam reflects differently off pits and lands, representing binary 0s and 1s.
- CD (Compact Disc): Typically stores around 700 MB. Used for audio and basic software.
- DVD (Digital Versatile Disc): Uses a finer laser, allowing for tighter tracks and a standard capacity of 4.7 GB. Used for movies and larger software.
- Blu-ray Disc: Uses a blue-violet laser with an even shorter wavelength, achieving capacities of 25 GB to 50 GB per layer. Used for HD movies and massive video games.
Solid State Storage (Flash Memory)
Uses electronic circuits (NAND flash memory) to store data persistently with zero moving mechanical parts.
- Solid State Drives (SSD): Serve the same function as HDDs but are orders of magnitude faster. They drastically reduce boot times and application loading times. Because there are no moving parts, they are silent, use less power, and are highly resistant to physical shock. The main drawback is a higher cost per gigabyte compared to HDDs.
- USB Flash Drives / SD Cards: Highly portable flash storage used for transferring files between devices and expanding storage in cameras and smartphones.
-
Data Access Methods
An access method refers to the way a computer reads data from or writes data to a storage medium. The efficiency of a program often heavily depends on the access method utilized by the underlying hardware.
1. Sequential Access
In sequential access, data must be accessed in a linear, consecutive sequence. To reach a specific piece of data, the system must read through all the preceding data items.
- Analogy: Like a cassette tape. If you want to listen to song #5, you must fast-forward past songs 1, 2, 3, and 4.
- Hardware Example: Magnetic Tape drives.
- Use Case: Excellent for processing massive batches of data where every record needs to be read in order (like payroll processing or generating monthly bank statements) and for deep-archive backups.
- Speed: Very slow if you need to find a specific, random piece of data.
2. Direct Access (Relative Access)
Direct access allows the mechanism to jump directly to a general vicinity of the data, and then perform a short sequential search to find the exact item. Records are usually stored with a unique identifier or physical address.
- Analogy: Like a CD or vinyl record. You can move the laser/needle directly to the start of track #5, bypassing tracks 1-4.
- Hardware Example: Hard Disk Drives (HDD). The read/write head moves directly to the correct track (cylinder), waits for the correct sector to rotate under it, and then reads the data.
- Speed: Much faster than sequential access for finding random data, but still involves mechanical latency (seek time and rotational delay).
3. Random Access
In random access, any location in the storage medium can be accessed directly in exactly the same amount of time, completely independent of the physical location of the data or the location of the previously accessed data.
- Analogy: Like opening a book directly to page 150 without flipping through pages 1 to 149.
- Hardware Example: RAM (Random Access Memory) and ROM. Every memory cell has a unique electronic address, and the CPU can request data from address 0x0001 or address 0xFFFF in the exact same number of clock cycles.
- Speed: The fastest access method, virtually instantaneous, as there are no moving mechanical parts involved.
-
Concepts of Computer Languages
A computer only understands binary electrical signals (on/off, 1/0). To bridge the gap between human thought and computer execution, programming languages are categorized into different levels of abstraction.
1. Low-Level Language (Machine Language)
Machine language is the lowest level of programming. It consists entirely of binary strings (0s and 1s) representing opcodes (operations) and operands (data/addresses). This is the only language the CPU natively understands.
- Pros: Executes at maximum possible speed with zero translation overhead. Gives the programmer absolute, hardware-level control.
- Cons: Extremely difficult for humans to read, write, or debug. Highly error-prone. It is entirely machine-dependent (code written for an Intel CPU will not work on an ARM CPU).
2. Assembly Language
Assembly language is a step up from machine code. Instead of binary, it uses short alphabetic mnemonics to represent machine instructions (e.g.,
ADD,MOV,SUB,JMP).- Translation: Requires a program called an Assembler to translate the mnemonics back into binary machine code before the CPU can execute it.
- Pros: Much easier to read and write than pure binary. Still provides near-absolute control over hardware and CPU registers, resulting in highly optimized, fast software.
- Cons: Still machine-dependent (tied to a specific CPU architecture). Writing large applications is incredibly tedious and slow. Mostly used today in embedded systems, writing OS kernels, or hardware drivers.
3. High-Level Language (HLL)
High-Level Languages (like C, Python, Java, C++) use English-like vocabulary and standard mathematical notation. They abstract away the underlying hardware details (like register allocation and memory addressing).
- Translation: Requires a Compiler (translates the entire program into machine code at once before execution) or an Interpreter (translates and executes the code line-by-line in real-time).
- Pros: Highly readable, easy to learn, and much faster to write code. Crucially, HLLs are portable (machine-independent). A C program written on a Windows PC can be compiled to run on a Linux server or a Mac.
- Cons: Generally runs slightly slower than perfectly optimized assembly code due to the translation overhead and abstraction layers.
-
Representing Algorithms: Flowcharts and Pseudo Code
Before writing a program in a specific language like C, programmers must design the logic. An Algorithm is a step-by-step procedure to solve a specific problem. Algorithms are language-independent and are typically represented using Pseudo code or Flowcharts.
1. Pseudo Code
Pseudo code (fake code) is an informal, plain English description of an algorithm. It uses the structural conventions of a programming language (like IF/ELSE, WHILE loops) but omits strict syntax rules (like missing semicolons or exact variable declarations). It is meant for human reading.
Example: Finding the largest of two numbers
START
INPUT number1, number2
IF number1 > number2 THEN
PRINT "number1 is larger"
ELSE
PRINT "number2 is larger"
ENDIF
STOP
2. Flowcharts
A flowchart is a graphical representation of an algorithm. It uses standard geometric shapes to represent different types of actions, and arrows (flowlines) to show the sequence of execution.
Standard Flowchart Symbols:
- Oval / Pill (Terminal): Represents the START or STOP of the program.
- Parallelogram (Input/Output): Represents taking input from the user or displaying output to the screen (e.g., "Read A", "Print Result").
- Rectangle (Process): Represents a computational action or assignment (e.g.,
Sum = A + B). - Diamond (Decision): Represents a conditional statement. It contains a question or comparison (e.g.,
Is A > B?). It always has two outgoing paths: Yes (True) and No (False). - Arrows (Flowlines): Connect the symbols to indicate the exact direction of logic flow.
Flowcharts are excellent for visualizing complex branching logic and loops before typing a single line of actual code, heavily reducing logical errors in the final program.
-
Theoretical Foundations of Number Systems
- Introduction to Number Systems: A number system is a mathematical framework used to represent numbers in various ways. In the context of computer science, number systems are fundamental because they dictate how hardware components, specifically logic gates and memory registers, store and manipulate data.
- The Radix and Positional Notation: The core of any positional number system is its base or radix. The radix defines the total number of unique digits or symbols available in that specific system to represent numbers. A radix of 'r' means the system uses digits from 0 to r-1. Furthermore, in a positional number system, the value of a digit depends not only on its inherent symbol but also on its position within the number. The position determines the weight of the digit, which is typically a power of the radix. Moving from right to left, the weight of each position increases by a factor of the base.
- The Decimal Number System (Base 10):
- It is the most universally used system by humans, operating on a base of 10.
- It utilizes ten unique symbols ranging from 0 to 9.
- Each position represents a power of 10, starting from 10^0 (units), 10^1 (tens), 10^2 (hundreds), and so forth.
- While highly intuitive for humans, the decimal system is highly inefficient for digital computers. Electronic circuits operate most reliably in two distinct states: high voltage (ON) and low voltage (OFF). Attempting to differentiate ten discrete voltage levels in a circuit would lead to significant errors due to electrical noise and signal degradation.
- The Binary Number System (Base 2):
- Because of hardware constraints, modern computers are built entirely upon the Binary Number System.
- It uses a base of 2, comprising only two symbols: 0 and 1.
- These two digits map perfectly to the two reliable electrical states of transistors and switches within a computer's processor.
- In binary, each digit is referred to as a "bit" (binary digit). The positional weights in binary are powers of 2, such as 2^0 (1), 2^1 (2), 2^2 (4), 2^3 (8), and so on.
- While binary is perfect for hardware, binary numbers tend to be extremely long and cumbersome for human programmers and engineers to read, write, and communicate. For example, a simple decimal number like 255 becomes an eight-bit string 11111111 in binary. This verbosity leads to a higher probability of human error when transcribing or debugging machine code.
- The Octal Number System (Base 8):
- To bridge the gap between computer-friendly binary and human readability, intermediate number systems like Octal are employed.
- It uses a base of 8, employing digits from 0 to 7. The positional weights are powers of 8.
- The mathematical relationship between base 2 and base 8 is crucial: 8 is exactly 2 to the power of 3.
- This means that exactly three binary bits can be represented by a single octal digit.
- Early computer architectures commonly used 12-bit, 24-bit, or 36-bit words, which were perfectly divisible by 3, making octal a very natural shorthand representation for binary strings in those eras.
- The Hexadecimal Number System (Base 16):
- As computer architectures evolved to favor 8-bit bytes, 16-bit words, and 32-bit/64-bit systems, the Hexadecimal Number System became the dominant shorthand.
- Hexadecimal uses a base of 16. Since we only have ten numeric digits (0-9), we borrow the first six letters of the alphabet (A, B, C, D, E, F) to represent the values 10 through 15 respectively.
- The positional weights are powers of 16. Just as 8 is 2^3, 16 is 2^4.
- Therefore, exactly four binary bits (a nibble) can be represented by a single hexadecimal digit.
- Because an 8-bit byte can be perfectly represented by exactly two hexadecimal digits, hex has become the standard for memory addresses, color codes in web design (like #FFFFFF for white), and low-level debugging.
- Conclusion and Practical Utility: Both octal and hex serve as compact, human-readable proxies for underlying binary data. They act as essential conceptual compression algorithms for computer scientists, allowing developers and engineers to work with complex data streams without drowning in endless sequences of ones and zeros. This significantly minimizes transcription errors and simplifies debugging processes while accurately reflecting the underlying binary state of the hardware.
Theoretical Methodologies for Base Conversions
The ability to convert numbers between different bases is a critical skill in computer science, bridging human input (typically decimal) with machine processing (binary) and programmer debugging (hexadecimal or octal). The theoretical foundation for these conversions relies heavily on the concepts of positional weighting and polynomial expansion. Every number in a positional system can be expressed as a polynomial where the coefficients are the digits and the variable is the radix of the system. Understanding this mathematical structure allows for standardized algorithms to translate values across any given radix.
To convert any number from a non-decimal base (like binary, octal, or hexadecimal) into the decimal system, we use the method of Polynomial Expansion or the Sum of Weights. This involves multiplying each digit of the number by its corresponding positional weight (which is the base raised to the power of the digit's position index, starting with index 0 at the rightmost integer digit) and summing all the resulting products. For example, converting a binary number involves multiplying the rightmost bit by 2^0, the next by 2^1, the next by 2^2, and so on. If the number has a fractional part (represented after a radix point), the positional indices become negative (e.g., -1, -2), meaning the weights become fractions like 2^-1 (0.5), 2^-2 (0.25). This expansion method theoretically proves that the core value of the number remains unchanged regardless of the symbols used to represent it.
Conversely, converting a decimal integer into any other base requires the Repeated Division Method. To find the equivalent representation of a decimal number in a target base 'r', the decimal number is successively divided by 'r'. In each division step, the integer quotient becomes the dividend for the next step, and the remainder becomes a digit of the new number. This process continues until the quotient reaches zero. The crucial aspect of this method is the order in which the remainders are read. The very first remainder obtained corresponds to the Least Significant Digit (LSD) — the rightmost digit of the new base. The final remainder obtained is the Most Significant Digit (MSD) — the leftmost digit. For fractional decimal numbers, a complementary Repeated Multiplication Method is used, where the fractional part is repeatedly multiplied by the target base, and the integer parts generated form the fractional digits in the new base, read from top to bottom.
While converting between decimal and other bases requires arithmetic (division or multiplication), conversions strictly between Binary, Octal, and Hexadecimal are purely structural, requiring no complex math. This is due to the exponential relationship between their bases: 8 = 2^3 and 16 = 2^4. To convert from Binary to Octal, one simply groups the binary bits into sets of three, starting from the radix point and moving outwards (left for integers, right for fractions). If the outermost group lacks three bits, it is padded with leading or trailing zeros. Each 3-bit group is then directly substituted with its equivalent single octal digit (from 0 to 7). For Binary to Hexadecimal, the exact same grouping principle applies, but the bits are grouped into sets of four, and substituted with hex digits (0-9, A-F).
To reverse the process (Octal or Hexadecimal back to Binary), the substitution is performed in reverse. Each octal digit is independently expanded into its exact 3-bit binary equivalent, and each hexadecimal digit is expanded into its exact 4-bit binary equivalent. These bit groups are then concatenated to form the complete binary string. The theoretical elegance of this structural conversion is what makes octal and hexadecimal such powerful tools for computer scientists; they act as perfect, error-free compression algorithms for binary data, allowing developers to mentally translate between the hardware's reality (binary) and a more manageable notation without needing calculators.
-
Representation of Numbers in Radix r
- What is Radix? The radix (r) of a number system is the base or number of distinct digits used, including 0. In radix r, the available digits are: 0, 1, 2, ..., (r - 1).
- General Representation: A number in radix r is written as (dₙ dₙ₋₁ ... d₁ d₀ . d₋₁ d₋₂ ... d₋ₘ)ᵣ.
- Value Formula: The value is calculated as: dₙrⁿ + dₙ₋₁rⁿ⁻¹ + ... + d₁r¹ + d₀r⁰ + d₋₁r⁻¹ + ... + d₋ₘr^(-m), where each dᵢ is a digit and 0 ≤ dᵢ ≤ r-1.
Special Cases of Radix r
- Binary (r=2): Digits used are 0, 1. Place values are ..., 4, 2, 1 . 1/2, 1/4, ... Example: (1011.01)₂ = 1×2³ + 0×2² + 1×2¹ + 1×2⁰ + 0×2⁻¹ + 1×2⁻² = 11.25₁₀.
- Octal (r=8): Digits used are 0-7. Place values are ..., 64, 8, 1 . 1/8, 1/64, ... Example: (347.56)₈ = 3×8² + 4×8¹ + 7×8⁰ + 5×8⁻¹ + 6×8⁻² = 231.8125₁₀.
- Decimal (r=10): Digits used are 0-9. Place values are ..., 100, 10, 1 . 1/10, 1/100, ... Example: (125.37)₁₀.
- Hexadecimal (r=16): Digits used are 0-9, A-F (where A=10, B=11, C=12, D=13, E=14, F=15). Place values are ..., 256, 16, 1 . 1/16, 1/256, ... Example: (2AF.C)₁₆ = 2×16² + 10×16¹ + 15×16⁰ + 12×16⁻¹ = 687.75₁₀.
Conversion Methodologies
- Decimal to Radix r:
- Integer Part: Divide the decimal number by r repeatedly. Write the remainders from bottom to top to get the representation.
- Fractional Part: Multiply the fractional number by r repeatedly. Write the integer parts from top to bottom.
- Radix r₁ to Radix r₂: This is generally done in two universal steps:
- Step 1: Convert the given number from radix r₁ to Decimal (base 10).
- Step 2: Convert the obtained Decimal number to radix r₂.
- Direct Shortcut Conversions (Without Decimal Bridge):
- Binary ↔ Octal (2 ↔ 8): Group binary digits into sets of 3 bits starting from the radix point (right for integer, left for fraction). Convert each group to its octal digit.
- Binary ↔ Hex (2 ↔ 16): Group binary digits into sets of 4 bits starting from the radix point. Convert each group to its hexadecimal digit.
- Octal ↔ Hex (8 ↔ 16): Convert octal to binary first (expand to 3 bits each), then regroup the binary into hex (4 bits each). Conversely, expand hex to binary (4 bits each), then regroup into octal (3 bits each).
-
Radix vs Number System: Understanding the Difference
1. The Radix (Base)
The radix, or base, is essentially a property of a number system. It simply defines the total count of unique digits or symbols available for use within that system, always including zero. For example, a radix of 10 means the system relies entirely on ten distinct digits, from 0 to 9, to construct any value. It acts purely as the inventory of allowed symbols.
2. The Number System
A number system is the complete, comprehensive method and set of rules used to represent numeric values. It utilizes a specific radix along with positional notation to give those digits mathematical meaning. While the radix just provides the raw building blocks (the digits), the number system provides the full structural language and grammar required to express complex quantities accurately.
-
Understanding r's and (r-1)'s Complements
In any base (radix) r number system, the complement of a number is a mathematical value that, when added to the original number, results in a specific power of the base. Complements are extremely useful in digital computers because they allow the system to perform subtraction operations using addition circuits, greatly simplifying hardware design.
1. The (r-1)'s Complement (Diminished Radix Complement)
To find the (r-1)'s complement of a number, you simply subtract each individual digit of that number from the highest possible digit in that base (which is r-1). For example, in the decimal system (r=10), this is the 9's complement, found by subtracting each digit from 9. In binary (r=2), this is the 1's complement, found by flipping every 0 to 1 and every 1 to 0.
2. The r's Complement (Radix Complement)
The r's complement is one step further. It is defined mathematically as the (r-1)'s complement plus 1 added to the least significant digit. For example, in decimal, the 10's complement is the 9's complement + 1. In binary, the 2's complement is the 1's complement + 1. The r's complement is the primary method used by modern CPUs for representing negative numbers and performing signed arithmetic.
-
Binary Arithmetic: Addition and Subtraction
Binary arithmetic forms the foundation of all computer processing. Despite appearing complex, it operates on the same mathematical principles as decimal arithmetic, but with only two digits: 0 and 1.
1. Binary Addition
Adding binary numbers is straightforward and follows four basic rules:
- 0 + 0 = 0
- 0 + 1 = 1
- 1 + 0 = 1
- 1 + 1 = 10 (Write down 0, carry over 1 to the next left column)
- If you have a carry input, 1 + 1 + 1 = 11 (Write down 1, carry over 1)
You always start adding from the rightmost column (Least Significant Bit) and move towards the left.
2. Binary Subtraction
Binary subtraction involves borrowing when you try to subtract a larger bit from a smaller bit. The four basic rules are:
- 0 - 0 = 0
- 1 - 0 = 1
- 1 - 1 = 0
- 0 - 1 = 1 (Requires a borrow of 1 from the next left column. In binary, borrowing 1 from the next column brings a value of 2 to the current column, making it 2 - 1 = 1)
Modern computers typically avoid direct binary subtraction circuits and instead use the 2's complement method to add the negative value, achieving the same result with simpler hardware.
-
Character Encoding Systems: Bridging Humans and Computers
Computers only understand numbers (binary). To process text, we must assign a unique number (a code) to every letter, number, and symbol. This mapping system is called a character encoding standard.
1. ASCII (American Standard Code for Information Interchange)
ASCII is one of the oldest and most fundamental encoding standards. It was originally designed as a 7-bit system, which means it can represent exactly 2⁷ = 128 unique characters. These 128 characters include the English alphabet (uppercase and lowercase), digits 0-9, standard punctuation, and invisible control codes (like Enter/Return or Tab). A handy trick in ASCII is that the difference between an uppercase letter (e.g., 'A' = 65) and its lowercase counterpart (e.g., 'a' = 97) is always exactly 32. Because 32 is a power of 2, computers can easily convert case by flipping a single bit.
2. Unicode
As computing went global, the 128-character limit of ASCII (or even the 256 limit of 8-bit Extended ASCII) proved vastly inadequate for representing all the world's languages, alphabets (like Arabic, Cyrillic, Chinese), and modern symbols (like emojis). The Unicode Consortium created a universal standard aiming to give every single character a unique, permanent code point, regardless of platform, program, or language. Unicode uses massive hexadecimal code points (e.g., U+1F600 for a grinning face) and is typically implemented using flexible encoding formats like UTF-8, which uses anywhere from 1 to 4 bytes per character, ensuring perfect backward compatibility with ASCII while supporting millions of global symbols.
-
C Programming: Basic Structure & Data Types
C is a powerful general-purpose programming language developed in 1972 by Dennis Ritchie at Bell Labs. It is a highly efficient, compiled, procedural language that heavily influenced almost all modern languages like C++, Java, and Python.
Basic Structure of a C Program
Every C program follows a rigid structural template:
#include <stdio.h> // Preprocessor directive to include standard I/O library // Global variable declarations (optional) // Main function: execution always begins here int main() { // Variable declarations // Statements & Expressions return 0; // Indicates successful execution to the operating system }Primary Data Types
Data types specify how data is stored in memory and how much space it occupies. C is a statically-typed language, meaning variable types must be declared before they are used.
int: Used to store whole integer numbers. Typically occupies 2 or 4 bytes. Format specifier:%d. Example:int age = 20;float: Used to store single-precision decimal (floating-point) numbers. Typically 4 bytes. Format specifier:%f. Example:float pi = 3.14f;double: Used to store double-precision decimal numbers. Much more accurate than float. Typically 8 bytes. Format specifier:%lf.char: Used to store a single character. It internally stores the ASCII integer value of the character. Typically 1 byte. Format specifier:%c. Example:char grade = 'A';
Derived & User-Defined Data Types
Derived types include Arrays, Pointers, and Functions. User-defined types include Structures (
struct), Unions, and Enumerations (enum).
-
Input/Output and Assignment Statements
A computer program requires data to process (Input) and a way to display the result (Output). In C, this is handled via standard library functions.
Assignment Statements
The assignment operator
=is used to assign a value to a variable. The value on the right side is evaluated and stored into the memory location of the variable on the left side.int a, b, sum; a = 10; // Direct assignment b = 20; sum = a + b; // Expression assignmentStandard Output: printf()
The
printf()function is used to print formatted data to the standard output screen (console). It utilizes format specifiers to insert variables into strings.int age = 20; float cgpa = 8.5; printf("Age is %d and CGPA is %.1f\n", age, cgpa); // Output: Age is 20 and CGPA is 8.5Standard Input: scanf()
The
scanf()function is used to read formatted data from the standard input (keyboard). You must provide the exact memory address (using the&ersand operator) of the variable where the data should be stored.int roll_no; printf("Enter your Roll No: "); scanf("%d", &roll_no); // The '&' passes the memory address of roll_no printf("You entered: %d", roll_no);Note: Strings (arrays of characters) do not require the
&operator because the name of an array naturally acts as a pointer to its first memory address.
-
Decision Making: If-Else and Switch Statements
Control statements alter the normal top-to-bottom sequential flow of a program based on specific conditions.
1. The If-Else Statement
Used when you have a condition that evaluates to either True (non-zero) or False (zero).
int marks = 85; if (marks >= 90) { printf("Grade: A+"); } else if (marks >= 80) { // Evaluated only if previous condition is false printf("Grade: A"); } else { // Executed if ALL above conditions are false printf("Grade: B"); }2. The Switch Statement
The
switchstatement is a cleaner alternative to a long, complex chain ofelse ifstatements when you are comparing a single integer or character variable against a list of constant values.char grade = 'A'; switch(grade) { case 'A': printf("Excellent performance!\n"); break; // Crucial: Stops execution from falling through to the next case case 'B': printf("Good performance.\n"); break; case 'C': printf("Needs improvement.\n"); break; default: // Executed if no case matches printf("Invalid grade.\n"); }Exam Tip: Always remember the
breakstatement. Without it, C will execute the matched case AND every single case below it (known as "fall-through") until it hits a break or the end of the switch block.
-
Looping Constructs (Iteration)
Loops are used to execute a block of code repeatedly as long as a specific condition remains true.
1. The 'for' loop
Best used when the exact number of iterations is known in advance. It condenses initialization, condition checking, and incrementing into a single, clean line.
// Syntax: for(initialization; condition; increment/decrement) for(int i = 1; i2. The 'while' loop
An entry-controlled loop. Best used when the number of iterations is unknown and depends on dynamic conditions (like waiting for a user to type 'quit'). The condition is checked before the loop body executes.
int count = 1; while(count3. The 'do-while' loop
An exit-controlled loop. The absolute key difference is that the code block is guaranteed to execute at least once, regardless of whether the condition is true or false, because the condition is checked at the end of the loop.
int x = 10; do { printf("This prints exactly once, even though 10 is not less than 5.\n"); x++; } while(xBreak and Continue
break;- Immediately terminates the entire loop and transfers execution to the statement immediately following the loop.continue;- Skips the remaining code inside the current loop iteration and immediately jumps back to the top to evaluate the condition for the next iteration.
-
Arrays and Strings (1D & 2D)
An array is a collection of variables of the same data type stored in contiguous memory locations. It is used to store multiple values in a single variable, rather than declaring separate variables for each value.
1-Dimensional Arrays
Used to represent a linear list of elements. Array indices in C strictly start at
0.// Declaration and Initialization int marks[5] = {85, 90, 78, 92, 88}; // Accessing elements printf("First student marks: %d\n", marks[0]); // Outputs 85 // Iterating through an array for(int i = 0; iStrings (Character Arrays)
C does not have a built-in String object type. Instead, strings are simply 1D arrays of
charthat are strictly terminated by a special Null character'\0'to signal the end of the text.char name[] = "Rahul"; // Automatically adds '\0' at the end // Internally stored as: ['R', 'a', 'h', 'u', 'l', '\0'] printf("Hello, %s", name);2-Dimensional Arrays
A 2D array is an array of arrays, most commonly used to represent tables or matrices (rows and columns).
// Declaring a 2x3 matrix (2 rows, 3 columns) int matrix[2][3] = { {1, 2, 3}, // Row 0 {4, 5, 6} // Row 1 }; // Accessing row 1, column 2 (value is 6) printf("Value: %d", matrix[1][2]); // Nested loops are required to iterate through 2D arrays for(int i = 0; i
-
Functions, Parameter Passing, and Recursion
A function is a self-contained block of code designed to perform a specific, reusable task. Functions break massive programs down into smaller, manageable, modular components.
Function Anatomy
// Function Declaration (Prototype) int addNumbers(int a, int b); // Function Definition int addNumbers(int a, int b) { int sum = a + b; return sum; // Return type must match the declaration } int main() { // Function Call int result = addNumbers(5, 10); printf("Sum: %d", result); }Parameter Passing Methods
- Call by Value: A copy of the actual argument is passed to the function. Any modifications made to the parameters inside the function do NOT affect the original variables in the calling function. (This is the default in C).
- Call by Reference: The memory address (pointer) of the variable is passed. Any modifications made via the pointer inside the function directly alter the original variable in memory.
Recursion
Recursion occurs when a function calls itself directly or indirectly to solve a smaller instance of the same problem. Every recursive function absolutely must have a Base Case to stop the recursion, otherwise it will result in an infinite loop and a Stack Overflow error.
// Classic Example: Factorial using Recursion int factorial(int n) { // Base Case: stops the recursion if (n == 0 || n == 1) { return 1; } // Recursive Case: calls itself else { return n * factorial(n - 1); } }
-
Structures and Pointers
Structures (struct)
While an array can only hold data of the same type, a
structis a user-defined data type that groups related variables of different data types under a single name. This is crucial for representing complex real-world entities (like a Student with an integer ID, a string Name, and a float CGPA).struct Student { int roll_no; char name[50]; float marks; }; int main() { // Creating a struct variable struct Student s1; // Accessing members using the dot (.) operator s1.roll_no = 101; s1.marks = 85.5; printf("Roll: %d, Marks: %.1f", s1.roll_no, s1.marks); }Pointers
A pointer is a special variable that stores the memory address of another variable, rather than a raw data value. Pointers are the most powerful (and dangerous) feature of C, allowing direct memory manipulation, dynamic memory allocation (malloc/free), and complex data structures like linked lists.
int var = 20; // A normal integer variable int *ptr; // Declaration of a pointer to an integer ptr = &var; // The '&' (address-of) operator gets the memory address of var // Accessing the value printf("Value of var: %d\n", var); // Prints 20 printf("Address of var: %p\n", ptr); // Prints the memory address (e.g., 0x7ffe...) // DEREFERENCING: Using the pointer to access/modify the original value *ptr = 50; printf("New value of var: %d\n", var); // Prints 50! We changed var via the pointer.
-
File Handling & Multi-file Programming
By default, data stored in variables is lost when the C program terminates. File handling allows programs to read from and persistently save data to physical files on the hard drive.
Basic File Operations
File operations use a special file pointer of type
FILE *. The workflow is always: Open -> Read/Write -> Close.#include <stdio.h> int main() { FILE *filePtr; // 1. Open the file in Write ("w") mode filePtr = fopen("data.txt", "w"); if (filePtr == NULL) { printf("Error opening file!"); return 1; } // 2. Write to the file fprintf(filePtr, "Hello, this is persistent data!\n"); // 3. Close the file (CRITICAL to save data and free resources) fclose(filePtr); return 0; }Common Modes:
"r"(Read),"w"(Write, overwrites existing),"a"(Append, adds to the end).Multi-File Handling
As enterprise programs grow to thousands of lines, it becomes impossible to manage everything inside one
main.cfile. Multi-file programming splits the code into logical modules.- Header Files (.h): Contain function prototypes, macros, and struct definitions. Example:
math_utils.h - Source Files (.c): Contain the actual implementation of the functions defined in the header. Example:
math_utils.c - Main File: Includes the custom header using quotes (
#include "math_utils.h") and calls the functions.
The compiler compiles each
.cfile independently into object files (.o), and then the Linker combines all the object files together into a single executable program. - Header Files (.h): Contain function prototypes, macros, and struct definitions. Example:
No card matches that search.
1/20
0
0:00
Question
Click the card or press Space to flip
Answer
Diagram for this card
Diagram
Handwritten diagram
Run complete
0 nailed · 0 in the pile · 0:00 · best combo 0
Scroll to zoom · drag to pan · Esc to close
Shortcuts
- S
- Start the run
- Space
- Show me the answer
- ← →
- Previous / next card
- 1 2
- Not yet / Nailed it
- D
- Open the diagram
- F
- Diagram full screen
- /
- Search the deck
- Esc
- Close whatever is open