Important Questions
Important Questions
Answer
int main() {
int choice;
printf("Enter a number (1-3): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("You chose 1.\n");
break;
case 2:
printf("You chose 2.\n");
break;
case 3:
printf("You chose 3.\n");
break;
default:
printf("Invalid choice.\n");
}
return 0;
}
2. Looping Constructs in C
Loop Types:
1. for loop: Used when the number of iterations is known in advance.
2. while loop: Used when the condition for looping depends on runtime checks.
3. do-while loop: Used when the loop body needs to execute at least once.
Role of break and continue:
break: Exits the loop prematurely.
continue: Skips the current iteration and moves to the next one.
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip printing 5
}
if (i == 8) {
break; // Exit loop when i is 8
}
printf("%d\n", i);
}
return 0;
}
3. Conditional Operator
What is a Conditional Operator?
The conditional operator (?:) is a shorthand for if-else statements. It evaluates a condition
and returns one of two values.
Example to Find Largest of Three Numbers:
#include <stdio.h>
int main() {
int a, b, c, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
return 0;
}
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
return 0;
}
int main() {
int n, even_sum = 0, odd_sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
int i = 1;
while (i <= n) {
if (i % 2 == 0) {
even_sum += i;
} else {
odd_sum += i;
}
i++;
}
return 0;
}
int main() {
int num, reverse = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}
return 0;
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
return 0;
}