Programming Concepts: Conditional, Branching, Loops, Iterative Statements, and Logical
1. Conditional Statements
Conditional statements are used to execute code based on specific conditions.
- if Statement: Executes a block of code if the condition is true.
if (x > 0) {
printf("x is positive\n");
- if-else Statement: Adds an alternate block of code if the condition is false.
if (x > 0) {
printf("x is positive\n");
} else {
printf("x is not positive\n");
- else if Ladder: Checks multiple conditions.
if (x > 0) {
printf("x is positive\n");
} else if (x < 0) {
printf("x is negative\n");
} else {
printf("x is zero\n");
}
- Switch Statement: Handles multiple cases efficiently.
switch (x) {
case 1:
printf("x is 1\n");
break;
case 2:
printf("x is 2\n");
break;
default:
printf("x is not 1 or 2\n");
2. Branching Statements
Branching alters the normal flow of execution.
- break: Exits the nearest loop or switch statement.
for (int i = 0; i < 10; i++) {
if (i == 5) break;
printf("%d ", i);
- continue: Skips the rest of the loop body and starts the next iteration.
for (int i = 0; i < 10; i++) {
if (i == 5) continue;
printf("%d ", i);
}
- goto: Jumps to a labeled part of the program (not recommended for structured programming).
goto label;
printf("This will not execute\n");
label:
printf("Jumped to label\n");
3. Loops
Loops are used to repeat a block of code.
- for Loop: Executes a block a specific number of times.
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
- while Loop: Repeats as long as the condition is true.
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
- do-while Loop: Executes at least once, even if the condition is false.
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
4. Iterative Statements
Iterative statements are another term for loops, focusing on repeated execution. All loops (for, while,
do-while) are iterative statements.
5. Logical Errors
Logical errors occur when the program runs but produces incorrect results due to flaws in logic.
Examples:
- Incorrect use of conditions:
if (x = 0) { // Logical error: `=` is assignment, not comparison
printf("x is zero\n");
Fix: Use == for comparison:
if (x == 0) {
printf("x is zero\n");
- Infinite loops:
int i = 0;
while (i < 5) {
printf("%d\n", i); // Logical error: `i` is never incremented
Fix: Increment i:
while (i < 5) {
printf("%d\n", i);
i++;
}
- Off-by-one errors:
for (int i = 1; i <= 5; i++) { // Logical error in range
printf("%d\n", i);
Fix: Adjust loop bounds as needed:
for (int i = 0; i < 5; i++) {
printf("%d\n", i);