C If Statements

if Syntax:

if(condition)
{
statement1;
statement2;
statement3;
statement4;
}

  • Constructing the body of if always optional i.e.recommended to create the body when we are having multiple statements.
  • For a single statement, it is not required to specify the body.
  • If the body is not specified, then automatically condition part will be terminated with next semicolon(;).

Examples:

void main()
{
printf(“Welcome to k2schools”);
if(5<2) { printf("Welcome to dummy schools") printf("No output"); } printf("website"); }

Out put will be ‘Welcome to k2schools website’.

Compare two numbers:

void main()
int a,b;
{
printf(“Enter the values of a and b’);
scanf(‘%d%d’,&a,&b);
if(a=b)
{
printf(“Both the values are same.”);
}
printf(“You entered the different values”);
}

else:

  • By using this keyword we can create a alternate block for if part.
  • Using else is always optional i.e. it is recommended to use when we are having alternate block of condition.
  • When we are working with if else among those two block at given any point of time only one block will be executed.
  • When if condition is false then else part will be executed, if statement is executed then automatically else will be ignored.

if-else Syntax:

if(condition)
{
statement1;
statement2;
}
else
{
statement3;
}

Examples:

void main()
{
{
print(“k2schools”);
}
if(7>1&&2<5) {printf("x"); printf("y"); } else { printf("a"); printf("b"); } } Compare two numbers:

void main()
int a,b;
{
printf(“Enter the values of a and b’);
scanf(‘%d%d’,&a,&b);
if(a=b)
{
printf(“Both the values are same.”);
}
else
{
printf(“You entered the different values”);
}
}

Powered by k2schools