C Programs With Conditional Statements

Share This Post

Conditional Statements in C

Conditional statements in C are critical for doing any sort of fun stuff in your programs. With conditions, we can introduce branches into our programs. If a state is true, then we can do this set of code. Otherwise, let’s do the other branch.

We can have sub-branches, combine multiple conditions and so much more!

Conditional statements are useful for evaluating truth statements with our variables. In other words, if we want to see which number is larger than another. We can also use them in control flow statements, which we’ll get into in this activity.

Truth values

You may have noticed a 1 and 0 on some of your utilities at home, such as coffee makers, flash lights, etc. These are actually truth values that indicate on and off! In programming, 0 indicates false while 1 indicates true. In C, any positive integer will return true.

In order to see these in action, let’s talk about control flow statements.

Control Flow Statements

You may have noticed that the programs we have written so far have limited capabilities. This is because there is no way to partition parts of our code to handle specific instances. Let’s say we wanted to develop a program that could tell you if your number was even or odd. We know how to do this by dividing by 2 and seeing if this division is even, however, we run into issues later on if we wanted to add more features.

#include <stdio.h>

int main(void)
{
   int a = 3;
   int result = a % 2;

   printf("Result: %d\n", result);
   return 0;
}

What if we wanted to tell the user if their number was even or odd? We can do so using control-flow statements like so:

#include <stdio.h>

int main(void)
{
   int a = 3;
   int result = a % 2;

   if (result == 0)
   {
      printf("Even number\n");
   }
   else
   {
      printf("Odd number\n");
   }
   return 0;
}

We can use if /else if/ else conditions to create logic in our code.

If Statement

We can check if a statement is true using the if keyword. If a statement is true, it will enter the block immediately following the conditional statement. We also can nest conditions together for more complex statements like so.

if (statement1)
{
   if (statement2)
   {
       printf("Nested If!\n");
   }
   else
   {
      printf("Still Nested!\n");
   }
}
else
{
   printf("Did not go in the nested condition.\n");
}

Else If Statements

If we have multiple scenarios, we can check for one and immediately check for others like so:

if (statement1)
{
   ...
}
else if (statement2)
{
   ...
}
else if (statement3)
{
   ...
}
...

If the first statement is true, it will enter the first block and skip the other conditions. If the first statement is false, the program will continue throughout each else if until it finds a true condition. On this occasion, it will enter the corresponding block and skip any remaining conditions.

Else if statements are not mandatory.

Else Statements

Else statements are not mandatory, but apply when we want to catch any case that may not be accounted for in our logic. Consider the previous even/odd example. Since we account for numbers that are even, the only other category of numbers left are odd numbers. Therefor, we can just simply use an else condition to catch the rest of the odd numbers rather than repeat the math done on the previous line.

Logical Operators

We can combine expressions using && and ||. && is a logical AND whereas || is a logical OR. AND conditions must have two expressions that are both true, where logical OR statements only require one statement (both will also return true). AND statements take precedence over OR statements, however, we can use parenthesis to invoke our own order of operations.

if (a && b)
{
   printf("Both are true\n");
}
else if (a || b)
{
   printf("One is true\n");
}
else
{
   printf("Neither are true\n");
}

We can also flip logical expressions to the opposite value using the NOT operator (!).

if (!(a && b) == 0)
{
   printf("Both are true\n");
}
else if (a || b)
{
   printf("One is true\n");
}
else
{
   printf("Both are false\n");
}

The previous two snippets of code are equivalent. While they use different techniques in the first line to make the comparison, they will both result in the exact same output.

Comparison Operators

We can also use greater than, less than, etc. operators to compare variables to each other like so:

int a = 4;
int b = 4;

// Equal
if (a == b)
{
   ...
}
// Not Equal
if (a != b)
{
   ...
}
// Less Than
if (a < b)
{
   ...
}
// Greater Than
if (a > b)
{
   ...
}
// Less Than OR Equal To
if (a <= b)
{
   ...
}
// Greater Than OR Equal To
if (a >= b)
{
   ...
}

It is also important to remember that floating point numbers are not entirely accurate. Consider using greater/less than or equal to operators to set a range of values with a given error like so:

double error_threshold = 0.00000001;
double value = 5.72;
double input = 5.723989801

if ((input <= value + error_threshold) && (input >= value - error_threshold))
{
   printf("Numbers are equal\n");
}
else
{
   printf("Numbers are not equal\n");
}

You can adjust the tolerance by adding or removing decimal places in the error_threshold. Also in this example, we can combine comparison expressions with logical expressions. We can combine any number of logical expressions together, so long as the resulting answer is true or false.

if (condition1 && condition 2)
{
// Both condition1 and condition2 need to be true
}

if (condition1 || condition 2)
{
// Either condition1, condition2 or both can be true
}

if (!condition1 || condition2)
{
// Condition1 must be false or condition2 must be true
}

Also, the ‘!’ operator is the NOT operator. If a condition is true, it gets flipped to false with the NOT operator; vice versa is true for false conditions turning to true.

To wrap this up, see if you can determine the output for the following program:

int a = 4;
int b = 5;
int c = 6;

if ((a > 5 || b == 5) && c < 2)

{
printf("It is true!\n");
}

 

You can see how repetitious this gets, especially when we have a lot of conditions we need to check for. What if we had many variables we needed to check? Better yet, what if we had to check for a condition over a range of numbers? Up next, we’ll go over how to simplify our conditions so our programs don’t take thousands of lines to run. Stay tuned and share this with a friend if you thought it was helpful! 

That's weird... something went wrong. Please try again.
Welcome to the R U Coding Me Newsletter!

R U Coding Me Newsletter

Subscribe to our newsletter and stay updated.

We use Brevo as our marketing platform. By Clicking below to submit this form, you acknowledge that the information you provided will be transferred to Brevo for processing in accordance with their terms of use

Are You Coding?

If the answer is no, you’re probably missing out on a large opportunity here. And yes, I said the name!

Our FREE developer resources will help you start programming. Additionally, consider applying for mentorship to accelerate you to your career. Click on the Student button below to get started. It will take you to our available courses and any relevant materials to help get you started.

Ready to take your business to the next level? Creating a robust solution in a short amount of time is hard to do if you’ve never done it before. Plus, why should you juggle yet another project with your business? Click on the Business button below if you’re looking to scale your current business online but don’t want to spend a few years to learn how to do it. It will take you to our services so you can see what would best work for you.

More To Explore
Learn C Programming
Multidimensional Arrays in C With Example

FacebookTweetPinLinkedInEmail Wait, You Said There Wouldn’t Be Any More Pointers! No, if you recall from last time, I mentioned there could be pointers that point

Learn C Programming
Efficiently Debugging C Programs

FacebookTweetPinLinkedInEmail What is Debugging? Overview of Debugging Debugging is an art form, rather than a science. Debugging is the act of removing any issues that

R U Coding Me LLC