Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 74

INTRODUCTION TO C

History of C language

• The base or father of programming languages is 'ALGOL.' It was first introduced in 1960. 'ALGOL' was used on a large basis
in European countries.

• 'ALGOL' introduced the concept of structured programming to the developer community.

• In 1967, a new computer programming language was announced called as 'BCPL' which stands for Basic Combined
Programming Language. BCPL was designed and developed by Martin Richards, especially for writing system software. This
was the era of programming languages.

• Just after three years, in 1970 a new programming language called 'B' was introduced by Ken Thompson that contained
multiple features of 'BCPL.' This programming language was created using UNIX operating system at AT&T and Bell
Laboratories. Both the 'BCPL' and 'B' were system programming languages.
• In 1972, a great computer scientist Dennis Ritchie created a new programming language called 'C' at the Bell
Laboratories. It was created from 'ALGOL', 'BCPL' and 'B' programming languages.
• 'C' programming language contains all the features of these languages and many more additional concepts
that make it unique from other languages.
• C' is a powerful programming language which is strongly associated with the UNIX operating system. Even
most of the UNIX operating system is coded in 'C'. 
• Today 'C' runs under a variety of operating systems and hardware platforms. As it started evolving many
different versions of the language were released.
• C' programming language is also called as 'ANSI C'.
Why we learn C language?
• C is a powerful general-purpose programming language. It can be used to develop software like operating
systems, databases, compilers, and so on.
• C programming is an excellent language to learn to program for beginners.
• C helps you to understand the internal architecture of a computer, how computer stores and retrieves
information.
• After learning C, it will be much easier to learn other programming languages like Java, Python, etc.
Intro…..
About C Programming
• Procedural Language - Instructions in a C program are executed step
by step.
• Portable - You can move C programs from one platform to another,
and run it without any or minimal changes.
• Speed - C programming is faster than most programming languages
like Java, Python, etc.
• General Purpose - C programming can be used to develop operating
systems, embedded systems, databases, and so on.
Key Applications

• C' language is widely used in embedded systems.


• It is used for developing system applications.
• It is widely used for developing desktop applications.
• Most of the applications by Adobe are developed using 'C' programming language.
• It is used for developing browsers and their extensions. Google's Chromium is built using 'C'
programming language.
• It is used to develop databases. MySQL is the most popular database software which is built using
'C'.
• It is used in developing an operating system. Operating systems such as Apple's OS X, Microsoft's
Windows, and Symbian are developed using 'C' language. It is used for developing desktop as well
as mobile phone's operating system.
• It is used for compiler production.
• It is widely used in IOT applications.
How C Programming Language Works?

• C is a compiled language.
• A compiler is a special tool that compiles the program and converts it
into the object file which is machine readable.
• After the compilation process, the linker will combine different object
files and creates a single executable file to run the program. The
following diagram shows the execution of a 'C' program
STRUCTURE of C
The components of the structure are:
Header Files Inclusion:
The first and foremost component is the inclusion of the Header files in a C program. 

A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files.
Some of C Header files: 
• stdint.h – Defines exact width integer types.
• stdio.h – Defines core input and output functions
• stdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocation
• string.h – Defines string handling functions
• math.h – Defines common mathematical functions
Main Method Declaration:
•   The main function is a part of every 'C' program. We can represent the main function in various forms,
such as:
• main()
• int main()
• void main()
• main(void)
• void main(void)
• int main(void)
• The empty parentheses indicate that this function does not take any argument, value or a parameter.
You can also represent this explicitly by placing the keyword void inside the parentheses. The keyword
void means the function does not return any value, in this case, the last statement is always getch ().
EG: int main()
{}
Variable Declaration: 
• The next part of any C program is the variable declaration. It refers to the variables that
are to be used in the function.
• Please note that in the C program, no variable can be used without being declared. Also
in a C program, the variables are to be declared before any operation in the function.
Example:
Int main()
{
Int a;
.
.
.
}
int main() { int a; printf("%d", a); . .

• Body: The body of a function in the C program, refers to the operations that are performed in the
functions. It can be anything like manipulations, searching, sorting, printing, etc.
Example: 

#include<stdio.h>
int main()
{
int a;
print(“%d”,a);
}

 
• Return Statement: 
• The last part of any C program is the return statement. The return
statement refers to the returning of the values from a function.
• This return statement and return value depend upon the return type
of the function. For example, if the return type is void, then there will
be no return statement.
• In any other case, there will be a return statement and the return
value will be of the type of the specified return type.
• Example:
int main()
{
int a;
printf(“%d”,a);
return 0;
}
Let us analyze the program line by line. 

Line 1: [ #include <stdio.h> ] 

• In a C program, all lines that start with # are processed by a preprocessor which is a program invoked by the
compiler. In a very basic term, the preprocessor takes a C program and produces another C program.

• The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the
above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called
header files in C.

• These header files generally contain declarations of functions. We need stdio.h for the function
printf() used in the program. 
• Line 2 [ int main(void) ] There must be a starting point from where
execution of compiled C program begins. In C, the execution typically
begins with the first line of main(). The void written in brackets
indicates that the main doesn’t take any parameter
• The int was written before main indicates return type of main(). The
value returned by main indicates the status of program termination.
See this post for more details on the return type.
• Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define scope
and are mainly used in functions and control statements like if, else,
loops. All functions must start and end with curly brackets.
• Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to
print something on standard output. The semicolon at the end of printf
indicates line termination. In C, a semicolon is always used to indicate end
of a statement.
• Line 5 [ return 0; ] The return statement returns the value from main().
The returned value may be used by an operating system to know the
termination status of your program. The value 0 typically means
successful termination. 
• Ex:2
• #include<stdio.h>
• Int main()
•{
• printf(“hello world”);
• Return 0;
•}
• C Basic commands
• Explanation
• #include <stdio.h>
This command includes standard input output header file(stdio.h) from the C library before compiling a C program
• int main()
It is the main function from where C program execution begins.
•{
Indicates the beginning of the main function.
• /*_some_comments_*/
Whatever written inside this command “/*   */” inside a C program, it will not be considered for compilation and
execution.
• printf(“Hello_World! “);
This command prints the output on the screen.
• getch();
This command is used for any character input from keyboard.
• return 0;
This command is used to terminate a C program (main function) and it returns 0.
•}
It is used to indicate the end of the main function.
What is Token in C?

• TOKEN is the smallest unit in a 'C' program.


• The compiler breaks a program into the smallest possible units
(Tokens) and proceeds to the various stages of the compilation.
• C Token is divided into six different types, viz, Keywords, Operators,
Strings, Constants, Special Characters, and Identifiers.
TOKENS

KEYWORDS STRING CONSTANTS IDENTIFIERS

OPERATORS SPECIAL
CHARACTERS
Keywords and Identifiers

• In 'C' every word can be either a keyword or an identifier.


• Keywords have fixed meanings, and the meaning cannot be changed.
They act as a building block of a 'C' program. There are a total of 32
keywords in 'C'. Keywords are written in lowercase letters.
Keywords in C Programming Language
auto double int struct
break else long switch
case enum register typedef
char extern return union
const short float unsigned
continue for signed void
default goto sizeof volatile
do if static while
IDENTIFIER
• An identifier is nothing but a name assigned to an element in a program. Example, name of a
variable, function, etc.
• Identifiers in C language are the user-defined names consisting of 'C' standard character set. As
the name says, identifiers are used to identify a particular element in a program.
• Each identifier must have a unique name. Following rules must be followed for identifiers:
• The first character must always be an alphabet or an underscore.
• It should be formed using only letters, numbers, or underscore.
• A keyword cannot be used as an identifier.
• It should not contain any whitespace character.
• The name must be meaningful.
VARIABLES
• A variable is an identifier which is used to store some value. Constants
can never change at the time of execution. Variables can change
during the execution of a program and update the value stored inside
it.
• A single variable can be used at multiple locations in a program. A
variable name must be meaningful. It should represent the purpose of
the variable.
Example: Height, age, are the meaningful variables that represent the purpose it is
being used for. Height variable can be used to store a height value. Age variable can
be used to store the age of a person.
Following are the rules that must be followed
while creating a variable:
• A variable name should consist of only characters, digits and an
underscore.
• A variable name should not begin with a number.
• A variable name should not consist of whitespace.
• A variable name should not consist of a keyword.
• 'C' is a case sensitive language that means a variable named 'age' and
'AGE' are different.
Data types

• C' provides various data types to make it easy for a programmer to select a suitable data type
as per the requirements of an application. Following are the three data types:
Primitive data types
Derived data types
User-defined data types
There are five primary fundamental data types,
int for integer data
char for character data
float for floating point numbers
double for double precision floating point numbers
void
• Array, functions, pointers, structures are derived data types. 'C' language provides more extended versions of
the above mentioned primary data types.
• Each data type differs from one another in size and range. Following table displays the size and range of each
data type.
Data type Size in bytes Range
Char or signed char 1 -128 to 127
Unsigned char 1 0 to 255
int or signed int 2 -32768 to 32767
Unsigned int 2 0 to 65535
Short int or Unsigned 2 0 to 255
short int
Signed short int 2 -128 to 127
Long int or Signed 4 -2147483648 to
long int 2147483647
Unsigned long int 4 0 to 4294967295
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to
1.1E+4932
Integer data type

• Integer is nothing but a whole number. The range for an integer data type varies from machine to
machine. The standard range for an integer data type is -32768 to 32767.
• An integer typically is of 2 bytes which means it consumes a total of 16 bits in memory. A single
integer value takes 2 bytes of memory. An integer data type is further divided into other data types
such as short int, int, and long int.
• Each data type differs in range even though it belongs to the integer data type family. The size may
not change for each data type of integer family.
• The short int is mostly used for storing small numbers, int is used for storing averagely sized integer
values, and long int is used for storing large integer values.
• Whenever we want to use an integer data type, we have place int before the identifier such as,

int age;
float division; double BankBalance;

Floating point data type


• 'C' program we can also make use of floating point data types.
• The 'float' keyword is used to represent the floating point data type. It can hold a floating point
value which means a number is having a fraction and a decimal part.
• A floating point value is a real number that contains a decimal point.
• Generally, a float can hold up to 6 precision values. If the float is not sufficient, then we can make
use of other data types that can hold large floating point values.
• The data type double and long double are used to store real numbers with precision up to 14 and
80 bits respectively.
• While using a floating point number a keyword float/double/long double must be placed before an
identifier. The valid examples are,
• EG: float division;
double Bankbalance;
Character data type

• Character data types are used to store a single character value enclosed in
single quotes.
• A character data type takes up-to 1 byte of memory space.
• Example:char letter;
Void data type
• A void data type doesn't contain or return any value. It is mostly used for
defining functions in 'C'.
• Example,
Void displayData ();
Type declaration of a variable
int main()
• Output:
{ • 59
int x, y;
float salary = 13.48; • 13.48
char letter = 'K';
x = 25; •k
y = 34;
int z = x+y;
printf("%d \n", z);
printf("%f \n", salary);
printf("%c \n", letter);
return 0;
}
Constants
• Constants are the fixed values that never change during the execution of a program. Following are the
various types of constants:
• Integer constants-nothing but a value consisting of digits or numbers. These values never change
during the execution of a program. Integer constants can be octal, decimal and hexadecimal.
Ex:111,065,0x2.
• Character constant: It contains only a single character enclosed within a single quote (''). We can also
represent character constant by providing ASCII value of it. Ex: ‘A’, ’9’.
• String constant:string constant contains a sequence of characters enclosed within double quotes ("").
Ex: “hi”, ”Hello”.
• Real Constants:Like integer constants that always contains an integer value. 'C' also provides real
constants that contain a decimal point or a fraction value. The real constants are also called as floating
point constants. The real constant contains a decimal point and a fractional value. Ex: 101.00,202.00
C Conditional Statement: IF, IF Else and
Nested IF Else
• Conditional Statements in C programming are used to make decisions
based on the conditions.
• Conditional statements execute sequentially when there is no condition
around the statements.
• If you put some condition for a block of statements, the execution flow
may change based on the result evaluated by the condition.
• In 'C' programming conditional statements are possible with the help of
the following two constructs:
1. If statement
2. If-else statement
Decision Making
If statement

If statement is responsible for modifying the flow of


execution of a program. If statement is always used with
a condition. The condition is evaluated first before Syntax: if (condition)
executing any statement inside the body of If. instructions;
• #include<stdio.h> • Output:
• int main()
•{
num1 is smaller than num2
• int num1=1;
• int num2=2;
• if(num1>num2) //test-condition
• {
• printf("num1 is smaller than num2");
• }
• return 0;
• }
EX:

#include<stdio.h> • Output:
Int main()
{ • You succeed!
int x = 41;
/*x =x+ 1*/;
if (x == 42)
{
printf("You succeed!");
}
RETURN 0;
}
Keep in mind that a condition that evaluates to a non-
zero value is considered as true
#include<stdio.h> • Output:
Int main() No errors or program output.
{
int x = 41;
x =x- 1;
if (x == 42)
{
printf("You succeed!");
} return 0;
}
IF-ELSE STATEMENT:The if-else is statement is an extended
version of If.
if the value of test-expression is true, then the true block of
statements will be executed. If the value of test-expression if false,
then the false block of statements will be executed. In any case,
after the execution, the control will be automatically transferred to SYNTAX
the statements appearing outside the block of If.

• if (test-expression)
•{
• True block of statements
•}
• Else
•{
• False block of statements
•}
• Statements;
Ex:
• #include<stdio.h>
• OUTPUT:
• int main()
•{ • THE VALUE IS GREATER THAN 10
• int num=19;
• if(num<10)
• {
• printf("The value is less than 10");
• }
• else
• {
• printf("The value is greater than 10");
• }
• return 0;
•}
Nested If-else Statements
int main() {
    int i = 10;
• When a series of decision is required, nested if-else is  
used. Nesting means using one if-else construct within     if (i == 10)
another one.     {
• if (condition1)         // First if statement
        if (i < 15)
• {            printf("i is smaller than 15\n");
• // Executes when condition1 is true  
        // Nested - if statement
• if (condition2)
        // Will only be executed if statement above
• {         // is true
        if (i < 12)
• // Executes when condition2 is true             printf("i is smaller than 12 too\n");
• }         else
            printf("i is greater than 15");
• }     }
 
    return 0;}

Output:
I is smaller than 15
I is smaller the 12 too

}
Conti…
• This type of structure is known as the else-if ladder. This chain
generally looks like a ladder hence it is also called as an else-if ladder.
• The test-expressions are evaluated from top to bottom. Whenever a
true test-expression if found, statement associated with it is executed.
• When all the n test-expressions becomes false, then the default else
statement is executed.
Nested Else-if statements:Nested else-if is used when multipath decisions are
required.
• if (test - expression 1) { • #include<stdio.h>
• int main()
• statement1;
• {
• } else if (test - expression 2) {
• int marks=83;
• Statement2; • if(marks>75){
• } else if (test - expression 3) { • printf("First class");

• Statement3; • }

• } else if (test - expression n) { • else if(marks>65){


• printf("Second class");
• Statement n;
• }
• } else {
• else if(marks>55){
• default; • printf("Third class");
• } • }

• Statement x; • else{
• printf("Fourth class");
• }
• return 0;
• }
Cont…..
• This type of structure is known as the else-if ladder. This chain
generally looks like a ladder hence it is also called as an else-if ladder.
• The test-expressions are evaluated from top to bottom. Whenever a
true test-expression if found, statement associated with it is executed.
• When all the n test-expressions becomes false, then the default else
statement is executed.
C Loops: For, While, Do While, Looping Statements

• What is Loop in C?
• Looping Statements in C execute the sequence of statements many times
until the stated condition becomes false.
• A loop in C consists of two parts, a body of a loop and a control statement.
• The control statement is a combination of some conditions that direct the
body of the loop to execute until the specified condition becomes false.
• The purpose of the C loop is to repeat the same code a number of times.
Types of Loops in C

• Depending upon the position of a control statement in a program, looping statement in


C is classified into two types:

1. Entry controlled loop

2. Exit controlled loop

• In an entry control loop in C, a condition is checked before executing the body of a loop.
It is also called as a pre-checking loop.

• In an exit controlled loop, a condition is checked after executing the body of a loop. It is
also called as a post-checking loop.
Flowchart for loop
• The control conditions must be well defined and specified otherwise the loop will execute an
infinite number of times.
• The loop that does not stop executing and processes the statements number of times is called as
an infinite loop.
• An infinite loop is also called as an "Endless loop." Following are some characteristics of an
infinite loop:
1. No termination condition is specified.
2. The specified conditions never meet.

• The specified condition determines whether to execute the loop body or not.
C' programming language provides us with three types of loop constructs:

• 1. The while loop Sr.


No
. Loop Type Description
1. While Loop In while loop, a condition is evaluated before
processing a body of the loop. If a condition
• 2. The do-while loop is true then and only then the body of a loop
is executed.

2. Do-While In a do...while loop, the condition is always


Loop executed after the body of a loop. It is also
• 3. The for loop called an exit-controlled loop.

3. For Loop In a for loop, the initial value is performed


only once, then the condition tests and
compares the counter to a fixed value after
each iteration, stopping the for loop when
false is returned.
While Loop in C

It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the loop.
If a condition is true then and only then the body of a loop is executed.
After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true,
the same process is executed until the condition becomes false.
Once the condition becomes false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately after the loop. The body of a loop can
contain more than one statement.
If it contains only one statement, then the curly braces are not compulsory. It is a good practice though to use the curly
braces even we have a single statement in the body.
In while loop, if the condition is not true, then the body of a loop will not be executed, not even once. It is different in do
while loop which we will see shortly.
While Loop in C
• #include<stdio.h>
• #include<conio.h>
• A while loop is the most • int main()
straightforward looping structure. •{
While loop syntax in C programming • int num=1; //initializing the variable
language is as follows: • while(num<=10) //while loop with condition
• {
• printf("%d\n",num);
• Syntax of While Loop in C: • num++; //incrementing operation
• while (condition) { • }
• return 0;
• statements; •}
•} Output:1 2 3 4 5 6 7 8 9 10
Do-While loop in C
• A do...while loop in C is similar to the while loop except that the condition is always executed after the body of a
loop. It is also called an exit-controlled loop.
• As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to
execute a body of the loop at least once even if the condition is false. This type of operation can be achieved by
using a do-while loop.

• In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it
checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is
transferred out of the loop.

• Similar to the while loop, once


• the control goes out of the loop the statements which are immediately after the loop is executed.

• The critical difference between the while and do-while loop is that in while loop the while is written at the
beginning. In do-while loop, the while condition is written at the end and terminates with a semi-colon (;)
Syntax of Do-While Loop in C: Program

• do { • #include<stdio.h>
• statements
• #include<conio.h>
• } while (expression);
• int main()
Ouput: •{
•2 • int num=1; //initializing the variable
•4
• do //do-while loop
•6
•8 • {
• 10 • printf("%d\n",2*num);
• 12 • num++; //incrementing operation
• 14
• 16
• }while(num<=10);
• 18 • return 0;
• 20 •}
For loop in C

• A for loop is a more efficient loop structure in 'C' programming. The


general structure of for loop syntax in C is as follows:
• Syntax of For Loop in C:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
The initial value of the for loop is performed only once.
The condition is a Boolean expression that tests and compares the counter to a fixed value after each
iteration, stopping the for loop when false is returned.
The incrementation/decrementation increases (or decreases) the counter by a set value.

• #include<stdio.h> • Output
• int main() 1
•{ 2
• int number; 3
• for(number=1;number<=10;number++) 4
//for loop to print 1-10 numbers
5
• {
6
• printf("%d\n",number); //to print the
number 7
• } 8
• return 0; 9
•} 10
Operators

• C provides a rich set of operators to manipulate data. We can divide


all the C operators into the following groups
• Arithmetic Operators
• Unary Operator
• Relational Operators
• Logical Operators
• Assignment Operator
• Bitwise Operators
Arithmetic Operators
• The following table list arithmetic operators
• Operator Description Example
•+ Addition A+B
•- Subtraction A - B
•* Multiplication A * B
•/ Division A/B
•% Modulus A%B
/* Example to understand Arithmetic operator */

• #include<stdio.h>
• #include<conio.h> • Output:
• void main() • a + b = 13
•{
• int a = 10, b=3; •a-b=7
• printf("a + b = ", (a + b) ); • a * b = 30
• printf("a - b = ",(a - b) );
• printf("a * b = ",(a * b) );
•a/b=3
• printf("a / b = ",(a / b) ); • a% b = 1
• printf("a % b = ",(a % b) );
•}
Unary Operators
• the following are the unary operators

• Operator Description Example


•+ Unary plus operator +A
•- Unary minus operator -A
• ++ Increment operator ++A or A++
• -- Decrement operator --A or A--
• ++ and - - works in two different modes
• i.Pre increment/decrement – When it is part of a statement,
increment/decrement gets evaluated first, followed by the execution
of the statement.
• ii.Post increment/decrement – When the operator is part of a
statement, the statement gets processed first, followed by
increment/decrement operation.
// Example for pre increment/decrement
• #include<stdio.h> • Output:
#include<conio.h>
• void main() • a++ = 11
• { • b-- = 2
• int a = 10,
• b=3;
• printf("a++ = ", (a ++) );
• printf("a - - = " , (a - -) );
•}
Relational Operators
• Relational operators are used to test condition and results true or false value, The following table lists
relational operators
• Operator Description Example
• == Two values are checked, and if equal, then the condition becomes true (A == B)

• != Two values are checked to determine whether they are equal or not, and if not equal, then the condition becomes
true (A != B)

• > Two values are checked and if the value on the left is greater than the value on the right, then the condition
becomes true. (A > B)

• < Two values are checked and if the value on the left is less than the value on the right, then the condition becomes
true (A < B)

• >= Two values are checked and if the value on the left is greater than equal to the value on the right, then the condition
becomes true (A >= B)

• <= Two values are checked and if the value on the left is less than equal to the value on the right, then the condition
becomes true (A <= B)
/* Example to understand Relational operator
*/
• #include<stdio.h>
• #include<conio.h> • Output:
• void main() • a == b = false
•{
• int a = 10, b=20;
• a != b = true
• printf("a= = b=", (a ==b) ); • a > b = false
• printf("a !=b= " , (a!=b) );
• printf(“a>b=”,(a>b));
• a < b = true
• printf(“a>=b=”,(a>=b)); • b >= a = true
• printf(“a<b=”,(a<b));
• b <= a = false
• printf(“a<=b=”,(a<=b))
•}
Logical Operators
• Logical operators are used to combine more than one condition. The
following table lists logical operators
Operator Description
Example

&& This is known as Logical AND & it combines (A && B) is false


two variables or expressions and if and only
if both the operands are true, then it will
return true

|| This is known as Logical OR & it combines (A || B) is true


two variables or expressions and if either
one is true or both the operands are true,
then it will return true

! Called Logical NOT Operator. It reverses the !(A && B) is true


value of a Boolean expression
Example

• #include<stdio.h> • Output:
• void main() • a && b = false
•{ • a || b = true
• boolean a = true; • !(a && b) = true
• boolean b = false;
• printf("a && b = " + (a&&b) );
• printf("a || b = " + (a||b) );
• printf("!(a && b) = " + !(a && b) );
•}
Assignment Operator

• Simple Assignment =, assigns right hand side value to left hand side variable Ex: int a; a = 10;

• Compound Assignment
• +=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=, assigns right hand side value after the computation to left
hand side variable

• Ex:
• int a;
• int b;
• a += 10; // means a = a + 10;
• a &= b; // means a = a & b;
Bitwise Operators
• Bitwise operator act on integral operands and perform binary
operations. The lists of bitwise operators are

i Bitwise AND &


ii Bitwise OR |
iii Bitwise EXOR ^
iv Bitwise NOT ~ (unary operator)

V Shift Left <<


Vi Shift Right >>
Bitwise AND
• The & operator compares corresponding bits between two numbers
and if both the bits are 1, only then the resultant bit is 1. If either one
of the bits is 0, then the resultant bit is 0.
• Example : int x = 5;
int y = 9;
x&y=1

• 5-> 0101
• 9-> 1001
• --------
• 0001
Bitwise OR
• The | operator will set the resulting bit to 1 if either one of them is 1.
It will return 0 only if both the bits are 0.
• Example :
int x = 5;
int y = 9;
x | y = 13
5 - >0 1 0 1
9 - >1 0 0 1
---------
1101
Bitwise EXOR

• The ^ operator compares two bits to check whether these bits are
different. If they are different, the result is 1.
• Otherwise, the result is 0. This operator is also known as XOR operator.
• Example :
int x = 5; 5-> 0101
int y = 9; 9-> 1001
x | y = 12 -------------------------
1 1 1 0
example

• #include<stdio.h>
• Output:
• void main()
•{ • x&y=1
• int x = 5; • x | y = 13
• int y = 9;
• x ^ y = 12
• int a = x & y; int b = x | y; int c = x ^ y;
• printf("x & y = "+a);
• printf(" x | y = "+b);
• printf("x ^ y = "+c);
•}
Bitwise NOT
• The negation ~ operators complements all the bits, 1 are converted to
0 and 0s are converted to 1s.
• For Eg. int a =5;
~a = -5
5 -> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
~5 - > 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0
• Shift Operators
The shift operators (<< and >>) shift the bits of a number to the left
or right, resulting in a new number. They are used only on integral
numbers (and not on floating point numbers, i.e. decimals).
Shift Right
• The right shift operator(>>) is used to divide a number in the multiples of 2, while the left
shift operator(<<) is used to multiply a number in the multiples of 2.
For Eg.
int x = 16; x = x >> 3;
• right shift operator >>, divides by 2 to the power of number specified after the operator. In
this case, we have 3 as the value after the right shift operator. So, 16 will be divided by the
value 2 to the power of 3, which is 8.
• The result is 2.
• When we represent 16 in binary form, we will get the following binary value :
• 0 0000000000000000000000000010000
• When we apply >> which is the right shift operator, the positions to the right (represented by
the number after the binary digit 1, we will get : bit represented by 1 moves by 3 right
shift operator). After shifting
• 00000000000000000000000000000010
Shift Left
• Eg.
int x = 8;
x = x << 4;
• left shift operator <<, multiplies by 2 to the power of number specified after the operator.
In this case, we have 4 as the value after the left shift operator. So, 8 will be multiplied by
the value 2 to the power of 4, which is 16.
• The result is 128. When we represent 8 in binary form, we will get the following binary
value:
• 00000000000000000000000000001000
• When we apply << which is the left shift operator, the positions to the left (represented by
the number after the binary digit 1, we will get : bit represented by right shift operator).
1 moves by 4 After shifting
• 00000000000000000000000010000000
example

• X=128 • Output:
#include<stdio.h> • The original value of x is 8
Void main() { • After using << 2, the new value is
int x =8; 2 After using >> 4, the new value
printf("The original value of x is “,x); is 128
printf("After using << 2, the new
value is “,x << 2);
printf("After using >> 4, the new
value is “, x >> 4); }
Assignment Questions

• Write a C program to check whether the number is palindrome


number or not a palindrome number.
Test Data : Input a three digit number : 121
Expected Output : The given number is : 121
The given number is palindrome number
• Write a program in C to calculate factorial of a given number.
Test Data : Input the given number :5
Expected Output : The factorial of a given number is : 120

You might also like