Course Topics
C Basics Introduction and Setup Syntax and Program Structure Comments and Documentation Compiling and Running C Programs Exercise Variables and Data Types Variables and Declaration Data Types (int, float, char, double) Constants and Literals Type Conversion and Casting Exercise Operators Arithmetic Operators Comparison Operators Logical Operators Assignment Operators Bitwise Operators Exercise Input and Output Standard Input/Output (scanf, printf) Format Specifiers File Input/Output Exercise Control Flow - Conditionals If Statements If-Else Statements Switch Statements Nested Conditionals Exercise Control Flow - Loops For Loops While Loops Do-While Loops Loop Control (break, continue) Nested Loops Exercise Functions Defining Functions Function Parameters and Arguments Return Statements Scope and Variables Recursion Exercise Arrays One-Dimensional Arrays Multi-Dimensional Arrays Array Operations Strings as Character Arrays Exercise Pointers Introduction to Pointers Pointer Arithmetic Pointers and Arrays Pointers and Functions Dynamic Memory Allocation Exercise Strings String Handling String Functions (strlen, strcpy, strcmp) String Manipulation Exercise Structures Defining Structures Structure Members Arrays of Structures Pointers to Structures Exercise File Handling Opening and Closing Files Reading from Files Writing to Files File Positioning Exercise Memory Management Static vs Dynamic Memory malloc() and free() Memory Leaks Best Practices Exercise Advanced Topics Preprocessor Directives Macros Header Files Modular Programming Exercise Final Project Project Planning Building Complete Application Code Organization Testing and Debugging Exercise

If Statements

Introduction

Welcome back to our C programming series! Today we'll be diving deep into If Statements, one of the most fundamental building blocks in C programming. This concept will empower you to create more complex and dynamic programs, allowing your code to make decisions based on certain conditions. By the end of this lesson, you'll be able to create your own conditional statements, making your programs smarter and more adaptable!

Core Concepts

If Statements are used to evaluate an expression, and if it is true, a block of code will execute. The basic syntax for an If Statement looks like this:

if (condition) {
    // Code that runs if the condition is true
}

Let's take a look at an example:

int age = 20;
if (age >= 18) {
    printf("You are eligible to vote.");
}

In this code snippet, we have declared an integer variable called age with the value of 20. We then check if the condition (age >= 18) is true. If it is, the message "You are eligible to vote." will be printed out.

Key Terminology:

  • Condition: A boolean expression that determines whether a block of code should run or not.
  • Boolean Expression: An expression that can evaluate to either true or false.

Practical Examples

Let's look at some real-world examples where If Statements come in handy:

Example 1 - Comparing Numbers

int num1 = 5;
int num2 = 7;
if (num1 > num2) {
    printf("num1 is greater than num2.");
} else {
    printf("num2 is greater than or equal to num1.");
}

In this example, we're comparing two numbers and printing out which one is greater. If the condition (num1 > num2) is true, it will print "num1 is greater than num2." If not, it will print "num2 is greater than or equal to num1."

Example 2 - Checking user input

char choice;
printf("Enter 'y' to continue or 'n' to quit: ");
scanf("%c", &choice);
if (choice == 'y') {
    printf("Continuing...\n");
} else if (choice == 'n') {
    printf("Quitting...\n");
} else {
    printf("Invalid input. Please enter 'y' to continue or 'n' to quit.\n");
}

In this example, we ask the user for input and use If Statements to check if they entered either 'y' or 'n'. Depending on their input, we print out an appropriate message.

Common Issues and Solutions

SyntaxError: Unexpected identifier

What causes it: Missing parentheses around the condition expression.

if condition expression;

Error message:

SyntaxError: unexpected identifier

Solution:

if (condition) { ... }

Why it happens: The parentheses are essential for correctly defining the condition expression.
How to prevent it: Always include parentheses around your condition expressions.

NameError: name 'var_name' is not defined

What causes it: Using a variable that has not been declared yet.

if (var_name > 10) { ... }

Error message:

NameError: name 'var_name' is not defined

Solution:

int var_name;
if (var_name > 10) { ... }

Why it happens: The variable var_name has not been declared before being used in the If Statement.
How to prevent it: Always declare your variables before using them in conditional statements or any other code.

Best Practices

  • Avoid unnecessary indentation: Only use indentation when it's necessary for readability and clarity, as required by C style guidelines.
  • Always include an else clause: It can help handle cases where the condition is not met, providing a clear response or action to be taken.
  • Use descriptive names for variables: This makes your code easier to understand, both for yourself and others who may read it in the future.

Key Takeaways

  • If Statements allow you to create conditional logic in your C programs.
  • Always include parentheses around the condition expression to avoid SyntaxErrors.
  • Make sure variables are declared before using them in If Statements to prevent NameErrors.
  • Use descriptive variable names for improved readability and maintainability of your code.
  • Keep practicing with different conditions and scenarios to master this essential concept!

Next up, we'll dive deeper into Else if Statements and Switch Statements, which will further expand your conditional programming skills in C!