Control Statements (if-else-switch) in C : CodeWithMe



Control Statements in C



In a C program, a decision causes a one-time jump to a different part of the program, depending on the value of an expression. Decisions in C can be made in several ways. The most important is with the if...else statement, which chooses between two alternatives. This statement can be used without the else, as a simple if statement. Another decision control statement, switch, creates branches for multiple alternative sections of code, depending on the value of a single variable.


1. Conditional Statements: if, else if and else

Conditional statement let us to execute different blocks of code based on a certain condition. In C language , the primary conditional statement is the if statement. Here's how it works:


sample code of if statemnt


flowchart of if statements







we can also use else if for multiple conditions.




2. Switch Statement:


Its objective is to check several possible constant values for an expression, something similar to what we had studied in the earlier sections, with the linking of several if and else if statements. When the actions to be taken depending on the value of control variable, are large in number, then the use of control structure Nested if…else makes the program complex. There switch statement can be used. Its form is the following: 


switch statement in c


It works in the following way: switch evaluates expression and checks if it is equivalent to expression1. If it is, it executes block of instructions 1 until it finds the break keyword, moment at finds the control will go to the end of the switch. If expression was not equal to expression 1 it will check whether expression is equivalent to expression 2. If it is, it will execute block of instructions 2 until it finds the break keyword. 


Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case statements as values you want to check), the program will execute the instructions included in the default: section, if it exists, as it is an optional statement. 




Conclusion

Control structures are very important building blocks in C programming, allowing us to create logic and structure in our programs. By mastering conditional statement we will learn to build logic in our program. Practice using these control structures in your programs, and you'll soon become proficient in controlling the flow of execution with precision and clarity. 
Happy coding!



No comments

Control Statements (if-else-switch) in C : CodeWithMe

Control Statements in C In a C program, a decision causes a one-time jump to a different part of the program, depending on the value of an e...

Powered by Blogger.