PSC Unit 1
PSC Unit 1
Course Objectives:
• To learn the fundamentals of computers.
• To understand the various steps in program development.
• To learn the syntax and semantics of C programming language.
• To learn the usage of structured programming approach in solving problems.
Course Outcomes:
At the end of the Course the students will be able to:
• Apply the fundamentals of computer and programming language, to draw flow chart, algorithm to solve
given program.
• Comprehend the general structure of C program using control structures, functions, recursion to support
reusability.
• Apply searching and sorting algorithms for the given list of elements
• Design an application to solve real world problem.
Module- 1: INTRODUCTION
Introduction to components of a computer: Memory, processor, I/O Devices, storage, operating system;
Concept of assembler, compiler, interpreter, loader and linker.
Idea of Algorithms: Algorithms, Flowcharts, Pseudo code with examples, from algorithm to Programs and
Source Code.
Introduction to C Programming Language: History of C, Basic structure of a C program, Process of compiling
and running a C program; C Tokens: Keywords, Identifiers, Constants, Strings, Special symbols, Variables, Data
types; Operators, Precedence of Operators, Expression evaluation, Formatted Input/Output functions, Type
Conversion and type casting.
TEXT BOOKS:
1. Byron Gottfried, “Programming with C”, Schaum's Outlines Series, McGraw Hill Education, 3rd Edition, 2017.
2. Reema Thareja, “Programming in C”, Oxford university press, 2nd Edition, 2016.
UNIT -I
INTRODUTION TO
COMPONENTS OF A
COMPUTER
SYSTEM
Programming for Problem Solving 2
INTRODUCTION TO PROGRAME
A Programe is a set of instructions given to the computer to do various tasks what the user wishes too.
The instructions can be in the form of commands also. A Program(or) Instructions (or) commands are given by
the user to computer to fulfill the desired task. As computer cannot understand human language so it needs the
translators like compiler, interpreter, assembler to convert the human language of instructions to binary.
Definition Of Computer:
• It is a high speed electronic device .
• It helps to store large volumes of data safely and securely & retrieves it whenever required by the
user.
• It receives input from user through input devices, process it, and sends output through output
devices to user again
Computer Systems :
• It is made up of 2 major components They are:
1) Hardware 2) Software
Computer Hardware :
• These are the physical components of a computer.
Programming for Problem Solving 3
• It consists of 5 Parts
1. Input Devices
2. Output Devices
3. CPU
4. Primary Storage
5. Secondary Storage
1. Input Devices
2. Output Devices
3. CPU
4. Primary Storage
5. Secondary Storage
Input Devices
• These are used to enter data and programs into the computer
Ex: Keyboard, mouse, scanner, touch screen, audio input, Digitizer, light pen, joysticks,
Programming for Problem Solving 4
Track ball, Space ball, z-mouse, Digital Camera, Microphone, finger print reader, barcode
reader, Data Glove, web cam,
Output Devices
• These are used to get the desired output from the computer
• If the output is printed on a paper using printer then it is called “hard copy”
• It consists of 3 parts
3. Memory
1.1.1 Disks
Programming for Problem Solving 5
A disk is a hard or floppy round, flat, and magnetic platter capable of having information read from and written
to it. The most commonly found disks with a computer are the hard disks and floppy disks (floppy diskette)
shown in the picture to the right.
Hard drives
A hard-disk drive (HDD) is a non-volatile device used for storage, located inside the computer case. Like the
floppy drive, it holds its data on rotating platters with a magnetic upper exterior which are changed or read by
electromagnetic tipped arms that move over the disk as it spins.
1.1.2 Memory
A memory is just like a human brain. It is used to store data and instructions. The memory is divided into large
number of small parts called cells. Each location or cell has a unique address, which varies from zero to
memory size minus one. For example, if the computer has 64k words, then this memory unit has 64 * 1024 =
65536 memory locations. The address of these locations varies from 0 to 65535.
• Memory is used for storage of data and programs. It is divided into 2 parts.
3. Cache Memory
1. Primary Memory :
• It is also called main memory or volatile memory.
• Data is stored temporarily i.e. data gets erased when computer is turned off.
• Faster than secondary memories.
• A computer cannot run without the primary memory
• Ex: RAM , ROM
Programming for Problem Solving 6
• Long life
• No need to refresh
• Faster
• Used as cache memory
• Large size
• Expensive
• High power consumption
b) DRAM (Dynamic Random Access Memory)
• DRAM is used for most system memory as it is cheap and small.
• All DRAMs are made up of memory cells, which are composed of one capacitor and one transistor.
Characteristics of Dynamic RAM
• Non-volatile in nature
• Cannot be accidentally changed
• Cheaper than RAMs
• Easy to test
• More reliable than RAMs
• Static and do not require refreshing
• Contents are always known and can be verified
Programming for Problem Solving 8
RAM is a volatile memory. It means that the data ROM is permanent memory. Data in ROM will stay
4.
in RAM will be lost if power supply is cut-off as it is even if we remove the power-supply
There are mainly two types of RAM; static There are several types of ROM; Erasable ROM,
5.
RAM and Dynamic RAM Programmable ROM, EPROM etc.
RAM stores all the applications and data when the ROM usually stores instructions that are required for
6. computer is up and running starting (booting) the computer
8. RAM chips are bigger in size ROM chips are smaller in size
3. Cache memory
• It is placed between the CPU and main memory, to operate at the speed of the CPU.
Advantages
• It stores the program that can be executed within a short period of time.
Disadvantages
• It is very expensive.
Access time is higher than secondary Access time is lower than primary
Access time
memory memory
Accessible It is directly accessible to the CPU It is not directly accessible to the CPU
1.1.3 PROCESSOR :
• A processor is an intExrated electronic circuit that performs the calculations that run a computer.
• A processor performs arithmetical, logical, input/output (I/O) and other basic instructions that are
passed from an operating system (OS).
1. System software
2. Application software
1. System Software:
• They constitute set of programs that manage the hardware resources of a computer
• It is divided into 3 types.
Operating System
• It acts as an interface between the user and the hardware
• It makes the system to operate in an efficient manner. Ex: MS DOS, Windows, UNIX, LINUX,
etc.
System Support
System Development
It includes
a) Language translators – Used for converting programs into machine language
b) Debuggers – for error free programs
c) CASE tools – Computer Assisted Software Engineering Tools
Programming for Problem Solving 12
2. Application Software
• It contains programs for performing tasks
Application
Software
General Application
purpose Specific
▪ It can be used only for intended purpose i.e. for which they were designed
Hardwa
• It is a Translator.
• A compiler is a software program which is used to convert human readable code into machine
understandable code.(Or)
• It’s a computer program which reads source code and outputs assembly code or executable code is
Programming for Problem Solving 13
called compiler.
• It Scans the entire program once and translates it as a whole into machine code.
• It reduces the execution time, it is the fastest translator.
• It generates the error message only after scanning the whole program. Hence debugging is
comparatively hard.
• Programming language like C, C++ use compilers.
• There are 4 steps for converting a ‘C’ program into machine language.
• Users can enter, change and store character data using text editors
• After writing the program, the file is saved to disk. It is known as ‘sourcefile’
• “Compiler” is a software that translates the source file into machine language
a) Preprocessor
b) Translator
a) Preprocessor
• It scans for special instructions known as ‘preprocessor’ commands which start with ‘ #’
symbol
• These commands tell the preprocessor to look for special code libraries and make
substitutions
b) Translator
• It does the actual work of converting the program into machine language
• It reads the translation unit and results in ‘object module’ i.e., code in machine language
• But it is not yet executable because it does not have the ‘C’ and other functions included.
Programming for Problem Solving 15
3) Linking programs
• ‘Linker’ assembles input /output functions, mathematical library functions and some of the
functions that are part of source program into final executable program. It is called as executable
file that it is ready for execution.
4) Executing Programs
• ‘Loader’ is the software that gets the program that is ready for execution into the memory
• When everything is loaded, the program takes control and the ‘Runner’ bExins its execution.
• In the process of execution, the program reads the data from the user, processes the data
and prepares the output.
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
5. Effectiveness: Each step of the algorithm must be easily convertible into program statements
1.2.2 Frequently used mnemonics in algorithm:
• Start = this label in algorithm indicates starting the task
• Repeat =do the step, logic or process for some time till condition gets failed
• goto=it states that control should go to a specific label and then start its execution
• break = it’s a termination point i.e control has to come out of the block or loop where the break is
specified
• Continue = When a continue statement is encountered inside a loop, control jumps to the bExinning
of the loop for next iteration, skipping the execution of statements inside the body of loop for the
current iteration.
• If-then-else= this decision making statement is used when we have two choices for selection
• Stop=This indicates end of algorithm
Programming for Problem Solving 26
Example-1
1. start
6. Stop
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)
Algorithm:
Step 1: Read temperature in Fahrenheit,
Step 2: Calculate temperature with formula C=5/9*(F-32),
Step 3: Print C,
➢ Arrows are used for connecting the symbols and show the flow of execution
Disadvantage :
1. Drawing flowchart for complex logic programs is difficult.
Programming for Problem Solving 27
2. If alterations are required the flowchart may require re-drawing completely. This will usually waste
valuable time.
Example 1:
help the programmer “think out” a program before attempting to write it in a programming language such
as C.
Advantages:
Disadvantages:
• It is not visual.
• We do not get a picture of the design
1) Requirements
2) Analysis
3) Design
4) Coding
5) Testing
6) Maintenance
❖ Requirements
• Main objective of this phase is to eliminate unimportant aspects and identify the root problem
❖ Analysis
• It involves identifying the problem inputs, outputs, that the program must produce
• Designing the ‘algorithm’ is to develop a list of steps called algorithm to solve the problem and
then verify that the algorithm solves the problem intended.
• “Top – down design” is followed i.e. list the major steps (or) sub problems that need to be solved
• “Flow charts” are used to get the pictorial representation of the algorithm.
• Algorithm for a programming problem consists of at least the following sub problems
❖ Coding / Implementation
• This step involves writing algorithm as a program by selecting any one of the high – level
languages that is suitable for the problem.
Programming for Problem Solving 31
• Each step of the algorithm is converted into one (or) more statements in a programming language.
❖ Testing
• Checking / verifying whether the completed program works as desired is called “ Testing”
• Running the program several times using different sets of data verifies whether a program
works correctly for every situation provided in the algorithm.
• After testing, the program must be free from the following errors.
a) Syntax errors
b) Logical errors
c) Run-time errors
❖ Maintenance
• It involves modifying a program to remove previously undetected errors and to keep it up-to-
date as government rExulations (or) company polices change.
• Many organizations maintain a program for some period of time i.e. 5 years.
⚫ It was primarily developed for systems programming i.e. for designing operating systems, compilers etc
1.3.1 Importance of ’C’ Language
1. It is a robust language, whose rich set of built-in functions and operations can be used to write any
complex program
2. The ‘C’ compiler combines the capabilities of an assembly language with the features of a high-level
language and therefore it is well suited for writing both system software and business packages.
3. ‘C’ Programs are efficient and fast, this is because it has variety of data types and powerful
operators
4. C is highly portable, that is c programs written for one computer can be run on another w ith little (or)
no modification.
5. ‘C’ Language is well suited for structured programming, thus requiring the user to think of a problem
in terms of function modules (or) blocks. The proper collection of these module make a complete
program. This modular structure makes program debugging, testing and maintenance easier.
6. ‘C’ program has the ability to extend itself. A 'c' program is basically a collection of functions that are
supported by the 'C' library. we can add our own functions to 'C' library..
7. 'C' is highly portable .I.e. 'C' programs written for one computer can be run on another with little or no
modifications .portability is important if we to run a program on a new computer with different
operating system. I.E "C " is a machine independent language.
8. 'C' is high-level language which allows the programmer to concentrate on the problem with out worry
about the machine that program will be using.
1.3.2 Data Types
Data Types
❖ Data type specifies the set of values and the type of data that can be stored in a variable.
❖ They allow the programmer to select the type appropriate to the needs of application.
Types: ANSI supports 3 classes of data types namely
Primary data type/fundamental data type/ Basic data type
1) Derived data type
2) User-defined data type
Programming for Problem Solving 33
i) Real:
Programming for Problem Solving 35
ii) Imaginary:
It is real number multiplied by root of -1
It has 3 different size of imaginary types
a. float imaginary
b. double imaginary
c. long double imaginary
iii) Complex type
--It is combination of real and an imaginary number
-- It have 3 different sizes
a. float complex
b. double complex
c. long double complex
While writing c programs, errors (also known as bugs) may occur unwillingly which may prevent the program
to compile and run correctly as per the expectation of the programmer.
1. Runtime Errors
Programming for Problem Solving 36
2. Compile Errors
3. Logical Errors
1. Runtime Errors:
C runtime errors are those errors that occur during the execution of a c program and generally occur due to
some illExal operation performed in the program.
Examples of some illExal operations that may produce runtime errors are:
Compile Errors: Compile errors are those errors that occur at the time of compilation of the program. C
compile errors may be further classified as:
o Syntax Errors
o Semantic Errors
• Syntax Errors:
A collection of rules for writing programs in a programming language is known as syntax.When the rules of the
c programming language are not followed, the compiler will show syntax errors.A program containing syntax
error cannot be compiled successfully.
The above statement will produce syntax error as the statement is terminated with : rather than ;
• Semantic Errors
Semantic errors are reported by the compiler when the statements written in the c program are not meaningful to
the compiler.
In the above statement we are trying to assign value of a in the value obtained by summation of b and c which
has no meaning in c. The correct statement will be
1a=b+c;
• Logical Errors
Logical errors are the errors in the output of the program. The presence of logical errors leads to undesired or
incorrect output and are caused due to error in the logic applied in the program to produce the desired output.
Also, logical errors could not be detected by the compiler, and thus, programmers have to check the entire
coding of a c program line by line.
A operator is a symbol that tells the computer to perform certain mathematical (or) Logical manipulations.
An operator indicates the operation to be performed on data that yields a value.
C Operators can be classifieds into
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment & Decrement Operators
6. Conditional Operators
7. Bitwise Operators &
8. Special Operators
1) Arithmetic operators:
❖ These operators are used for numerical calculations (or) to perform arithmetic operations like addition,
Programming for Problem Solving 38
subtraction etc.
❖ Arithmetic Operator involving only real operands is called “ Real Arithmetic”
❖ When one of the operands is real and other is integer then expansion is called as “ Mixed – Mode
arithmetic Expression “"
2) Relational operators:
The comparisons can be done with relational operators .
C supports six relational operators .
The output of relational expression is either one or zero (i.,e True or False).
Programming for Problem Solving 39
here arg1 & arg2 are arithmetic expressions which may be simple constants variables or combination of
them .
The output of a relational expression is either true (1) (or) false (0)
Operator Description Examble a =10, b=20 output
< less than a<b 10<20 1
<= less than (or) equal to a<=b 10< = 20 1
> greater than a>b 10>20 0
>= greater than (or) equal a>=b 10> =20 0
to
== equal to a= =b 10 = = 20 0
!= not equal to a! = b 10 ! =20 1
Table 1.21: Relational Operators
❖ Program to demonstrate relational operators
main ( ) Output
{
3) Logical operators:
C has three logical operators namely
- Logical AND (&&)
- Logical OR (||)
- Logical NOT(!)
Logical Operators && and || used when we want to test more than one condition
Logical expression will yield a value i.e. either one or zero (true or false)
❖ These are used to combine 2 (or) more expressions logically
Logical AND ( && )
T T T
T F F
F T F
F F F
Table 1.22: Logical AND ( && )
T T T
T F F
F T F
F F F
exp !(exp)
T F
F T
}
4) Assignment operators:
It is used to assign the result of an expression to a variable.
Types :
⚫ Simple Assignment
⚫ Compound Assignment
4: x/=y+1
x= x/(y+1)
5: x%=y
x= x%y
❖ Increment operator is placed after the operand in post increment and the value is incremented
after the operation is performed
Ex: z = a++;
first: z=a
second: a= a+1
❖ decrement operator is placed after the operand in post decrement and the value is decremented after the
operation is performed
Program: main ( )
main ( ) {
{
int a= 10, z;
int a= 10, z;
Output
z= --a Output z= a--;
z=10
printf (“z= %d”, z); z=9 printf (“z= %d”, z); a=9
printf (“ a=%d”, a); a =9
printf (“a=%d”, a);
}
}
Programming for Problem Solving 44
Conditional Operators:
A ternary operator pair “ ? : ” is used to construct conditional expressions.
Syntax:
exp1 ? exp2 : exp3;
int a=10;
float b=20 ;
printf (“ a= %d b=%f’, a,b );
printf (“ Adderss of a =%u “ &a ) ;
printf (“ Adderss of b =%u” &b ) ;
printf (“Size of a = %d ” , sizeof (a) ) ;
printf ( “ Size of b = %d ” . sizeof (b) ) ;
} a b
Output : 10 20.00
Precedence:
The order in which the operators in a complex expression are evaluated is determined by a set of priorities
known as precedence.
Programming for Problem Solving 49
Associativity :
Associativity is used to determine the order in which operators with same precedence are evaluated in
complex expression
Associativity can be i) Left to Right. ii) Right to left .
i) Left to Right associativity evaluates the expression by starting on left and moving to the
right side of expression.
ii) Right to Left associativity evaluates the expression by starting on right and moving to the
left side of expression.
Side effect:
A side effect is an action that results from the evaluation of a expression..
Ex: int x=3;
x = x+ 4;
here initial value of x is 3 and the value of the expression on right side of assignment is 7 (ie 3+4).so the final
value of x is 7 this is side effect.
Ex 1: evaluate 2+3*4
Since * has high precedence than the + so multiplication is performed first than followed by addition
i.e. 2+ 12---- 14
Ex 2: evaluate –b++ where b=5;
In the above expression both – and ++ are having same precedence i.e 2 nd so we consider associativity for these
operators ,which is left to right…hence given expression is evaluated as –(b++) which yield to 5 and value of b
after completion of expression is 6( since b++ is post increment)
Ex 3: evaluate 3 * 8 / 4 % 4 * 5
Programming for Problem Solving 50
In the given expression all three operators(* / %) are belonging to same precedence and their associativity is
from left to right. so given expression should be evaluated from left to right
i.e. ((((3*8)/4)%4)*5)
(((24/4)%4)*5)
((6%4)*5)
❖ 2*5
❖ 10
Ex 4: Evaluate a+=b*=c-=5 where a=2,b=3 and c=7
In the given expression all assignment operators i.e += ,*=,-= are with same precedence and have associativity
from right to left . So the rightmost expression is evaluated first and the value is assigned to operand on the left
of the assignment operator and next expression is evaluated.
Given expression is a+=b*=c -=5
❖ (a+=(b*=( c-=5)))
❖ (a+=(b*=( c=c-5)))
❖ (a+=(b*=( c=7-5)))
❖ (a+=(b*=2))
❖ (a+=(b=b*2))
❖ (a+=(b=3*2))
❖ (a+=6)
❖ a=a+6
❖ a= 2+6
❖ 8
After the side effect a=8,b=6 and c=2
Ex 5: Evaluate - -a * (3+b) / 2 - c++ * b, where a =3,b=4 and c=5
In the given expression () is having higher precedence so it is evaluated fist
--a*(3+4)/2-c++ *b
• -- a *7/2 -c ++ * b ( in this expression - - and ++ have higher precedence than * / - and
associativity is right to left.)
• --a*7/2 -5*b // post increment takes place after evaluating expression i.e after these ‘c’ value is 6
• 2*7/2 -5 *b // --a is pre decrement so a is decreased by 1
In the above expression operators * / are having same and higher precedence than’ –‘ and their associativity is
left to right so
❖ (2*7)/2 –5 *b
❖ 14/2 – 5*b
❖ 7- 5 *4 // in this expression * has high precedence than – so it is evaluate first
Programming for Problem Solving 51
❖ 7-20
❖ 13
After the side effect a=2 ;b=4 and c=6
Ex6: evaluate x = a - b / 3 + c * 2 -1,where a=9,b=12,c=3
9 - 12 / 3 + 3* 2–1 since / and * have same and high precedence than + and – with
left to right assoiciativity .
❖ Step1: x=9 - 4 + 3* 2 -1
❖ Step2: x= 9 -4 + 6 -1 // - and + have same precedence and left to right Associativity
❖ Step3: x= 5+6-1
❖ Step4:x=11-1
❖ Stept5: x=10
Programming for Problem Solving 50
Output:
5
6
Ex:2:
#include<stdio.h>
void display();
void main()
{
extern int i; i=10
printf(“i=%d”,i);
display();
getch();
return;
}
int i;
void display()
{
printf(“i=%d”,i);
return;
}
Static variables
The value of a static variable persists until the end of the program. A variable can be declared static using the
keyword static like static int x;
A static variable may be either an internal type or an external type depending on the place of declaration.
Internal static variables are those which are declared inside a function. The scope of internal static variables
extends up to the end of the function in which they are defined. Therefore, int ernal static variables are similar to
auto variables, except that they remain in existence (alive) throughout the remainder of the program. Therefore,
internal static variables can be used to retain values between function calls. For example it can be used to count
the number of calls made to a function.
Ex:
void func1 ( void ) ; //function prototpye
void main( )
Programming for Problem Solving 53
{
int i;
for( i = 0; i < 3 ; i ++ )
func1( ); //function call
}
void func1 ( void )
{
static int x = 0;
x=x +1;
printf(“x = %d \n ”, x );
}
Output
x=1
x=2
x=3
A static variable is initialized only once, when the program is compiled. It is never initialized again. During the
first call to func1, x is incremented to 1. Because x is static, this value persists and therefore, the next call adds
another 1 to x giving it a value of 2. The values of x becomes 3 when the third call is made.
If we declared x as an auto variable, the output would have been:
x=1
x=1
x=1
This is because each time func1 is called, the auto variable x is initialized to zero. When the function terminates,
its value of 1 is lost.
An external static variable is declared outside of all functions and is available to all functions in that program.
The difference between a static external variable and a simple external variable is that the static external
variable is available only within the file where it is defined while the simple external variable can be accessed
by other files.
Rexister variables
Keyword : rExister
❖ RExister variables values are stored in CPU rExisters rather than in memory where normal variables are
stored.
❖ RExisters are temporary storage units in CPU .
Programming for Problem Solving 54
❖ The time required to access rExister value is less than values stored in memory.
Restriction on RExister variables:
i) RExister variable address is not available to user.
ii) We can not use address operator(&) and indirect operator (*) on rExister variable.
iii) RExistered variables does not allow implicit conversions.
Ex:
main ( )
{
rExister int i;
for (i=1; i< =5; i++)
printf (”%d ”,i);
}
Output: 1 2 3 4 5
1.3.7 Type conversions
Converting one data type into another is the concept of type conversion
2 types
1. Implicit type conversion
2. Explicit type conversion
1) Implicit type conversion
❖ ‘C ‘ compiler converts one data type to another automatically so that expression can be evaluated
without losing any significance. This automatic conversion is known as “implicit type conversion”
❖ Implicit type conversion is automatically done by the compiler by convert ing smaller data type into a
larger data type.
❖ During the evaluation , ‘C’ uses a rule that in all expressions except in assignment, any implicit type
conversion are made from lower size type to higher size type as shown below
Programming for Problem Solving 55
int float
float
int
Here, the resultant of ‘a+b’ is converted into ‘into’ explicitty and then assigned to ‘c’
Example for Explicit conversion :
main ( )
{
Output
printf (“%d”, 5/2); printf 2
(“%f”, 5.5/2); printf 2.75
(“%f”, (float) 5/2); 2.5
}
Programming for Problem Solving 57
or
▪ argc (ARGument Count) is int and stores number of command-line arguments passed by the user
including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for
argument and one for program name)
▪ The value of argc should be non nExative.
▪ argv(ARGument Vector) is array of character pointers listing all the arguments.
▪ If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings.
▪ Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line
arguments.
Example:
return 0;
}
Programming for Problem Solving 58
| Bitwise OR
^ Bitwise XOR
~ One’s complement
a b a &b
0 0 0
0 1 0
1 0 0
1 1 1
a b a|b
0 0 0
0 1 1
1 0 1
Programming for Problem Solving 59
1 1 1
a b a ^b
0 0 0
0 1 1
1 0 1
1 1 0
8 4 2 1 8 4 2 1
a =12 1 1 0 0 a =12 1 1 0 0
b =10 1 0 1 0 b =10 1 0 1 0
a &b 1 0 0 0 a|b 1 0 1 0
a&b = 8 a | b = 14
8 4 2 1 a^b
a =12
1 1 0 0
b =10 1 0 1 0
a ^b 0 1 1 0
a^b=6
Program
Output
main ( )
{ 8
Left Shift
❖ If the value of a variable is left shifted one time, then its value gets doubled
❖ eg: a = 10 then a<<1 = 20
32 16 8 4 2 1
a=10
1 0 1 0
a<<1 = 20
Formula: n * 2s where n is the given number and s in the number of shifts.
Example: left shift 4 by 2 (i.e 4<<2),here n=4 and s=2 then result is 16 i.e(4* 2 2 )
Right shift :
If the value of a variable is right shifted one time, then its value becomes half the original value
❖ eg: a = 10 then a>>1 = 5
8 4 2 1
a=10
1 0 1 0
a>>1 0 Discard it
1 0 1
a>>1 = 5
formula: n / 2s where n is the given number and s in the number of shifts.
Example: Right shift 4 by 2 (i.e. 4>>2),here n=4 and s=2 then result is 1 i.e.(4 / 22 )
Ones complement
❖ If converts all ones to zeros and zeros to ones
❖ Ex: a = 5 then ~a=2 [only if 4 bits are considered]
8 4 2 1
a=5
1 0 1 ~a
0 1 0 ~a = 2
Programming for Problem Solving 61
Program
main ( ) Output
{ 40
int a= 20, b = 10,c=10;
5
printf (“ %d”, a<<1);
printf (“ %d”, b>>1); 11
printf (“ %d”, ~c);
}
Signed
1’s complement = - [ give no +1]
Eg : ~10 = - [10+1] = -11
~-10 = - [-10+1] = 9
unsigned
1’s complement = [65535 – given no]