C Programming

if & if...else

Posted on 06th June 2013

if

The if statement will check if a condition is true or false. If condition is true then the next statement or a block of statements are executed. If the condition is false then the statement or statement block is skipped. A statement block is a set of statements enclosed in curly braces.

The if statement is written as

if (condition) statement;

or

if (condition) {
statement-block;
}

Example

if (count < 5) printf("The count is %d",count);

if (count < 5) {
	printf("The count is %d",count);
	count=count+1;
}


if ... else

The if ... else statement will evaluate the condition and execute one set of statements if the condition is true or an alternate set of statement if the condition is false.

The if ... else statement is written as

if (condition) statement1; else statement2;

or

if (condition) {
statement_block1;
}
else {
statement_block2;
}

Example

if (count > 5) {
	printf("Count is greater than 5");
}
else {
	printf("Count is not greater than 5 \\n");
	printf("Please input new value for count \\n");
	scanf("%d",&count);
}

Post a comment

Comments

Nothing yet..be the first to share wisdom.