×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Logical NOT (!) operator with example in C language

C language Logical NOT (!) operator: Here, we are going to learn about the Logical NOT (!) operator in C language with its syntax, example.
Submitted by IncludeHelp, on April 14, 2019

Logical operators work with the test conditions and return the result based on the condition's results, these can also be used to validate multiple conditions together.

In C programming language, there are three logical operators Logical AND (&&), Logical OR (||) and Logician NOT (!).

Logical NOT (!) operator in C

Logical NOT is denoted by exclamatory characters (!), it is used to check the opposite result of any given test condition.

If any condition's result is non-zero (true), it returns 0 (false) and if any condition's result is 0(false) it returns 1 (true).

Syntax of Logical NOT operator:

    !(condition)

Truth table of logical NOT operator:

condition	!(condition)
1		0
0		1

C examples of Logical NOT (!) operator

Example 1: Take a number and apply some of the conditions and print the result of expression containing logical NOT operator.

// C program to demonstrate example of 
// Logical NOT (!) operator 

#include <stdio.h>

int main()
{
    int num =10;
    
    //printing result with OR (||) operator
    printf("%d\n", !(num==10));
    printf("%d\n", !(num!=10));
    printf("%d\n", !(num>5));
    printf("%d\n", !(num<5));
    
    return 0;
}

Output

0
1
0
1

Example 2: Input a year and check it is leap year or not (it will use Logical AND (&&), Logical OR (||) and Logical NOT (!) operators).

// C program to demonstrate example of 
// Logical NOT (!) operator 

// Input a year and check it is leap year or not 
#include <stdio.h>

int main()
{
    int y;
    
    //input year 
    printf("Enter year: ");
    scanf("%d", &y);
    
    //check condition
    if((y%400==0) || (y%4==0 && y%100!=0))
        printf("%d is a leap year\n",y);
    else
        printf("%d is not a leap year\n",y);
    
    return 0;
}

Output

First run:
Enter year: 2004
2004 is a leap year

Second run:
Enter year: 2100
2100 is not a leap year

Third run:
Enter year: 2400
2400 is a leap year

Fourth run:
Enter year: 2003
2003 is not a leap year



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.