Unit 2 subjective questions Control structures and Input/Output functions
CSE101 — Computer Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Explain the switch-case statement in C with its syntax. What is the role of the
breakanddefaultkeywords?Model answer
The switch-case statement is a multi-way decision-making control statement that selects one of several code blocks to be executed based on a matching case value.
Syntax:
c
switch(expression) {
case constant_value1:
// statements
break;
case constant_value2:
// statements
break;
default:
// default statements
}Roles of Keywords:
break: It is used to terminate the switch block. Withoutbreak, the program falls through to the subsequent cases even if they don't match (known as fall-through).default: It acts like theelseblock in an if-else structure. It executes if none of the specified cases match the switch expression.
-
Question 2 of 20
Differentiate between Entry-Controlled and Exit-Controlled loops with examples.
Model answer
Loops are classified based on where the test condition is checked.
Feature Entry-Controlled Loop Exit-Controlled Loop Definition The test condition is checked before entering the loop body. The test condition is checked after executing the loop body. Execution Loop body may not execute at all if the condition is false initially. Loop body executes at least once irrespective of the condition. Examples forloop,whileloopdo-whileloopExample (Entry-Controlled):
c
while(n > 0) { ... } // Checks firstExample (Exit-Controlled):
c
do { ... } while(n > 0); // Executes then checks -
Question 3 of 20
Describe the Type Conversion mechanism in C. Differentiate between Implicit and Explicit type casting.
Model answer
Type Conversion is the process of converting one data type into another.
1. Implicit Type Conversion (Coercion)
- Performed automatically by the compiler.
- Usually happens when different data types are mixed in an expression.
- Rule: Smaller data types are promoted to larger data types (e.g.,
inttofloat). - Example:
float x = 5 + 2.5;(Here 5 is converted to 5.0 automatically).
2. Explicit Type Conversion (Type Casting)
- Performed manually by the programmer using the cast operator.
- Syntax:
(type_name) expression; - Used when we want to force a conversion that might not happen naturally or to prevent integer division errors.
- Example:
float x = (float)5 / 2;(Results in 2.5 instead of 2).
-
Question 4 of 20
Explain the syntax and execution flow of the
forloop.Model answer
The
forloop is a versatile repetition control structure that allows writing a loop that needs to execute a specific number of times.Syntax:
c
for (initialization; condition; increment/decrement) {
// Loop body
}Execution Flow:
- Initialization: Executed only once at the beginning. It sets the loop control variable.
- Condition: Evaluated before every iteration. If true, the loop body executes. If false, the loop terminates.
- Body: The code block inside the loop is executed.
- Update (Increment/Decrement): Updates the loop control variable. The flow returns to step 2.
Example:
c
for(int i = 0; i < 5; i++) {
printf("%d ", i);
} -
Question 5 of 20
Compare the
breakandcontinuestatements.Model answer
Both
breakandcontinueare jump statements used to alter the flow of control within loops.Basis breakcontinueFunction Terminates the loop or switch statement immediately. Skips the current iteration and jumps to the next iteration. Control Flow Control passes to the statement following the loop. Control passes to the loop update/condition check. Scope Used in loops ( for,while,do-while) andswitch.Used only in loops. Example:
break;inside a loop stops the looping entirely.continue;inside a loop skips the rest of the code for the current pass and starts the next pass.
-
-
Question 6 of 20
Write a C program using a
whileloop to calculate the sum of digits of a number given by the user.Model answer
C#include <stdio.h> int main() { int n, t, sum = 0, remainder; printf("Enter an integer: "); scanf("%d", &n); t = n; // Loop to extract digits while (t != 0) { remainder = t % 10; // Get the last digit sum = sum + remainder; // Add to sum t = t / 10; // Remove the last digit } printf("Sum of digits of %d = %d", n, sum); return 0; }Logic:
- Take Modulo 10 to get the last digit.
- Add it to
sum. - Divide by 10 to discard the last digit.
- Repeat until the number becomes 0.
-
Question 7 of 20
What are Data Type Modifiers in C? List and explain them.
Model answer
Data type modifiers alter the data storage size or range of the fundamental data types (
int,char,double).Types of Modifiers:
signed: Allows storage of both positive and negative numbers. This is the default forintandchar.unsigned: Restricts storage to only non-negative (positive) numbers. It effectively doubles the positive range.- Example:
unsigned int x;
- Example:
short: Reduces the storage size (usually 2 bytes for int). Used for small numbers to save memory.- Example:
short int s;
- Example:
long: Increases the storage size (usually 4 or 8 bytes). Used for very large numbers.- Example:
long long int bigNum;
- Example:
-
Question 8 of 20
Explain the
printf()function with respect to format specifiers, width, and precision.Model answer
printf()is a formatted output function in<stdio.h>.Syntax:
printf("control_string", argument_list);Components:
-
Format Specifiers: Start with
%to define the type of data.%dor%i: Integer%f: Float%c: Character%s: String
-
Field Width (
%wd): Specifies the minimum number of characters to be printed. If the value is shorter, it is padded with spaces.- Example:
%5dprints10.
- Example:
-
Precision (
%.nf): For floating-point numbers, it specifies the number of decimal places.- Example:
%.2fprints3.14for3.14159.
- Example:
-
-
Question 9 of 20
Discuss the
scanf()function. Why do we use the ampersand (&) operator with variables inscanf?Model answer
scanf()is a formatted input function used to read data from standard input (keyboard).Syntax:
scanf("format_specifiers", &variable1, &variable2, ...);Role of Ampersand (
&):- The
&is the Address-of Operator. scanfrequires the memory address of the variable where the read value should be stored, not the value of the variable itself.- Exception: When reading strings into character arrays (e.g.,
char str[20];), the array name acts as a pointer to the base address, so&is not required (scanf("%s", str);).
- The
-
Question 10 of 20
Differentiate between Formatted and Unformatted I/O functions with examples.
Model answer
Feature Formatted I/O Unformatted I/O Definition Functions that allow data to be read or written in a specific user-defined format. Functions that read or write data in a raw form (usually characters or strings) without formatting options. Format Specifiers Uses specifiers like %d,%f,%s.Does not use format specifiers. Flexibility More flexible, can handle mixed data types. Less flexible, usually handles one type at a time (char/string). Functions printf(),scanf(),fprintf(),fscanf()getch(),putch(),getchar(),putchar(),gets(),puts() -
Question 11 of 20
What is the
gotostatement? Why is its usage generally discouraged in structured programming?Model answer
gotois an unconditional jump statement that transfers control to a labeled statement within the same function.Syntax:
c
goto label;
...
label:
// codeWhy Discouraged?
- Spaghetti Code: Frequent use makes the logic difficult to follow, leading to unstructured "spaghetti code."
- Debugging Difficulty: It breaks the standard top-to-bottom flow, making debugging and testing harder.
- Violation of Structure: It violates the principles of Structured Programming (Sequence, Selection, Iteration). It is mostly replaced by loops and
break/continue.
-
Question 12 of 20
Explain the usage of
puts()andgets()functions. How doesgets()differ fromscanf("%s", ...)?Model answer
These are unformatted string I/O functions.
gets(str)- Reads a line of text from the standard input into the buffer
str. - Difference from
scanf:scanf("%s", ...)stops reading at the first whitespace (space/tab).gets()reads the entire line until a newline is encountered. Note:gets()is unsafe and deprecated in modern C due to buffer overflow risks.
puts(str)- Writes a string to the standard output.
- Automatically appends a newline character (
\n) at the end of the string output.
- Reads a line of text from the standard input into the buffer
-
Question 13 of 20
What is Structured Programming? List its main advantages.
Model answer
Structured Programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures, and loops.
Advantages:
- Readability: Code is easier to read and understand due to logical flow.
- Maintainability: Easier to update and fix bugs.
- Modularity: Complex problems are broken down into smaller functions/modules.
- Development Speed: Different modules can be developed by different programmers simultaneously.
-
Question 14 of 20
Write a C program to check if a number is Prime or not using a
forloop.Model answer
C#include <stdio.h> int main() { int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d", &n); if (n == 0 || n == 1) flag = 1; // 0 and 1 are not prime // Loop from 2 to n/2 for (i = 2; i <= n / 2; ++i) { // If n is divisible by i, then n is not prime if (n % i == 0) { flag = 1; break; } } if (flag == 0) printf("%d is a prime number.", n); else printf("%d is not a prime number.", n); return 0; } -
Question 15 of 20
Explain the concept of Nested Loops. Provide an example to print a right-angled triangle pattern.
Model answer
Nested Loops refer to a loop inside another loop. The inner loop executes completely for every single iteration of the outer loop.
Example: Right-Angled Triangle Pattern
cinclude <stdio.h>
int main() {
int i, j, rows = 5;
// Outer loop for rows
for (i = 1; i <= rows; ++i) {
// Inner loop for columns
for (j = 1; j <= i; ++j) {
printf("*");
}
printf("\n"); // Newline after each row
}
return 0;
}Output:
*
**
-
Question 16 of 20
What is the
returnstatement? Can a function have multiple return statements?Model answer
returnis a jump statement used to terminate the execution of a function and return control to the calling function. It can also pass a value back to the caller.Can a function have multiple returns?
- Yes. A function can have multiple
returnstatements, usually inside conditional blocks (if-elseorswitch). - However, only one
returnstatement is executed during a specific function call because the function terminates immediately once a return is encountered.
Example:
c
int check(int n) {
if (n > 0) return 1;
else return 0;
} - Yes. A function can have multiple
-
Question 17 of 20
Write a C program to find the roots of a Quadratic Equation () using
if-elseladders.Model answer
C#include <math.h> #include <stdio.h> int main() { double a, b, c, discriminant, root1, root2, realPart, imagPart; printf("Enter coefficients a, b and c: "); scanf("%lf %lf %lf", &a, &b, &c); discriminant = b * b - 4 * a * c; // Condition for real and different roots if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("root1 = %.2lf and root2 = %.2lf", root1, root2); } // Condition for real and equal roots else if (discriminant == 0) { root1 = root2 = -b / (2 * a); printf("root1 = root2 = %.2lf;", root1); } // Condition for imaginary roots else { realPart = -b / (2 * a); imagPart = sqrt(-discriminant) / (2 * a); printf("root1 = %.2lf+%.2lfi and root2 = %.2lf-%.2lfi", realPart, imagPart, realPart, imagPart); } return 0; } -
Question 18 of 20
Explain the "Dangling Else" problem in C programming and how it is resolved.
Model answer
The Problem:
The "Dangling Else" ambiguity arises when nestedifstatements are used without braces, and there are fewerelseclauses thanifclauses. The compiler must decide whichiftheelsebelongs to.Example:
c
if (condition1)
if (condition2)
statement;
else
statement; // Which if does this belong to?Resolution:
- C Rule: The
elseis associated with the nearest precedingifthat does not already have anelse. - Best Practice: Always use braces
{ }to explicitly define the scope and avoid ambiguity.
c
if (condition1) {
if (condition2) {
...
}
} else {
// Now clearly belongs to first if
}
- C Rule: The
-
Question 19 of 20
Compare the
whileanddo-whileloops with suitable syntax.Model answer
Feature whileLoopdo-whileLoopType Entry-controlled loop. Exit-controlled loop. Min Iterations 0 (if condition is false initially). 1 (always executes once). Semicolon No semicolon after the condition. Requires a semicolon ;afterwhile(condition).Syntax while(condition) { body; }do { body; } while(condition);Use Case When the number of iterations is unknown but depends on a condition checked beforehand. When the code must execute at least once (e.g., menu-driven programs). -
Question 20 of 20
Write a C program to reverse a given number using a loop.
Model answer
C#include <stdio.h> int main() { int n, reverse = 0, remainder; printf("Enter an integer: "); scanf("%d", &n); while (n != 0) { remainder = n % 10; // Get last digit reverse = reverse * 10 + remainder; // Append digit n /= 10; // Remove last digit } printf("Reversed number = %d", reverse); return 0; }Example:
Input:123rem=3,rev=3,n=12rem=2,rev=32,n=1rem=1,rev=321,n=0
Output:321
That's unit 2
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 2 of CSE101 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 2 of CSE101 save you a night before the exam?
Then you can help keep it free for the next batch. Ads cover part of the server bill; the rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks.