Linguagem C - Aula 4.2 - Domine os comandos IF e ELSE em C (2022)
Understanding Decision Structures in Programming
Introduction to Decision Structures
- The discussion begins with an overview of decision structures, emphasizing the ability to create chains of decision-making processes.
- A review of logical operators is provided, focusing on how they can create more complex conditions within
ifstatements.
Logical Operators Explained
- Disjunction: At least one operand must be true for the expression to be true.
- Conjunction: Both operands must be true for the expression to be true; if any operand is false, the entire expression is false.
- Negation: Inverts the logical value of a statement.
Understanding if and else
- The mechanics of
ifandelseare explained. If the condition inifis true, its block executes; otherwise, the block underelseexecutes.
- It’s highlighted that there cannot be an
elsewithout a precedingif, as it relies on the opposite condition established byif.
Important Rules for Using else
- An important note is that an
elsemust always follow an associatedif.
- Only one corresponding
elsecan exist for eachif, reinforcing binary logic (true/false).
Practical Example: Grading System
- A practical example illustrates a program that checks if a student has passed based on their score.
- If the score is greater than or equal to 7, "approved" is printed; otherwise, "reproved" appears.
Code Logic Breakdown
- The program prompts for input and reads a score. It then evaluates whether this score meets passing criteria using an if statement.
- If the condition (
score >= 7) holds true, it prints "approved"; if false, it prints "reproved".
Alternative Approaches
- The speaker discusses alternative ways to structure similar logic while achieving identical outcomes semantically but differing syntactically.
- For instance, checking if a score is less than 7 first could yield similar results.
Conclusion and Next Steps