POCP Module2
POCP Module2
1. Operators in C
2. Type conversion and Typecasting
3. Decision control and Looping statements:
4. Introduction to Decision control,
5. Conditional branching statements,
6. Iterative statements
7. Nested loops
8. Break and Continue statements
9. goto statement.
Operators in C
Operators in C are symbols used to perform operations on variables and values. They are classified
based on the type of operation they perform. Here's a breakdown of different types of operators in
C:
1. Arithmetic Operators
These operators perform basic arithmetic operations like addition, subtraction, multiplication, etc.
|----------|-------------------------|---------------|
| `+` | Addition | `x + y` |
| `-` | Subtraction | `x - y` |
| `*` | Multiplication | `x * y` |
| `/` | Division | `x / y` |
```c
int a = 10, b = 5;
```
Relational operators are used to compare two values. The result is either `true` (non-zero) or `false`
(zero).
|----------|------------------------|---------------|
| `==` | Equal to | `x == y` |
#### Example:
```c
int a = 10, b = 5;
```
|----------|------------------------|---------------|
| `||` | Logical OR | `x || y` |
#### Example:
```c
int a = 1, b = 0;
```
|----------|---------------------------------|---------------|
| `|` | Bitwise OR | `x | y` |
#### Example:
```c
```
### 5. Assignment Operators
|----------|-------------------------------|---------------|
#### Example:
```c
int a = 10;
a += 5; // a = a + 5, now a = 15
a *= 2; // a = a * 2, now a = 30
```
### 6. Increment and Decrement Operators
- Prefix: `++x` increments `x` first and then returns the value.
- Postfix: `x++` returns the value of `x` first and then increments it.
#### Example:
```c
int x = 10;
```
?: Conditional evaluation x ? y : z
It evaluates the first expression (`x`). If `x` is true, the value of the expression is `y`; otherwise, it's `z`.
#### Example:
```c
int a = 10, b = 5;
```
The comma operator allows multiple expressions to be evaluated in a single statement, with the last
expression being the result.
#### Example:
```c
```
The type cast operator explicitly converts one data type into another.
#### Example:
```c
float x = 5.75;
The `sizeof` operator returns the size (in bytes) of a variable or data type.
#### Example:
```c
int x = 10;
printf("Size of x: %lu bytes\n", sizeof(x)); // Output: Size of x: 4 bytes (on most systems)
```
These are used with pointers to get the address of a variable or the value stored at an address.
|----------|-----------------------------------|---------------|
#### Example:
```c
int x = 10;
```
C has two operators specific to pointers: the address-of operator (`&`) and the dereference operator
(`*`).
#### Example:
```c
int x = 10;
int *p = &x; // p stores the address of x
```
Implicit conversion occurs automatically when the compiler converts one data type to another,
usually when assigning values between different types or during arithmetic operations. The C
compiler automatically promotes smaller data types (like `char`, `short`) to larger ones (`int`, `float`,
`double`) based on specific rules.
- No loss of data (usually): Conversion occurs from a smaller to a larger data type.
- No explicit instruction: The programmer does not have to specify the conversion.
#### Example:
```c
int a = 10;
```
In this example, `a` (an `int`) is implicitly converted to a `float` during the assignment to `b`. The
value `10` becomes `10.0`.
When performing arithmetic operations between two different types, C promotes the smaller data
type to the larger data type to avoid loss of precision.
```c
int x = 5;
float y = 4.5;
float result = x + y; // x is implicitly converted to float
```
Here, `x` (an `int`) is implicitly converted to a `float`, so the operation proceeds in floating-point
arithmetic, and the result is `9.5`.
Typecasting, also called explicit conversion, allows the programmer to manually convert one data
type to another. This is done using the cast operator. Typecasting is required when you want to
forcefully convert a value from one type to another, especially when there is a risk of data loss (e.g.,
converting from a larger type to a smaller type).
#### Syntax:
```c
(type) expression
```
Where `type` is the target data type and `expression` is the value or variable to be converted.
#### Example:
```c
float x = 3.14;
```
In this example, the `float` value `3.14` is cast to an `int`, and the fractional part (`0.14`) is discarded,
leaving `y` with the value `3`.
```c
float f = 9.99;
int i = (int)f; // i will hold the value 9, as the fractional part is discarded
```
```c
int a = 5, b = 2;
```
- Pointer typecasting:
Sometimes, typecasting is needed when working with pointers to convert between different
pointer types.
```c
void *ptr;
int *int_ptr;
```
```c
double d = 3.14159;
int i = (int)d; // i will hold the value 3, the fractional part is lost
```
|----------------------|--------------------------------------------------------|-------------------------------------------|
| Data Loss Risk | Generally no data loss (safe promotions) | Possible data loss (e.g., float
to int) |
Type promotion is a type of implicit conversion where smaller data types are promoted to larger
data types to prevent data loss during operations. This often happens during arithmetic expressions
and function calls.
In C, types smaller than `int` (like `char` and `short`) are promoted to `int` during arithmetic
operations if the value can be stored in an `int`.
```c
char c = 10;
```
When two different types are used in an expression, C automatically converts all the operands to the
largest data type involved.
```c
int i = 10;
float f = 5.5;
```
Typecasting can also be used to convert between different pointer types, especially in the case of
`void*` (a generic pointer type that can hold the address of any type of variable). For example, when
working with dynamic memory allocation, pointer typecasting is commonly required.
#### Example:
```c
```
In this example, the `malloc()` function returns a `void*`, which is then explicitly cast to an `int*` to
be used as an integer pointer.
- Data Loss: When typecasting between incompatible types, data loss may occur. For example,
casting a `float` to an `int` will discard the fractional part.
```c
float f = 9.99;
```
- Undefined Behavior: Improper typecasting, especially with pointers, can lead to undefined
behavior and runtime errors.
```c
int x = 5;
float *ptr = (float *)&x; // This type of pointer casting can cause issues
```
### Summary
- Implicit Conversion: Automatically performed by the compiler without explicit instructions, often
promoting smaller types to larger types to prevent data loss.
- Explicit Conversion (Typecasting): Done explicitly by the programmer using the cast operator
`(type)`. It is useful when you need to force a conversion between incompatible types or when
implicit conversion is insufficient.
Understanding how and when to use implicit conversion and typecasting is essential in C
programming, particularly for handling mixed data types and ensuring that operations are
performed as intended.
Decision control statements allow the program to choose different actions based on certain
conditions. The most common decision-making statements in C are:
The `if` statement is used to execute a block of code only if a specified condition is true.
#### Syntax:
```c
if (condition) {
```
#### Example:
```c
int x = 10;
if (x > 5) {
```
The `if-else` statement extends the `if` statement by providing an alternative block of code to
execute if the condition is false.
#### Syntax:
```c
if (condition) {
} else {
```
#### Example:
```c
int x = 3;
if (x > 5) {
} else {
```
The `else if` ladder allows you to check multiple conditions in sequence. If one condition is true, the
corresponding block is executed, and the rest of the conditions are skipped.
#### Syntax:
```c
if (condition1) {
} else if (condition2) {
```
#### Example:
```c
int x = 10;
if (x > 20) {
} else if (x > 5) {
} else {
```
The `if` statements can be nested, meaning you can place an `if` statement inside another `if`
statement.
#### Syntax:
```c
if (condition1) {
if (condition2) {
}
```
#### Example:
```c
int x = 10, y = 5;
if (x > 5) {
if (y < 10) {
```
The `switch` statement is used when you have multiple conditions based on the value of a variable.
It allows you to execute a block of code depending on the value of the expression.
#### Syntax:
```c
switch (expression) {
case constant1:
break;
case constant2:
break;
// more cases...
default:
```
#### Example:
```c
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
```
- **break**: It exits the `switch` statement. Without `break`, the program continues executing the
next case (fall-through behavior).
---
## 2. **Looping Statements**
Looping statements allow a set of instructions to be executed repeatedly based on a condition. The
main looping statements in C are:
The `while` loop repeats a block of code as long as a specified condition is true.
#### Syntax:
```c
while (condition) {
```
#### Example:
```c
int i = 0;
while (i < 5) {
i++;
```
- In this example, the loop runs while `i` is less than 5, incrementing `i` after each iteration.
The `do-while` loop is similar to the `while` loop, but it ensures that the block of code is executed at
least once, even if the condition is false.
#### Syntax:
```c
do {
} while (condition);
```
#### Example:
```c
int i = 0;
do {
i++;
```
- Here, the block is executed once before checking the condition. The loop will continue as long as `i`
is less than 5.
The `for` loop is often used when the number of iterations is known. It consists of three parts:
initialization, condition, and increment/decrement.
#### Syntax:
```c
```
#### Example:
```c
```
- **Condition**: Evaluated before each iteration; the loop runs as long as it is true.
You can nest loops, meaning you can place a loop inside another loop. This is useful for working with
multi-dimensional data, such as matrices.
#### Example:
```c
```
- This prints all combinations of `i` and `j` for `i` from 0 to 2 and `j` from 0 to 2.
---
The `break` statement is used to exit a loop prematurely, regardless of the loop's condition.
#### Example:
```c
if (i == 5) {
```
The `continue` statement skips the current iteration and moves to the next one.
#### Example:
```c
if (i == 2) {
```
### C. **goto Statement**
The `goto` statement transfers control to a labeled statement within the same function. It can be
used to jump to specific points in code.
#### Syntax:
```c
goto label;
...
label:
```
#### Example:
```c
int i = 0;
loop:
i++;
if (i < 5) {
```
- The use of `goto` is generally discouraged because it can lead to unstructured, hard-to-read code
(spaghetti code).
---
## 4. **Infinite Loops**
An infinite loop occurs when the terminating condition is never met or omitted, causing the loop to
execute indefinitely. These can be useful in situations where a program should keep running until
explicitly terminated.
#### Example:
```c
while (1) {
```
```c
for (;;) {
// Infinite loop
```
---
| Loop Type | Condition Check Time | Guaranteed Execution at Least Once? | Use Case
|
|---------------|----------------------|-------------------------------------|------------------------------------|
Both **decision control statements** and **looping statements** provide essential ways to control
the flow of a program, helping you build logic based on conditions and repetitive tasks.
- A temperature control system that turns on the heater if the temperature is too low.
- A traffic signal that switches between different light colors based on time.
Decision control allows a program to execute different blocks of code depending on the conditions
being true or false. Without decision control, a program would have a linear flow and be unable to
respond to dynamic situations.
2. **if-else Statement**: Executes one block of code if the condition is true, otherwise, executes
another block of code.
5. **switch Statement**: A multi-way branch statement, allowing the execution of one block of
code among many options based on the value of a variable.
---
### 1. **if Statement**
The `if` statement is the simplest decision control structure. It evaluates a condition, and if the
condition is true, it executes the block of code inside the `if` statement.
#### Syntax:
```c
if (condition) {
```
#### Example:
```c
```
In this example, the message "You are eligible to vote." will be printed only if the value of `age` is 18
or more.
---
The `if-else` statement adds an alternative block of code to execute when the condition is false.
#### Syntax:
```c
if (condition) {
} else {
```
#### Example:
```c
} else {
```
In this case, since `age` is less than 18, the message "You are not eligible to vote." will be printed.
---
The `else if` ladder is used when multiple conditions need to be tested. It checks each condition one
by one, and when a condition is true, it executes the corresponding block of code.
#### Syntax:
```c
if (condition1) {
} else if (condition3) {
} else {
```
#### Example:
```c
printf("Grade: A\n");
printf("Grade: B\n");
printf("Grade: C\n");
} else {
printf("Grade: F\n");
```
This checks the value of `marks` and prints the corresponding grade based on the conditions.
---
### 4. **Nested if Statement**
An `if` statement can be placed inside another `if` statement. This is called **nesting**. Nested `if`
statements allow you to check for additional conditions only when a previous condition is true.
#### Syntax:
```c
if (condition1) {
if (condition2) {
```
#### Example:
```c
if (num > 0) {
if (num % 2 == 0) {
```
Here, the program checks if the number is positive first, and only if that is true, it then checks
whether the number is even.
---
### 5. **switch Statement**
The `switch` statement is a multi-way branch that makes decisions based on the value of a variable.
It is especially useful when a variable can have multiple possible values, and you want to execute
different code for each value.
#### Syntax:
```c
switch (expression) {
case constant1:
break;
case constant2:
break;
// more cases...
default:
```
#### Example:
```c
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
```
In this example, the value of `day` is compared with the constants, and when a match is found, the
corresponding code is executed.
- **break**: Exits the `switch` statement after a case is executed to prevent "fall-through" (i.e.,
running subsequent cases).
---
- **Conditions**: Conditions in `if`, `else if`, and `switch` statements must evaluate to either true
(non-zero) or false (zero).
- **Comparisons**: Conditions often involve comparison operators (`==`, `!=`, `>`, `<`, `>=`, `<=`),
logical operators (`&&`, `||`), and bitwise operators.
- **Flow Control**: These decision-making statements allow for non-linear control of the program,
enabling the program to make decisions at runtime.
- **Efficiency**: While `switch` is more efficient for evaluating multiple conditions that depend on
the same variable, `if-else` is more flexible for complex conditions involving multiple variables.
---
### **Conclusion**
Decision control statements are essential for writing dynamic programs that can respond to different
inputs or situations. They allow the program to "make decisions" and execute different code paths
based on conditions, making your program more flexible and responsive to various scenarios.
Conditional branching statements in C allow the flow of program execution to change based on the
evaluation of conditions. These statements let the program decide which path to follow during
execution, depending on whether a condition is true or false.
1. **if statement**
2. **if-else statement**
3. **else if ladder**
4. **switch statement**
---
The `if` statement is the simplest form of a conditional branch. It checks a condition, and if the
condition is true, it executes the block of code inside the `if`.
#### **Syntax**:
```c
if (condition) {
```
#### **Example**:
```c
int x = 10;
if (x > 5) {
```
In this example, the program checks whether `x` is greater than 5. If the condition is true, the
message is printed.
---
The `if-else` statement extends the `if` statement by providing an alternative block of code that is
executed when the condition is false.
#### **Syntax**:
```c
if (condition) {
} else {
```
#### **Example**:
```c
int x = 3;
if (x > 5) {
printf("x is greater than 5\n");
} else {
```
If the condition `x > 5` is false, the else block is executed, printing "x is not greater than 5."
---
The `else if` ladder allows multiple conditions to be checked in sequence. If one condition is true, the
corresponding block of code is executed, and the rest of the conditions are skipped.
#### **Syntax**:
```c
if (condition1) {
} else if (condition2) {
} else {
```
#### **Example**:
```c
printf("Grade A\n");
printf("Grade B\n");
printf("Grade C\n");
} else {
printf("Fail\n");
```
Here, depending on the value of `marks`, the program checks conditions in sequence, and the
appropriate grade is printed.
---
The `switch` statement is a multi-way branch that allows one out of many code blocks to be
executed, based on the value of an expression. It is especially useful when a variable or expression
can take a finite number of values.
#### **Syntax**:
```c
switch (expression) {
case constant1:
break;
case constant2:
// code to execute if expression equals constant2
break;
// more cases...
default:
```
#### **Example**:
```c
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
```
The `switch` statement checks the value of `day` and executes the corresponding case. If no case
matches, the `default` case is executed.
- **`break`**: Terminates the `switch` statement. Without `break`, the program continues to
execute the next case, a behavior called "fall-through."
---
The **ternary operator** is a shorthand for `if-else` statements. It is written in a compact form and
is used for simple conditions.
#### **Syntax**:
```c
```
#### **Example**:
```c
int x = 10;
```
In this example, if `x` is greater than 5, `y` is assigned the value 100. Otherwise, `y` is assigned the
value 0.
---
- Use `if-else` for complex conditions that may involve multiple variables or logical comparisons.
- Use `switch` when a single variable needs to be checked against several constant values.
2. **Ternary operator**:
- The ternary operator is used for compact, simple conditions, where a full `if-else` block would be
overkill.
---
- **if-else statement**: Executes one block of code if the condition is true, another if the condition
is false.
- **switch statement**: A multi-way branch, used for checking a single variable against multiple
constant values.
These conditional branching statements provide powerful ways to control the flow of a C program,
enabling decision-making based on runtime conditions.
**Conditional branching statements** in C are used to direct the flow of program execution based
on certain conditions. These statements help in making decisions within the code, allowing different
paths to be taken depending on whether the condition is true or false. The main types of conditional
branching statements in C are `if`, `if-else`, `else-if`, and `switch`.
The `if` statement is the simplest form of conditional branching. It allows a block of code to be
executed only if a specified condition evaluates to true.
#### Syntax:
```c
if (condition) {
```
#### Example:
```c
```
The `if-else` statement extends the `if` statement by adding an alternative block of code to be
executed if the condition is false.
#### Syntax:
```c
if (condition) {
} else {
```
#### Example:
```c
} else {
```
In India, the legal voting age is 18, so this example checks whether the person is eligible to vote
based on their age.
The `else if` ladder allows multiple conditions to be checked in sequence. The program evaluates
each condition, and when a condition is found to be true, the corresponding block of code is
executed.
#### Syntax:
```c
if (condition1) {
// code for condition1
} else if (condition2) {
} else {
```
#### Example:
```c
printf("Grade: A\n");
printf("Grade: B\n");
} else {
printf("Grade: C\n");
```
The `switch` statement is used when a variable can have multiple possible values, and you want to
execute different code depending on the value of the variable. It's particularly useful when the
decision is based on the value of a single variable.
#### Syntax:
```c
switch (expression) {
case value1:
break;
case value2:
break;
default:
```
#### Example:
```c
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
```
In India, using `switch` statements can be practical when programming systems like automated
scheduling or ticketing systems for bus or train services, where different actions need to be taken
based on the day of the week.
---
- **if**: Evaluates a condition and runs a block of code if the condition is true.
- **switch**: Provides a more efficient way to handle multi-way branching when checking a
variable's value.
These conditional branching statements are essential for developing programs that respond
dynamically to input or external conditions, making them highly valuable in both local and global
applications.
6.Iterative statements
1. **while Loop**
2. **do-while Loop**
3. **for Loop**
4. **Nested Loops**
5. **Infinite Loops**
---
The `while` loop executes a block of code as long as a specified condition is true. The condition is
evaluated before each iteration.
#### **Syntax**:
```c
while (condition) {
```
#### **Example**:
```c
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
return 0;
```
In this example, the loop will run as long as `i` is less than 5, printing the value of `i` each time.
---
The `do-while` loop is similar to the `while` loop, but it guarantees that the block of code will be
executed at least once, regardless of the condition.
#### **Syntax**:
```c
do {
} while (condition);
```
#### **Example**:
```c
#include <stdio.h>
int main() {
int i = 0;
do {
i++;
return 0;
```
In this case, the loop executes the code block first and then checks the condition. The loop continues
as long as `i` is less than 5.
---
The `for` loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and increment/decrement.
#### **Syntax**:
```c
```
#### **Example**:
```c
#include <stdio.h>
int main() {
return 0;
```
Here, the loop initializes `i` to 0, checks if `i` is less than 5, and increments `i` after each iteration.
---
You can place loops inside other loops, which is useful for working with multi-dimensional data
structures like matrices.
#### **Example**:
```c
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
return 0;
```
This example uses a nested loop to print all combinations of `i` and `j` for `i` from 0 to 2 and `j` from
0 to 2.
---
An infinite loop occurs when the terminating condition is never met or omitted, causing the loop to
execute indefinitely. This can be useful in certain situations where you want a program to keep
running until explicitly stopped.
#### **Example**:
```c
#include <stdio.h>
int main() {
while (1) {
}
```
```c
#include <stdio.h>
int main() {
for (;;) {
```
---
The `break` statement is used to exit a loop prematurely. This is useful when a certain condition is
met, and you want to terminate the loop early.
#### **Example**:
```c
#include <stdio.h>
int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
return 0;
```
The `continue` statement skips the current iteration of the loop and moves to the next iteration. This
is useful when you want to skip certain values based on a condition.
#### **Example**:
```c
#include <stdio.h>
int main() {
if (i == 2) {
return 0;
}
```
In this case, when `i` is 2, the iteration is skipped, and the program continues with the next value.
---
| Loop Type | Condition Check Time | Guaranteed Execution at Least Once? | Use Case
|
|---------------|----------------------|-------------------------------------|------------------------------------|
| `do-while` | After the loop body | Yes | When loop should execute at least
once, condition checked afterward |
---
### **Conclusion**
Iterative statements are essential in C programming, allowing for repetitive execution of code blocks
based on conditions. They provide a way to process data efficiently, handle tasks that require
repetition, and create complex algorithms that can respond to various inputs dynamically.
Understanding these loops and their control statements is fundamental for mastering C
programming.
7.Nested loops
Nested loops in C are loops that exist inside another loop. This allows you to perform repeated
operations within a loop, enabling you to work with multi-dimensional data structures such as
matrices or to perform complex iterations where each iteration of the outer loop requires a full
iteration of the inner loop.
```c
```
```c
#include <stdio.h>
int main() {
rows = 5;
columns = 5;
return 0;
```
### **Output**
```
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
```
In this example:
- The outer loop (`for (int i = 1; i <= rows; i++)`) iterates through each row.
- The inner loop (`for (int j = 1; j <= columns; j++)`) iterates through each column, multiplying the
current values of `i` and `j` and printing the result.
You can also use `while` loops for nesting. Here’s an example that prints the same multiplication
table using nested `while` loops.
```c
#include <stdio.h>
int main() {
int i = 1;
i++; // Increment i
return 0;
```
### **Output**
```
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
```
1. **Complexity**: The time complexity of nested loops can grow quickly. If you have an outer loop
that runs `n` times and an inner loop that runs `m` times, the total number of iterations is `n * m`.
This can lead to performance issues for large values of `n` and `m`.
2. **Readability**: While nested loops are powerful, they can make code harder to read and
maintain. It’s important to keep your loops manageable and well-commented.
3. **Deep Nesting**: Avoid deep nesting (more than two or three levels) whenever possible. It can
lead to code that is difficult to understand and maintain.
- **Working with Matrices**: Accessing elements in a 2D array or matrix requires nested loops.
- **Complex Data Processing**: Tasks like comparing all pairs in a list or generating combinations of
items often require nested iterations.
- **Pattern Generation**: Nested loops are often used to generate patterns or shapes in console
applications.
### **Conclusion**
Nested loops are a fundamental concept in C programming, allowing for complex data processing
and iteration over multi-dimensional data structures. Understanding how to use and manage nested
loops is essential for tackling a wide range of programming challenges, especially those involving
arrays and matrices.
---
The `break` statement is used to terminate a loop prematurely. When `break` is executed, control
is transferred to the statement immediately following the loop, effectively exiting the loop
regardless of the loop's condition.
#### **Syntax**:
```c
break;
```
#### **Example**:
```c
#include <stdio.h>
int main() {
if (i == 5) {
printf("Loop terminated.\n");
return 0;
```
#### **Output**:
```
i=0
i=1
i=2
i=3
i=4
Loop terminated.
```
In this example, the loop iterates from 0 to 9, but when `i` reaches 5, the `break` statement is
executed, and the loop is exited.
---
The `continue` statement is used to skip the current iteration of a loop and move to the next
iteration. Unlike `break`, `continue` does not terminate the loop; it only skips the rest of the code
inside the loop for the current iteration.
#### **Use Cases**:
#### **Syntax**:
```c
continue;
```
#### **Example**:
```c
#include <stdio.h>
int main() {
if (i % 2 == 0) {
printf("Loop completed.\n");
return 0;
```
#### **Output**:
```
i=1
i=3
i=5
i=7
i=9
Loop completed.
```
In this example, the loop iterates from 0 to 9, but when `i` is an even number (i.e., divisible by 2),
the `continue` statement is executed. This skips the `printf` statement for that iteration, resulting
in only the odd numbers being printed.
---
You can also use `break` and `continue` within nested loops. However, it’s important to note that
these statements will only affect the innermost loop in which they are called.
```c
#include <stdio.h>
int main() {
if (j == 3) {
}
printf("i = %d, j = %d\n", i, j);
return 0;
```
#### **Output**:
```
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2
```
In this example, the inner loop is exited whenever `j` reaches 3, meaning for each `i`, only the
values of `j` from 0 to 2 are printed.
```c
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
if (j == 2) {
return 0;
```
#### **Output**:
```
i = 0, j = 0
i = 0, j = 1
i = 0, j = 3
i = 0, j = 4
i = 1, j = 0
i = 1, j = 1
i = 1, j = 3
i = 1, j = 4
i = 2, j = 0
i = 2, j = 1
i = 2, j = 3
i = 2, j = 4
```
Here, when `j` equals 2, the `continue` statement is executed, skipping the rest of the inner loop's
body and moving to the next iteration, thus printing all other values of `j`.
---
### **Conclusion**
The `break` and `continue` statements are powerful tools for controlling the flow of loops in C
programming.
- **`break`** allows you to exit a loop early when a specific condition is met.
- **`continue`** allows you to skip the current iteration and continue with the next iteration of
the loop.
Understanding how and when to use these statements can help you write more efficient and
readable code.
goto Statement
### **Syntax**
The syntax of the `goto` statement consists of a label followed by the `goto` statement itself:
```c
label_name:
// code
```
2. **Goto Statement**: When the `goto` statement is executed, the program control jumps to the
labeled statement, skipping any intervening code.
```c
#include <stdio.h>
int main() {
int i = 0;
if (i < 5) {
i++;
printf("Loop finished.\n");
return 0;
```
#### **Output**
```
i=0
i=1
i=2
i=3
i=4
Loop finished.
```
In this example:
Although the use of `goto` is generally discouraged, there are a few scenarios where it might be
useful:
1. **Breaking Out of Nested Loops**: It can provide a way to break out of multiple nested loops
when other control statements like `break` don’t suffice.
2. **Error Handling**: In some programs, particularly in low-level code or legacy systems, `goto`
can be used to handle errors by jumping to a cleanup section of code.
```c
#include <stdio.h>
int main() {
int num;
if (scanf("%d", &num) != 1) {
if (num < 0) {
return 0;
error:
return -1;
```
```
```
1. **Reduced Readability**: Code that uses `goto` can be harder to read and understand, as the
control flow becomes less clear and can jump around unpredictably.
2. **Difficult to Maintain**: It can complicate the flow of a program, making it harder to maintain
and debug.
3. **Spaghetti Code**: Overuse of `goto` can lead to "spaghetti code," where the program
structure becomes tangled and difficult to follow.
### **Conclusion**
While the `goto` statement provides a way to control program flow by jumping to different parts
of code, it should be used with caution. In most cases, structured programming constructs like
loops and functions (along with control statements such as `break`, `continue`, and `return`)
provide clearer, more maintainable alternatives. It's generally best to avoid using `goto` unless
there is a compelling reason to do so.
IF statement
In C programming, the `if` statement is used to make decisions based on certain conditions. It
allows the program to execute a specific block of code only if a defined condition evaluates to
true.
```c
if (condition) {
```
```c
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number > 0) {
}
return 0;
```
You can also use an `else` clause to execute code when the condition is false.
```c
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number > 0) {
} else {
return 0;
```
```c
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number > 0) {
} else {
return 0;
```
```c
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number != 0) {
if (number > 0) {
} else {
} else {
return 0;
```
You can combine conditions using logical operators (&& for AND, || for OR).
```c
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
} else {
return 0;
```
These examples demonstrate how to use `if` statements in C to control the flow of a program
based on conditions. Feel free to modify these examples to suit your needs!