| Feature | Compiler | Interpreter |
|---|---|---|
| Translation Process | Scans the entire program and translates it into machine code as a whole. | Translates the program one statement at a time. |
| Execution Time | Execution is faster because the program is already compiled into machine code. | Execution is slower as it translates and executes simultaneously. |
| Error Detection | Errors are reported all at once after scanning the whole program. Difficult to debug. | Stops translation when the first error is met. Easier to debug. |
| Memory Requirement | Requires more memory since object code is generated and stored. | Memory efficient as no intermediate object code is generated. |
| Examples | C, C++, Java (uses both compiler and interpreter). | Python, Ruby, PHP. |
Definition: An algorithm is a finite sequence of unambiguous instructions that, when executed, solves a problem in a finite amount of time and terminates.
Characteristics of a Good Algorithm:
Use as a Problem-Solving Tool:
Algorithms bridge the gap between a real-world problem and a computer program. They allow developers to:
1. Break down complex problems into smaller, manageable logical steps.
2. Verify the logic independently of any programming language syntax.
3. Analyze the efficiency (time and space complexity) before writing the actual code.
4. Provide a blueprint that any programmer can follow to implement the solution in languages like C, Python, or Java.
Definition: The prefix "pseudo" means false. Thus, pseudocode is "false code". It has no strict syntax rules like a real programming language, combining English-like statements with standard programming structures (like IF-ELSE, WHILE loops).
Example:
IF marks > 50 THEN
PRINT "Pass"
ELSE
PRINT "Fail"
END IF
Use as a Problem-Solving Tool:
1. Focus on Logic: It allows programmers to concentrate on the logical flow of the algorithm without worrying about the strict syntax (like missing semicolons or curly braces) of languages like C or Java.
2. Easy Transition to Code: Because it uses programming constructs (loops, conditionals), it is extremely easy to translate pseudocode directly into any high-level language.
3. Communication: It acts as a universal language among programmers, project managers, and stakeholders to discuss how a system will function before development begins.
BEGIN
DECLARE n, a=0, b=1, c, i
INPUT n
PRINT a, b
FOR i = 2 TO n-1 DO
c = a + b
PRINT c
a = b
b = c
END FOR
END
3. Flow Chart Description:Since flowcharts are graphical, draw an Oval for Start/Stop, Parallelogram for Input/Output (Read n, Print a,b,c), Rectangle for processing (c = a+b, a=b), and a Diamond for the condition (i < n).
BEGIN
INPUT num
temp = num
sum = 0
WHILE temp > 0 DO
rem = temp MOD 10
sum = sum + (rem * rem * rem)
temp = temp / 10
END WHILE
IF sum == num THEN
PRINT "Armstrong"
ELSE
PRINT "Not Armstrong"
END IF
END
BEGIN
INPUT num
temp = num
rev = 0
WHILE temp > 0 DO
rem = temp MOD 10
rev = (rev * 10) + rem
temp = temp / 10
END WHILE
IF rev == num THEN
PRINT "Palindrome"
ELSE
PRINT "Not Palindrome"
END IF
END
BEGIN
INPUT n
fact = 1
IF n < 0 THEN
PRINT "Error"
ELSE
FOR i = 1 TO n DO
fact = fact * i
END FOR
PRINT fact
END IF
END
BEGIN
INPUT n
count = 0
IF n <= 1 THEN
PRINT "Not Prime"
ELSE
FOR i = 1 TO n DO
IF n MOD i == 0 THEN
count = count + 1
END IF
END FOR
IF count == 2 THEN
PRINT "Prime"
ELSE
PRINT "Not Prime"
END IF
END IF
END
For Sum of Odd Digits, replace the condition in Step 6 with: If rem % 2 != 0, then sum = sum + rem
There are 6 basic types of tokens in C:
int, return, if, else.main, sum, _count.10 (Integer), 3.14 (Floating), 'A' (Character)."Hello World"., (comma), ; (semicolon), [], {}.+, -, *, ==.getchar(): Reads a single character from standard input.getch(): Reads a single character immediately without waiting for Enter key (mostly non-standard).getche(): Same as getch() but echoes the typed character to the screen.gets(): Reads an entire string (including spaces) until Enter is pressed (deprecated in C11).putchar(): Outputs a single character to standard output.putch(): Prints a single character to the console.puts(): Outputs a string to standard output, automatically appending a newline at the end.| Storage Class | Keyword | Default Value | Scope | Lifetime |
|---|---|---|---|---|
| Automatic | auto |
Garbage Value | Local (within block) | Until the end of the block. |
| Register | register |
Garbage Value | Local | Until the end of the block (stored in CPU registers for fast access). |
| Static | static |
Zero (0) | Local (if inside block) or Global | Retains value between function calls (lives until program ends). |
| External | extern |
Zero (0) | Global (accessible in multiple files) | Until program ends. |
+ (Add), - (Sub), * (Mul), / (Div), % (Mod). Example: a + b==, !=, >, <, >=, <=. Example: a > b&& (Logical AND), || (Logical OR), ! (Logical NOT). Example: (a > b) && (b > c)& (AND), | (OR), ^ (XOR), ~ (Complement), << (Left Shift), >> (Right Shift).=, +=, -=, *=, /=, %=. Example: a += 5 (same as a = a + 5)++ (increment by 1), -- (decrement by 1). Example: x++? :. Example: (a > b) ? a : b (Returns 'a' if true, else 'b')sizeof() (returns size of variable in bytes), & (address of), * (pointer to).() and brackets []++, --, !, ~ (Associativity: Right to Left)*, /, % (Associativity: Left to Right)+, - (Associativity: Left to Right)<, <=, >, >===, !=&&||=, +=, etc. (Associativity: Right to Left)Example Evaluation:
x = 5 + 3 * 2 - 8 / 4
Step 1: Evaluate Multiplication & Division (L to R): 3 * 2 = 6, 8 / 4 = 2
Step 2: Expression becomes x = 5 + 6 - 2
Step 3: Evaluate Addition & Subtraction (L to R): 5 + 6 = 11, 11 - 2 = 9
Step 4: x = 9
#include <stdio.h>
int main() {
float r, d, c, a;
const float PI = 3.14159;
printf("Enter radius of the circle: ");
scanf("%f", &r);
d = 2 * r;
c = 2 * PI * r;
a = PI * r * r;
printf("Diameter = %.2f\n", d);
printf("Circumference = %.2f\n", c);
printf("Area = %.2f\n", a);
return 0;
}
#include <stdio.h>
int main() {
int a, b;
printf("Enter a and b: ");
scanf("%d %d", &a, &b);
a = a + b; // a now holds the sum
b = a - b; // b now holds original a
a = a - b; // a now holds original b
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Method 2: Using Bitwise XOR (^)#include <stdio.h>
int main() {
int a, b;
printf("Enter a and b: ");
scanf("%d %d", &a, &b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
#include <stdio.h>
int main() {
float length, width, area, perimeter;
printf("Enter length and width of rectangle: ");
scanf("%f %f", &length, &width);
area = length * width;
perimeter = 2 * (length + width);
printf("Area = %.2f\n", area);
printf("Perimeter = %.2f\n", perimeter);
return 0;
}
#include <stdio.h>
int main() {
float angle1, angle2, angle3;
float base, height, area;
// Part 1: Angles
printf("Enter two angles of triangle: ");
scanf("%f %f", &angle1, &angle2);
angle3 = 180 - (angle1 + angle2);
printf("Third angle = %.2f\n", angle3);
// Part 2: Area
printf("Enter base and height of triangle: ");
scanf("%f %f", &base, &height);
area = (base * height) / 2.0;
printf("Area of triangle = %.2f\n", area);
return 0;
}
#include <stdio.h>
int main() {
float basic, ta, hra, pf, gross, net;
float grade_pay = 9000.0;
printf("Enter basic salary: ");
scanf("%f", &basic);
ta = 0.15 * basic;
hra = 0.08 * basic;
pf = 0.15 * basic;
gross = basic + ta + hra + grade_pay;
net = gross - pf;
printf("--- Pay Slip ---\n");
printf("Basic Salary : Rs. %.2f\n", basic);
printf("TA (15%%) : Rs. %.2f\n", ta);
printf("HRA (8%%) : Rs. %.2f\n", hra);
printf("Grade Pay : Rs. %.2f\n", grade_pay);
printf("Gross Salary : Rs. %.2f\n", gross);
printf("PF (15%%) : Rs. %.2f\n", pf);
printf("Net Salary : Rs. %.2f\n", net);
return 0;
}
Executes a block of code only if a specified condition is true.
if (condition) {
// code to be executed if condition is true
}
Example:
if (age >= 18) {
printf("Eligible to vote");
}
2. if...else statement:Executes one block of code if the condition is true, and another if it is false.
if (condition) {
// code if true
} else {
// code if false
}
Example:
if (num % 2 == 0) printf("Even");
else printf("Odd");
3. else if ladder:Used to test multiple conditions sequentially.
if (marks > 90) printf("Grade A");
else if (marks >= 80) printf("Grade B");
else printf("Grade C");
4. Nested if:An if statement inside another if statement. Used for evaluating multiple criteria.
if (num > 0) {
if (num % 2 == 0) {
printf("Positive Even");
}
}
5. switch case:Used to select one of many code blocks to be executed based on the value of a variable/expression. It is a cleaner alternative to multiple else-if statements when checking equality against constants.
switch (day) {
case 1:
printf("Monday");
break; // break exits the switch block
case 2:
printf("Tuesday");
break;
default:
printf("Invalid day");
}
The condition is checked before executing the loop body. If false initially, the loop never runs.
while (condition) {
// code to execute
}
Example:
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
2. do...while loop (Exit-Controlled):The condition is checked after executing the loop body. The loop runs at least once regardless of the condition.
do {
// code to execute
} while (condition);
Example:
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
3. for loop (Entry-Controlled):Combines initialization, condition, and increment/decrement in a single line. Best when the number of iterations is known.
for (initialization; condition; increment/decrement) {
// code to execute
}
Example:
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
for(i=0; i<r; i++) {
for(j=0; j<c; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
2. Matrix Subtraction:for(i=0; i<r; i++) {
for(j=0; j<c; j++) {
diff[i][j] = a[i][j] - b[i][j];
}
}
3. Matrix Multiplication:Condition: Columns of 1st matrix (c1) must equal Rows of 2nd matrix (r2).
for(i=0; i<r1; i++) {
for(j=0; j<c2; j++) {
mul[i][j] = 0;
for(k=0; k<c1; k++) {
mul[i][j] += a[i][k] * b[k][j];
}
}
}
4. Array Sorting (Bubble Sort - Ascending):for(i=0; i<n-1; i++) {
for(j=0; j<n-i-1; j++) {
if(arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
Declared using * (Value at address / Indirection operator). We use & (Address of operator) to get the address.
int a = 10;
int *ptr = &a;
printf("Address of a = %p\n", ptr);
printf("Value of a = %d\n", *ptr); // Outputs 10
Dynamic Memory Allocation (DMA):Functions defined in <stdlib.h>.
ptr = (int*) malloc(n * sizeof(int));ptr = (int*) calloc(n, sizeof(int));ptr = realloc(ptr, newSize);free(ptr);<string.h> and are used to manipulate arrays of characters ending with a null character (\0).strlen(str): Returns the length of the string (excluding \0).int len = strlen("Hello"); // Returns 5strcpy(dest, src): Copies the source string to destination.strcpy(str2, "Hello");strcat(dest, src): Concatenates (appends) source string to the end of destination string.strcat(str1, " World");strcmp(str1, str2): Compares two strings. Returns 0 if identical, <0 if str1 < str2, and >0 if str1 > str2.if(strcmp(a,b)==0)strrev(str): Reverses a string (non-standard, works in Borland C/Turbo C).strlwr(str) / strupr(str): Converts string to lowercase or uppercase respectively.Any modifications made inside the function do NOT reflect in the original variables because a copy is passed.
void swap(int x, int y) {
int temp = x; x = y; y = temp;
}
// Calling: swap(a, b); (a and b will NOT change in main)
Call by Reference:Modifications inside the function directly affect the original variables because pointers (addresses) are passed.
void swap(int *x, int *y) {
int temp = *x; *x = *y; *y = temp;
}
// Calling: swap(&a, &b); (a and b WILL change in main)
4 Types of User-Defined Functions:void printHello() { printf("Hello"); }int getAge() { return 20; }void printSum(int a, int b) { printf("%d", a+b); }int getSum(int a, int b) { return a+b; }int (10), float (3.14), complex (2+3j)str ("Hello")bool (True/False)Created using [].
append(x): Adds item to the end.insert(i, x): Inserts item at index i.remove(x): Removes first occurrence of x.pop(i): Removes and returns item at index i.sort(): Sorts the list in ascending order.Created using ().
count(x): Returns number of times x appears in the tuple.index(x): Returns the first index of x.Created using {} or set().
add(x): Adds an element.remove(x): Removes an element (throws error if not found).union(s): Returns union of two sets.intersection(s): Returns intersection of two sets.Created using {key: value}.
keys(): Returns a list-like object of all keys.values(): Returns a list-like object of all values.items(): Returns all key-value pairs as tuples.get(key): Returns value for a key (avoids KeyError).update(dict2): Updates dictionary with elements from another.if, elif, else for conditions and for, while for loops. It relies on indentation instead of curly braces.if marks > 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
else:
print("Grade C")
2. Looping Statements (for loop):Iterates over a sequence (list, string, range).
for i in range(1, 6):
print(i) # Prints 1 to 5
3. Looping Statements (while loop):Executes as long as a condition is true.
i = 1
while i <= 5:
print(i)
i += 1
ndarray is a multidimensional, homogeneous array of fixed-size items.
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print(arr[1:4]) # Output: [20 30 40]2. Dealing with Rows/Columns in Pandas:
Pandas uses DataFrames (2D tabular data).
import pandas as pd
df = pd.read_csv("data.csv")
# Selecting a column
print(df['Name'])
# Selecting a row using loc (label-based)
print(df.loc[0])
# Selecting a row using iloc (index-based)
print(df.iloc[0])
3. Working with Missing Data:df.isnull(): Checks for missing values (NaN).df.dropna(): Drops rows containing missing values.df.fillna(value): Fills missing values with a specific value.The apply() function can be used to apply a custom function to elements/rows/columns.
df['Salary'] = df['Salary'].apply(lambda x: x + 1000)5. Comparison: NumPy vs Pandas
| Feature | NumPy | Pandas |
|---|---|---|
| Primary Data Structure | ndarray (n-dimensional array) | Series (1D) and DataFrame (2D) |
| Data Types | Homogeneous (all elements must be same type) | Heterogeneous (columns can have different types) |
| Use Case | Mathematical operations, linear algebra, numerical data. | Data cleaning, manipulation, analysis, working with tabular data like CSV/Excel. |
| Indexing | Integer based default indexing. | Supports custom row/column labels and time-series indexing. |