Skip to main content

In this blogging you know about digital world.

Function in C

  Function Function : In C programming, a function is a self-contained block of code that performs a specific task or a set of related tasks. Functions are used to break down a program into smaller, more manageable pieces, making the code more organized, readable, and reusable. C supports various types of functions, including library functions and user-defined functions. Below, I'll describe functions in C with examples and discuss their types. Function Syntax: return_type function_name(parameters) {     // Function body     // Statements to perform a task     return value; // (optional) Return value } Here's a breakdown of the elements: - `return_type`: Specifies the data type of the value the function returns. Use `void` if the function doesn't return anything. - `function_name`: A unique identifier for the function. - `parameters`: Input values that the function can accept (optional). - `function_body`: Conta...

Decision Control Structure in C, Boolean Operator and Expression

Decision Structure in C, Boolean Operator and Expression

In C programming, decision structures allow you to make decisions in your code based on certain conditions. This is typically achieved using `if`, `else if`, and `else` statements along with Boolean operators and expressions. Boolean operators are used to compare values and produce a result of either true (1) or false (0). Let's explore these concepts with examples and their expected outputs.


1. The goto Statement: In C programming, the `goto` statement is a control statement that allows you to transfer the program's control to a labeled statement within the same function or block of code. While `goto` can be a powerful tool in some situations, it is generally discouraged and considered bad practice because it can make code harder to understand and maintain. Structured programming constructs like loops (`for`, `while`, `do-while`) and conditional statements (`if`, `else`, `switch`) are preferred in most cases because they provide clearer program flow and maintainability.

The basic syntax of the `goto` statement in C is as follows:

goto label;

 

// ...

 

label:

// Statement(s) to execute

 

Here's a simple example of how the `goto` statement can be used:

Example

#include <stdio.h>

int main() {

    int i = 0;

start:

    if (i < 5) {

        printf("%d ", i);

        i++;

        goto start; // Jump back to the 'start' label

    }

    return 0;

    }

In this example, the program uses a `goto` statement to create a loop. It repeatedly prints the value of `i` and increments it until `i` is no longer less than 5. When `i` becomes 5, the program exits the loop.

 

While this code works, it is generally not recommended to use `goto` for creating loops or controlling program flow because it can lead to "spaghetti code" that is difficult to read and maintain. Instead, you should use structured control flow constructs like `for`, `while`, and `do-while` loops to achieve the same results in a more organized and understandable way,

   Here's an example of the same behaviour using a `while` loop, which is a better practice:

Example

#include <stdio.h>

int main() {

    int i = 0;

    while (i < 5) {

        printf("%d ", i);

        i++;

    }

    return 0;

}

 

In this `while` loop example, the code is more readable and follows a structured approach to looping, making it easier to understand and maintain.

 

2. If Statement: The `if` statement is a fundamental control structure in most programming languages, including C. It allows you to conditionally execute a block of code based on the evaluation of a specified condition. The syntax of the `if` statement in C is as follows:

if (condition) {

    // Code to execute if the condition is true

}

Here's a breakdown of how the `if` statement works:

i. `if`: This keyword begins the `if` statement and is followed by a set of parentheses `( )`. The condition you want to evaluate goes inside these parentheses.

ii. `condition`: The condition is a boolean expression that can be either true or false. It's the criteria you want to test. If the condition evaluates to true, the code inside the block will be executed. If it evaluates to false, the code inside the block will be skipped.

iii. `{ }` Block: The block of code enclosed within curly braces `{ }` is the code that will be executed if the condition inside the parentheses is true. This block can contain one or more statements, and it is often indented for readability.

Here's an example of how the `if` statement is used in C:

#include <stdio.h>

int main() {

                                int num = 10;

                                                if (num > 5) {

                                               printf("The number is greater than 5.\n");

                                    }

                                printf("This code always runs.\n");

                                return 0;

    }

In this example, the condition `num > 5` is true because the value of `num` is 10, which is indeed greater than 5. Therefore, the code inside the `if` block is executed, and "The number is greater than 5." is printed. The code outside the `if` block, after the `if` statement, is also executed regardless of the condition's outcome.

It's important to note that you can use `if` statements in conjunction with `else` and `else if` statements to create more complex branching logic, allowing your program to take different paths based on different conditions. 2. If-Else Statement:

 

3. `if-else` statement : The `if-else` statement is an extension of the basic `if` statement in C programming. It allows you to create a decision-making structure where you can specify two different blocks of code to be executed based on the evaluation of a condition. If the condition is true, one block of code is executed, and if it is false, another block of code is executed.

The syntax of the `if-else` statement is as follows:

if (condition) {

    // Code to execute if the condition is true

} else {

    // Code to execute if the condition is false

}

Here's a breakdown of how the `if-else` statement works:

 

1. `if`: This keyword starts the `if-else` statement and is followed by a set of parentheses `( )`. Inside these parentheses, you specify the condition you want to evaluate.

2. `condition`: The condition is a boolean expression that can be either true or false. It's the criteria you want to test.

3. `{ }` Block (if true): The block of code enclosed within curly braces `{ }` immediately after the `if` statement is the code that will be executed if the condition is true.

4. `else`: After the closing curly brace `}`, the `else` keyword is used to specify a block of code that will be executed if the condition is false.

5. `{ }` Block (if false): The block of code enclosed within curly braces `{ }` immediately after the `else` statement is the code that will be executed if the condition is false.

Here's an example of how the `if-else` statement is used in C:

#include <stdio.h>

int main() {

                                int num = 3;

if (num > 5) {

                                                               printf("The number is greater than 5.\n");

       }

                else {

                                                               printf("The number is not greater than 5.\n");

                                                       }

                                                printf("This code always runs.\n");

return 0;

}

In this example, the condition `num > 5` is false because the value of `num` is 3, which is not greater than 5. Therefore, the code inside the `else` block is executed, and "The number is not greater than 5." is printed. The code outside the `if-else` block, after the `if-else` statement, is also executed regardless of the condition's outcome.

The `if-else` statement is crucial for creating branching logic in your programs, allowing you to handle different cases or outcomes based on the evaluation of a condition. You can also chain multiple `if-else` statements together to create more complex decision structures.

The `if-else` statement allows you to execute one block of code if a condition is true and another block if it's false.                           

#include <stdio.h>

int main() {

                                                                int x = 3;

                                                                if (x > 5) {

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

                                                                                }

else {

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

                                                                                         }

return 0;

}

 

Output:

x is not greater than 5.

4. If-Else If-Else Statement:

In C programming, an "if-else if-else" statement is used to create a conditional branching structure that allows you to execute different blocks of code based on multiple conditions. It provides a way to handle multiple possible outcomes in a program.

The basic syntax of an "if-else if-else" statement in C is as follows:

if (condition1) {

                                // Code to execute if condition1 is true

} else if (condition2)

{

                                // Code to execute if condition1 is false and condition2 is true

} else

{

                                // Code to execute if both condition1 and condition2 are false

}

Here's how the "if-else if-else" statement works:

1. The program evaluates the condition1. If condition1 is true, the code block inside the first `if` statement is executed, and then the program exits the entire `if-else if-else` structure.

2. If condition1 is false, the program evaluates condition2. If condition2 is true, the code block inside the `else if` statement is executed, and then the program exits the structure.

3. If both condition1 and condition2 are false, the code block inside the `else` statement is executed.

You can have multiple `else if` blocks to test additional conditions. The first condition that evaluates to true will execute its corresponding block of code, and the program will exit the entire structure.

Here's an example of how you might use an "if-else if-else" statement in C:

#include <stdio.h>

int main() {

                                                                int num = 5;

                                                    if (num == 1) {

                                                                 printf("Number is 1\n");

                                                                  } else if

(num == 2) {

                                                                   printf("Number is 2\n");

} else if (num == 3)

   {

                                                                   printf("Number is 3\n");

                                                                    } else

        {

                                                                  printf("Number is not 1, 2, or 3\n");

                                                                   }

                                                                return 0;

}

In this example, the program checks the value of the `num` variable and prints a message based on its value. Since `num` is 5, the output will be "Number is not 1, 2, or 3."

 

You can use `else if` statements to evaluate multiple conditions in sequence.

 

#include <stdio.h>

int main() {

                                                 int x = 3;

                                                                if (x > 5)

{

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

                                                                                } else if (x == 5)

{

                                                                                               printf("x is equal to 5.\n");

                                                                                } else

{

                                                                                               printf("x is less than 5.\n");

                                                                                }

                                                                return 0;

}

Output:

x is less than 5.

5. nested if Statement: In C programming, you can use nested if statements to create complex conditional branching logic. Nested if statements involve placing one or more if statements inside another if statement's block. This allows you to check multiple conditions in a hierarchical manner. 

Here's the basic syntax and an example of nested if statements in C:

 

if (condition1) {

                                                                // Code to execute if condition1 is true

                                                          if (condition2) {

                                                                 // Code to execute if both condition1 and condition2 are true

                                                                          }

                                                                  else {

                                                                  // Code to execute if condition1 is true, but condition2 is false

}

                 }

                else {

                                                                 // Code to execute if condition1 is false

                                                                    }

Here's a simple example to illustrate the concept:

        

#include <stdio.h>

                int main() {

                                                int num = 10;

                                                if (num > 0) {

                                               printf("num is positive\n");

                                               if (num % 2 == 0) {

                                               printf("num is even\n");

                                               }

                                               else {

                                               printf("num is odd\n");

                                    }

                                }

                                 else {

                                               printf("num is not positive\n");

                                          }

 

                                                 return 0;

}

 

In this example:

1. The first `if` statement checks if `num` is greater than 0.

2. If `num` is greater than 0, it enters the inner `if-else` block to check if `num` is even or odd.

3. If `num` is not greater than 0, it goes to the `else` block of the outer `if` statement.

 

Nested if statements can be used to create more complex conditions and execute different code blocks based on various combinations of conditions. Just be careful to maintain proper indentation and structure to ensure code readability.

 

7. switch Statement:  A switch statement in C is a control statement that allows you to perform different actions based on the value of a variable or an expression. It provides a way to replace multiple `if-else if-else` constructs when you have a single variable to test against multiple possible values. The switch statement is often more efficient and easier to read when dealing with such situations.

 

The basic syntax of a switch statement in C is as follows:

switch (expression) {

                                                                case value1:

                                                                                     // Code to execute if expression equals value1

                                                               break;

 

                                                                case value2:

                                                            // Code to execute if expression equals value2

                                                               break;

 

                                                            // Additional cases...

                                                                default:

// Code to execute if expression does not match any of the                                                             above cases

}

 

Here's how a switch statement works:

 

1. The `expression` is evaluated, and its value is compared to the values in each `case` label sequentially.

2. If a match is found between the `expression` value and a `case` label value, the code block associated with that case is executed. The `break` statement is used to exit the switch block once a case is executed.

3. If no match is found, the code block associated with the `default` case (if present) is executed. The `default` case is optional and serves as a catch-all for values that don't match any of the defined cases.

Here's an example of a switch statement in C:

 

            #include <stdio.h>

                        int main() {

                                                                int day = 3;

                                                                switch (day) {

                                                                                               case 1:

                                                                                               printf("Monday\n");

                                                                                               break;

                                                                                               case 2:

                                                                                               printf("Tuesday\n");

                                                                                               break;

                                                                                               case 3:

                                                                                               printf("Wednesday\n");

                                                                                               break;

                                                                                               case 4:

                                                                                               printf("Thursday\n");

                                                                                               break;

                                                                                               case 5:

                                                                                               printf("Friday\n");

                                                                                               break;

                                                                                               default:

                                                                                               printf("Weekend\n");

                                                                                }

                                                                return 0;

}

 

In this example, the value of the variable `day` is compared to the cases, and the corresponding code block for "Wednesday" is executed because `day` has the value 3.

 

Note that it's essential to include a `break` statement after each case to prevent "fall-through." Fall-through happens when the code execution continues to the next case even after a match. This can be useful in some cases, but it's usually a source of bugs if not handled intentionally.

 

Boolean Operator

In C programming, boolean operators are used to perform logical operations on boolean values, which can be either true or false. These operators are typically used in conditional statements and loops to control the flow of a program based on certain conditions. C provides three main boolean operators: AND, OR, and NOT. Here's an explanation of each of them:

1. Logical AND (&&):

   - Syntax: `expr1 && expr2`

   - Description: The logical AND operator returns true if both `expr1` and `expr2` are true. If either `expr1` or `expr2` (or both) is false, the result is false.

   Example:

   if (x > 5 && y < 10) {

       // Code executes if both conditions are true

   }

2. Logical OR (||):

   - Syntax: `expr1 || expr2`

   - Description: The logical OR operator returns true if either `expr1` or `expr2` (or both) is true. It only returns false if both `expr1` and `expr2` are false.

   Example:

   if (x == 0 || y == 0) {

       // Code executes if either condition is true

   }

3. Logical NOT (!):

   - Syntax: `!expr`

   - Description: The logical NOT operator is a unary operator that reverses the boolean value of `expr`. If `expr` is true, `!expr` will be false, and if `expr` is false, `!expr` will be true.

   Example:

   if (!flag) {

       // Code executes if flag is false

   }

These boolean operators are commonly used in conditional statements (such as `if`, `while`, and `for` loops) to make decisions based on the truth or falsity of certain conditions. They allow you to create complex logical expressions by combining simple conditions. It's essential to understand how these operators work to write efficient and effective C programs with proper control flow.

 

 

Comments

Popular Posts