Unit2 - Subjective Questions
CSE101 • Practice Questions with Detailed Answers
Explain the switch-case statement in C with its syntax. What is the role of the break and default keywords?
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.
Differentiate between Entry-Controlled and Exit-Controlled loops with examples.
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 | for loop, while loop |
do-while loop |
Example (Entry-Controlled):
c
while(n > 0) { ... } // Checks first
Example (Exit-Controlled):
c
do { ... } while(n > 0); // Executes then checks
Describe the Type Conversion mechanism in C. Differentiate between Implicit and Explicit type casting.
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).
Explain the syntax and execution flow of the for loop.
The for loop 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);
}
Compare the break and continue statements.
Both break and continue are jump statements used to alter the flow of control within loops.
| Basis | break |
continue |
|---|---|---|
| Function | 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) and switch. |
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.
Write a C program using a while loop to calculate the sum of digits of a number given by the user.
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.
What are Data Type Modifiers in C? List and explain them.
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:
Explain the printf() function with respect to format specifiers, width, and precision.
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:
Discuss the scanf() function. Why do we use the ampersand (&) operator with variables in scanf?
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);).
Differentiate between Formatted and Unformatted I/O functions with examples.
| 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() |
What is the goto statement? Why is its usage generally discouraged in structured programming?
goto is an unconditional jump statement that transfers control to a labeled statement within the same function.
Syntax:
c
goto label;
...
label:
// code
Why 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.
Explain the usage of puts() and gets() functions. How does gets() differ from scanf("%s", ...)?
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 (
) at the end of the string output.
What is Structured Programming? List its main advantages.
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.
Write a C program to check if a number is Prime or not using a for loop.
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;
}
Explain the concept of Nested Loops. Provide an example to print a right-angled triangle pattern.
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
c
include <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("
"); // Newline after each row
}
return 0;
}
Output:
*
**
What is the return statement? Can a function have multiple return statements?
return is 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;
}
Write a C program to find the roots of a Quadratic Equation () using if-else ladders.
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;
}
Explain the "Dangling Else" problem in C programming and how it is resolved.
The Problem:
The "Dangling Else" ambiguity arises when nested if statements are used without braces, and there are fewer else clauses than if clauses. The compiler must decide which if the else belongs 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
}
Compare the while and do-while loops with suitable syntax.
| Feature | while Loop |
do-while Loop |
|---|---|---|
| Type | 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 ; after while(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). |
Write a C program to reverse a given number using a loop.
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: 123
rem=3,rev=3,n=12rem=2,rev=32,n=1rem=1,rev=321,n=0
Output:321