0% found this document useful (0 votes)
2 views

Module 2

Fyug second semester C programming

Uploaded by

ABDUL MAJEED.K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 2

Fyug second semester C programming

Uploaded by

ABDUL MAJEED.K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 15
Decision Making with .: Statements in C + Decision-making is an essential concept in programming that allows us to control the flow of execution based on specific conditions. + InC, decision-making statements enable the program to choose different paths based on. conditions + The i statement and its variations (i £-e1se, nested if-else, and else~if ladde2) help us execute different code blocks depending on whether a condition is true (non ero) or false (rero). Cc ‘There are four main types of 1 statements in C: 2. Types of ic Statements 1. Simple if Statement 2. if-else Statement 3. Nested if-else Statement 4. else-it Ladder 3. Simple is Statement Definition + The simplest form of decision-making + Executes a block of code only if the condition is true + If the condition is false, the block is skipped. Syntax Lf (condi // Code to execute if the condit onie true Syntax Explanation * if: The keyword used for decision-making. ‘© condition: A logical expression that evaluates to true (non-zero) of £3 (zero). © Curly Braces (}: Encloses the code block to execute if the condition is true. (Optional for single statements) Example #include int num if (num 0) “Number is Explanation + um > ois true (since 10 > + The code inside {) executes, and "Number is positive” is printed Output: Nunber is posit 4. is-e1se Statement Definition + Extends the i¢ statement to execute one block if the condition is true, and another if it is false. Syntax iE (condition le to execute if the condition is true ute Lf the condition is false Example int num if (num>=0) { , Explanation * pum >= 0 is false (since -5 >= 0 is false). © block executes, printing "Negative number". Output: Negative nunber 5. Nested ir-eise Statement Definit © An Le or Lr-elce inside another i¢ or + Used for multiple level checks. Syntax if (condi nt) (condition2) {/ Code if both conditios pelse ( // Code if cond onl is true but condit. istalse // Code if conditionl is false ' Example #nclude int num =; if (num >=0) { £ (nui Explanation © pum>= 0 is true, © Inside it, non 0 is also true, so "Number is zero" is printed, Definition + Used when multiple conditions need to be checked one after another. «Ifa condition is true, its corresponding block executes and the rest are skipped } elseif (condition2) { // Code for condi ndi tions are true int mark if (mark print } else if (marks >= 80) pEintE ("Grade B\n") 7 } else if (marks >= 70) “Grade C\n") 7 belse ( PEinté ("Grade D\n") 7 b , Explanation e omar 0 is false. © marks >= 30 is false. @ narke >= 10 is true, so "Grade C" is printed Output: Summary Statement Type Purpose Executes When fimpie se [Burra bloc oF code ita sndonis ion is true lLe-e1se Jeuns one block if true, another false [ERE 1 Block: False ~ wise [Nested if-else |ir-cise inside another ti-cise JOne condition inside another le1se-it Ladder|Checks multiple conditions in sequence [First true condition executes 8. Key Points to Remember Always use curly braces {} for multiple statements inside i, else, or © «Conditions must evaluate to true (non-zero) or false (zero). + The else block (if present) executes only if all conditions are false. «Nested if statements should be properly indented for better readability + The else-ig ladder executes only the first true condition and skips the rest. Switch Statement in C + The switch statement in C is a multi-way decision-making statement. + Itallows one variable to be tested against multiple possible values. + Itis an alternative to multiple if-else statements, making the code more readable and efficient © The switch statement evaluates an expression and executes the block of code that matches a specified case, + Ifno cases match, an optional defautt case is executed Syntax witeh (expre: t ase valuel 7/ Cade to execute Lf expression == valuel break; values 1/ Code to execute if no case matches Syntax Explanation «switch (expression) ion is evaluated first. © It must be an integer, char, or enum (not sat of string), © case value: © Each case represents a possible value for the expression © expression matches value, the corresponding block executes. © break; Stops execution after a case is matched. © If'missing, the execution falls through to the next case. © dofause: © Executes only if none of the cases match. It is optional but recommended. Example 1: Basic switcn Statement #include mint day = 37 MWeekend\n") 5 Explanation xecutes. o aay= 3,80 ca + Since break; is present, execution stops after "iesinesday" is printed Output: Wednesday 6. Example 2: «wiecn Without preax (Fall-through Behavior) #include nain() Explanation xecules, ‘+ Since break is missing, execution falls through to the next cases. Output: Two The Other Example 3: switcn With char # ude char grade= "5"; eturn 0 ' Output: switch vs if-else Feature if-else [Data Type [Works with in [Works with all data types [Multiple [Efficient for checking a single variable [Can handle complex conditions [Conditions [against multiple values \Code Readability |Cleaner and easier to read }Becomes lengthy with multiple conditions WWa-through [Executes next cases if breax is missing _ [N° fallthrough, each condition is separate Loops in C ‘+ Loops are control structures that repeat a block of code multiple times. + They are used when we need to execute a set of statements multiple times with a condition. © Types of Loops in C: 1. while loop 2. do-while loop 3. for loop 4. Nested Loops (Loop inside another loop) 1. wnize Loop Defini nm + The whtLe loop executes repeatedly as long as the given condition is true. + If the condition becomes false, the loop terminates. Syntax while (condition) { /{ Code to execute ' Syntax Explanation # while (condition): The loop runs as long as the condition is true. + Inside (), we write the statements that execute repeatedly. Example #include nile (i<=5 "ed\n itty // Inc. ent infinite loop 2. ao-wnsre Loop Definition * Similar to while, but executes at least once, even if the condition is false. + Condition is checked after executing the loop body Syntax > / Code to execute puhtle (condition); Syntax Explanation + The loop executes once first + Then, it checks the condition. + If true, it repeats; if false, it stops Example ude peinte(mad\n", 40 bunite ( : y Output Key Difference («nite Vs do-white) Feature while loop do-whiie loop [Condition Checking [Before executing the body [After executing the bod) [Minimum Executions [0 times (if false at start) [At least 1 time 4. cor Loop Definition + The most commonly used loop, best for situations where the number of iterations is known. + It includes initialization, condition, and update in a single line. Syntax for (initializat: // Code to exe ) Syntax Explanation nz conditions update) { © Initialization: Runs once before the loop starts. + Condition: Checked before each iteration. + Update: Runs after each iteration. Example hide Comparison (white vs for) Feature while loop for loop |Use Case |When number of iterations is unknown |When number of iterations is fixed [Syntax [More flexible but longer [Compact and easier to read 5. Nested Loops Definition +A loop inside another loop is called a nested loop. + Used for working with multidimensional data (like matrices, pattems) Syntax for (initializations conditions update) { for [initializations conditions update / Inner loop code ' i Example: Printing a Star Pattern Hinclude Mor inti= “pein see) 1 3 5e+) printt ' ' Output ine after inner loop Explanation ‘© Outer loop (i) runs 3 times (rows). «Inner loop (j) runs 5 times per outer loop iteration (columns), 6. Summary Table Loop Type ‘When to Use Execution Condition \while |When condition-based looping is (Runs while the condition is true needed eee [Nie the loop must execute at least |, tes first, then checks conditi leor bing the number of iterations is feeetges dition is false INested |When working with tables, Each inner loop completes for every outer [Loops |matrices, patterns jloop iteration Key Points to Remember [19 Use white when the number of iterations is unknown. (19 Use do-whi1e when the loop must execute at least once. (09 Use for when the number of iterations is known in advance. [19 Nested loops are useful for multidimensional problems but can be inefficient if deeply nested. Jumps in Loops — soroy vreary ANA contine i C + InC, jump statements are used to alter the flow of execution in loops and functions. ‘© The main jump statements in C are: 1. goto — Transfers control to a labeled statement. 2. break — Exits the loop or switch statement, 3. continue — Skips the remaining statements of the current iteration and moves to the next iteration, 1. coto Statement Definition © The goto statement jumps to a labeled statement in the program. + It can transfer control forward or backward within the same function. + Not recommended as it makes code harder to read (considered bad practice). Syntax goto Label: lab 7 Code to execute Syntax Explanation + goto Label; moves the control to Labet : in the program, * label: is a user-defined name followed by a colon (:). Example finclude for lintiziri if 3) break; // Exit Loop when i peinte("sd\n", i); + Loop breaks when 3, so numbers 3, 4, 5 are not printed 3. continue Statement Defini «The continue statement skips the remaining code in iteration and moves to the next iteration. le the loop for the current + Unlike prea, it does not exit the loop but simply skips the rest of the current iteration Syntax Syntax Explanation © When continues is encountered, the remaining statements in the eurrent iteration are skipped, and the loop moves to the next iteration Example: Skipping a specific iteration tinclude int main printé ( \n' for (inti itt , printé("\nUsingcontinue:\n") ¢ for (inti=1zi i++) 3) continu med", ids ' Output g break: + break exits the loop when i == «continue skips iteration i == 3 but continues the loop. 6. Summary Table some, | ‘Fumetion Effect on Execution Use Case jumps to a labeled |Unconditionally jumps to another _ [Avoid unless necessary joto i tatement wart of the code (bad practice) eee Exits the loop of stops loop execution completely a we need to exit continue Skips the current [Moves to next iteration, skipping When we need to skip iteration jremaining statements [certain iterations 7. Key Points to Remember Use break when you want to exit a loop early. C0 Use continue when you want to skip an iteration but keep looping. 1 Avoid goto whenever possible (can make code confusing). 1 Never forget to use proper conditions with break and continue to prevent infinite loops.

You might also like