If you have completed my last tutorials then you are ready to move some difficult but very important parts of c programming. So, today’s C programming tutorial for beginners post will be for you about conditional statements in C. Also you will learn about what is the conditional operator with examples. So, let’s get started.
What Is Conditional Statement With Example?
In our real life, we have to face so many problems and we have to define some things depending on one or more conditions.
Suppose, I told you to go to your friend’s house and then watch a movie with him in the cinema hall.
To do so, you will face so many conditions. For example, First, you went out of your house and look for a rickshaw or taxi to reach your friend’s house. There would be a condition is there any vehicle to go to your friend’s house? If YES. Then you can go to your friend’s house by vehicle otherwise you have to go there walk or even get back to your home. Then after reaching your friend’s house you have to check if your friend is in the house? If he is. Then you should tell him to went to the cinema hall with you. If he isn’t then you should go back to your home. If you and your friend went to the cinema hall then there will be another question. Is there any movie is coming for streaming? If the answer is yes. Then watch the movie with your friend and then head back home. If the answer is no then return home without watching the movie.
You see in the whole story each of the next steps goes depending on different conditions. In our programming life we will have to face so many problems which depend on various conditions like the above. And we have to solve them using our programming language. For solving these kinds of problems we have to use conditional statements. In C there are actually four types of conditional statements these are as follows:
1) If statement. If statements are also 4 types and they are:
Simple if statement.
Nested if…else statement.
4)go to statement.
In the next tutorials, we will learn about numbers 1,2, and 4th types of conditional statements.
Now, we will learn and try to write a simple program using a conditional operator.
Conditional Operator With Example:
int main ()
Here, at first, we take 2 variables as input x and y. Then we check if y is larger than or equal to x then the current value of y is replaced by x-y. If it is not then the current value of y is replaced by x+y.
Here, (x>y)? at first check the condition then after the ? means y-x execute if the condition is true. Otherwise after the : means y+x execute and returns the value to y. And by the printf function, we just print the value of y after the operation.
I hope you understand the conditional operator. Now try to solve the following problem using the conditional operator by yourself.
Write a program to take an integer value x as input range from -20000 to +200000 then check is it an even number or an odd number? If it is even then print even otherwise print odd.