Viva Questions on C Decision Making Statements with Answers
(if, if-else, nested if, switch, conditional operator)
1. What is a decision-making statement in C?
Answer:
A decision-making statement allows the program
to take different actions based on conditions. Examples are if, if-else, nested
if, switch, and the conditional (ternary) operator ?:.
2. What is the difference between if and if-else statements?
Answer:
if executes a
block of code only if the condition is true.
if-else
provides an alternative block of code to execute when the condition is false.
3. Can we use multiple if-else statements in C?
Answer:
Yes, we can
use multiple if-else
if constructs, also known as ladder if-else, to check multiple conditions
sequentially.
4. What is a nested if statement?
Answer:
A nested if means writing an if statement inside another if
or else
block. It is useful when multiple levels of decision-making are required.
5. How does a switch statement work in C?
Answer:
A switch evaluates an expression and compares it
with multiple case
labels. When a match is found, the corresponding block is executed until a break
statement is encountered.
6. What happens if we don’t use break in a switch case?
Answer:
Without break, the program executes the matched case
and then continues executing subsequent cases (fall-through) until it
encounters a break or the end of the switch block.
7. Can a switch statement work with floating-point values?
Answer:
No, in C, a switch
statement works only with integer and character values, not with float
or double.
8. What is the difference between if-else and switch?
Answer:
if-else can handle
complex conditions (logical expressions, ranges, multiple conditions).
switch
is limited to checking equality of a single expression against constant values
but is often faster and more readable.
9. What is the conditional (ternary) operator in C?
Answer:
The conditional operator ?: is a shorthand for if-else.
Example:
int max = (a > b) ? a : b;
This assigns a to max if a > b, otherwise
assigns b.
10. Is it possible to use a switch inside another switch?
Answer:
Yes, we can
have nested switch statements, but it is not commonly used because it reduces
readability.
11. What is the difference between = and == in decision-making?
Answer:
= is the assignment operator (assigns value).
== is the equality operator (compares two values).
Using = instead of == inside conditions is a common error.
12. Can if statements be written without curly braces {}?
Answer:
Yes, if there
is only one statement inside the if or else block, curly braces are optional.
But for multiple statements, curly braces are required.
No comments:
Post a Comment