In computer programming, decision-making is a fundamental concept. It allows programs to execute different code blocks based on certain conditions. One of the most essential tools for implementing decision-making in C programs is the if statement. In this lab, we will explore the importance of if statements and how to use them effectively.
if statements are used in programming to create conditions and control the flow of a program. They allow you to execute specific code blocks only if certain conditions are met. This makes your programs more flexible, responsive, and capable of handling various scenarios.
You should use if statements when you need to:
Let's start with a basic if statement. In this example, we'll check if a number is positive:
#include <stdio.h> int main() { int number = 5; if (number > 0) { printf("The number is positive.\n"); } return 0; }
Run this code by clicking the Execute button in the Jdoodle window.
You should see the following output.
The number is positive.
An if-else statement allows you to specify both the "if" and "else" code blocks. If the condition is true, the "if" block is executed; otherwise, the "else" block is executed:
#include <stdio.h> int main() { int number = -3; if (number > 0) { printf("The number is positive.\n"); } else { printf("The number is not positive.\n"); } return 0; }
Run this code by clicking the Execute button in the Jdoodle window.
You should see the following output.
The number is not positive.
You can use else if statements to check multiple conditions sequentially. The first true condition's block is executed:
#include <stdio.h> int main() { int score = 75; if (score >= 90) { printf("A grade\n"); } else if (score >= 80) { printf("B grade\n"); } else if (score >= 70) { printf("C grade\n"); } else { printf("F grade\n"); } return 0; }
Run this code by clicking the Execute button in the Jdoodle window.
You should see the following output.
C grade
You can nest if statements inside each other to create more complex conditions. Enter the following code into the Jdoodle editor.
#include <stdio.h> int main() { int x = 5; int y = 10; if (x > 0) { if (y > 0) { printf("Both x and y are positive.\n"); } else { printf("x is positive, but y is not positive.\n"); } } else { printf("x is not positive.\n"); } return 0; }
Run this code by clicking the Execute button in the Jdoodle window.
You should see the following output.
Both x and y are positive.
In this lab, you've learned the importance of if statements in programming and how to use them to create conditions and make decisions. You've seen examples of basic if statements, if-else statements, and if-else if-else statements, as well as nested if statements. These concepts are essential for controlling the flow and behavior of your C programs, allowing them to respond dynamically to different situations and inputs.
File: labc_if_1.md
© Copyright 2023 Destin Learning