C Programming Control Flow Statements
C Programming Control Flow Statements
1. Basics of C Programming
C is a procedural programming language used for system and
application software.
Key Elements of C:
1. Variables: Used to store data. Example: int a = 10;
2. Data Types: Define the type of data. Examples: int, float, char.
3. Operators: Perform operations like +, -, *, /, % (arithmetic); >, <, ==
(relational).
4. Input/Output: printf to print, scanf to take input.
Example:
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered %d", num);
Example:
int a = 5;
if (a > 0) {
printf("Positive number");
}
2. if-else Statement:
Executes one block if the condition is true, and another if false.
Syntax:
if (condition) {
// Code if true
} else {
// Code if false
}
Example:
int a = -5;
if (a > 0) {
printf("Positive");
} else {
printf("Negative");
}
3. Nested if-else:
An if-else inside another if-else.
Example:
int a = 0;
if (a > 0) {
printf("Positive");
} else {
if (a == 0) {
printf("Zero");
} else {
printf("Negative");
}
}
4. else-if Ladder:
Used to check multiple conditions.
Syntax:
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the above is true
}
Example:
int marks = 75;
if (marks >= 90) {
printf("Grade A");
} else if (marks >= 75) {
printf("Grade B");
} else {
printf("Grade C");
}
5. Switch Statement:
An alternative to multiple if-else statements.
Syntax:
switch (variable) {
case value1:
// Code for value1
break;
default:
// Code if none of the cases match
}
Example:
int day = 3;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day");
}
Example:
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
2. do-while Loop:
Ensures the block is executed at least once.
Syntax:
do {
// Code to execute
} while (condition);
Example:
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
3. for Loop:
Used when the number of iterations is known.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example:
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
printf("%d\n", i);
}
2. continue Statement:
Skips the current iteration and moves to the next.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
printf("%d\n", i);
}
3. goto Statement:
Transfers control to a labeled statement.
Example:
int i = 1;
start:
if (i <= 5) {
printf("%d\n", i);
i++;
goto start;
}