0% found this document useful (0 votes)
16 views78 pages

POCP Module2

Module II covers key concepts in C programming, including operators, type conversion, and control statements. It details various operators such as arithmetic, relational, logical, and bitwise operators, along with typecasting methods for data type conversion. Additionally, it introduces decision control statements and looping constructs essential for program flow management.

Uploaded by

werisif605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views78 pages

POCP Module2

Module II covers key concepts in C programming, including operators, type conversion, and control statements. It details various operators such as arithmetic, relational, logical, and bitwise operators, along with typecasting methods for data type conversion. Additionally, it introduces decision control statements and looping constructs essential for program flow management.

Uploaded by

werisif605
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Module – II

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.

| Operator | Description | Example |

|----------|-------------------------|---------------|

| `+` | Addition | `x + y` |

| `-` | Subtraction | `x - y` |

| `*` | Multiplication | `x * y` |

| `/` | Division | `x / y` |

| `%` | Modulus (remainder) | `x % y` |


#### Example:

```c

int a = 10, b = 5;

int sum = a + b; // sum = 15

int div = a / b; // div = 2

int rem = a % b; // rem = 0 (remainder when 10 is divided by 5)

```

### 2. Relational Operators

Relational operators are used to compare two values. The result is either `true` (non-zero) or `false`
(zero).

| Operator | Description | Example |

|----------|------------------------|---------------|

| `==` | Equal to | `x == y` |

| `!=` | Not equal to | `x != y` |

| `>` | Greater than | `x > y` |

| `<` | Less than | `x < y` |


| `>=` | Greater than or equal | `x >= y` |

| `<=` | Less than or equal | `x <= y` |

#### Example:

```c

int a = 10, b = 5;

int result = (a > b); // result = 1 (true)

```

### 3. Logical Operators

Logical operators are used to perform logical operations, primarily in conditions.

| Operator | Description | Example |

|----------|------------------------|---------------|

| `&&` | Logical AND | `x && y` |

| `||` | Logical OR | `x || y` |

| `!` | Logical NOT | `!x` |

#### Example:

```c

int a = 1, b = 0;

int result1 = (a && b); // result1 = 0 (false)

int result2 = (a || b); // result2 = 1 (true)

```

### 4. Bitwise Operators

These operators work on bits and perform bit-level operations.


| Operator | Description | Example |

|----------|---------------------------------|---------------|

| `&` | Bitwise AND | `x & y` |

| `|` | Bitwise OR | `x | y` |

| `^` | Bitwise XOR (exclusive OR) | `x ^ y` |

| `~` | Bitwise NOT (one's complement) | `~x` |

| `<<` | Left shift | `x << n` |

| `>>` | Right shift | `x >> n` |

#### Example:

```c

int x = 5, y = 3; // x = 0101, y = 0011 in binary

int andResult = x & y; // 0001 = 1

int orResult = x | y; // 0111 = 7

int xorResult = x ^ y; // 0110 = 6

int leftShift = x << 1; // 1010 = 10 (shift left by 1 bit)

int rightShift = x >> 1; // 0010 = 2 (shift right by 1 bit)

```
### 5. Assignment Operators

These operators assign values to variables.

| Operator | Description | Example |

|----------|-------------------------------|---------------|

| `=` | Simple assignment | `x = y` |

| `+=` | Add and assign | `x += y` |

| `-=` | Subtract and assign | `x -= y` |

| `*=` | Multiply and assign | `x *= y` |

| `/=` | Divide and assign | `x /= y` |

| `%=` | Modulus and assign | `x %= y` |

#### 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

These operators are used to increase or decrease a value by 1.

Operator Description Example

++ Increment by 1 x++ or ++x

-- Decrement by 1 x-- or --x

- 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;

int y = ++x; // x is incremented to 11, y = 11

int z = x--; // z = 11, then x is decremented to 10

```

### 7. Conditional (Ternary) Operator

The conditional (ternary) operator is a shorthand for an `if-else` condition.

?: 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;

int max = (a > b) ? a : b; // max = 10

```

### 8. Comma Operator

The comma operator allows multiple expressions to be evaluated in a single statement, with the last
expression being the result.
#### Example:

```c

int x = (1, 2, 3); // x = 3 (the last value)

```

### 9. Type Cast Operator

The type cast operator explicitly converts one data type into another.

(type) Type conversion (int)x

#### Example:

```c

float x = 5.75;

int y = (int)x; // y = 5 (float to int conversion)

### 10. Sizeof Operator

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)
```

### 11. Address-of and Dereference Operators

These are used with pointers to get the address of a variable or the value stored at an address.

| Operator | Description | Example |

|----------|-----------------------------------|---------------|

| `&` | Address of a variable | `&x` |

| `*` | Value at the address (dereference)| `*p` |

#### Example:

```c

int x = 10;

int *p = &x; // p stores the address of x

int y = *p; // y = 10 (value at the address stored in p)

```

### 12. Pointer Operators

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

int y = *p; // y = 10 (value at the address stored in p)

```

Type conversion and Typecasting


In C, type conversion and typecasting are mechanisms that allow data to be converted from one
type to another. This is essential when performing operations between different data types to
ensure compatibility. There are two main types of type conversion: implicit conversion (also known
as automatic conversion) and explicit conversion (also known as typecasting).

### 1. Implicit Type Conversion (Automatic Conversion)

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.

#### Key Points:

- 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;

float b = a; // Implicit conversion from int to float

```

In this example, `a` (an `int`) is implicitly converted to a `float` during the assignment to `b`. The
value `10` becomes `10.0`.

#### Implicit Conversion During Arithmetic Operations:

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`.

### 2. Explicit Type Conversion (Typecasting)

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;

int y = (int) x; // Explicit typecasting from float to int

```

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`.

#### Common Uses of Typecasting:


- Converting floating-point numbers to integers:

Typecasting can be used to truncate or round floating-point numbers to integers.

```c

float f = 9.99;

int i = (int)f; // i will hold the value 9, as the fractional part is discarded

```

- Changing the type in arithmetic expressions:

If you want to control how an expression is evaluated by forcing a specific type.

```c

int a = 5, b = 2;

float result = (float)a / b; // a is cast to float, result is 2.5

```

- Pointer typecasting:

Sometimes, typecasting is needed when working with pointers to convert between different
pointer types.

```c

void *ptr;

int *int_ptr;

ptr = int_ptr; // This is implicit

int_ptr = (int *)ptr; // Explicit cast from void* to int*

```

#### Example of Possible Data Loss:


Typecasting from a larger data type to a smaller one can result in loss of data.

```c

double d = 3.14159;

int i = (int)d; // i will hold the value 3, the fractional part is lost

```

### 3. Differences Between Implicit and Explicit Conversion

| Aspect | Implicit Conversion | Explicit Conversion (Typecasting) |

|----------------------|--------------------------------------------------------|-------------------------------------------|

| Conversion Trigger | Happens automatically by the compiler | Must be explicitly done by


the programmer |

| Data Loss Risk | Generally no data loss (safe promotions) | Possible data loss (e.g., float
to int) |

| Syntax | No special syntax required | Requires cast operator `(type)` |

| Common Use Cases | Assignments, mixed-type expressions, function arguments | Forceful


conversion of values |
### 4. Type Promotion

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.

#### Integer Promotion:

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;

int result = c + 5; // c is promoted to int for the addition

```

#### Promotion in Mixed-Type Expressions:

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;

float result = i + f; // i is promoted to float, result = 15.5

```

### 5. Typecasting and Pointers

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

int *ptr = (int *)malloc(sizeof(int) * 10); // Casting void* to int*

```

In this example, the `malloc()` function returns a `void*`, which is then explicitly cast to an `int*` to
be used as an integer pointer.

### 6. Common Pitfalls of Typecasting

- 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;

int i = (int)f; // i will become 9, fractional part is lost

```

- 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.

In C, **decision control statements** and **looping statements** are fundamental control


structures that allow a program to make decisions and repeat actions, respectively. Here's a
breakdown of both concepts:
## 1. **Decision Control Statements**

Decision control statements allow the program to choose different actions based on certain
conditions. The most common decision-making statements in C are:

### A. **if Statement**

The `if` statement is used to execute a block of code only if a specified condition is true.

#### Syntax:

```c

if (condition) {

// code to execute if condition is true

```

#### Example:

```c

int x = 10;

if (x > 5) {

printf("x is greater than 5\n");

```

### B. **if-else Statement**

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) {

// code to execute if condition is true

} else {

// code to execute if condition is false

```

#### Example:

```c

int x = 3;

if (x > 5) {

printf("x is greater than 5\n");

} else {

printf("x is not greater than 5\n");

```

### C. **else if Ladder**

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) {

// code if condition1 is true

} else if (condition2) {

// code if condition2 is true


} else {

// code if none of the conditions are true

```

#### Example:

```c

int x = 10;

if (x > 20) {

printf("x is greater than 20\n");

} else if (x > 5) {

printf("x is greater than 5 but less than or equal to 20\n");

} else {

printf("x is less than or equal to 5\n");

```

### D. **Nested if Statement**

The `if` statements can be nested, meaning you can place an `if` statement inside another `if`
statement.

#### Syntax:

```c

if (condition1) {

if (condition2) {

// code if both condition1 and condition2 are true

}
```

#### Example:

```c

int x = 10, y = 5;

if (x > 5) {

if (y < 10) {

printf("x is greater than 5 and y is less than 10\n");

```

### E. **switch Statement**

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:

// code to execute if expression equals constant1

break;

case constant2:

// code to execute if expression equals constant2

break;

// more cases...

default:

// code to execute if no case matches


}

```

#### 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).

- **default**: This block is executed if none of the cases match.

---

## 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:

### A. **while Loop**

The `while` loop repeats a block of code as long as a specified condition is true.

#### Syntax:

```c

while (condition) {

// code to be executed repeatedly as long as the condition is true

```

#### Example:

```c

int i = 0;

while (i < 5) {

printf("i = %d\n", i);

i++;

```

- In this example, the loop runs while `i` is less than 5, incrementing `i` after each iteration.

### B. **do-while Loop**

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 {

// code to be executed at least once

} while (condition);

```

#### Example:

```c

int i = 0;

do {

printf("i = %d\n", i);

i++;

} while (i < 5);

```

- Here, the block is executed once before checking the condition. The loop will continue as long as `i`
is less than 5.

### C. **for Loop**

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

for (initialization; condition; increment/decrement) {

// code to be executed in each iteration

```
#### Example:

```c

for (int i = 0; i < 5; i++) {

printf("i = %d\n", i);

```

- **Initialization**: Executes once before the loop starts.

- **Condition**: Evaluated before each iteration; the loop runs as long as it is true.

- **Increment/Decrement**: Executed after each iteration.

### D. **Nested Loops**

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

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

printf("i = %d, j = %d\n", i, j);

```

- This prints all combinations of `i` and `j` for `i` from 0 to 2 and `j` from 0 to 2.

---

## 3. **Control Statements within Loops**


### A. **break Statement**

The `break` statement is used to exit a loop prematurely, regardless of the loop's condition.

#### Example:

```c

for (int i = 0; i < 10; i++) {

if (i == 5) {

break; // Loop stops when i equals 5

printf("i = %d\n", i);

```

### B. **continue Statement**

The `continue` statement skips the current iteration and moves to the next one.

#### Example:

```c

for (int i = 0; i < 5; i++) {

if (i == 2) {

continue; // Skip the iteration when i equals 2

printf("i = %d\n", i);

```
### 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:

// code to execute when goto is called

```

#### Example:

```c

int i = 0;

loop:

printf("i = %d\n", i);

i++;

if (i < 5) {

goto loop; // Jumps back to the label

```

- 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) {

// Infinite loop, runs until manually stopped

```

Or using a `for` loop:

```c

for (;;) {

// Infinite loop

```

---

### Summary of Looping Statements:

| Loop Type | Condition Check Time | Guaranteed Execution at Least Once? | Use Case
|

|---------------|----------------------|-------------------------------------|------------------------------------|

| `while` | Before the loop body | No | When condition needs to be checked


before each iteration |
| `do-while` | After the loop body | Yes | When loop should execute at least
once, condition checked afterward |

| `for` | Before each iteration | No | When the number of iterations is known


in advance |

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.

### **Introduction to Decision Control in C**


In C programming, **decision control statements** are used to make choices and direct the flow of
execution based on certain conditions. This enables a program to behave differently under various
circumstances, allowing the developer to control the logic depending on the input or the
environment.

### **Why Decision Control is Important**

In real-world scenarios, a program often needs to make decisions. For example:

- A login system that checks if the entered password is correct or incorrect.

- 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.

### **Types of Decision Control Statements in C**

C provides several decision control structures to handle different conditions:

1. **if Statement**: Executes a block of code if a given condition is true.

2. **if-else Statement**: Executes one block of code if the condition is true, otherwise, executes
another block of code.

3. **else if Ladder**: Allows testing multiple conditions in sequence.

4. **Nested if Statement**: An `if` statement inside another `if` statement.

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) {

// code to execute if condition is true

```

#### Example:

```c

int age = 18;

if (age >= 18) {

printf("You are eligible to vote.\n");

```

In this example, the message "You are eligible to vote." will be printed only if the value of `age` is 18
or more.

---

### 2. **if-else Statement**

The `if-else` statement adds an alternative block of code to execute when the condition is false.

#### Syntax:

```c
if (condition) {

// code to execute if condition is true

} else {

// code to execute if condition is false

```

#### Example:

```c

int age = 16;

if (age >= 18) {

printf("You are eligible to vote.\n");

} else {

printf("You are not eligible to vote.\n");

```

In this case, since `age` is less than 18, the message "You are not eligible to vote." will be printed.

---

### 3. **else if Ladder**

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) {

// code if condition1 is true


} else if (condition2) {

// code if condition2 is true

} else if (condition3) {

// code if condition3 is true

} else {

// code if none of the conditions are true

```

#### Example:

```c

int marks = 75;

if (marks >= 90) {

printf("Grade: A\n");

} else if (marks >= 80) {

printf("Grade: B\n");

} else if (marks >= 70) {

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) {

// code if both condition1 and condition2 are true

```

#### Example:

```c

int num = 10;

if (num > 0) {

if (num % 2 == 0) {

printf("The number is positive and even.\n");

```

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:

// code to execute if expression equals constant1

break;

case constant2:

// code to execute if expression equals constant2

break;

// more cases...

default:

// code to execute if no case matches

```

#### 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).

- **default**: Executes when no cases match the expression.

---

### **Key Points About Decision Control Statements**:

- **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


### **Conditional Branching Statements in C**

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.

C provides several **conditional branching** statements, including:

1. **if statement**

2. **if-else statement**

3. **else if ladder**

4. **switch statement**

5. **Conditional (Ternary) operator**

---

### **1. `if` 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) {

// code to execute if condition is true

```

#### **Example**:

```c
int x = 10;

if (x > 5) {

printf("x is greater than 5\n");

```

In this example, the program checks whether `x` is greater than 5. If the condition is true, the
message is printed.

---

### **2. `if-else` Statement**

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) {

// code to execute if condition is true

} else {

// code to execute if condition is false

```

#### **Example**:

```c

int x = 3;

if (x > 5) {
printf("x is greater than 5\n");

} else {

printf("x is not greater than 5\n");

```

If the condition `x > 5` is false, the else block is executed, printing "x is not greater than 5."

---

### **3. `else if` Ladder**

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) {

// code to execute if condition1 is true

} else if (condition2) {

// code to execute if condition2 is true

} else {

// code to execute if all conditions are false

```

#### **Example**:

```c

int marks = 85;


if (marks >= 90) {

printf("Grade A\n");

} else if (marks >= 80) {

printf("Grade B\n");

} else if (marks >= 70) {

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.

---

### **4. `switch` Statement**

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:

// code to execute if expression equals constant1

break;

case constant2:
// code to execute if expression equals constant2

break;

// more cases...

default:

// code to execute if no case matches

```

#### **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."

- **`default`**: Executes if no cases match the value of the expression.

---

### **5. Conditional (Ternary) Operator**

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

condition ? expression_if_true : expression_if_false;

```

#### **Example**:

```c

int x = 10;

int y = (x > 5) ? 100 : 0;

printf("y = %d\n", y);

```

In this example, if `x` is greater than 5, `y` is assigned the value 100. Otherwise, `y` is assigned the
value 0.

---

### **Key Differences Between Conditional Branching Statements**


1. **if-else vs. switch**:

- 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.

---

### **Summary of Conditional Branching Statements in C**:

- **if statement**: Executes a block of code if a condition is true.

- **if-else statement**: Executes one block of code if the condition is true, another if the condition
is false.

- **else if ladder**: Tests multiple conditions in sequence.

- **switch statement**: A multi-way branch, used for checking a single variable against multiple
constant values.

- **ternary operator**: A concise way to write simple if-else conditions.

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**

**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`.

### **1. `if` Statement**

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) {

// code to execute if the condition is true

```

#### Example:

```c

int age = 20;

if (age >= 18) {

printf("You are eligible to vote.\n");

```

### **2. `if-else` Statement**

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) {

// code to execute if the condition is true

} else {

// code to execute if the condition is false

```

#### Example:

```c

int age = 16;

if (age >= 18) {

printf("You are eligible to vote.\n");

} else {

printf("You are not eligible to vote.\n");

```

In India, the legal voting age is 18, so this example checks whether the person is eligible to vote
based on their age.

### **3. `else if` Ladder**

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) {

// code for condition2

} else {

// default code if no conditions are true

```

#### Example:

```c

int marks = 85;

if (marks >= 90) {

printf("Grade: A\n");

} else if (marks >= 75) {

printf("Grade: B\n");

} else {

printf("Grade: C\n");

```

### **4. `switch` Statement**

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:

// code for value1

break;

case value2:

// code for value2

break;

default:

// code if no case matches

```

#### 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.

---

### **Key Points:**

- **if**: Evaluates a condition and runs a block of code if the condition is true.

- **if-else**: Adds an alternative block of code to be run if the condition is false.

- **else if**: Allows checking multiple conditions in sequence.

- **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

### **Iterative Statements in C**


Iterative statements, also known as looping statements, allow a block of code to be executed
repeatedly based on a specified condition. This is useful for tasks that require repeated execution,
such as processing elements in an array, performing calculations, or reading user input until a certain
condition is met.

C provides several types of iterative statements:

1. **while Loop**

2. **do-while Loop**

3. **for Loop**

4. **Nested Loops**

5. **Infinite Loops**

6. **Control Statements in Loops** (break, continue)

---

### **1. `while` Loop**

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) {

// code to be executed repeatedly as long as the condition is true

```
#### **Example**:

```c

#include <stdio.h>

int main() {

int i = 0;

while (i < 5) {

printf("i = %d\n", i);

i++; // Increment i to avoid an infinite loop

return 0;

```

In this example, the loop will run as long as `i` is less than 5, printing the value of `i` each time.

---

### **2. `do-while` Loop**

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 {

// code to be executed at least once

} while (condition);

```
#### **Example**:

```c

#include <stdio.h>

int main() {

int i = 0;

do {

printf("i = %d\n", i);

i++;

} while (i < 5);

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.

---

### **3. `for` Loop**

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

for (initialization; condition; increment/decrement) {

// code to be executed in each iteration


}

```

#### **Example**:

```c

#include <stdio.h>

int main() {

for (int i = 0; i < 5; i++) {

printf("i = %d\n", i);

return 0;

```

Here, the loop initializes `i` to 0, checks if `i` is less than 5, and increments `i` after each iteration.

---

### **4. Nested Loops**

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++) {

for (int j = 0; j < 3; j++) {

printf("i = %d, j = %d\n", i, j);

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.

---

### **5. Infinite Loops**

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) {

printf("This loop will run forever until terminated.\n");

return 0; // This line will never be reached

}
```

Or using a `for` loop:

```c

#include <stdio.h>

int main() {

for (;;) {

printf("This loop will run forever until terminated.\n");

return 0; // This line will never be reached

```

---

### **6. Control Statements in Loops**

#### A. **break Statement**

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) {

break; // Exit the loop when i equals 5

printf("i = %d\n", i);

return 0;

```

In this example, the loop will terminate when `i` reaches 5.

#### B. **continue Statement**

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() {

for (int i = 0; i < 5; i++) {

if (i == 2) {

continue; // Skip the iteration when i equals 2

printf("i = %d\n", i);

return 0;
}

```

In this case, when `i` is 2, the iteration is skipped, and the program continues with the next value.

---

### **Summary of Iterative Statements in C**:

| Loop Type | Condition Check Time | Guaranteed Execution at Least Once? | Use Case
|

|---------------|----------------------|-------------------------------------|------------------------------------|

| `while` | Before the loop body | No | When condition needs to be checked


before each iteration |

| `do-while` | After the loop body | Yes | When loop should execute at least
once, condition checked afterward |

| `for` | Before each iteration | No | When the number of iterations is known


in advance |

| **Nested** | Varies | Depends on the outer loop | For multi-dimensional data


structures |

---

### **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**

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.

### **Basic Structure of Nested Loops**

The general structure for a nested loop in C is as follows:

```c

for (initialization; condition; increment) {

// Outer loop code

for (initialization; condition; increment) {

// Inner loop code

// More outer loop code (if needed)

```

### **Example of Nested Loops**


Here’s a simple example that demonstrates nested loops using `for` statements. This example will
print a multiplication table.

#### **Multiplication Table Example**

```c

#include <stdio.h>

int main() {

int rows, columns;

// Number of rows and columns

rows = 5;

columns = 5;

// Outer loop for rows

for (int i = 1; i <= rows; i++) {

// Inner loop for columns

for (int j = 1; j <= columns; j++) {

printf("%d\t", i * j); // Print the product of i and j

printf("\n"); // Move to the next line after each row

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.

### **Nested `while` Loop Example**

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 rows = 5, columns = 5;

int i = 1;

while (i <= rows) {

int j = 1; // Initialize j for inner loop

while (j <= columns) {

printf("%d\t", i * j); // Print the product of i and j


j++; // Increment j

printf("\n"); // Move to the next line after each row

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

```

### **Performance Considerations**

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.

### **Common Use Cases for Nested Loops**

- **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.

BREAK & CONTINUE

### **Break and Continue Statements in C**


The `break` and `continue` statements in C are control statements used within loops to alter the
flow of execution. They are particularly useful for managing loop behavior based on specific
conditions.

---

### **1. Break Statement**

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.

#### **Use Cases**:

- Exiting a loop when a certain condition is met.

- Breaking out of nested loops.

#### **Syntax**:

```c

break;

```

#### **Example**:

```c

#include <stdio.h>

int main() {

for (int i = 0; i < 10; i++) {

if (i == 5) {

break; // Exit the loop when i equals 5


}

printf("i = %d\n", i);

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.

---

### **2. Continue Statement**

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**:

- Skipping specific iterations based on a condition.

- Filtering values in a loop without terminating it.

#### **Syntax**:

```c

continue;

```

#### **Example**:

```c

#include <stdio.h>

int main() {

for (int i = 0; i < 10; i++) {

if (i % 2 == 0) {

continue; // Skip even numbers

printf("i = %d\n", i);

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.

---

### **Nested Loops with Break and Continue**

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.

#### **Example of Nested Loops with Break**:

```c

#include <stdio.h>

int main() {

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 5; j++) {

if (j == 3) {

break; // Break out of the inner loop when j equals 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.

#### **Example of Nested Loops with Continue**:

```c

#include <stdio.h>

int main() {
for (int i = 0; i < 3; i++) {

for (int j = 0; j < 5; j++) {

if (j == 2) {

continue; // Skip the iteration when j equals 2

printf("i = %d, j = %d\n", i, j);

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

### **Goto Statement in C**


The `goto` statement in C is a control statement that allows for an unconditional jump to a labeled
statement within the program. It can be used to transfer control to different parts of the program,
but its usage is generally discouraged in modern programming due to potential readability and
maintenance issues.

### **Syntax**

The syntax of the `goto` statement consists of a label followed by the `goto` statement itself:

```c

label_name:

// code

goto label_name; // Jumps to the labeled statement

```

### **How It Works**

1. **Label Declaration**: A label is defined by an identifier followed by a colon (`:`).

2. **Goto Statement**: When the `goto` statement is executed, the program control jumps to the
labeled statement, skipping any intervening code.

### **Example of Goto Statement**

Here’s a simple example demonstrating the use of the `goto` statement:

```c

#include <stdio.h>
int main() {

int i = 0;

loop_start: // Label declaration

if (i < 5) {

printf("i = %d\n", i);

i++;

goto loop_start; // Jump back to the loop_start label

printf("Loop finished.\n");

return 0;

```

#### **Output**

```

i=0

i=1

i=2

i=3

i=4

Loop finished.

```

In this example:

- The program defines a label `loop_start`.


- The `goto` statement causes the program to jump back to `loop_start` until `i` is no longer less
than 5, at which point the loop terminates.

### **Use Cases for Goto**

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.

### **Example of Goto for Error Handling**

```c

#include <stdio.h>

int main() {

int num;

printf("Enter a positive number: ");

if (scanf("%d", &num) != 1) {

goto error; // Jump to the error label if input fails

if (num < 0) {

goto error; // Jump to the error label if the number is negative


}

printf("You entered: %d\n", num);

return 0;

error:

printf("Invalid input! Please enter a positive number.\n");

return -1;

```

#### **Output Example**

```

Enter a positive number: -5

Invalid input! Please enter a positive number.

```

### **Disadvantages of Using Goto**

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.

### Basic Syntax

```c

if (condition) {

// Code to execute if condition is true

```

### Example 1: Simple `if` statement

Here's a basic example that checks if a number is positive.

```c

#include <stdio.h>

int main() {

int number;

printf("Enter a number: ");

scanf("%d", &number);

if (number > 0) {

printf("The number is positive.\n");

}
return 0;

```

### Example 2: `if-else` statement

You can also use an `else` clause to execute code when the condition is false.

```c

#include <stdio.h>

int main() {

int number;

printf("Enter a number: ");

scanf("%d", &number);

if (number > 0) {

printf("The number is positive.\n");

} else {

printf("The number is not positive.\n");

return 0;

```

### Example 3: `if-else if-else` statement


For multiple conditions, you can chain `if` statements with `else if`.

```c

#include <stdio.h>

int main() {

int number;

printf("Enter a number: ");

scanf("%d", &number);

if (number > 0) {

printf("The number is positive.\n");

} else if (number < 0) {

printf("The number is negative.\n");

} else {

printf("The number is zero.\n");

return 0;

```

### Example 4: Nested `if` statement

You can also nest `if` statements to check additional conditions.

```c
#include <stdio.h>

int main() {

int number;

printf("Enter a number: ");

scanf("%d", &number);

if (number != 0) {

if (number > 0) {

printf("The number is positive.\n");

} else {

printf("The number is negative.\n");

} else {

printf("The number is zero.\n");

return 0;

```

### Example 5: Using logical operators

You can combine conditions using logical operators (&& for AND, || for OR).

```c

#include <stdio.h>
int main() {

int number;

printf("Enter a number: ");

scanf("%d", &number);

if (number > 0 && number < 100) {

printf("The number is positive and less than 100.\n");

} else {

printf("The number does not meet the criteria.\n");

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!

You might also like