Conditional & Looping Statements in C

Introduction

Conditional and looping statements allow decision-making and repetition in C programs. Conditional statements execute code based on certain conditions, while loops repeat a block of code until a condition is met. These are fundamental for building logical and efficient programs.


Key Points

1. Conditional Statements

  1. if Statement
  • Executes a block of code if the condition is true.
  • Syntax: if(condition) { // code }
  1. if-else Statement
  • Provides two branches: executes one if condition is true, another if false.
  • Syntax: if(condition) { // true block } else { // false block }
  1. Nested if
  • if statements inside another if statement for multiple conditions.
  1. switch-case Statement
  • Selects one of many blocks based on variable value.
  • Syntax: switch(variable) { case 1: // code break; case 2: // code break; default: // code }

2. Looping Statements

  1. for Loop
  • Repeats code a known number of times.
  • Syntax: for(initialization; condition; increment/decrement) { // code }
  1. while Loop
  • Repeats code while condition is true.
  • Syntax: while(condition) { // code }
  1. do-while Loop
  • Executes code at least once, then repeats while condition is true.
  • Syntax: do { // code } while(condition);

3. Break & Continue

  • break: exits the loop immediately
  • continue: skips the current iteration and continues with next

Example Code

#include <stdio.h>
int main() {
    int i;
    for(i = 1; i <= 5; i++) {
        if(i == 3) continue; // skips 3
        if(i == 5) break;    // exits loop at 5
        printf("%d\n", i);
    }

    int num = 2;
    switch(num) {
        case 1: printf("One"); break;
        case 2: printf("Two"); break;
        default: printf("Other");
    }
    return 0;
}
Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *