PPS Important Questions - Solutions

UNIT 1 - Question 1
Compare compiler and interpreter.
Click to Reveal Answer & Solution
Answer: Both are language translators that convert high-level language to machine code, but they differ in execution methodology. A compiler translates the entire program at once, whereas an interpreter translates line-by-line.
Detailed Comparison:
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.
UNIT 1 - Question 2
What is an algorithm? How is it used as a problem-solving tool?
Click to Reveal Answer & Solution
Answer: An algorithm is a step-by-step procedure or a well-defined set of instructions to solve a specific problem.
Detailed Solution:

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:

  • Input: Should have zero or more inputs.
  • Output: Should produce at least one output.
  • Definiteness: Each step must be clear and unambiguous.
  • Finiteness: Must terminate after a finite number of steps.
  • Effectiveness: Every step must be basic enough to be carried out practically.

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.

UNIT 1 - Question 3
What is pseudo code? How is it used as a problem-solving tool?
Click to Reveal Answer & Solution
Answer: Pseudocode is an informal, high-level description of an algorithm that uses structural conventions of programming languages but is intended for human reading rather than machine execution.
Detailed Solution:

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.

UNIT 1 - Question 4(a)
Writing algorithms, Pseudo code and Flow Chart for: Fibonacci Series
Click to Reveal Answer & Solution
Answer: The Fibonacci series is a sequence where each number is the sum of the two preceding ones, usually starting with 0 and 1.
1. Algorithm:
Step 1: Start
Step 2: Declare variables n, a=0, b=1, c, i
Step 3: Read the value of n (number of terms)
Step 4: Print a and b
Step 5: Initialize i = 2
Step 6: If i < n, repeat steps 7 to 10. Else go to step 11.
Step 7: c = a + b
Step 8: Print c
Step 9: a = b, b = c
Step 10: i = i + 1, go to step 6
Step 11: Stop

2. Pseudo Code:
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).

UNIT 1 - Question 4(b)
Writing algorithms, Pseudo code for: Check Number Is Armstrong or Not
Click to Reveal Answer & Solution
Answer: An Armstrong number is a number that is equal to the sum of cubes of its digits (for 3-digit numbers). Example: 153 = 1³ + 5³ + 3³ = 153.
1. Algorithm:
Step 1: Start
Step 2: Declare variables num, temp, rem, sum = 0
Step 3: Read num
Step 4: temp = num
Step 5: If temp > 0, repeat steps 6 to 8. Else go to step 9.
Step 6: rem = temp % 10
Step 7: sum = sum + (rem * rem * rem)
Step 8: temp = temp / 10, go to step 5
Step 9: If sum == num, Print "Armstrong Number"
Step 10: Else, Print "Not an Armstrong Number"
Step 11: Stop

2. Pseudo Code:
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
UNIT 1 - Question 4(c)
Writing algorithms, Pseudo code for: Check a Number is Palindrome or Not
Click to Reveal Answer & Solution
Answer: A palindrome number remains the same when its digits are reversed (e.g., 121).
1. Algorithm:
Step 1: Start
Step 2: Declare variables num, temp, rem, rev = 0
Step 3: Read num
Step 4: temp = num
Step 5: If temp > 0, repeat steps 6 to 8. Else go to step 9.
Step 6: rem = temp % 10
Step 7: rev = (rev * 10) + rem
Step 8: temp = temp / 10, go to step 5
Step 9: If rev == num, Print "Palindrome Number"
Step 10: Else, Print "Not a Palindrome"
Step 11: Stop

2. Pseudo Code:
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
UNIT 1 - Question 4(d)
Writing algorithms, Pseudo code for: Find Factorial of a Number
Click to Reveal Answer & Solution
Answer: Factorial of a non-negative integer n is the product of all positive integers less than or equal to n. Denoted by n!
1. Algorithm:
Step 1: Start
Step 2: Declare variables n, fact = 1, i
Step 3: Read n
Step 4: If n < 0, Print "Factorial not defined" and go to Step 8
Step 5: Initialize i = 1
Step 6: If i <= n, repeat step 7. Else go to step 8.
Step 7: fact = fact * i, i = i + 1, go to step 6
Step 8: Print fact
Step 9: Stop

2. Pseudo Code:
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
UNIT 1 - Question 4(e) & 4(f)
Algorithms for Temperature Conversion (Celsius to Fahrenheit & vice versa)
Click to Reveal Answer & Solution
Answer: Formulas used are: F = (C * 9/5) + 32 and C = (F - 32) * 5/9
Celsius to Fahrenheit Algorithm:
Step 1: Start
Step 2: Declare variables c, f
Step 3: Read celsius value into c
Step 4: Calculate f = (c * 9/5) + 32
Step 5: Print f
Step 6: Stop

Fahrenheit to Celsius Algorithm:
Step 1: Start
Step 2: Declare variables c, f
Step 3: Read fahrenheit value into f
Step 4: Calculate c = (f - 32) * 5/9
Step 5: Print c
Step 6: Stop
UNIT 1 - Question 4(g)
Writing algorithms, Pseudo code for: Prime Number or Not
Click to Reveal Answer & Solution
Answer: A prime number is a number greater than 1 that is completely divisible only by 1 and itself.
1. Algorithm:
Step 1: Start
Step 2: Declare n, i, count = 0
Step 3: Read n
Step 4: If n <= 1, Print "Not Prime" and go to step 9
Step 5: Initialize i = 1
Step 6: If i <= n, repeat step 7 to 8. Else go to step 9.
Step 7: If n % i == 0, then count = count + 1
Step 8: i = i + 1, go to step 6
Step 9: If count == 2, Print "Prime Number". Else Print "Not Prime"
Step 10: Stop

2. Pseudo Code:
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
UNIT 1 - Question 4(h) & 4(i)
Writing algorithms for: Sum of even digits / Sum of odd digits in a number
Click to Reveal Answer & Solution
Answer: We extract digits one by one using modulo 10 and check if they are even (rem % 2 == 0) or odd (rem % 2 != 0).
Sum of Even Digits Algorithm:
Step 1: Start
Step 2: Declare num, sum = 0, rem
Step 3: Read num
Step 4: If num > 0, repeat steps 5 to 7. Else go to step 8.
Step 5: rem = num % 10
Step 6: If rem % 2 == 0, then sum = sum + rem
Step 7: num = num / 10, go to step 4
Step 8: Print sum
Step 9: Stop

For Sum of Odd Digits, replace the condition in Step 6 with: If rem % 2 != 0, then sum = sum + rem

UNIT 1 - Question 4(j)
Algorithm for: Sum of N Natural Numbers
Click to Reveal Answer & Solution
Answer: Natural numbers are positive integers (1, 2, 3...). Sum = n(n+1)/2, or found using a loop.
Algorithm:
Step 1: Start
Step 2: Declare n, i, sum = 0
Step 3: Read n
Step 4: Initialize i = 1
Step 5: If i <= n, repeat step 6. Else go to step 7.
Step 6: sum = sum + i, i = i + 1, go to step 5
Step 7: Print sum
Step 8: Stop
UNIT 1 - Question 5
What is a token? What are different types of tokens available in C language? Explain with example Keywords, Identifiers, Constants and Special Characters.
Click to Reveal Answer & Solution
Answer: A token is the smallest individual unit in a C program. The compiler breaks the source code into these tokens before processing them.
Types of Tokens in C:

There are 6 basic types of tokens in C:

  • 1. Keywords: Reserved words with pre-defined meanings. Examples: int, return, if, else.
  • 2. Identifiers: User-defined names for variables, functions, and arrays. Must start with a letter or underscore. Example: main, sum, _count.
  • 3. Constants: Fixed values that do not change during execution. Examples: 10 (Integer), 3.14 (Floating), 'A' (Character).
  • 4. Strings: Sequence of characters enclosed in double quotes. Example: "Hello World".
  • 5. Special Characters: Symbols used for specific purposes. Examples: , (comma), ; (semicolon), [], {}.
  • 6. Operators: Symbols that trigger an action/computation. Examples: +, -, *, ==.
UNIT 1 - Question 6
Unformatted Input/Output functions.
Click to Reveal Answer & Solution
Answer: Unformatted I/O functions deal with reading or writing single characters or strings without using format specifiers (like %d, %s).
1. Unformatted Input Functions:
  • 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).
2. Unformatted Output Functions:
  • 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.
UNIT 1 - Question 7
Storage Class (Auto, static, extern, register)
Click to Reveal Answer & Solution
Answer: A storage class defines the scope (visibility), lifetime, and default initial value of a variable in C.
The 4 Storage Classes in C:
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.
UNIT 1 - Question 8
Operators (all operators with example)
Click to Reveal Answer & Solution
Answer: Operators are symbols that tell the compiler to perform specific mathematical or logical manipulations.
Types of Operators in C:
  • Arithmetic Operators: + (Add), - (Sub), * (Mul), / (Div), % (Mod). Example: a + b
  • Relational Operators: ==, !=, >, <, >=, <=. Example: a > b
  • Logical Operators: && (Logical AND), || (Logical OR), ! (Logical NOT). Example: (a > b) && (b > c)
  • Bitwise Operators: & (AND), | (OR), ^ (XOR), ~ (Complement), << (Left Shift), >> (Right Shift).
  • Assignment Operators: =, +=, -=, *=, /=, %=. Example: a += 5 (same as a = a + 5)
  • Increment/Decrement Operators: ++ (increment by 1), -- (decrement by 1). Example: x++
  • Conditional (Ternary) Operator: ? :. Example: (a > b) ? a : b (Returns 'a' if true, else 'b')
  • Special Operators: sizeof() (returns size of variable in bytes), & (address of), * (pointer to).
UNIT 1 - Question 9
Operator Precedence (Evaluating Expressions)
Click to Reveal Answer & Solution
Answer: Operator precedence determines which operator is evaluated first in an expression containing multiple operators.
Basic Rules of Precedence (from highest to lowest):
  1. Parentheses () and brackets []
  2. Unary Operators: ++, --, !, ~ (Associativity: Right to Left)
  3. Multiplicative: *, /, % (Associativity: Left to Right)
  4. Additive: +, - (Associativity: Left to Right)
  5. Relational: <, <=, >, >=
  6. Equality: ==, !=
  7. Logical AND: &&
  8. Logical OR: ||
  9. Assignment: =, +=, 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

UNIT 1 - Question 10
Write a C program to read a radius of a Circle as an input and Calculate its Diameter, Circumference, and Area.
Click to Reveal Answer & Solution
Answer: Use formulas: Diameter = 2*r, Circumference = 2*π*r, Area = π*r²
#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;
}
UNIT 1 - Question 11 & 13
Write a C program to swap two numbers without using third variable (and using bitwise operator).
Click to Reveal Answer & Solution
Answer: Arithmetic logic uses + and -, while Bitwise logic uses XOR (^).
Method 1: Using Arithmetic (+ and -)
#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;
}
UNIT 1 - Question 12
Write a C program to enter length and width of a rectangle as an input and calculate its perimeter and its area.
Click to Reveal Answer & Solution
Answer: Area = l * w, Perimeter = 2 * (l + w)
#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;
}
UNIT 1 - Question 14
Read two angles of a triangle and find the third angle. Read base and height and find area of a triangle.
Click to Reveal Answer & Solution
Answer: Third angle = 180 - (a + b). Area = (base * height) / 2.
#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;
}
UNIT 1 - Question 16
Write a C program to enter basic salary and prepare pay slip. TA = 15%, HRA = 8%, Grade Pay = 9000, PF = 15%. Calculate Gross and Net salary.
Click to Reveal Answer & Solution
Answer: Gross = Basic + TA + HRA + Grade Pay. Net = Gross - PF.
#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;
}
UNIT 2 - Question 1
Explain in detail about Conditional Control Statements. (Simple if, if...else, else if and nested if, Switch case with example)
Click to Reveal Answer & Solution
Answer: Conditional control statements in C are used to make decisions and execute specific blocks of code based on certain conditions.
1. Simple if statement:

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");
}
UNIT 2 - Question 2
Explain in detail about Looping Control Statements. (for, While, do..while with example)
Click to Reveal Answer & Solution
Answer: Looping statements allow a block of code to be executed repeatedly as long as a specified condition is true.
1. while loop (Entry-Controlled):

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);
}
UNIT 2 - Question 4(a,b,c,d)
Write a C program for Matrix Addition, Subtraction, Multiplication, and Array Sorting.
Click to Reveal Answer & Solution
Answer: Matrix operations use 2D arrays (nested loops), while array sorting uses 1D arrays (e.g., Bubble Sort).
1. Matrix Addition:
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;
        }
    }
}
UNIT 2 - Question 6 & 7
Pointer & Dynamic Memory Allocation
Click to Reveal Answer & Solution
Answer: A pointer is a variable that stores the memory address of another variable. DMA allows allocation/deallocation of memory at runtime.
Pointers:

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

  • malloc(): Allocates a single large block of memory. Leaves memory uninitialized (garbage values).
    ptr = (int*) malloc(n * sizeof(int));
  • calloc(): Allocates multiple blocks of memory and initializes them to zero.
    ptr = (int*) calloc(n, sizeof(int));
  • realloc(): Reallocates (resizes) an existing block of dynamically allocated memory without losing data.
    ptr = realloc(ptr, newSize);
  • free(): Deallocates dynamically allocated memory to prevent memory leaks.
    free(ptr);
UNIT 3 - String Functions
Explain string functions with an example (strlen, strcpy, strcat, strcmp, strrev, strlwr, strupr).
Click to Reveal Answer & Solution
Answer: String functions in C are declared in <string.h> and are used to manipulate arrays of characters ending with a null character (\0).
Key Functions:
  • strlen(str): Returns the length of the string (excluding \0).
    Ex: int len = strlen("Hello"); // Returns 5
  • strcpy(dest, src): Copies the source string to destination.
    Ex: strcpy(str2, "Hello");
  • strcat(dest, src): Concatenates (appends) source string to the end of destination string.
    Ex: strcat(str1, " World");
  • strcmp(str1, str2): Compares two strings. Returns 0 if identical, <0 if str1 < str2, and >0 if str1 > str2.
    Ex: 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.
UNIT 3 - Functions (Call by Value & Reference)
Explain Call by Value and Call by Reference with an example. Also explain function argument and return values (4 types).
Click to Reveal Answer & Solution
Answer: Call by Value passes copies of arguments, while Call by Reference passes memory addresses.
Call by Value:

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:
  1. Function with no arguments and no return value: void printHello() { printf("Hello"); }
  2. Function with no arguments and a return value: int getAge() { return 20; }
  3. Function with arguments and no return value: void printSum(int a, int b) { printf("%d", a+b); }
  4. Function with arguments and a return value: int getSum(int a, int b) { return a+b; }
UNIT 4 - Python Basics & Data Structures
Basic Data Types in Python. List, Tuple, Set, and Dictionaries methods.
Click to Reveal Answer & Solution
Answer: Python supports Numbers, Strings, Lists, Tuples, Sets, and Dictionaries natively.
1. Basic Data Types:
  • Numeric: int (10), float (3.14), complex (2+3j)
  • Text: str ("Hello")
  • Boolean: bool (True/False)
2. List Methods (Mutable, Ordered):

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.
3. Tuple Methods (Immutable, Ordered):

Created using ().

  • count(x): Returns number of times x appears in the tuple.
  • index(x): Returns the first index of x.
4. Set Methods (Mutable, Unordered, No Duplicates):

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.
5. Dictionary Methods (Key-Value Pairs):

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.
UNIT 4 - Python Control Flow
Explain Conditional and Looping Control Statements in Python.
Click to Reveal Answer & Solution
Answer: Python uses if, elif, else for conditions and for, while for loops. It relies on indentation instead of curly braces.
1. Conditional Statements:
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
UNIT 5 - NumPy & Pandas
Explain NumPy ndarray, Slicing, Pandas Rows/Columns, Missing Data, and Comparison between NumPy and Pandas.
Click to Reveal Answer & Solution
Answer: NumPy is for numerical computations using multidimensional arrays, while Pandas is for data manipulation using Series and DataFrames.
1. NumPy ndarray & Slicing:

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.
4. Applying Functions to DataFrames:

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.