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 sufficient balance is available for withdrawal. Evaluate the condition, complete the code, and justify the result produced.
void main()
{
    int balance=5000, amount=3000;
    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 5000, amount holds 3000.
  • Relational Operator: The greater-than-or-equal-to operator (>=) checks if the customer possesses at least as much money as they intend to withdraw. A strictly greater condition (>) would incorrectly reject exact withdrawals (e.g., withdrawing 5000 with 5000 balance).
  • Evaluation: 5000 >= 3000 yields the boolean integer 1 (True in C).

3. Justification of Output: Because the conditional expression resolves to non-zero, the program enters the true branch and executes printf("Success");, outputting Success. The else branch is bypassed entirely.

Question 2: An ATM allows a customer to enter the PIN repeatedly until the correct PIN is entered. Analyze the requirement and determine whether while or do-while is more appropriate. Give a reason.

1. Determination: do-while loop is significantly more appropriate.

2. Detailed Architectural Comparison:

  • Entry-Controlled (while): Evaluates the condition prior to entering the loop body. For a while loop to evaluate enteredPin != correctPin on the first iteration, the developer must either initialize enteredPin with a dummy/sentinel value (e.g., -1) or duplicate the input prompt outside the loop body before entry. This introduces code redundancy and maintenance overhead.
  • Exit-Controlled (do-while): Guarantees that the loop body executes at least once before checking the termination condition. In ATM PIN entry, user interaction must occur first to capture the PIN before validation can proceed.

3. Exemplary Code Structure:

int enteredPin;
const int CORRECT_PIN = 1234;

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

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

1. Construct & Syntax:

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

2. In-Depth Component Breakdown:

  • float temperature;: Atmospheric temperatures routinely exhibit fractional values (e.g., 36.6 °C, -4.2 °C). Choosing int causes truncation of fractional data, losing critical meteorological accuracy. A 32-bit single-precision IEEE 754 float provides sufficient 6-7 decimal digits of precision for consumer weather applications.
  • %f: The exact format specifier corresponding to float for standard C input/output streams.
  • &temperature: The address-of operator (&) extracts the raw memory address where the variable resides. The function scanf() requires pointer access to modify variable memory directly by reference (pass-by-reference simulation in C).

3. Robust Error-Handling Extension: In enterprise C code, scanf() returns the number of successfully assigned items: if (scanf("%f", &temperature) != 1) { /* handle invalid non-numeric input */ }.

Question 4: A restaurant provides four menu options: Pizza, Burger, Pasta, and Sandwich. The customer enters a choice number. Apply the switch-case concept and design the decision structure for displaying the selected food 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. Sandwich\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 Sandwich.\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: The C compiler can compile switch constructs into jump tables (branch tables) when case labels are dense integers, executing in $O(1)$ constant time compared to sequential $O(n)$ if-else-if evaluations.
  • The break Statement: Halts statement execution and transfers control past the switch block. Omitting break causes fall-through, which would mistakenly execute lower case statements.
  • The default Case: Acts as a catch-all safety block handling out-of-range user entries (such as 0, 5, or negative numbers).
Question 5: A billing application must display a customer's name, item purchased, and total amount on a single receipt line with proper spacing. 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: Reserver a minimum field width of 20 character columns. The minus sign (-) enforces left-justification. Without the minus sign, text is right-aligned, producing ragged, uneven columns on variable-length names.
  • %-20s (second instance): Allocates a fixed 20-character column for the purchased item description.
  • %10.2f: Formats the floating-point financial amount to exactly 2 digits after the decimal point (cents/paise standard), right-aligned across a 10-character field width. Right-justifying numerical columns aligns decimal separators neatly in receipts.
  • \n: Carriage return and line feed flushing the output buffer to display the next line cleanly.

Visual Output Simulation:
Rahul Sharma         Wireless Mouse           749.50

Question 6: An ATM checks the PIN and account balance before processing a withdrawal. Analyze the situation and identify the appropriate branching structure required to handle these decisions.

1. Architectural Decision: Nested if-else Control Structure

2. Detailed System Architecture Analysis:

An ATM transaction workflow represents a multi-tier security boundary. The authentication phase (PIN verification) must be isolated from the transactional verification phase (account balance check):

  • Security Separation: A single compound statement (e.g., if (pin == ok && balance >= amt)) fails because it cannot pinpoint why the request failed. It provides ambiguous error feedback to the user and leaks transaction state.
  • Resource Optimization: Querying account balances or executing ledger operations over banking networks is computationally expensive. If the PIN check fails at Layer 1, the program terminates immediately, avoiding the balance query altogether.

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 calculates the final amount using recharge amount and service charge. Apply suitable arithmetic and assignment expressions to obtain 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 (+): Takes the value stored in operand rechargeAmount and operand serviceCharge, places them into ALU CPU registers, and calculates their arithmetic sum.
  • Assignment Operator (=): Stores the evaluated right-hand side r-value into the designated memory address assigned to finalAmount (the l-value).
  • Compound Operator (+=): The statement finalAmount += serviceCharge is shorthand for finalAmount = finalAmount + serviceCharge. In compiled assembly, it uses an in-place accumulation register instruction.
  • Data Type Sizing: Both components should be declared as float or double to handle monetary fractions (such as a 2.5% service tax adding ₹7.45).
Question 8: A shopkeeper records the odd-numbered customers in a queue. Apply the concept of a while loop, determine the output, and describe the loop's execution.
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: The code employs an entry-controlled loop with an initialization counter i=1. The modulus operator (%) extracts the remainder after division by 2. When the remainder is non-zero, the number is odd, triggering printing. The post-increment operator updates the loop control variable on each iteration, preventing infinite looping.

Question 9: A restaurant application must keep the value of GST fixed throughout the program. Evaluate the suitability of #define and const for storing the GST value.

1. Technical Comparison:

Dimension #define GST 0.18 (Macro Constant) const float GST = 0.18f; (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 in symbol table (harder to debug) Visible in symbol table, inspectable in GDB/debuggers
Scoping Behavior Global from definition point until #undef Obeys lexical block scoping (can be local or global)

2. Evaluation Verdict: const float GST = 0.18f; is the superior choice for financial software. Because monetary transactions rely on precise numeric types, const guarantees compile-time type enforcement, prevents accidental scope pollution, and allows debuggers to inspect the GST constant directly during execution.

Question 10: A fitness application needs to display a user's age, weight, and membership grade. Develop suitable C statements for storing these values and displaying them using output statements.

1. Code Implementation:

#include <stdio.h>

int main() {
    /* 1. Variable Storage with Optimal Data Types */
    int age = 26; /* Whole years */
    float weight = 72.45f; /* Fractional mass in kilograms */
    char membershipGrade = 'A'; /* 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 discrete and whole; floating-point representation would be inaccurate and wasteful.
  • float: Human body weight fluctuates by fractions of a kilogram (grams), requiring floating-point support.
  • char: Tier categories (e.g., Grades A, B, C) represent individual ASCII characters, requiring a 1-byte char variable enclosed in single quotes ('A').
Question 11: A game gives a player three attempts, but the first attempt is always displayed before checking the condition. 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 allocated in stack memory and initialized to 1.
  • Step 2 (Iteration 1 - Unconditional Entry): The program enters the loop body without evaluating any condition. It runs printf("%d ", 1) (printing 1 ) and then evaluates i++, setting i to 2.
  • Step 3 (Post-Condition Evaluation 1): The loop evaluates while(i < 4)2 < 4 is TRUE. Control branches back to the do label.
  • Step 4 (Iteration 2): It runs printf("%d ", 2) (printing 2 ) and increments i to 3.
  • Step 5 (Post-Condition Evaluation 2): Checks while(i < 4)3 < 4 is TRUE. Control returns to the top.
  • Step 6 (Iteration 3): It runs printf("%d ", 3) (printing 3 ) and increments i to 4.
  • Step 7 (Loop Termination): Checks while(i < 4)4 < 4 is FALSE (0). The loop terminates.

3. Architectural Takeaway: The output confirms exactly three attempts are processed, and the design verifies that attempt 1 ran prior to any relational checks taking place.

Question 12: A parking system records the number of vehicles, parking fee, vehicle category, and parking area name. Construct suitable C declarations for storing these four types 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[50];   /* Fixed string buffer for zone name (e.g., "North Wing B") */

2. Detailed Memory Allocation Breakdown:

  • int numberOfVehicles: Requires 4 bytes of signed integer memory; vehicles enter as discrete non-fractional units.
  • float parkingFee: Requires 4 bytes of IEEE 754 floating-point storage to record currency amounts (e.g., ₹45.50).
  • char vehicleCategory: Requires 1 byte to store individual category codes in standard ASCII.
  • char parkingAreaName[50]: Allocates a contiguous 50-byte array in memory, supporting strings of up to 49 characters plus the terminating null byte (\0).
Question 13: A login application uses the scanf() statement given below to read a username and age, but it fails to work as expected:
scanf("%s %d", username, &age);
Examine the statement and identify the error(s) responsible for the incorrect behaviour.

1. Detailed Error Analysis:

  • Security Flaw (Buffer Overflow Vulnerability): The unbounded %s directive reads incoming characters continuously until encountering whitespace, without checking the size of the target buffer. If a user inputs 50 characters into a 20-character array, adjacent stack memory is overwritten, causing undefined behavior, application crashes, or security exploits.
  • Input Stream Desynchronization: Because %s breaks on spaces, if a user enters a first and last name separated by a space (e.g., "John Doe 25"), %s reads only "John". The string "Doe" remains in the input buffer, where the subsequent %d specifier fails to parse it as an integer, causing input failure and leaving age unassigned with garbage data.

2. Production-Grade Corrections:

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

/* Correction B: Safe enterprise 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 asks the user to enter a valid recharge amount. The system must display the menu at least once, even if the user initially enters an invalid value. 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: A recharge menu and its input prompt must render on screen before evaluating whether the entered monetary value is valid (e.g., positive, non-zero, within recharge plans).
  • Comparison with while: A standard while loop tests its condition before executing the loop body. To make a while loop run the first time, developers often initialize the test variable with an arbitrary dummy value (e.g., float amount = -1.0;). This introduces fragile sentinel 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 increases a customer's balance by ₹500. Select the appropriate assignment statement for performing this operation.

1. Recommended Assignment Statements:

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

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

2. Detailed Architectural Assessment:

  • Left-Hand Side Evaluation: In balance += 500, the l-value expression (balance) is evaluated only once. In complex structures (e.g., accounts[userIndex].balance += 500;), using += prevents the compiler from computing the array offset address twice, producing cleaner and more efficient machine code.
  • Readability & Maintainability: Compound assignment clearly expresses the intent: updating an existing state variable rather than computing an unrelated assignment.
Question 16: A shopkeeper is developing a C program to calculate a customer’s bill. 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.05f /* 5% 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 (5%%)       : ₹%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: Every standard C program follows this sequence: Header linkingEnvironment setupVariable declarationInput acquisitionData processingOutput generationExit status code return.

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

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

2. Internal Execution Cycle:

  1. R-Value Fetch: The runtime reads the current numerical value stored at the memory address bound to seats.
  2. ALU Subtraction: The CPU Arithmetic Logic Unit subtracts the integer literal constant 1 from that value.
  3. L-Value Storage: The assignment operator (=) writes the new decremented result back into the memory location of seats, overwriting the previous 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 100 and const float FEE = 500.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 100 const float FEE = 500.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). You can reference its address using 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 enclosing {} block or global if outside functions).
Typical Use Case Fixed array dimension sizes (e.g., int students[MAX]; in C89). Mathematical, scientific, and business constants used throughout calculation routines.
Question 19: A college attendance system needs to display attendance percentages for 5 students. Apply the concept of looping and design the looping logic for this requirement.

1. Designed C Loop Implementation:

#include <stdio.h>

int main() {
    /* Dataset: Floating point percentage records for 5 students */
    float attendancePercentages[5] = {84.50f, 92.25f, 76.00f, 68.75f, 95.50f};

    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 is ideal for determinate iteration, where the number of cycles is known at compile time (exactly 5 students). It groups initialization (int i = 0), continuation test (i < 5), and step update (i++) into a single line.
  • Zero-Based Array Indexing: In C, arrays are 0-indexed, meaning the 5 students map to indices 0, 1, 2, 3, 4. To display user-friendly output, i + 1 prints human-readable IDs 1 through 5.
  • Escape Formatting: The double percent sign (%%) in printf() prints an actual literal % character to the terminal.
Question 20: A game asks the player whether they want to play again. The game must run at least once before asking for the next attempt. 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: In game development, the sequence is strictly: Initialize round → Execute gameplay logic → Render result → Solicit restart decision. The continuation check cannot occur until gameplay finishes and the user provides replay input.
  • Drawback of Alternative Loops: In a pre-tested loop (while or for), the condition is checked before entering the body. To force a while loop to run the first time, developers must preset a priming character (e.g., char choice = 'y';). This introduces redundant state and can mask input logic 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!