Monday, April 27, 2009

The if statement

The if statement is very common in most of the computer languages. Alike C also reserve this keyword to implement the decision control instruction.
The syntax of this instruction is as follows:
if( The condition = True )
  execute the statements;


The if statement tell the compiler to take a decision based on the condition provided with in the bracket, and if its true then execute the statement(s) preceding it. And if the condition is not true then the statement(s) is/are not executed, instead the program control skips it.
In general, C's relational operator is used to compare two values. The relational operators used in C language are as follows:


Relational Operator
Condition satisfies if
x==y x is equal to y
x!=y x is not equal to y
x<y x is less than y
x>y x is greater than y
x<=y x is less than or equal to y
x>=y x is greater than or equal to y
Note: Only ‘=’ is used to assign a value to a variable, whereas ‘==’ is used to compare two quantities.


A simple example is shown to understand the if statement {Also See: Program with if Statement}.


/* A program to understand the if statement */
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf(“Please enter an odd number: ”);
scanf(“%d”, &num);
if(num%2!=0)
printf(“\nThank you, for being an obedient user.”);
getch();
}

Explanation: So in this program, the user is asked to enter an odd number, and the inputted number is checked whether it is odd or not. If by the logic implemented in the program finds that the user has inputted an odd number then the system will generate an output else will skip the output statement and will end the program.


Output of the program:
Please enter an odd number: 5
Thank you, for being an obedient user.


For alternate input:
Please enter an odd number: 6


As because 6 is an even number so, it will not print anything more and will end the program.

No comments:

Post a Comment

Please give your valuable comments or queries if you fell its helpful or if you like the contents of the site. Thanks...