If statement in c
C Programming if, if..else and Nested if...else Statement
Decision making are needed when, the program encounters the situation to choose a particular statement among many statements. In C, decision making can be performed with following two statements.
Decision making are needed when, the program encounters the situation to choose a particular statement among many statements. In C, decision making can be performed with following two statements.
1. if...else statement
2. switch statement
2. switch statement
if statement syntax
if (test expression){
statement/s to be executed if test expression is true;
}
If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are executed. But, if the test expression is false, the execution of the statements for the body of if statements are skipped.
Flowchart of if statement
Example of if statement
Write a C program to print the number entered by user only if the number entered is negative.
#include <stdio.h>
int main(){
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0) /* checking whether number is less than 0 or not. */
printf("Number=%d\n",num);
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
printf("The if statement in C programming is easy.");
return 0;
}
Output 1
Enter a number to check.
-2
Number=-2
statement/s to be executed if test expression is true;
}
If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are executed. But, if the test expression is false, the execution of the statements for the body of if statements are skipped.
Flowchart of if statement
Example of if statement
Write a C program to print the number entered by user only if the number entered is negative.
#include <stdio.h>
int main(){
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0) /* checking whether number is less than 0 or not. */
printf("Number=%d\n",num);
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
printf("The if statement in C programming is easy.");
return 0;
}
Output 1
Enter a number to check.
-2
Number=-2
The if statement in C programming is easy.
When user enters -2 then, the test expression (num<0) becomes true. Hence, Number=-2 is displayed in the screen.
Output 2
Enter a number to check.
5
The if statement in C programming is easy.
When the user enters 5 then, the test expression (num<0) becomes false. So, the statement for body of if is skipped and only the statement below it is executed.
0 comments:
Post a Comment
Dont Forget for Commets