C if statement
Created By: chatGPT
C programming language uses an
if
statement to execute a block of code based on a specific condition. The condition is evaluated as either true or false. If the condition is true, the code block within the if
statement is executed; otherwise, it is skipped. Here’s a simple example to demonstrate the usage of an if
statement in C.int main() {
int number = 10;
if (number > 5) {
printf("Number is greater than 5\n");
}
return 0;
}
In this example, the variable
number
is initialized with the value 10. The if
statement checks if number
is greater than 5. Since this condition is true, the message "Number is greater than 5" will be printed to the console.if (number == 10) {
printf("Number is exactly 10\n");
}
We can also include an optional
else
statement that executes if the condition is false. This can help in handling cases where the condition does not meet expectations.if (number < 5) {
printf("Number is less than 5\n");
} else {
printf("Number is 5 or greater\n");
}
For even more complex logic, you can chain
if
and else if
statements together. This allows you to check multiple conditions in sequence.if (number < 5) {
printf("Number is less than 5\n");
} else if (number == 10) {
printf("Number is exactly 10\n");
} else {
printf("Number is greater than 10\n");
}
Remember, using curly braces
{ }
is good practice, even if there is only one statement to execute. This way, your code remains readable and it's easier to manage as it grows.// single statement without braces
if (number > 5)
printf("Number is greater than 5\n");
// with braces
if (number > 5) {
printf("Number is greater than 5\n");
}