C Language Tutorials by Ghulam Murtaza Dahar - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

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.

if...else statement

The if...else statement is used, if the programmer wants to execute some code, if the test expression is true and execute some other code if the test expression is false.

Syntax of if...else

if (test expression)

statements to be executed if test expression is true;

else

statements to be executed if test expression is false;

Flowchart of if...else statement

Example of if...else statement

Write a C program to check whether a number entered by user is even or odd

#include <stdio.h>

int main(){

int num;

printf("Enter a number you want to check.\n");

scanf("%d",&num);

if((num%2)==0) //checking whether remainder is 0 or not.

printf("%d is even.",num);

else

printf("%d is odd.",num);

return 0;

}