Week 1: Overview of C, Constants, Variables, Data Types C Language Basics What is C? A powerful, general-purpose programming language. Think of it as the sturdy brick foundation for many modern buildings (other programming languages and operating systems). Compilation: Source code (.c) $\rightarrow$ Compiler $\rightarrow$ Object code (.obj) $\rightarrow$ Linker $\rightarrow$ Executable code (.exe). Structure: #include <stdio.h> // Preprocessor directive int main() { // Main function: program execution starts here // Your code goes here return 0; // Indicates successful execution } Constants Definition: Values that do not change during program execution. Like a fixed North Star in the night sky. Types: Integer Constants: $10, -5, 0$. Floating-Point Constants: $3.14, -0.5$. Character Constants: 'A', 'a', '7'. Enclosed in single quotes. String Literals: "Hello World". Enclosed in double quotes. Defined Constants: Using #define PI 3.14159 (no semicolon). const Keyword: const int MAX_USERS = 100; (type-safe). Variables Definition: Named storage locations in memory. Imagine a variable as a labeled box where you can put different items (values) over time. Declaration: dataType variableName; (e.g., int age; ). Initialization: Assigning an initial value (e.g., int age = 30; ). Rules for Naming: Can contain letters, digits, and underscore (_). Must start with a letter or underscore. Case-sensitive ( age is different from Age ). Cannot be a C keyword (e.g., int, float, if ). Data Types Definition: Specifies the type of data a variable can hold and the operations that can be performed on it. Primary Data Types: Type Description Size (typical) Range (typical) int Integer numbers 2 or 4 bytes $-32,768$ to $32,767$ (2-byte) char Single character 1 byte $-128$ to $127$ or $0$ to $255$ float Single-precision floating point 4 bytes $\pm 3.4 \times 10^{-38}$ to $\pm 3.4 \times 10^{38}$ double Double-precision floating point 8 bytes $\pm 1.7 \times 10^{-308}$ to $\pm 1.7 \times 10^{308}$ void Absence of type N/A N/A Type Modifiers: short, long, signed, unsigned . unsigned int : Only non-negative integers. long double : Even higher precision. Practice Problems (Week 1) Declare an int variable named numStudents and initialize it to $45$. Declare a float variable named piValue and assign it $3.14159$. What is the difference between 'A' and "A" ? Which of the following are invalid variable names and why: _count, 1st_name, total_$, if ? Week 2: Operators & Expressions, Input/Output Operators Definition: Symbols that perform operations on operands. Like tools in a toolbox, each with a specific job. Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus - remainder). Example: int result = 10 / 3; (result is $3$, integer division). 10 % 3; (result is $1$). Relational Operators: Compare two values; result is $0$ (false) or $1$ (true). Like a judge making a true/false ruling. == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to). Logical Operators: Combine or negate relational expressions. Like a traffic controller directing based on multiple conditions. && (AND): True if both operands are true. || (OR): True if at least one operand is true. ! (NOT): Reverses the logical state of its operand. Assignment Operators: Assign a value to a variable. = (simple assignment), +=, -=, *=, /=, %= (compound assignment). Example: x += 5; is equivalent to x = x + 5; . Increment/Decrement Operators: ++ (increment by $1$), -- (decrement by $1$). Prefix: ++x (increment then use). Postfix: x++ (use then increment). Analogy: Prefix is like putting on your shoes *before* leaving the house; Postfix is like putting them on *after* you've walked out the door (but before taking your first step). Bitwise Operators: Operate on bits ( &, |, ^, ~, <<, >> ). Ternary/Conditional Operator: condition ? expression_if_true : expression_if_false; Expressions Definition: A combination of operators, operands, and function calls that evaluates to a single value. Precedence & Associativity: Rules determining the order of evaluation (PEMDAS/BODMAS applies here too, but for C operators). Parentheses () override default precedence. Managing Input and Output Operations Standard I/O: Using <stdio.h> . Output: printf() Syntax: printf("format string", arg1, arg2, ...); Format Specifiers: Specifier Data Type Example %d or %i int printf("Age: %d", age); %f float printf("Pi: %f", pi); %lf double printf("Value: %lf", val); %c char printf("Grade: %c", grade); %s String (char array) printf("Name: %s", name); %p Pointer printf("Address: %p", &var); Escape Sequences: \n (newline), \t (tab), \\ (backslash), \" (double quote). Input: scanf() Syntax: scanf("format string", &variable1, &variable2, ...); CRITICAL: Use the address-of operator & before variable names to store input. Think of & as telling scanf exactly *where* to put the incoming data, like giving a postal worker the exact address for a package. Example: int num; scanf("%d", &num); For strings (char arrays), & is usually not needed as array name itself is a pointer: char name[50]; scanf("%s", name); (Note: scanf("%s", ...) stops at whitespace). Character I/O: getchar(), putchar(), getch(), getche() (latter two often non-standard). Practice Problems (Week 2) Evaluate the following C expression: int x = 5, y = 2; float z = (float)x / y; What is z ? Write a C program that asks the user for two integers, calculates their sum, difference, product, and quotient, and prints all results. Predict the output: int a = 10; printf("%d %d %d\n", a++, ++a, a); Write a program to read a character from the user and print it. Week 3: Decision Making and Branching & Switch-Case Decision Making and Branching ( if statements) Definition: Allows your program to execute different blocks of code based on conditions. Like a GPS directing you down different roads based on traffic. if Statement: Executes a block if a condition is true. if (condition) { // Code to execute if condition is true } if-else Statement: Executes one block if true, another if false. if (condition) { // Code for true } else { // Code for false } else-if Ladder: Checks multiple conditions sequentially. if (condition1) { // Code for condition1 } else if (condition2) { // Code for condition2 } else { // Code if none of the above are true } Nested if : An if statement inside another if or else block. switch-case Statement Definition: A multi-way branch statement that provides an alternative to a long if-else if ladder for checking equality against multiple constant values. Imagine a central train switchyard directing trains to different tracks based on their destination number. Syntax: switch (expression) { // expression must evaluate to an integer type case constant1: // Code block 1 break; // VERY IMPORTANT: Exits the switch case constant2: // Code block 2 break; default: // Code block if no match (optional) } break Keyword: Essential to prevent "fall-through" (executing code of subsequent cases). Without break , the program will execute all cases from the matching one downwards until a break or the end of switch . default Case: Optional. Executed if no case matches the expression. Practice Problems (Week 3) Write a program that takes an integer score as input and prints "Pass" if score $\ge 50$, otherwise "Fail". Expand the previous program: prints "Excellent" for $\ge 90$, "Very Good" for $\ge 75$, "Pass" for $\ge 50$, and "Fail" otherwise. Write a program using switch-case that takes a character representing a day of the week ('M', 'T', 'W', 'H', 'F', 'S', 'U') and prints the full day name (e.g., 'M' $\rightarrow$ "Monday"). Handle invalid input. What happens if you remove the break statements from a switch-case construct? Demonstrate with an example. Week 4: Decision Making and Looping Looping (Iteration) Definition: Allows a block of code to be executed repeatedly. Like a record player spinning the same song over and over until you lift the needle. while Loop: Repeats a block of code as long as a condition is true. while (condition) { // Code to be executed repeatedly // Make sure condition eventually becomes false to avoid infinite loop! } do-while Loop: Similar to while , but guarantees the loop body executes at least once before checking the condition. do { // Code to be executed } while (condition); // Semicolon is required here! for Loop: Ideal for situations where the number of iterations is known or can be easily determined. for (initialization; condition; increment/decrement) { // Code to be executed repeatedly } Initialization: Executed once at the beginning. Condition: Checked before each iteration; if false, loop terminates. Increment/Decrement: Executed after each iteration. Practice Problems (Week 4) Write a C program to print numbers from $1$ to $10$ using a for loop. Modify the above program to print numbers from $1$ to $10$ using a while loop. Write a program that calculates the sum of the first $N$ natural numbers, where $N$ is input by the user. Use a for loop. Write a program using a do-while loop to repeatedly ask the user to enter a number between $1$ and $10$ until a valid number is entered. Week 5: Nested Loops, Jumps in Loops (Continue and Break) Nested Loops Definition: A loop inside another loop. Think of setting up a grid: the outer loop handles rows, and the inner loop handles columns within each row. Any type of loop ( for, while, do-while ) can be nested inside another. Example (Nested for for a multiplication table): for (int i = 1; i Complexity: If outer loop runs $M$ times and inner loop $N$ times, total operations are roughly $M \times N$. Jumps in Loops break Statement: Purpose: Immediately terminates the innermost loop ( for, while, do-while ) or switch statement it is contained within. Analogy: It's like an emergency exit. You immediately leave the current room (loop) and go to the next part of the building (code after the loop). Example: for (int i = 0; i < 10; i++) { if (i == 5) { break; // Loop terminates when i is 5 } printf("%d ", i); // Prints 0 1 2 3 4 } continue Statement: Purpose: Skips the rest of the current iteration of the innermost loop and proceeds to the next iteration. Analogy: It's like skipping a turn in a game. You don't leave the game (loop), but you miss out on the current round's actions and move straight to the next round. Example: for (int i = 0; i < 5; i++) { if (i == 2) { continue; // Skips printing for i == 2 } printf("%d ", i); // Prints 0 1 3 4 } goto Statement: (Generally discouraged in modern programming) Purpose: Transfers control unconditionally to a labeled statement. Analogy: A teleportation device that can send your program anywhere, but often leads to "spaghetti code" that's hard to follow. Use with extreme caution, if at all. Practice Problems (Week 5) Write a C program to print a $5 \times 5$ square of asterisks ( * ) using nested loops. Modify the above program to print a right-angled triangle pattern of asterisks. * ** *** **** ***** Write a program that prints numbers from $1$ to $10$, but skips printing the number $7$ using the continue statement. Write a program that asks the user for numbers repeatedly. Stop asking and print the sum of all entered numbers if the user enters $0$. Use a while loop and a break statement. General Practice Problems (Across Topics) Missing Line Code: #include <stdio.h> int main() { int num; printf("Enter an integer: "); // MISSING LINE: Read the integer from the user and store it in 'num' if (num % 2 == 0) { printf("The number is even.\n"); } else { printf("The number is odd.\n"); } return 0; } Complete the missing line. Program 1: Factorial Calculator Write a C program that prompts the user to enter a non-negative integer and calculates its factorial. The factorial of a non-negative integer $n$ is the product of all positive integers less than or equal to $n$. Handle edge cases like $0! = 1$ and negative inputs. Program 2: Prime Number Checker Write a C program that takes an integer from the user and determines if it is a prime number. A prime number is a natural number greater than $1$ that has no positive divisors other than $1$ and itself. Program 3: Simple Calculator Write a C program that acts as a simple calculator. It should ask the user to enter two numbers and an operator ( +, -, *, / ). Based on the operator, perform the calculation and display the result. Use a switch-case statement for the operators. Handle division by zero. Program 4: Pattern Printing (Pyramid) Write a C program to print the following pyramid pattern for $N$ rows, where $N$ is input by the user (e.g., $N=4$): * *** ***** *******