Comprehensive Study Guide for C Programming Fundamentals

Introduction to C Programming

  • Definition of C:

    • C is a general-purpose programming language.

    • It is known as a Structured programming paradigm, which emphasizes clarity, quality, and modularity by organizing code into discrete blocks and subroutines.

  • History and Context:

    • Created by Dennis Ritchie at Bell Labs in the year 19721972.

    • It is closely connected to UNIX because a significant portion of the UNIX operating system was written in C.

    • It is considered a fundamental language in the field of Computer Science.

  • Popularity and Benefits:

    • It is fast, widely supported, and helps users understand the internal workings of programs.

    • It provides a deep understanding of memory, performance, and how computers handle data.

  • Applications of C:

    • Operating Systems: Parts of Windows, Linux, and macOS.

    • Embedded Systems: Programs inside devices such as cars, TVs, and home electronics.

    • High-Performance Software: Databases and system tools that require high speed.

    • Game Development: Game engines and programs handling complex graphics.

    • Core Libraries: It serves as the foundation for libraries that other programming languages rely on.

  • Why Learn C?:

    • It is one of the most widely used programming languages in the world.

    • Learning C makes it easier to learn other languages like Java, Python, C++C++, and C#C\# because they share similar syntax.

Basic Program Structure

  • Code Example:

    • #include <stdio.h>: This is a preprocessor directive.

    • int main() { ... }: This is the entry point of the program.

    • printf("Hello, world!");: This is a statement used to output text.

    • return 0;: This is the return value, indicating the program finished successfully.

  • Detailed Breakdown of Components:

    • #include <stdio.h>: This is a library or header file that provides a variety of functions for input, output, and file handling. Examples include printf and scanf.

    • int main():

      • int is a data type used to return an integer value.

      • main is the starting point of any C program.

    • printf: A function used to display output on the screen.

    • return 0: Signifies there are 00 errors and the program has executed successfully.

Comments in C

  • Definition: Comments are notes for humans and are ignored by the compiler.

  • Single-Line Comments:

    • Start with two forward slashes //.

    • Any text between // and the end of the line is ignored.

    • Example: // This is a comment.

  • Multi-Line Comments:

    • Start with /* and end with */.

    • Any text between these delimiters is ignored, even if it spans multiple lines.

    • Example: /* The code below will print the words Hello world! to the screen */.

Variables and Syntax

  • Definition: Variables are containers for storing data values, such as numbers and characters. They can be thought of as a named box where a value is kept for later use.

  • C Variable Rules:

    • Variables must have a specific type, which tells the program what kind of data the variable stores.

    • Syntax: type variableName = value;

  • Example Declarations:

    • int myNum = 15; (Declaration and assignment in one line).

    • int myNum; myNum = 15; (Declaration followed by assignment later).

  • Naming Rules:

    • Valid: age_count, totalsum.

    • Invalid: 1age (starts with a number), my-age (contains a hyphen), int (reserved keyword).

Format Specifiers

  • Definition: Format specifiers are placeholders used with the printf() function to tell C what kind of value to print. They always start with a percentage sign \% followed by a letter.

  • Common Specifiers:

    • \%d: For int (integers).

    • \%f: For float values (decimals).

    • \%lf: For double values (high-precision decimals).

    • \%c: For char (individual characters).

Data Types

  • Every variable in C must be a specified data type.

  • Basic Data Types Table:

    • int: Size is 22 or 44 bytes. Stores whole numbers without decimals. Example: 11.

    • float: Size is 44 bytes. Stores fractional numbers. Sufficient for storing 66 to 77 decimal digits. Example: 1.991.99.

    • double: Size is 88 bytes. Stores fractional numbers. Sufficient for storing 1515 decimal digits. Example: 1.991.99.

    • char: Size is 11 byte. Stores a single character, letter, number, or ASCII value. Characters are surrounded by single quotes. Example: 'A'.

Type Conversion

  • Definition: The process of converting the value of one data type to another.

  • Implicit Conversion (Automatic):

    • Done automatically by the compiler.

    • Example: Assigning an int to a float: float myFloat = 9; results in 9.0000009.000000.

    • Example: Assigning a float to an int: int myInt = 9.99; results in 99 (the decimal is truncated).

  • Explicit Conversion (Manual):

    • Done manually by placing the target type in parentheses in front of the value.

    • Example: float sum = (float) 5 / 2; results in 2.5000002.500000.

Constants

  • Used when a variable should remain unchangeable (read-only) throughout the program.

  • Uses the const keyword.

  • Example: const int minutesPerHour = 60;.

  • If you attempt to reassign a value to a constant (e.g., minutesPerHour = 61;), the compiler will throw an error: assignment of read-only variable.

Operators

  • Used to perform operations on variables and values. In the expression int myNum = 100 + 50;, + is the operator and 100 and 50 are operands.

  • Arithmetic Operators:

    • + (Addition): Adds two values.

    • - (Subtraction): Subtracts one value from another.

    • * (Multiplication): Multiplies two values.

    • / (Division): Divides one value by another.

    • \% (Modulus): Returns the division remainder.

    • ++ (Increment): Increases the value by 11.

    • -- (Decrement): Decreases the value by 11.

  • Assignment Operators:

    • =: x = 5

    • +=: x += 3 is the same as x = x + 3.

    • -=: x -= 3 is the same as x = x - 3.

    • *=: x *= 3 is the same as x = x * 3.

    • /=: x /= 3 is the same as x = x / 3.

    • \%=: x \%= 3 is the same as x = x \% 3.

    • Bitwise assignments include &=, |=, ^=, >>=, <<=.

  • Comparison Operators:

    • These return either 11 (true) or 00 (false).

    • ==: Equal to.

    • !=: Not equal to.

    • >: Greater than.

    • <: Less than.

    • >=: Greater than or equal to.

    • <=: Less than or equal to.

  • Logical Operators:

    • Used to combine multiple conditions.

    • && (Logical AND): Returns 11 if both statements are true.

    • || (Logical OR): Returns 11 if at least one statement is true.

    • ! (Logical NOT): Reverses the result; returns 00 if the result is 11.

  • Order of Operations (Precedence):

    1. () Parentheses

    2. *, /, \% (Multiplication, Division, Modulus)

    3. +, - (Addition, Subtraction)

    4. <, <=, >, >= (Comparison)

    5. ==, != (Equality)

    6. && (Logical AND)

    7. || (Logical OR)

    8. = (Assignment)

Booleans in C

  • Booleans represent values that are either true or false (or 11/00, YES/NO, ON/OFF).

  • The bool type is NOT built-in for older C versions; it was introduced in C99.

  • You must include the header file #include <stdbool.h> to use the bool keyword.

  • Example: bool isProgrammingFun = true;.

Control Flow: If…Else

  • If Statement: Performs an operation based on a specific condition. If true, the code block executes; otherwise, it is skipped.

  • Else Statement: Specifies a block of code to run if the if condition is false.

  • Else If: Tests a new condition if the first condition is false. C checks these from top to bottom and runs only the first true block.

  • Short Hand If…Else (Ternary Operator):

    • Known as the ternary operator because it uses three operands.

    • Syntax: Variable = (condition) ? expressionTrue : expressionFalse;

    • Example: (time < 18) ? printf("Good day.") : printf("Good evening.");.

  • Nested If:

    • An if statement inside another if statement.

    • Allows checking a condition only if a previous condition is already true.

Switch Statement

  • Used to select one of many code blocks to be executed, providing an alternative to multiple if...else statements.

  • How it works:

    • The switch expression is evaluated once.

    • The value is compared with the values of each case.

    • If a match occurs, the associated block runs.

    • The break keyword stops execution and breaks out of the switch block.

    • The default keyword (optional) specifies code to run if no cases match.

Loops

  • Definition: Loops execute a block of code as long as a specified condition is true. They save time, reduce errors, and increase readability.

  • While Loop:

    • Repeats code as long as the condition is true.

    • Checks condition first, then executes.

    • Syntax: while (condition) { // code }.

  • Do/While Loop:

    • A variant of the while loop that executes the code block once before checking the condition.

    • It will continue repeating as long as the condition is true.

  • For Loop:

    • Used when you know exactly how many times the code should run.

    • Syntax: for (expression 1; expression 2; expression 3) { // code }.

      • Expression 1: Executed once before the loop (initialization).

      • Expression 2: Defines the condition for the loop to run.

      • Expression 3: Executed every time after the code block runs (increment/decrement).

  • Nested Loops:

    • A loop inside another loop.

    • The inner loop executes fully for every single iteration of the outer loop.

Internals and Compilation Workflow

  • Compilation Steps:

    1. C File (Source Code): Human-readable file (e.g., program.c) containing functions and variables.

    2. Preprocessor (.i file): Handles lines starting with # (like #include), replaces macros, removes comments, and performs conditional compilation.

    3. Compiler (.s file): Converts preprocessed code to Assembly Language. It checks for syntax and type errors.

    4. Assembler (.o file): Converts assembly code into machine code (binary). This is an object file and is not yet executable.

    5. Linker (Executable): Combines object files with library code (e.g., printf from the standard library). Outputs a.out (Linux) or .exe (Windows).

    6. OS Process Creation: When run (./a.out), the OS creates a process with a unique PID (Process ID).

    7. CPU Execution: The CPU executes instructions step-by-step.

    8. Output: The result is displayed on the terminal or screen.

  • Process Memory Layout:

    • Stack: Stores local variables, function parameters, and return addresses. It is automatically managed and grows downward.

    • Heap: Used for dynamic memory allocation (e.g., using malloc). Requires manual management using free(). It grows upward.

    • BSS Section: Stores uninitialized global and static variables. Default value is 00.

    • Data Section: Stores initialized global and static variables. These persist for the entire program life.

    • Code Section (Text Segment): Stores the actual compiled machine instructions. This area is read-only.

  • Memory Visualization Example:

    • A global int g = 100; is in the Data segment.

    • An uninitialized global int h; is in the BSS segment.

    • Local variables int a inside main() are on the Stack.

    • Memory allocated via malloc is on the Heap.

Program Workflows

  • If Workflow: Start -> Check condition -> If True, execute statement; If False, terminate/skip.

  • If-Else Workflow: Start -> Check condition -> If True, execute if-block; If False, execute else-block -> End.

  • If-Else-If Workflow: Start -> Check 1st condition -> If False, check 2nd condition -> If any are True, execute that block and end; otherwise, execute the final else block.

  • Nested If Workflow: Start -> Check 1st condition -> If True, check 2nd condition -> If 2nd is True, run Block A; If 2nd is False, run Block B (if else exists).