C Programming Scenario Questions with Detailed Explanations

TECHVIPUL
0


C Programming: Comprehensive Questions & In-Depth Analysis

Detailed Solutions, Execution Traces, Memory Internals, and Code Implementations

Question 1: An ATM checks whether the available balance is enough to permit a cash withdrawal. Evaluate the condition, complete the code, and justify the result produced.
void main()
{
    int balance=8000, amount=4500;
    if(________)
        printf("Success");
    else
        printf("Failed");
}

1. Missing Relational Condition:

if (balance >= amount)
    printf("Success");
else
    printf("Failed");

2. Detailed Mathematical & Logical Evaluation:

  • Variables: balance holds 8000, amount holds 4500.
  • Relational Operator: The greater-than-or-equal-to operator (>=) checks whether the customer has at least as much money as they wish to withdraw. Using a strictly greater condition (>) instead would wrongly reject an exact withdrawal (e.g., withdrawing the full 8000 balance).
  • Evaluation: 8000 >= 4500 yields the boolean integer 1 (True in C).

3. Justification of Output: Since the conditional expression resolves to a non-zero value, the program enters the true branch and executes printf("Success");, displaying Success. The else branch is skipped entirely.

Question 2: An ATM lets a customer keep entering their PIN until the correct one is typed. Analyze the requirement and determine whether while or do-while is more suitable. Give a reason.

1. Determination: do-while loop is clearly the better fit.

2. Detailed Architectural Comparison:

  • Entry-Controlled (while): Checks the condition before the loop body ever runs. For a while loop to test enteredPin != correctPin on the very first pass, the programmer would need to pre-load enteredPin with a sentinel value (e.g., -1) or repeat the input prompt before the loop starts — both add unnecessary redundancy.
  • Exit-Controlled (do-while): Guarantees the body runs at least once before the condition is checked. For PIN entry, the user must be prompted and must type something before any validation can happen.

3. Exemplary Code Structure:

int enteredPin;
const int CORRECT_PIN = 4321;

do {
    printf("Enter your 4-digit ATM PIN: ");
    scanf("%d", &enteredPin);
    if (enteredPin != CORRECT_PIN)
        printf("Incorrect PIN. Please try again.\n");
} while (enteredPin != CORRECT_PIN);

printf("PIN accepted. Redirecting to main menu...\n");
Question 3: A weather application takes a temperature reading from the user. Construct a C statement that stores this value in a suitable variable.
float temperature;
scanf("%f", &temperature);

1. Construct & Syntax:

float temperature;
scanf("%f", &temperature);

2. In-Depth Component Breakdown:

  • float temperature;: Real-world temperature readings almost always include fractional values (e.g., 31.4 °C, -2.6 °C). Declaring it as int would truncate the decimal part, losing accuracy. A 32-bit single-precision IEEE 754 float offers plenty of precision (around 6-7 significant digits) for a consumer weather app.
  • %f: The correct format specifier for reading and writing a float value in standard C.
  • &temperature: The address-of operator (&) supplies the memory address of the variable so scanf() can write directly into it (C's way of simulating pass-by-reference).

3. Robust Error-Handling Extension: In production-quality C code, the return value of scanf() (the count of successfully read items) should be checked: if (scanf("%f", &temperature) != 1) { /* handle invalid, non-numeric input */ }.

Question 4: A restaurant offers four menu items: Pizza, Burger, Pasta, and Noodles. The customer types in a choice number. Apply the switch-case concept and design the decision structure needed to display the chosen item.

1. Full Decision Structure Implementation:

#include <stdio.h>

int main() {
    int choice;
    printf("=== RESTAURANT MENU ===\n");
    printf("1. Pizza\n2. Burger\n3. Pasta\n4. Noodles\n");
    printf("Enter your choice (1-4): ");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            printf("Order Confirmed: You selected Pizza.\n");
            break;
        case 2:
            printf("Order Confirmed: You selected Burger.\n");
            break;
        case 3:
            printf("Order Confirmed: You selected Pasta.\n");
            break;
        case 4:
            printf("Order Confirmed: You selected Noodles.\n");
            break;
        default:
            printf("Error: Invalid choice! Please pick an option between 1 and 4.\n");
            break;
    }
    return 0;
}

2. Structural Mechanism & Rationale:

  • Jump Table Optimization: When case labels are dense integers, a compiler can turn a switch into a jump table (branch table), giving $O(1)$ lookup rather than the $O(n)$ sequential checks of an if-else-if chain.
  • The break Statement: Stops execution of the current case and jumps past the whole switch block. Leaving it out causes fall-through, unintentionally running the code of the following case as well.
  • The default Case: A catch-all block that handles out-of-range entries such as 0, 5, or negative numbers.
Question 5: A billing application needs to print a customer's name, purchased item, and total amount on one neatly spaced receipt line. Construct a suitable printf() statement to produce this formatted output.

1. Formatted Construction:

printf("%-20s %-20s %10.2f\n", customerName, itemPurchased, totalAmount);

2. Formatting Flags & Alignment Breakdown:

  • %-20s: Reserves a field width of at least 20 character columns. The minus sign (-) forces left-justification. Without it, text is right-aligned by default, giving uneven, ragged columns for names of different lengths.
  • %-20s (second instance): Allocates a fixed 20-character column for the item description.
  • %10.2f: Formats the floating-point amount to exactly 2 decimal places (paise/cents), right-aligned within a 10-character field, keeping the decimal points aligned down the receipt.
  • \n: Newline character that flushes the current output line and moves to the next.

Visual Output Simulation:
Priya Verma          Bluetooth Speaker         1299.00

Question 6: An ATM must first verify the PIN and then check the account balance before allowing a withdrawal. Analyze the situation and identify the appropriate branching structure needed to handle these two decisions.

1. Architectural Decision: Nested if-else Control Structure

2. Detailed System Architecture Analysis:

An ATM transaction really involves two separate checks stacked on top of each other: authentication (PIN) first, then the transactional check (balance):

  • Security Separation: Combining both checks into one compound condition (e.g., if (pin == ok && balance >= amt)) makes it impossible to tell the user exactly why the transaction failed, giving vague feedback.
  • Resource Optimization: Balance/ledger lookups over a banking network are relatively costly. If the PIN check fails at the outer level, the program can skip the balance query entirely, saving that cost.

3. Structured Implementation Model:

if (enteredPin == actualPin) {
    /* Security Layer 1 Cleared */
    if (accountBalance >= withdrawalAmount) {
        accountBalance -= withdrawalAmount;
        printf("Withdrawal successful! Please collect cash.\n");
    } else {
        printf("Transaction Declined: Insufficient account balance.\n");
    }
} else {
    printf("Transaction Declined: Incorrect PIN entered.\n");
}
Question 7: A mobile recharge program works out the final payable amount from the recharge amount plus a service charge. Apply suitable arithmetic and assignment expressions to compute the final amount.

1. Suitable C Expressions:

/* Approach A: Standard Binary Arithmetic Addition */
finalAmount = rechargeAmount + serviceCharge;

/* Approach B: Sequential Compound Assignment */
finalAmount = rechargeAmount;
finalAmount += serviceCharge;

2. Detailed Operational Mechanics:

  • Binary Operator (+): Reads the values stored in rechargeAmount and serviceCharge, loads them into CPU registers, and computes their sum.
  • Assignment Operator (=): Stores the computed right-hand-side r-value into the memory location reserved for finalAmount (the l-value).
  • Compound Operator (+=): finalAmount += serviceCharge is shorthand for finalAmount = finalAmount + serviceCharge, and typically compiles to an efficient in-place accumulate instruction.
  • Data Type Sizing: Both quantities should be float or double so fractional charges (like a 2.5% service tax adding ₹6.20) aren't lost.
Question 8: A shopkeeper wants to note down only the odd-numbered customers in today's queue. Apply the concept of a while loop, determine the output, and describe how the loop executes.
void main()
{
    int i=1;
    while(i<=5)
    {
        if(i%2!=0)
            printf("%d ",i);
        i++;
    }
}

1. Final Output:

1 3 5

2. Detailed Iteration-by-Iteration Execution Trace:

Pass i Value While Condition (i <= 5) If Condition (i % 2 != 0) Output Next i (i++)
1 1 1 <= 5 → TRUE 1 % 2 = 1 → TRUE 1 2
2 2 2 <= 5 → TRUE 2 % 2 = 0 → FALSE None 3
3 3 3 <= 5 → TRUE 3 % 2 = 1 → TRUE 3 4
4 4 4 <= 5 → TRUE 4 % 2 = 0 → FALSE None 5
5 5 5 <= 5 → TRUE 5 % 2 = 1 → TRUE 5 6
6 6 6 <= 5 → FALSE N/A (Terminated) None Loop Exits

3. Structural Description: This is an entry-controlled loop starting from counter i=1. The modulus operator (%) gives the remainder after dividing by 2; a non-zero remainder marks an odd number and triggers the print. The post-increment operator advances the counter each pass, ensuring the loop eventually terminates.

Question 9: A restaurant billing application needs the GST rate to stay fixed for the entire program run. Evaluate the suitability of #define versus const for storing this GST value.

1. Technical Comparison:

Dimension #define GST 0.12 (Macro Constant) const float GST = 0.12f; (Type-Qualified)
Processing Phase Text replacement handled by Preprocessor Semantic analysis handled by Compiler
Type Safety Untyped literal; can cause implicit type coercion surprises Strongly typed as float
Symbol Table & Debugging Stripped before compiling; absent from the symbol table (harder to debug) Visible in the symbol table, inspectable in GDB/debuggers
Scoping Behavior Global from the definition point until #undef Obeys lexical block scoping (can be local or global)

2. Evaluation Verdict: const float GST = 0.12f; is the better choice for a billing application. Because monetary calculations depend on precise numeric types, const enforces compile-time type checking, respects scope boundaries, and lets a debugger inspect the GST value at runtime.

Question 10: A fitness application must show a member's age, weight, and membership grade. Develop suitable C statements to store these values and print them using output statements.

1. Code Implementation:

#include <stdio.h>

int main() {
    /* 1. Variable Storage with Optimal Data Types */
    int age = 29; /* Whole years */
    float weight = 68.30f; /* Fractional mass in kilograms */
    char membershipGrade = 'B'; /* Single tier classification letter */

    /* 2. Formatted Output Statement */
    printf("===== Fitness Profile =====\n");
    printf("Age              : %d years\n", age);
    printf("Weight           : %.2f kg\n", weight);
    printf("Membership Grade : %c\n", membershipGrade);

    return 0;
}

2. Detailed Type Justifications:

  • int: Age is a discrete whole number; a floating-point type would be both inaccurate and wasteful here.
  • float: Body weight varies by fractions of a kilogram, so a floating-point type is required.
  • char: Membership tiers (Grade A, B, C, etc.) map to single ASCII characters, so a 1-byte char in single quotes ('B') is sufficient.
Question 11: A game gives a player three attempts, and the first attempt always plays out before any condition is checked. Analyze the do-while loop, determine the output, and interpret its execution.
void main()
{
    int i=1;
    do
    {
        printf("%d ",i);
        i++;
    }while(i<4);
}

1. Determined Program Output:

1 2 3

2. Detailed Step-by-Step Cycle Interpretation:

  • Step 1 (Initialization): Variable i is created in stack memory and set to 1.
  • Step 2 (Iteration 1 - Unconditional Entry): The loop body runs without checking any condition first. It prints 1 via printf("%d ", 1), then i++ updates i to 2.
  • Step 3 (Post-Condition Evaluation 1): while(i < 4) checks 2 < 4, which is TRUE, so control loops back to the top.
  • Step 4 (Iteration 2): Prints 2 and increments i to 3.
  • Step 5 (Post-Condition Evaluation 2): 3 < 4 is TRUE, so the loop continues.
  • Step 6 (Iteration 3): Prints 3 and increments i to 4.
  • Step 7 (Loop Termination): 4 < 4 evaluates to FALSE (0), so the loop stops.

3. Architectural Takeaway: The output confirms exactly three attempts run, and that the first attempt always executes before any condition is evaluated.

Question 12: A parking system needs to keep track of the number of vehicles, the parking fee, the vehicle category, and the name of the parking area. Construct suitable C declarations for storing these four pieces of information.

1. Variable Declarations in C:

int numberOfVehicles;       /* Whole numeric count of parked units */
float parkingFee;           /* Decimal financial charge per hour/stay */
char vehicleCategory;       /* Single character code: 'B'=Bike, 'C'=Car, 'T'=Truck */
char parkingAreaName[40];   /* Fixed string buffer for zone name (e.g., "East Wing A") */

2. Detailed Memory Allocation Breakdown:

  • int numberOfVehicles: Needs 4 bytes of signed integer storage since vehicle counts are whole numbers.
  • float parkingFee: Needs 4 bytes of IEEE 754 floating-point storage to represent currency amounts (e.g., ₹35.75).
  • char vehicleCategory: Needs just 1 byte to hold a single ASCII category code.
  • char parkingAreaName[40]: Reserves a contiguous 40-byte array, allowing strings up to 39 characters plus the terminating null byte (\0).
Question 13: A login application uses the following scanf() statement to read a username and age, but it does not behave as expected:
scanf("%s %d", username, &age);
Examine the statement and identify the error(s) causing this incorrect behaviour.

1. Detailed Error Analysis:

  • Security Flaw (Buffer Overflow Vulnerability): The unbounded %s directive keeps reading characters until it meets whitespace, with no check against the target buffer's size. If a user types 50 characters into a 20-character array, adjacent stack memory gets overwritten, leading to undefined behavior, crashes, or a possible security exploit.
  • Input Stream Desynchronization: Because %s stops at the first space, an entry like "John Doe 25" causes %s to capture only "John". The leftover token "Doe" stays in the input buffer, so the following %d fails to parse it as a number, leaving age with garbage or unassigned data.

2. Production-Grade Corrections:

/* Correction A: Bound the field width (assuming char username[20]) */
scanf("%19s %d", username, &age);

/* Correction B: Safer input using fgets + sscanf */
char lineBuffer[100];
if (fgets(lineBuffer, sizeof(lineBuffer), stdin) != NULL) {
    sscanf(lineBuffer, "%19s %d", username, &age);
}
Question 14: A mobile recharge system must display the plan menu at least once, even if the customer's very first entry turns out to be an invalid amount. Evaluate the situation and select the appropriate type of loop. Justify your answer.

1. Loop Selection: do-while loop (Post-Tested / Exit-Controlled)

2. Detailed Justification:

  • Execution Ordering: The recharge menu and its prompt need to appear on screen first, before the program can even check whether the entered amount is valid (positive, non-zero, within an allowed plan).
  • Comparison with while: A standard while loop checks its condition before the body runs at all. Making it run the first time would require initializing the test variable with an arbitrary dummy value (e.g., float amount = -1.0;), which is fragile sentinel-based logic.

3. Practical Code Architecture:

float rechargeAmount;
do {
    printf("\n--- RECHARGE PLANS ---\n");
    printf("Enter a valid recharge plan amount (> 0): ₹");
    scanf("%f", &rechargeAmount);

    if (rechargeAmount <= 0) {
        printf("Invalid amount! Minimum transaction is ₹1.00.\n");
    }
} while (rechargeAmount <= 0);

printf("Processing recharge of ₹%.2f...\n", rechargeAmount);
Question 15: A bank application needs to credit ₹750 to a customer's balance. Select the appropriate assignment statement for performing this operation.

1. Recommended Assignment Statements:

/* Primary: Compound Assignment (Idiomatic C) */
balance += 750;

/* Alternative: Explicit Reassignment */
balance = balance + 750;

2. Detailed Architectural Assessment:

  • Left-Hand Side Evaluation: With balance += 750, the l-value expression (balance) is evaluated only once. In more complex expressions (e.g., accounts[userIndex].balance += 750;), this avoids the compiler having to compute the same array offset twice, giving slightly cleaner generated code.
  • Readability & Maintainability: Compound assignment reads naturally as "update this existing balance" rather than a fresh, unrelated computation.
Question 16: A shopkeeper wants a C program that computes a customer's final bill including tax. Construct the basic structure of the program for this task.

1. Complete Structural Architecture:

/* SECTION 1: Preprocessor Directive Section */
#include <stdio.h>

/* SECTION 2: Global Definitions & Constants */
#define TAX_RATE 0.06f /* 6% Local Sales Tax */

/* SECTION 3: Main Execution Entry Point */
int main() {
    /* 3.1 Variable Declarations */
    float unitPrice, subtotal, taxAmount, totalBill;
    int quantity;

    /* 3.2 Input Acquisition */
    printf("Enter item unit price (₹): ");
    scanf("%f", &unitPrice);
    printf("Enter quantity purchased: ");
    scanf("%d", &quantity);

    /* 3.3 Computational Processing */
    subtotal = unitPrice * quantity;
    taxAmount = subtotal * TAX_RATE;
    totalBill = subtotal + taxAmount;

    /* 3.4 Formatted Receipt Output */
    printf("\n=============================\n");
    printf("Subtotal       : ₹%10.2f\n", subtotal);
    printf("Tax (6%%)       : ₹%10.2f\n", taxAmount);
    printf("-----------------------------\n");
    printf("Final Bill Amount: ₹%10.2f\n", totalBill);
    printf("=============================\n");

    /* 3.5 System Termination Status */
    return 0;
}

2. Structural Breakdown: A typical C program follows this flow: Header linking → Environment setup → Variable declaration → Input acquisition → Data processing → Output generation → Exit status return.

Question 17: A bus-booking program runs seats = seats - 1; right after every successful booking. Analyze the statement and classify the operation being performed on the variable.

1. Formal Classification: Arithmetic Decrement / Self-Reassignment Operation

2. Internal Execution Cycle:

  1. R-Value Fetch: The current value stored at the memory address of seats is read.
  2. ALU Subtraction: The CPU's Arithmetic Logic Unit subtracts the literal constant 1 from that value.
  3. L-Value Storage: The assignment operator (=) writes the decremented result back into seats' memory location, overwriting the old value.

3. Equivalent C Syntactical Forms:

  • seats--; (Postfix decrement operator)
  • --seats; (Prefix decrement operator)
  • seats -= 1; (Compound subtraction assignment)
Question 18: A school program uses #define MAX 60 and const float FEE = 750.0;. Assess the two declarations based on their purpose, type checking, and usage in the program.

1. Comprehensive Technical Assessment Matrix:

Assessment Vector #define MAX 60 const float FEE = 750.0;
Core Purpose Defines a preprocessor text-substitution token (symbolic macro constant). Defines a typed, read-only variable whose value is protected by the compiler.
Type Checking Zero Type Safety: Treated as raw textual tokens; type validity is checked only after replacement. Strict Type Checking: Enforced by the compiler as an explicit IEEE 754 float.
Memory & Pointers Allocates no memory address. Cannot be referenced with &MAX. Allocates storage in memory (typically .rodata). Its address can be captured with a pointer to const (const float *ptr = &FEE;).
Scope Control Ignores block boundaries (valid from definition until end of file or #undef). Obeys standard C block scope (local to its enclosing {} block or global if declared outside functions).
Typical Use Case Fixed array dimension sizes (e.g., int students[MAX]; in C89). Mathematical, scientific, and business constants used across calculation routines.
Question 19: A college attendance system must show attendance percentages for a batch of 5 students. Apply the concept of looping and design the looping logic needed for this requirement.

1. Designed C Loop Implementation:

#include <stdio.h>

int main() {
    /* Dataset: Floating point percentage records for 5 students */
    float attendancePercentages[5] = {88.00f, 91.50f, 72.25f, 65.00f, 96.75f};

    printf("=== STUDENT ATTENDANCE REPORT ===\n");
    /* Counted Loop Construct */
    for (int i = 0; i < 5; i++) {
        printf("Student ID #%d | Attendance: %6.2f%% | Status: %s\n",
               i + 1,
               attendancePercentages[i],
               attendancePercentages[i] >= 75.0f ? "Eligible" : "Shortage (Condone Required)");
    }
    return 0;
}

2. Detailed Loop Logic Justification:

  • Why a for Loop? A for loop suits determinate iteration, where the number of passes is fixed and known ahead of time (exactly 5 students). It neatly bundles initialization (int i = 0), the continuation test (i < 5), and the step update (i++) into one line.
  • Zero-Based Array Indexing: C arrays are 0-indexed, so the 5 students occupy indices 0, 1, 2, 3, 4. Printing i + 1 instead gives a more human-friendly ID range of 1 to 5.
  • Escape Formatting: The double percent sign (%%) inside printf() prints a literal % character on screen.
Question 20: A game must play at least one round before it asks the player whether they'd like to play again. Evaluate the requirement and justify the suitable loop type.

1. Evaluation & Loop Selection: do-while loop (Exit-Controlled Loop)

2. Exhaustive Architectural Justification:

  • Operational Sequence: The natural game flow is: Start round → Run gameplay logic → Show result → Ask whether to replay. The replay check simply cannot happen before the round itself has finished and the user has responded.
  • Drawback of Alternative Loops: A pre-tested loop (while or for) checks its condition before the body runs at all. To force it to run the first time, a priming value (e.g., char choice = 'y';) would need to be preset, adding redundant state that can hide real input bugs.

3. Exemplary Implementation Model:

#include <stdio.h>

int main() {
    char userChoice;

    do {
        printf("\n[GAME RUNNING] Rolling dice... You scored 6!\n");

        /* Prompt user after game loop body completes */
        printf("Do you want to play another round? (y/n): ");
        /* Note: leading space in ' %c' skips trailing newline buffers */
        scanf(" %c", &userChoice);
    } while (userChoice == 'y' || userChoice == 'Y');

    printf("Thanks for playing! Final session terminated.\n");
    return 0;
}




Tags
C

Post a Comment

0 Comments

If you have any doubts, Please let me know

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!