Movatterモバイル変換


[0]ホーム

URL:


OverIQ.com

  1. Home
  2. C Programming Tutorial
  3. if-else statements in C

if-else statements in C

Last updated on July 27, 2020


Control statements in C#

In all the programs we have written so far statements execute sequentially in the order in which they appear. But sometimes we want statements to execute only when some condition is true For example, If the bank balance is above seven figures buy a new car else renew monthly bus pass. To make such decisions C provides a facility called Control Statements.

Control statements are used to alter the flow of the program. They are used to specify the order in which statements can be executed. They are commonly used to define how control is transferred from one part of the program to another.

C language has following control statements:

  • if… else
  • switch
  • Loops
    • for
    • while
    • do... while

Compound statement#

A Compound statement is a block of statement grouped together using braces ({}). In a compound statement, all statements are executed sequentially. A compound statement is also known as a block. It takes the following form:

1234567
{statement1;statement2;statement3;...statementn;}

We have learned that all statements end with a semicolon (;) but the compound statement is an exception to this rule. Another important thing to understand is that a compound statement is syntactically equivalent to a single statement, this means that we can place a compound statement where a single statement is allowed. This means the following code is perfectly valid.

 1 2 3 4 5 6 7 8 91011121314151617
#include<stdio.h>intmain(){inti=100;printf("A single statement\n");{// a compound statementprintf("A statement inside compound statement\n");printf("Another statement inside compound statement\n");}// signal to operating system everything works finereturn0;}

Expected Output:

123
A single statementA statement inside compound statementAnother statement inside compound statement

if statement#

If statement is used to test a condition and take one of the two possible actions. The syntax of the if statement is:

Syntax:#

123456
if(condition){// if blockstatement1;statement2;}

the condition can be any constant, variable, expression, relational expression, logical expression and so on. Just remember that in C, any non-zero value is considered as true while0 is considered as false.

How it works:

The statements inside the if block (i.estatement1 andstatement2 ) are executed only when the condition is true. If it is false then statements inside if the block are skipped. The braces ({}) are always required when you want to execute more than one statement when the condition is true. Also, note that the statements inside the if block are slightly indented. This is done to improve readability, indentation is not syntactically required.

If you want to execute only one statement when the condition is true then braces ({}) can be omitted. In general, you should not omit the braces even if there is a single statement to execute.

12
if(condition)statement1;

The following program prints a message if the number entered by the user is even.

 1 2 3 4 5 6 7 8 91011121314151617
#include<stdio.h>intmain(){intn;printf("Enter a number: ");scanf("%d",&n);if(n%2==0){printf("%d is even",n);}// signal to operating system everything works finereturn0;}

1st run:

Run the program and enter an even number and you will get the following output:

Expected Output:

12
Enter a number: 4646 is even

2nd run:

Run the program again but this time, enter an odd number.

Expected Output:

Enter a number: 21

This time, the condition (n % 2 == 0) evaluates to false, as a result, statement inside the if block is skipped.

Which statement belongs to if?#

1234
if(condition)statement1;statement2;statement3;

Can you find which statement(s) will be omitted if the condition is false?

If there are no braces ({}) following the if statement then only the next immediate statement belongs to the if statement. The same thing is true for else and else-if clause (else and else-if clause are discussed later in this chapter).

Therefore, only thestatement1 belongs to the if statement. So if the condition is false then onlystatement1 will be omitted. Thestatement2 andstatement3 will be always executed regardless of the condition. The following example demonstrates this fact:

 1 2 3 4 5 6 7 8 9101112
#include<stdio.h>intmain(){if(0)printf("statement 1\n");printf("statement 2\n");printf("statement 3\n");// signal to operating system everything works finereturn0;}

Expected Output:

12
statement 2statement 3

Here the condition is false, that’s why only the last two statements are executed. This verifies the fact the statement in line 6 only belongs to the if statement. At a glance, it is slightly confusing to determine which statement belongs to the if statement, that’s why it is recommended to always use braces ({}) to wrap statements you want to execute with the if statement.

 1 2 3 4 5 6 7 8 9101112131415
#include<stdio.h>intmain(){if(0){printf("statement 1\n");}printf("statement 2\n");printf("statement 3\n");// signal to operating system prgram ran finereturn0;}

Now you can clearly see that only first statement belongs to the if statement.

The else clause#

Theelse clause allows us to add an alternative path to theif condition. Statements under theelse block are executed only when theif condition is false.

Syntax:

 1 2 3 4 5 6 7 8 910111213
if(condition){// if blockstatement1;statement2;}else{// else blockstatement3;statement4;}

As usual, if you have only one statement in the else block then the braces ({}) can be omitted. Although, it is not recommended.

1234
if(expression)statement1;elsestatement2;

As already said, indentation is not required, so the above code can also be written as:

1234
if(expression)statement1;elsestatement2;

But why kill the readability? Be a good programmer and always indent our code.

Now, let's add anelse clause to our previously written program.

 1 2 3 4 5 6 7 8 910111213141516171819202122
#include<stdio.h>intmain(){intn;printf("Enter a number: ");scanf("%d",&n);if(n%2==0){printf("%d is even",n);}else{printf("%d is odd",n);}// signal to operating system everything program ran finereturn0;}

1st run: Run the program and enter an even number.

12
Enter a number: 4444 is even

2nd run:

Run the program again but this time, enter an odd number.

12
Enter a number: 9191 is odd

Consider one more example. The following program determines the larger of the two entered numbers:

 1 2 3 4 5 6 7 8 910111213141516171819202122
#include<stdio.h>intmain(){inta,b;printf("Enter two numbers: ");scanf("%d %d",&a,&b);if(a>b){printf("%d is greater than %d",a,b);}else{printf("%d is greater than %d",b,a);}// signal to operating system everything works finereturn0;}

Expected Output:

1st run:

12
Enter two numbers: 344 200344 is greater than 200

2nd run:

12
Enter two numbers: 99 999999 is greater than 99

Nesting if… else#

We can addif..else statement insideif block orelse block. This is called nesting ofif..else.Syntax:

 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829
if(condition1){if(condition2){statement1;statement2;}else{statement3;statement4;}}else{if(condition3){statement5;statement6;}else{statement7;statement8;}}

We can nestif..else statement to any depth.

How it works:

First, thecondition1 is checked, if it is true, then thecondition2 is checked, if it is true then statements inside theif block (lines 4-7) are executed.

Otherwise, the statements in theelse block (lines 10-13) are executed. Otherwise, if thecondition1 is false, then thecondition3 is checked, if it is true then the statements under the if block in lines 19-22 are executed. Otherwise, the statements in theelse block (lines 25-28) are executed.

The following program uses 2 nested if-else statements to determine the larger of the three numbers:

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839
#include<stdio.h>intmain(){inta,b,c,larger;printf("Enter three numbers: ");scanf("%d %d %d",&a,&b,&c);if(a>b){if(a>c){larger=a;}else{larger=c;}}else{if(b>c){larger=b;}else{larger=c;}}printf("Largest number is %d",larger);// signal to operating system everything works finereturn0;}

Expected Output:

1st run:

12
Enter three numbers: 12 35 54Largest number is 54

2nd run:

12
Enter three numbers: 77 23 871Largest number is 871

Matching if.. else parts#

Sometimes it becomes confusing to associate an else clause with theif statement. Consider the following example:

12345
if(a<10)if(a%2==0)printf("a is even and less than 10\n");elseprintf("a is greater than 10");

Whichif statement is associated with theelse block? According to the way code is indented you might thinkelse belongs to the firstif statement, but it is not. The compiler does not associateif andelse statement according to indentation, it matches the else part with the closest unmatchedif part. So theelse statement is associated with the secondif statement.

We can always avoid such complications using braces ({}).

 1 2 3 4 5 6 7 8 9101112
if(a<10){if(a%2==0){printf("a is even and less than 10\n");}else{printf("a is greater than 10");}}

Now everything is crystal clear.

else if clause#

if-else is a bi-directional statement that is used to test a condition and take one of the possible two actions. What if we to perform a series of tests? One way to check for multiple conditions is to use the nestedif-else statement. We have seen an example of this technique earlier in this chapter. Another way to accomplish this is to use the else-if clause. The else-if clause extends the basic if-else statement and allows us to perform a series of tests. The updated syntax of the if-else statement looks like this:

 1 2 3 4 5 6 7 8 9101112131415161718192021
if(condition1){statement1;}elseif(condition2){statement2;}elseif(condition3){statement3;}...else{statement4;}

Here, each condition is checked one by one. As soon as a condition is found to be true then statements corresponding to that block are executed. The conditions and statements in the rest of the if-else statement are skipped and program control comes out of theif-else statement. If none of the conditions is true then statements in theelse block are executed.

Usingelse-if clause we can write nestedif-else statement in a more compact form.

Let's rewrite the program to determine the largest of the two numbers using the else-if clause.

 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829
#include<stdio.h>intmain(){inta,b,c,larger;printf("Enter three numbers: ");scanf("%d %d %d",&a,&b,&c);if(a>b&&a>c){larger=a;}elseif(b>a&&b>c){larger=b;}else{larger=c;}printf("Largest number is %d",larger);// signal to operating system everything works finereturn0;}

This version of the program is functionally equivalent to the one that uses nested if-else statement. But it avoids deep indentation making the code more readable.


Load Comments


C Programming Tutorial

Recent Posts

x

[8]ページ先頭

©2009-2025 Movatter.jp