You are on page 1of 238

Computer Fundamentals and

C Programming

Prashant Kumar
CSED
NITJ

1
What Is A Computer?
A computer is an electronic device,

• Accepts input

• Processes data

• Stores data

• Produces output

2
Hardware Devices that comprise a computer system

Monitor
Speaker
(output)
(output) System unit
(processor, memory…)

Printer
(output)

Storage devices
(CD-RW, Floppy,
Hard disk, zip,…)
Mouse
(input)
Scanner
Keyboard
(input)
(input)

3
Types of Computers

4
6
I/O Components

7
CPU

8
CPU
■ The CPU is a silicon chip that contains millions
of tiny electrical components.

■ The CPU’s three main parts are:


■ Control Unit
■ Arithmetic Logic Unit (ALU)
■ Registers

9
Performs calculations and
decisions
Arithmetic / Logic Unit

Coordinates
Control Unit processing steps

Small, fast storage


Registers areas for
instructions and
data

10
11
Computer Components: Top Level View
Registers
▪ Registers are small, fast memory within the CPU
▪ Different registers hold different things like
instructions and addresses of instructions, data
(operands) and results of operations
Two types
1. Special Purpose Registers contain specific
information the CPU needs.
▪ Instruction Register (IR) contains the actual
instruction which is currently being executed by
the CPU.
• The Program Counter (PC) contains the address
of the next instruction to be executed by the
program.
2.General Purpose Registers hold:
▪ the operands for arithmetic and logical operations (ie.
the values on which the operation will be performed)
▪ the results of such operations
▪ So General Purpose Registers are used for holding and
manipulating data used by the CPU 14
Memory

15
Memory
Computer Memory : millions/billions of on/off charges
• Bits: 0 or 1
• Bytes: Groups of 8 bits, A byte is the smallest unit of storage.
(Can hold one text character)
• Words: Groups of bits/bytes (8, 16, 32, 64-bits)
Storage is usually too large to be expressed in bytes or
words.
▪ Kilobyte (KB) = 1024 bytes (210 bytes)
▪ Megabyte (MB) = 1024 x 1024 bytes or one million bytes (220
bytes)
▪ Gigabyte (GB) = 1024 x 1024 x 1024 bytes or 1 trillion bytes
(230 bytes)
▪ Terabyte (TB) = 1024 x 1024 x 1024 x 1024 bytes one
quadrillion bytes (240 bytes)
16
Memory
• What is the difference between followings:
– RAM
– CACHE
– SSD
– HDD
– OPTANE MEMORY
MEMORY CLASSIFICATION
Registers
2ns
Cache (I, II, III)
Volatile SRAM
DRAM
Primary SDRAM
(Semiconductor – RAM EDRAM
chip). Main Memory
EDO
Memory Types & FLASH RAM
Storage Devices PROM
Non-volatile EPROM
ROM EEPROM
Tape
Magnetic memory HD, Zip Disk
Secondary FDD
(Devices)
Optical
CD-ROM, CD-R, CD-RW
Memory DVD-ROM, DVD-R 5ms
DVD- RW
Memory
PRIMARY MEMORY: RAM AND ROM
▪ The CPU accesses each location in memory by using a unique
number, called a memory address.
Main Memory

Each memory cell 5248 Each memory cell stores a


has a numeric 5249 set number of bits (some
10011010
address, which 5250 computers use 8 bits/one
uniquely identifies its 5251 byte, others use words)
location 5252
5253 A word is stored in
5254 consecutive
5255 memory bytes.
5256
Random Access Memory
(RAM) –
• It is also called as read write memory or
the main memory or the primary memory.
• The programs and data that the CPU
requires during execution of a program are
stored in this memory.
• It is a volatile memory as the data loses when
the power is turned off.
– RAM is further classified into two types- SRAM
(Static Random Access Memory) and DRAM
(Dynamic Random Access Memory).
Read Only Memory (ROM) –
• Stores crucial information essential to
operate the system, like the program
essential to boot the computer.
– It is not volatile.
– Always retains its data.
• Used in embedded systems or where the
programming needs no change.
• Used in calculators and peripheral
devices.
Types of Read Only Memory
(ROM) –
• PROM (Programmable read-only memory) – It
can be programmed by user. Once programmed,
the data and instructions in it cannot be changed.

• EPROM (Erasable Programmable read only


memory) – It can be reprogrammed. To erase
data from it, expose it to ultra violet light. To
reprogram it, erase all the previous data.

• EEPROM (Electrically erasable programmable


read only memory) – The data can be erased by
applying electric field, no need of ultra violet light.
We can erase only portions of the chip.
Secondary Storage Devices
▪Storage devices hold data, even when the
computer is turned off.
▪The physical material that actually holds
data is called a storage medium. The
surface of a floppy disk is a storage
medium.
▪The two primary storage technologies are
magnetic and optical.

27
Secondary Storage Devices

▪ Magnetic Storage Devices


• Diskettes (floppy disks) (FDD)
• Hard disks (HD)
• USB flash drive
• Magnetic tape

▪ Optical Storage Devices


• Compact Disk Read-Only Memory (CD-ROM)
• Digital Video Disk Read-Only Memory
• (DVD-ROM
• CD-Recordable (CD-R)
• CD-Rewritable (CD-RW)
Magnetic Disks
• A read/write head travels across a spinning
magnetic disk, retrieving or recording data

The organization
of a magnetic disk
How Magnetic Storage Works
• https://www.youtube.com/watch?v=3owq
vmMf6No

• https://www.youtube.com/watch?v=wteU
W2sL7bc
Cache Memory

31
Cache Memory
• But as CPU speeds became faster, the main
memory couldn’t provide the CPU with the
instructions at a fast enough rate.
• So even faster memory ( cache memory) is now
placed between the CPU and main memory to
provide the instructions at an quicker rate to the
CPU.
Cache Memory

When an instruction or data is accessed from main memory, it is placed in


the cache. Second and subsequent use of the same instruction/data will
then be faster, since it is accessed directly from the cache.
Cache
L1 and L2 Cache
• Most modern CPUs now have a cache
memory (L1), on the same silicon wafer
as the CPU, to provide the CPU with
instructions at the same clock speed as
the CPU.

• An additional off-the-chip secondary


cache (L2) may also interact with the
CPU at a slower speed.
Main Memory Characteristics
• Very closely connected to the CPU.
• Contents are quickly and easily changed.
• Holds the programs and data that the
processor is actively working with.
• Interacts with the processor millions of times
per second.
• Nothing permanent is kept in main memory.
Secondary Storage
Characteristics
• Connected to main memory through a bus and a
device controller.
• Contents are easily changed, but access is very
slow compared to main memory.
• Only occasionally interacts with CPU.
• Used for long-term storage of programs and data.
• Much larger than main memory (GBs vs. MBs).
CPU interaction with
Memory

39
CPU and Memory
• CPU can interact with main memory in two
ways:
– It can write a byte/word to a given memory location.
• The previous bits that were in that location are
destroyed
• The new bits are saved for future use.
– It can read a byte/word from a given memory location.
• The CPU copies the bits stored at that location and
stores them in a CPU register
• The contents of the memory location are NOT
changed.
Access to Instructions

The hard disk is too slow to provide instructions to the CPU.


So programs are first loaded into main memory, which is much faster.
The CPU can then access the instructions more quickly.
User view of Computer Systems

Applications
e.g. Word, Netscape, etc

Operating System –
- the user interface

Software that
controls the
hardware devices
How Does a Computer Know what
to do?
• It must be given a detailed list of instructions,
called a compute program or software, that
tells it exactly what to do.
• Before processing a specific job, the
computer program corresponding to that job
must be stored in memory.
• Once the program is stored in memory the
compute can start the operation by executing
the program instructions one after the other.

43
**Program**

44
Program
• A computer program is a collection
of instructions that performs a specific task
when executed by a computer.
• Most computer devices require programs
to function properly.

• Program is a sequence of instruction


along with data

45
Programming Language
• A programming language is a formal
language, which comprises a set of
instructions that produce various kinds
of output.

• Programming languages are used


in computer programming to
implement algorithms.

46
Programming paradigms
(models)
• Unstructured

• Structured

• Object oriented

47
Unstructured programming
• Writing small and simple programs
consisting of only one main function in the
program.

• Uses goto statement to jump from any


statement to any other statement (spagetti
code)

48
Structured programming
• A program is broken down into small
independent tasks that are small enough
to be understood easily, without having to
understand the whole program at once.

• When these tasks are completed, they are


combined together to solve the problem.

• Example – C language
49
Object oriented programming
• A style of computer programming which
focuses on objects (actors) and their
private functionality.

• Objects are variables of user defined data


types known as classes which contain
functions and variables. Objects interact
by using message passing.

• C++ and Java are examples of OOP.


50
Components in
Programming

51
What is?
• Editor

• Translator
– Complier
– Assembler
– Interpreter
• Linker
• Loader
Translator
• A translator is a programming language
processor
– that converts a computer program from one
language to another.
• It takes a program written in source code
and converts it into machine code.
• It discovers and identifies the error during
translation.

54
55
Complier
• A compiler is a program that accepts a
source program in a “high-level language
“and produces a corresponding object
program.
Assembler
• Input to an assembler is an assembly
language program.
• Output is an object program plus
information that enables the loader to
prepare the object program for execution.
Loader
• A Loader is a routine that loads an object
program and prepares it for execution.
• In general, the loader must load, relocate
and link the object program.
• Loader is a program that places programs
into memory and prepares them for
execution. The loader places into memory
the machine language version of the
user’s program and transfers control to it.
First Program
#include<stdio.h>
/*first program*/
int main()
{
printf(“Hello-CP”);
return 0;
}

59
Second Program
#include<stdio.h>
/*first program*/
int main()
{
int a;
a=4+7;
printf(“value=%d”,a);
return 0;
} 60
How a simple program (C/C++)
executes??
Flow chart
END

63
Extra Slides

64
Some Basics about CS

65
What happens when we turn on
computer?
• Bootstrap program is loaded at power-up
or reboot
– Typically stored in ROM or EPROM, generally
known as firmware
– Initializes all aspects of system
– Loads operating system kernel and starts
execution
System Boot
• When power initialized on system, execution starts
at a fixed memory location
– Firmware ROM used to hold initial boot code
• Operating system must be made available to
hardware so hardware can start it
– Small piece of code – bootstrap loader, stored in
ROM or EEPROM locates the kernel, loads it into
memory, and starts it
– Sometimes two-step process where boot block at
fixed location loaded by ROM code, which loads
bootstrap loader from disk
• Common bootstrap loader, GRUB, allows
selection of kernel from multiple disks, versions,
kernel options
• Kernel loads and system is then running
What is the difference between
32 bit and 64 bit OS??
Answer
• When talking about CPUs, the number of
bits usually refers to the size of a CPU’s
register. Each register bit can reference a
byte in memory.
• 16 bit computers can reference up to
64KB of RAM and 32 bit computers can
reference up to 4GB of RAM.
• A 64 bit CPU can reference up to 16EB
(8TB) of RAM.
Answer
• In computing, 32-bit and 64-bit are two different
types of processorsIn computing, 32-bit and 64-bit
are two different types of processors. The bit
number (usually 8, 16, 32, or 64) refers to how
much memoryIn computing, 32-bit and 64-bit are
two different types of processors. The bit number
(usually 8, 16, 32, or 64) refers to how
much memory a processor can access from
the CPU register.
• A 32-bit system can access 232 (4,294,967,296)
memory addresses. Practically speaking, a 32-bit
computer is limited to accessing 4,294,967,296
bytes (4 GB) of RAM.
• A 64-bit processor can access 264memory
addresses. This means a 64-bit machine could
What is Clock speed?
• The GHz represents the number of clock
cycles (calculations) a processor can
manage in a second.
• Putting simply, a bigger number means a
faster processor.
What is the difference between:

– I3
– I5
– I7
– I9
PROCESSORS?
I3 I5 i7
No. of Cores 2 2-4 4-8
Turbo Boost N Y Y
Cache size 2-4MB 4-6MB 6-9MB
Hyper-Threading N M Y

Hyper-Threading: This enables a single core to


serve multiple threads.
Why not i2, i4, i6?
Computer Memory Hierarchy

77
Program Concept
▪ Hardwired systems are inflexible
▪ General purpose hardware can do different tasks, given correct
control signals
▪ Instead of re-wiring, supply a new set of control signals
What is a program?
▪ A sequence of steps
▪ For each step, an arithmetic or logical operation is done
▪ For each operation, a different set of control signals is needed
Four important aspects of a
language/program

▪ The way it stores data


▪ The way it operates upon it
▪ How it accomplishes input and output
▪ How it controls the sequence of instructions

3
Introduction to C language
▪ C is a programming language developed at AT & T’s Bell
Laboratories of USA in 1972.
▪ It was designed and written by a man named Dennis Ritchie.
▪ Possibly why C seems so popular is because it is reliable, simple
and easy to use.
▪ A language that has survived for more than 3 decades.
▪ C has been already superceded by languages like C++, C# and Java
so why bother to learn C today???

4
Similar to Natural Languages

C Tokens
Identifiers,
Keywords,
Strings,
operators,
constants, etc. 5
A simplest C Program
main()
{

6
A typical C program
/* Calculation of simple interest */
/* Author gekay Date: 25/05/2004 */
main( )
{
int p, n ; // Variable declaration
float r, si ;
p = 1000 ;
n=3;
r = 8.5 ;
/* formula for simple interest */
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}

7
The C Character Set

8
Keywords
▪ C keywords are the words that convey a special meaning to the c
compiler.
▪ The keywords cannot be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword
which is not allowed.

9
Identifiers
▪ Identifiers are used as the general terminology for the names of
variables, functions and arrays.
▪ There are certain rules that should be followed while naming c
identifiers:
• They must begin with a letter or underscore(_).
• They must consist of only letters, digits, or underscore. No other special
character is allowed.
• It should not be a keyword.
• It must not contain white space.
• It should be up to 31 characters long as only first 31 characters are
significant.
• Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If
• Invalid: 324, short, price$, My Name

10
Identifiers

11
Variables
▪ An entity that may vary during program execution is called a
variable.
▪ Variable names are names given to locations in memory.

12
C Constants
▪ C constants refers to the data items that do not change their value
during the program execution.
▪ Several types of C constants that are allowed in C are:
▪ 1. Integer Constants: numbers without any fractional part. may
contain either + or – sign. No sign is assumed to be positive.
▪ There are three types of integer constants:
▪ 1.1. Decimal Integer Constants
• Integer constants consisting of a set of digits, 0 through 9, preceded by an
optional – or + sign.
• Example of valid decimal integer constants
341, -341, 0, 8972
▪ 1.2. Octal Integer Constants
• Integer constants consisting of sequence of digits from the set 0 through 7
starting with 0 is said to be octal integer constants.
• Example of valid octal integer constants 010, 0424, 0, 0540

13
C Constants
▪ 1.3. Hexadecimal Integer Constants
• Hexadecimal integer constants are integer constants having sequence of digits
preceded by 0x or 0X. They may also include alphabets from A to F
representing numbers 10 to 15.
• Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
▪ 2. Real Constants: The numbers having fractional parts are called
real or floating point constants.
▪ These may be represented in one of the two forms called fractional
form or the exponent form and may also have either + or – sign
preceding it.
▪ Example of valid real constants in fractional form or decimal
notation
0.05, -0.905, 562.05, 0.015
14
C Constants
• Representing a real constant in exponent form
• mantissa e exponent
• The letter e or E separating the mantissa and the exponent.
• Examples of valid real constants in exponent form are:
252E85, 0.15E-10, -3e+8

▪ 3. Character Constants
• Contains one single character enclosed within single quotes.
• Examples of valid character constants: ‘a’ , ‘Z’, ‘5’
• It should be noted that character constants have numerical values known as
ASCII values, for example, the value of ‘A’ is 65 which is its ASCII value.
• Some special character are represented as two characters in single quotes.
‘\n’ = newline, ‘\t’= tab, ‘\\’ = backlash, ‘\”’ = double quotes.
Char constants also can be written in terms of their ASCII code.
‘\060’ = ‘0’ (Decimal code is 48).
15
C Constants
Escape
▪ Escape Characters/ Escape Sequenc Description
e
Sequences
a Audible alert(bell)
• Non graphic characters that cannot be
typed directly from keyboard, for b Backspace
example, tabs, carriage return, etc. f Form feed

• These non graphic characters can be n New line


represented by using escape sequences r Carriage return
represented by a backslash() followed t Horizontal tab
by one or more characters. v Vertical tab
• NOTE: An escape sequence consumes \ Backslash
only one byte of space as it represents a “ Double quotation mark
single character. ‘ Single quotation mark
? Question mark
Null
4. String Constants: sequence of characters enclosed within
double quotes. For example, “hello” “abc” “hello911” 16
Escape Sequence
▪ Print below lines by using single printf() statement.

you
are learning
‘C’ Language
“Do you know C language”

17
Special Symbols
[] () {} , ; : * … = #
▪ Braces{}: These opening and ending curly braces marks the start
and end of a block of code containing more than one executable
statement.
▪ Parentheses(): These special symbols are used to indicate function
calls and function parameters.
▪ Brackets[]: Opening and closing brackets are used as array
element reference. These indicate single and multidimensional
subscripts.

18
C Operators
▪ C operators are symbols that triggers an action when applied to C
variables and other objects.
▪ The data items on which operators act upon are called operands.
▪ Unary Operators: Those operators that require only single
operand to act upon are known as unary operators. (-,~)
▪ Binary Operators: Those operators that require two operands to
act upon are called binary operators. (+,-,*,/,%, etc.)
▪ Ternary Operators: These operators requires three operands to
act upon. (?:)

19
C Instructions
▪ There are basically three types of instructions in C:
(1) Type Declaration Instruction
(2) Input / Output Instructions
(3) Arithmetic Instruction
(4) Control Instruction

20
Type Declaration Instruction
▪ A form of a declaration statement is: data-type var1, var2,…;
▪ Declaration announces the data type of a variable and allocates appropriate
memory location. No initial value (like 0 for integers) should be assumed.
▪ It is possible to assign an initial value to a variable in the declaration itself.
data-type var = expression;
▪ Any variable must be declared before using it in any statement.
Ex.: int bas ;
float rs, grosssal ;
char name, code ;
▪ Some more examples are
int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;
float a = 1.5, b = a + 3.1 ; is correct
float b = a + 3.1, a = 1.5 ; is incorrect
int a, b, c, d ;
a = b = c = 10 ; Correct
int a = b = c = d = 10 ; incorrect
21
Input/Output Instructions
▪ C has no built-in statements for input or output.
▪ A library of functions is supplied to perform these operations. The I/O
library functions are listed the “header” file <stdio.h>.
▪ The header has the prototype for input/output function like printf();
scanf(); puts(); gets(); etc.
printf ( ) ;- Function
▪ This function provides for formatted output to the screen.
▪ The syntax is:
printf ( “format”, var1, var2, … ) ;
▪ The “format” includes a listing of the data types of the variables to be
output and, optionally, some text and control character(s).
▪ Example:
float a ; int b ;
scanf ( “%f%d”, &a, &b ) ;
printf ( “You entered %f and %d \n”, a, b ) ; 22
Input/Output Instructions
▪ Format Conversion Specifiers:
%d -- displays a decimal (base 10) integer
%l -- used with other specifiers to indicate a "long"
%e -- displays a floating point value in exponential notation
%f -- displays a floating point value
%c -- displays a single character
%s -- displays a string of characters
▪ Some Examples of printf()
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f \t and principle is=Rs.%d", si, p) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;

23
Input/Output Instructions
scanf ( ) ; -Function
▪ This function provides for formatted input from the keyboard. The
syntax is:
scanf ( “format” , &var1, &var2, …) ;
▪ The “format” is a listing of the data types of the variables to be
input and the & in front of each variable name tells the system
WHERE to store the value that is input. It provides the address for
the variable.
▪ Example:
float a; int b;
scanf (“%f”, &a);
scanf (“%d”, &b);
or
scanf (“%f%d”, &a, &b);
24
Arithmetic Instructions
▪ A C arithmetic instruction consists of a variable name on the left hand
side of = and variable names & constants on the right hand side of =.
▪ The variables and constants appearing on the right hand side of = are
connected by arithmetic operators like +, -, *, and /.
int ad ;
float kot, deta, alpha, beta, gamma ;
ad = 3200 ;
kot = 0.0056 ;
deta = alpha * beta / gamma + 3.2 * 2 / 5 ;
▪ Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables. 25
Arithmetic Instructions
▪ Could be of three types:
▪ (a) Integer mode arithmetic statement - all operands are either
integer variables or integer constants
int i, king, issac, noteit ;
i=i+1;
king = issac * 234 + noteit - 7689 ;

▪ (b) Real mode arithmetic statement -all operands are either real
constants or real variables.
float qbee, antink, si, prin, anoy, roi ;
qbee = antink + 23.123 / 4.5 * 0.3442 ;
si = prin * anoy * roi / 100.0 ;

26
Arithmetic Instructions
▪ Mixed mode arithmetic statement-some of the operands are
integers and some of the operands are real.
float si, prin, anoy, roi, avg ;
int a, b, c, num ;
si = prin * anoy * roi / 100.0 ;
avg = ( a + b + c + num ) / 4 ;

▪ Firstly, the right hand side is evaluated using constants and the
numerical values stored in the variable names.
▪ This value is then assigned to the variable on the left-hand side.

27
Arithmetic Instructions
▪ Some important things to remember-
1. C allows only one variable on left-hand side of =. That is, z = k *
l is legal, whereas k * l = z is illegal.
2. An arithmetic instruction is often used for storing character
constants in character variables.
char a, b, d ; a = 'F' ; b = 'G' ; d = '+' ;
3. Arithmetic operations can be performed on ints, floats and chars.
char x, y ; int z ; x = 'a' ; y = 'b' ; z=x+y;
4. No operator is assumed to be present. It must be written
explicitly.
a = c.d.b(xy) usual arithmetic statement
b = c * d * b * ( x * y ) equivalent C statement

28
Arithmetic Instructions
5. There is no operator for performing exponentiation operation.
Thus following statements are invalid.
a = 3 ** 2 ; b=3^2;
6. To perform other mathematical operations there are functions like
pow(), abs(), sqrt(), sin(), cos(), tan() etc. Which are listen in
header file math.h can be include as #include<math.h>

29
Data Types
▪ Data types in C refer to an extensive system used for declaring
variables or functions of different types.
▪ The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.
▪ There are two categories:
▪ Primary data types: These are fundamental data types in C
namely integer(int), floating point(float), character(char) and
void.
▪ Derived data types: Derived data types are nothing but primary
data types but a little twisted or grouped together like array,
stucture, union and pointer. These are discussed in details later.

30
Primary Data Types

31
Primary Data Types
Type Storage size Value range Format String

char 1 byte -128 to 127 or 0 to 255 %c

unsigned char 1 byte 0 to 255 %c

signed char 1 byte -128 to 127 %c

-32,768 to 32,767 or -2,147,483,648 to %d


int 2 or 4 bytes
2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 %u

short 2 bytes -32,768 to 32,767 %d

unsigned short 2 bytes 0 to 65,535 %u

long 4 bytes -2,147,483,648 to 2,147,483,647 %ld

unsigned long 4 bytes 0 to 4,294,967,295 %ud

float 4 byte 1.2E-38 to 3.4E+38 %f


6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 %lf


(15 decimal places)

long double 10 byte 3.4E-4932 to 1.1E+4932 %Lf 32


(19 decimal places)
Integer and float conversions
▪ An arithmetic operation between an integer and integer always
yields an integer result.
▪ An operation between a real and real always yields a real result.
▪ An operation between an integer and real always yields a real
result. In this operation the integer is first promoted to a real and
then the operation is performed.

33
Type Conversion in Assignments
▪ If type of expression on right side of an assignment ‘=‘ is not same
as the type of variable on left side then,
▪ The value of the expression is promoted or demoted depending on
the type of variable on left-hand side and then assigned to it.
Ex: int i;
float b;
i=3.5 // the value 3.5 first be demoted into int (3) and then will assign to i.
b=30 // the value 30 first be promoted into float (30.000000) then assigned to b

In case of complex expression also same rules apply. For example


float a, b, c ;
int s ;
s = a * b * c / 100 + 33 / 4 - 3 * 1.1 ; // During evaluation ints (100, 3) will promote
into float and the result of expression will be in float. However, 33/4 will be processed in int
and the result will be promoted into float. But when this float value is assigned to s, it is
again demoted to an int and then stored in s.
34
Type Conversion in Assignments
▪ Here k is int and a is real.

35
Type Conversions
• Integer division:
c = (9 / 5)*(f - 32)
The operands of the division are both int and hence the result also would be
int. For correct results, one may write
c = (9.0 / 5.0)*(f - 32)
• In case the two operands of a binary operator are different, but compatible,
then they are converted to the same type by the compiler. The mechanism (set
of rules) is called Automatic Type Casting.
c = (9.0 / 5)*(f - 32)
• It is possible to force a conversion of an operand. This is called Explicit Type
casting.
c = ((float) 9 / 5)*(f - 32)

Lectures on Numerical Methods 36


Operators in C
▪ An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions.

• · Arithmetic Operators
• · Relational Operators
• · Logical Operators
• · Bitwise Operators
• · Assignment Operators
• · Misc Operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after B%A=0
an integer division.
++ Increment operator increases the integer A++ = 11
value by one.
-- Decrement operator decreases the integer A-- = 9
value by one.

38
Examples for ++ & -- operators
Let the value of a =5 and b=++a then
a = b =6
Let the value of a = 5 and b=a++ then
a =5 but b=6
i.e.:
1. a prefix operator first adds 1 to the operand and then the
result is assigned to the variable on the left
2. a postfix operator first assigns the value to the variable
on left and then increments the operand.
Relational Operators
Assume variable A holds 10 and variable B holds 20 then
Operator Description Example
== Checks if the values of two operands are (A == B) is not true.
equal or not. If yes, then the condition
becomes true.
!= Checks if the values of two operands are (A != B) is true.
equal or not. If the values are not equal,
then the condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right operand. If
yes, then the condition becomes true.
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand. If yes, then
the condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of right
operand. If yes, then the condition
becomes true.
40
<= Checks if the value of left operand is less (A <= B) is true.
than or equal to the value of right operand.
Logical Operators
Assume variable A holds 1 and variable B holds 0. In C zero
value treated as false while any non-zero as true.

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then the
condition becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then the
condition becomes true.

! Called Logical NOT Operator. It is used to !(A && B) is true.


reverse the logical state of its operand. If
a condition is true, then Logical NOT
operator will make it false.

41
Bitwise Operators
▪ Bitwise operator works on bits and perform bit-by-bit operation.
The truth tables for &, |, and ^ is as follows
p q p&q p|q p^q Assume A = 60 and B
= 13
0 0 0 0 0
in binary format, they
0 1 0 1 1 will be as follows −
1 1 1 1 0
A = 0011 1100
1 0 0 1 1 B = 0000 1101

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011
42
Bitwise Operators
Assume variable 'A' holds 60 and variable 'B' holds 13

Operator Description Example


& Binary AND Operator copies a bit to the (A & B) = 12, i.e., 0000
result if it exists in both operands. 1100
| Binary OR Operator copies a bit if it exists (A | B) = 61, i.e., 0011
in either operand. 1101
^ Binary XOR Operator copies the bit if it is (A ^ B) = 49, i.e., 0011
set in one operand but not both. 0001
~ Binary Ones Complement Operator is (~A ) = ~60, i.e,. 1100
unary and has the effect of 'flipping' bits. 0011

<< Binary Left Shift Operator. The left


operands value is moved left by the A << 2 = 240 i.e., 1111
number of bits specified by the right 0000
operand.
>> Binary Right Shift Operator. The left
operands value is moved right by the A >> 2 = 15 i.e., 0000
number of bits specified by the right 1111 43
operand.
Assignment Operators
Operator Description Example
= Simple assignment operator. Assigns values from right C = A + B will assign the value
side operands to left side operand of A + B to C
+= Add AND assignment operator. It adds the right operand to C += A is equivalent to C = C +
the left operand and assign the result to the left operand. A
-= Subtract AND assignment operator. It subtracts the right
operand from the left operand and assigns the result to the C -= A is equivalent to C = C - A
left operand.
*= Multiply AND assignment operator. It multiplies the right
operand with the left operand and assigns the result to the C *= A is equivalent to C = C * A
left operand.
/= Divide AND assignment operator. It divides the left
operand with the right operand and assigns the result to C /= A is equivalent to C = C / A
the left operand.
%= Modulus AND assignment operator. It takes modulus using C %= A is equivalent to C = C %
two operands and assigns the result to the left operand. A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C44
|2
Assignment Operators
Operator Description Example
= Simple assignment operator. Assigns values from right C = A + B will assign the value
side operands to left side operand of A + B to C
+= Add AND assignment operator. It adds the right operand to C += A is equivalent to C = C +
the left operand and assign the result to the left operand. A
-= Subtract AND assignment operator. It subtracts the right
operand from the left operand and assigns the result to the C -= A is equivalent to C = C - A
left operand.
*= Multiply AND assignment operator. It multiplies the right
operand with the left operand and assigns the result to the C *= A is equivalent to C = C * A
left operand.
/= Divide AND assignment operator. It divides the left
operand with the right operand and assigns the result to C /= A is equivalent to C = C / A
the left operand.
%= Modulus AND assignment operator. It takes modulus using C %= A is equivalent to C = C %
two operands and assigns the result to the left operand. A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C45
|2
Misc Operators

Operato Description Example


r
sizeof() Returns the size of a sizeof(a), where a is
variable. integer, will return 4.
& Returns the address of a &a; returns the actual
variable. address of the variable.
* Pointer to a variable. *a;
?: If Condition is true ? then
Conditional Expression.
value X : otherwise value Y
. Member selection operators
-> Member selection operators

46
Operator Precedence/ Hierarchy
▪ Does the expression 2 * x - 3 * y correspond to (2x)-(3y) or to 2(x-3y)?
▪ Similarly, does A / B * C correspond to A / (B * C) or to (A / B) * C?
▪ If more than one operators are there in an expression then the operator with
higher precedence will evaluate first.
▪ If two operators have same precedence then they will evaluate as per their
associativity (either left-to-right or right-to-left)
▪ Ex: Evaluate the following expression where i is integer
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +
47
Rules for evaluation of expression
▪ First parenthesized sub expression from left to right are evaluated.
▪ If parentheses are nested, the evaluation begins with the innermost sub
expression
▪ The precedence rule is applied in determining the order of application of
operators in evaluating sub expressions
▪ The associatively rule is applied when 2 or more operators of the same
precedence level appear in a sub expression.
▪ Arithmetic expressions are evaluated from left to right using the rules of
precedence
▪ When parentheses are used, the expressions within parentheses assume highest
priority
Operators Precedence and Associativity
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
49
Comma , Left to right
Arithmetic Expressions

Algebraic expression C expression


axb-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
a*b/c

3x2+2x+1 3*x*x+2*x+1
a/b

S=
S=(a+b+c)/2
Arithmetic Expressions
Algebraic expression C expression
area= area=sqrt(s*(s-a)*(s-b)*(s-c))

Sin
sin(b/sqrt(a*a+b*b))

tow1=sqrt((rowx-rowy)/2+tow*x*y*y)

tow1=sqrt(pow((rowx-rowy)/2,2)+tow*x*y*y)
Decision Statements
▪ Three major decision making instructions—
• the if statement,
• the if-else statement,
• and the switch statement.

The if Statement
Syntax:
if (this condition is true)
execute this statement ;

▪ Example 2.1: While purchasing certain items, a discount of 10% is


offered if the quantity purchased is more than 1000. If quantity and
price per item are input through the keyboard, write a program to
calculate the total expenses.
52
Decision Statements

▪ /* Calculation of total expenses */


main( )
{
int qty, dis = 0 ;
float rate, tot ;
printf ( "Enter quantity and rate " ) ;
scanf ( "%d %f", &qty, &rate) ;
if ( qty > 1000 )
dis = 10 ;
tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ;
printf ( "Total expenses = Rs. %f", tot ) ;
}

53
Forms of if
(a) if ( condition ) (d) if ( condition )
{ (e) if ( condition )
do this ;
do this ; do this ;
and this ; else
(b) if ( condition ) } {
{ else if ( condition )
do this ; { do this ;
do this ; else
and this ;
and this ; {
} } do this ;
(c) if ( condition ) (e) if ( condition ) and this ;
do this ; do this ; }
else }
else
{
do this ; if ( condition )
do this ;
else
{
do this ;
and this ;
} 54
}
The Real Thing
if ( condition )
statement ;
Or
if ( expression )
statement ;

if ( 3 + 2 % 5 )
printf ( "This works" ) ;

if ( a = 10 )
printf ( "Even this works" ) ;

if ( -5 )
printf ( "Surprisingly even this works" ) ;
55
Multiple Statements within if
Example 2.2: The current year and the year in which the employee joined the
organization are entered through the keyboard. If the number of years for which the
employee has served the organization is greater than 3 then a bonus of Rs. 2500/- is
given to the employee. If the years of service are not greater than 3, then the
program should do nothing.
/* Calculation of bonus */
main( )
{
int bonus, cy, yoj, yr_of_ser ;
printf ( "Enter current year and year of joining " ) ;
scanf ( "%d %d", &cy, &yoj ) ;
yr_of_ser = cy - yoj ;
if ( yr_of_ser > 3 )
{
bonus = 2500 ;
printf ( "Bonus = Rs. %d", bonus ) ;
}
}
56
57
The if-else Statement
Example 2.3: In a company an employee is paid as under: If his basic salary is less than Rs.
1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either
equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the
employee's salary is input through the keyboard write a program to find his gross salary.
main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ;
scanf ( "%f", &bs ) ;
if ( bs < 1500 )
{
hra = bs * 10 / 100 ;
da = bs * 90 / 100 ;
}
else
{
hra = 500 ;
da = bs * 98 / 100 ;
}
gs = bs + hra + da ;
printf ( "gross salary = Rs. %f", gs ) ;}
58
Use of Logical Operators
▪ Example 2.4: The marks obtained by a student in 5 different
subjects are input through the keyboard. The student gets a division
as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the student.

59
/* Method – I */
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division ") ;
else
{
if ( per >= 50 )
printf ( "Second division" ) ;
else
{
if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "Fail" ) ;
}
}
}
60
/* Method – II */
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division" ) ;
if ( ( per >= 50 ) && ( per < 60 ) )
printf ( "Second division" ) ;
if ( ( per >= 40 ) && ( per < 50 ) )
printf ( "Third division" ) ;
if ( per < 40 )
printf ( "Fail" ) ;
}

61
The else if Clause
main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1+ m2 + m3 + m4+ m5 ) / per ;
if ( per >= 60 )
printf ( "First division" ) ;
else if ( per >= 50 )
printf ( "Second division" ) ;
else if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "fail" ) ;
}
62
The Conditional Operators
expression 1 ? expression 2 : expression 3

int x, y ;
scanf ( "%d", &x ) ;
y=(x>5?3:4);

63
Some Example
▪ Example 2.5: A company insures its drivers in the following cases:
− If the driver is married.
− If the driver is unmarried, male & above 30 years of age.
− If the driver is unmarried, female & above 25 years of age.
In all other cases the driver is not insured. If the marital status, gender and age of
the driver are the inputs, write a program to determine whether the driver is to be
insured or not.

64
Some Examples
▪ Example 2.6: Write a program to calculate the salary as per the
following table:

65
Examples
▪ [A] What would be the output of the following programs:
(a) main( )
(b) main( )
{ {
int a = 300, b, c ; int x = 30 , y = 40 ;
if ( a >= 400 ) if ( x == y )
b = 300 ; printf( "x is equal to y" ) ;
c = 200 ; else if ( x > y )
printf( "x is greater than y" ) ;
printf ( "\n%d %d", b, c ) ;
else if ( x < y )
} printf( "x is less than y" ) ;
}
(c) main( ) main( )
{ {
int x = 10, y = 20 ; int kk = 65, ll ;
ll = ((kk == 65)? printf ( "\n kk is equal to 65"):
if ( x == y ) ;
printf("\n kk is not equal to 65"));
printf ( "\n%d %d", x, y ) ; printf( "%d\n", ll );
} }
66
examples
main( )
{
int i = 4, z = 12 ;
if ( i = 5 || z > 50 )
printf ( "\nDean of students affairs" ) ;
else
printf ( "\nDosa" ) ;
}

main( )
{
int i = 4, j = -1, k = 0, y, z ;
y = i + 5 && j + 1 || k + 2 ;
z = i + 5 || j + 1 && k + 2 ;
printf ( "\ny = %d z = %d", y, z ) ;
}
67
The Switch Case Control Structure
switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}

68
Example
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
}

69
Example
main( )
{
int i = 2 ;
switch ( i )
{
case 1 :
printf ( "I am in case 1 \n" ) ;
break ;
case 2 :
printf ( "I am in case 2 \n" ) ;
break ;
case 3 :
printf ( "I am in case 3 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
} 70
}
The Tips and Traps
▪ (a) The earlier program that used switch may give you the wrong impression that you can
use only cases arranged in ascending order, 1, 2, 3 and default. You can in fact put the
cases in any order you please. Here is an example of scrambled case order:
main( )
{
int i = 22 ;
switch ( i )
{
case 121 :
printf ( "I am in case 121 \n" ) ;
break ;
case 7 :
printf ( "I am in case 7 \n" ) ;
break ;
case 22 :
printf ( "I am in case 22 \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}
71
The Tips and Traps
(b) You are also allowed to use char values in case and switch as
shown in the following program:
main()
{
char c = 'x' ;
switch ( c )
{
case 'v' :
printf ( "I am in case v \n" ) ;
break ;
case 'a' :
printf ( "I am in case a \n" ) ;
break ;
case 'x' :
printf ( "I am in case x \n" ) ;
break ;
default :
printf ( "I am in default \n" ) ;
}
}

72
The Tips and Traps
▪ At times we may want to execute a common set of statements for multiple cases. How
this can be done is shown in the following example.
main( )
{
char ch ;
printf ( "Enter any of the alphabet a, b, or c " ) ;
scanf ( "%c", &ch ) ;
switch ( ch )
{
case 'a' :
case 'A' :
printf ( "a as in ashar" ) ;
break ;
case 'b' :
case 'B' :
printf ( "b as in brain" ) ;
break ;
case 'c' :
case 'C' :
printf ( "c as in cookie" ) ;
break ;
default :
printf ( "wish you knew what are alphabets" ) ;
}
} 73
The Tips and Traps
▪ Even if there are multiple statements to be executed in each case there is no need to
enclose them within a pair of braces (unlike if, and else).
▪ Every statement in a switch must belong to some case or the other. If a statement doesn’t
belong to any case the compiler won’t report an error. However, the statement would
never get executed. For example, in the following program the printf( ) never goes to
work.
main( )
{
int i, j ;
printf ( "Enter value of i" ) ;
scanf ( "%d”, &i ) ;
switch ( i )
{
printf ( "Hello" ) ;
case 1 :
j = 10 ;
break ;
case 2 :
j = 20 ;
break ;
} 74
}
The Tips and Traps
▪ If we have no default case, then the program simply falls through the entire switch and
continues with the next instruction (if any,) that follows the closing brace of switch.
▪ Is switch a replacement for if? Yes and no. Yes, because it offers a better way of writing
programs as compared to if, and no because in certain situations we are left with no
choice but to use if. The disadvantage of switch is that one cannot have a case in a switch
which looks like:
case i <= 20 :
▪ All that we can have after the case is an int constant or a char constant or an expression
that evaluates to one of these constants. Even a float is not allowed.
▪ We can check the value of any expression in a switch. Thus the following switch
statements are legal.
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
switch ( a < 4 && b > 7 )
▪ Expressions can also be used in cases provided they are constant expressions. Thus case 3
+ 7 is correct, however, case a + b is incorrect.

75
The Tips and Traps
▪ The break statement when used in a switch takes the control outside the switch.
However, use of continue will not take the control to the beginning of switch as
one is likely to believe.
▪ In principle, a switch may occur within another, but in practice it is rarely done.
Such statements would be called nested switch statements.
▪ The switch statement is very useful while writing menu driven programs. This
aspect of switch is discussed in the exercise at the end of this chapter.

76
Arrays
▪ Arrays a kind of data structure that can store a fixed-size sequential
collection of elements of the same type.
▪ An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same
type.
▪ All arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest address to
the last element.

77
Array Declaration
▪ Syntax
type arrayName [arraySize ];
▪ Example
double balance[10];
int arr[5];
char name[10];

78
Array Initialization
Examples
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
▪ Till the array elements are not given any specific values, they are supposed to
contain garbage values.
▪ int B[20] = {2, 4, 8, 16, 32};
• Unspecified elements are guaranteed to be zero
▪ int C[4] = {2, 4, 8, 16, 32};
• Error — compiler detects too many initial values
▪ int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n};
• Automatically only; array initialized to expressions
▪ int E[5] = {1};
• Dynamically allocated array (automatic only). Zeroth element initialized to 1; all
other elements initialized to 0.
▪ int E[5] = {0};
▪ All elements initialize to zero
79
Memory Organization for an array
Suppose we have declared and initializes an array as
int score[7]={5,2,8,0,1,9,4};

80
Entering Data into array
void main()
{ Assigning values to array
int marks[5], i;
for ( i = 0 ; i <= 4 ; i++ ) marks[0]=50;
{ marks[1]=60;
printf ( "\nEnter marks " ) ; marks[2]=55;
scanf ( "%d", &marks[i] ) ; marks[3]=45;
} marks[4]=55;
}

Reading data from an array


for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ;
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;

81
Bounds Checking
▪ In C there is no check to see if the subscript used for an array
exceeds the size of the array.

main( )
{
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[i] = i ;
}

82
Two Dimensional Array
▪ The two dimensional array is also called a matrix.
main( )
{
int stud[4][2] ; //declaration
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
}
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
}

83
Initialising a 2-Dimensional Array
int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};

int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;

It is important to remember that while initializing a 2-D array it is


necessary to mention the second (column) dimension, whereas the
first dimension (row) is optional.
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
are perfectly acceptable,
whereas,
int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ;
would never work.
84
Memory Map of a 2-Dimensional Array

85
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.

86
What are Pointers?
• A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location.
• Like any variable or constant, you must declare a pointer before using it
to store any variable address.
Pointer variable declaration:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and
varname is the name of the pointer variable. The asterisk * used to declare a
pointer is the same asterisk used for multiplication.
Examples: some of the valid pointer declarations:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */ 87
How to Use Pointers?
Three things need to do
(1) We define a pointer variable,
(2) Assign the address of a variable to a pointer, and
(3) Finally access the value at the address available in the pointer variable.
This is done by using unary operator *. Which says the value at the address.
main( ) output:
{
int i = 3 ; Address of i = 65524
printf ( "\nAddress of i = %u", &i ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ;
}

main( ) output
{
int i = 3 ; Address of i = 65524
printf ( "\nAddress of i = %u", &i ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ; Value of i = 3
printf ( "\nValue of i = %d", *( &i ) ) ;
} 88
How to Use Pointers?
The expression &i gives the address of the variable i. This address can be
collected in a variable, by saying,
j = &i ;
But remember that j is not an ordinary variable like any other integer variable.
It is a variable that contains the address of other variable (i in this case).

j is a variable that contains the address of i, it is declared as,


int *j ;

89
How to Use Pointers?

main( ) The output of the above program would


{ be:
int i = 3 ; Address of i = 65524
int *j ; Address of i = 65524
j = &i ; Address of j = 65522
printf ( "\nAddress of i = %u", &i ) ; Value of j = 65524
printf ( "\nAddress of i = %u", j ) ; Value of i = 3
printf ( "\nAddress of j = %u", &j ) ; Value of i = 3
printf ( "\nValue of j = %u", j ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}

90
Pointer to Pointer or Double pointer
• A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
• When we define a pointer to a pointer, the first pointer contains the address of
the second pointer, which points to the location that contains the actual value as
shown below.
int i=3;
int *j=&i;
int **k=&j;

91
Example
main( ) The output of the above program would be:
{ Address of i = 65524
int i = 3, *j, **k ; Address of i = 65524
j = &i ; Address of i = 65524
k = &j ; Address of j = 65522
printf ( "\nAddress of i = %u", &i ) ; Address of j = 65522
printf ( "\nAddress of i = %u", j ) ; Address of k = 65520
printf ( "\nAddress of i = %u", *k ) ; Value of j = 65524
printf ( "\nAddress of j = %u", &j ) ; Value of k = 65522
printf ( "\nAddress of j = %u", k ) ; Value of i = 3
printf ( "\nAddress of k = %u", &k ) ; Value of i = 3
printf ( "\nValue of j = %u", j ) ; Value of i = 3
printf ( "\nValue of k = %u", k ) ; Value of i = 3
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", * ( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
printf ( "\nValue of i = %d", **k ) ;
}

92
NULL Pointers
• It is always a good practice to assign a NULL value to a pointer variable in case
you do not have an exact address to be assigned.
• This is done at the time of variable declaration.
• A pointer that is assigned NULL is called a null pointer.
• The NULL pointer is a constant with a value of zero defined in several standard
libraries.

#include <stdio.h> Output


int main ()
{ The value of ptr is 0
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}

93
Operations on pointers (Pointers arithmetic)
• There are four arithmetic operators that can be used in pointers: ++, --, +, -
• A pointer in C is an address, which is a numeric value. Therefore, you can
perform arithmetic operations on a pointer just as you can on a numeric value.

Incrementing a Pointer
#include <stdio.h> Output
int main ()
{ Address of var[0] = bf882b30
int var[] = {10, 100, 200}; Value of var[0] = 10
int i, *ptr; Address of var[1] = bf882b34
/* let us have array address in pointer */ Value of var[1] = 100
ptr = var; Address of var[2] = bf882b38
for ( i = 0; i < 3; i++) Value of var[2] = 200
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
} 94
Operations on pointers (Pointers arithmetic)
Decrementing a Pointer

#include <stdio.h> Address of var[3] =


const int MAX = 3; bfedbcd8
int main () Value of var[3] = 200
{ int var[] = {10, 100, 200}; Address of var[2] =
int i, *ptr; bfedbcd4
ptr = &var[MAX-1]; Value of var[2] = 100
for ( i = MAX; i > 0; i--) Address of var[1] =
{ bfedbcd0
printf("Address of var[%d] = %x\n", i, ptr ); Value of var[1] = 10
printf("Value of var[%d] = %d\n", i, *ptr );
ptr--;
}
return 0;
}

95
Operations on pointers (Pointers arithmetic)
• Addition of a number to a pointer. For example,
int i = 4, *j, *k ;
j = &i ;
j=j+1;
j=j+9;
k=j+3;

• Subtraction of a number from a pointer. For example,


int i = 4, *j, *k ;
j = &i ;
j=j-2;
j=j-5;
k=j-6;

96
Operations on pointers (Pointers arithmetic)
Subtraction of one pointer from another.
• One pointer variable can be subtracted from another provided both variables point to
elements of the same array.
• The resulting value indicates the number of bytes separating the corresponding array
elements.

main( )
{
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;
i = &arr[1] ;
j = &arr[5] ;
printf ( "%d %d", j - i, *j - *i ) ;
}

97
Comparison of two pointer variables
Pointer variables can be compared provided both variables point to objects of the
same data type.
Such comparisons can be useful when both pointer variables point to elements of
the same array.
The comparison can test for either equality or inequality. Moreover, a pointer
variable can be compared with zero (usually expressed as NULL).

main( )
{
int arr[ ] = { 10, 20, 36, 72, 45, 36 } ;
int *j, *k ;
j = &arr [ 4 ] ;
k = ( arr + 4 ) ;
if ( j == k )
printf ( "The two pointers point to the same location" ) ;
else
printf ( "The two pointers do not point to the same
location" ) ;
} 98
Operation do not work with pointer
Do not attempt the following operations on pointers... they
would never work out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant

99
Array of pointers
• There may be a situation when we want to maintain an array, which can store
pointers to an int or char or any other data type available.
• Following is the declaration of an array of pointers to an integer:
int *ptr[MAX];
• Each element in ptr holds a pointer to an int value.

#include <stdio.h> Value of var[0] = 10


const int MAX = 3; Value of var[1] = 100
int main () Value of var[2] = 200
{
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++)
{
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
100
}
Pointer and Array
▪ Array elements are always stored in contiguous memory locations.
▪ A pointer when incremented always points to an immediately next location of its type.
▪ Suppose we have an array num[ ] = { 24, 34, 12, 44, 56, 17 }

main( ) output
{ element no. 0 address = 65512 value=24
int num[ ] = { 24, 34, 12, 44, 56, 17 } ; element no. 1 address = 65514 value=34
int i ; element no. 2 address = 65516 value=12
for ( i = 0 ; i <= 5 ; i++ ) element no. 3 address = 65518 value=44
{ element no. 4 address = 65520 value=56
printf ( "\nelement no. %d ", i ) ; element no. 5 address = 65522 value=17
printf ( "address = %u", &num[i] ) ;
printf ( “value = %d", num[i] ) ;
}
}
101
Pointer and Array
Accessing elements of the array elements using pointers.
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i, *j ;
j = &num[0] ; /* assign address of zeroth element */
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", j ) ;
printf ( "element = %d", *j ) ;
j++ ; /* increment pointer to point to next location */
}
}
The output of this program would be:
address = 65512 element = 24
address = 65514 element = 34
address = 65516 element = 12
address = 65518 element = 44
address = 65520 element = 56
address = 65522 element = 17 102
The real thing
int num[ ] = { 24, 34, 12, 44,
56, 17 } ;

• num, is an integer pointer that point the base address of this integer array
so *num will give 24, which can be accessed equivalently as *(num+0)
and num[0]
• Similarly, (num+1) will increment the pointer by one location and thus
*(num+1) give 34, which can be accessed equivalently as *(num+1) and
num[1]
• Generalize one is (num+i) to point the address of ith location in an array,
where *(num+i) or num[i] are used to access the value at the address of ith
position and can also be written as *( i + num ), i[num].

103
Example
/* Accessing array elements in different ways */
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\naddress = %u ", &num[i] ) ;
printf ( "element = %d %d ", num[i], *( num + i ) ) ;
printf ( "%d %d", *( i + num ), i[num] ) ;
}
}
Output
address = 65512 element = 24 24 24 24
address = 65514 element = 34 34 34 34
address = 65516 element = 12 12 12 12
address = 65518 element = 44 44 44 44
address = 65520 element = 56 56 56 56
address = 65522 element = 17 17 17 17
104
Decision Control
Statements
{for}
{while}
{do-while}
{WHILE}
Hello world using LooPs

int main()
{
int count=0;
while(count<=3)
{
printf(“hello %d”, count)

return 0;
}
initialize loop counter ;
while ( test loop counter using a
condition )
{
do this ;
and this ;
increment loop counter ;
}
• Any type of correct expression is valid inside loop’s condition

• while ( i <= 10 )
• while ( i >= 10 && j <= 15 )
• while (i)
• while (i+2)
WAP to print 10 numbers using loops

main( )
{
int i = 1 ;
while (i<=10)
{
printf( “hello”);
i=i+1; // i++ // i+=1
}

}
Predict Output

main( )
{
int i = 1 ;
while (i<=10)
printf ( “hello”);
}
We can also decrement the counters

main( )
{
int i = 5 ;
while (i>=0)
{
printf( “hello”);
i=i-1;
}

}
Float counters??

main( )
{
float i = 5.0 ;
while (i>=0)
{
printf("hello“);
i=i-0.5;
}

}
Predict Output

main( )
{
int i = 1 ;
while (i<=10);
{
printf( “hello”);
i=i+1;
}
Printf(“HI”);
}
Output: Infinite LOOP
Predict Output

main( ) main( )
{ {
int i = 1 ; int i = 1 ;
while (i++<=10) while (++i<=10)
printf ( “hello%d”,i); printf ( “hello%d”,i);
} }
Predict Output

main( )
{
int i = 1 ;
while (i=10)
{
printf ( “hello%d”,i);
i=i+1;
}
}
Predict Output

main( )
{
float i = 1.1 ;
while (i==1.1)
{
printf ( “hello%d”,i);
i=i+0.1;
}
}
WAP to calculate Factorial of a given
number.
WAP to print ASCII value of ‘A’ to ‘Z’
{for} -loop
WAP to print 10 numbers using loops

main( ) main( )
{ {
int i = 1 ;
while (i<=10) for(int i = 1;i<=10;i++)
{ {
printf( “%d”,i); printf( “%d”,i);
i=i+1; } }

} }
WAP to print 10 numbers using loops

main( ) main( )
{ {
Int i=0;
for(int i = 1;i<=10;) for(;i<=10;)
{ {
printf( “%d”,i); printf( “%d”,i);
i++; i++;
} }

} }
WAP to print 10 numbers using loops

main( )
{

for(int i = 0;i++<=10;)
{
printf( “%d”,i);

}
Predict Output.

int main()
{
int i=0;
for ( i = 10 ; i ; i -- )
printf ( "%d", i ) ;

return 0;
}
Predict Output.

int main()
{
int i=0,j=0;
for ( i < 4 ; j = 5 ; j = 0 )
printf ( "%d", i ) ;

return 0;
}
Predict Output.

int main()
{
int i;
for ( i = 1; i <=10 ; printf ( "%d",i++ )
;

return 0;
}
Predict Output.

int main()
{
int i;
for ( scanf ( "%d", &i ) ; i <= 10 ; i++ )
printf ( "%d", i ) ;

return 0;
}
Factorial of a number using for loop
Multiple Initializations in the for Loop

for ( i = 1, j = 2 ; j <= 10 ; j++ )

Any example…???

DIY...
Break
Break: Jump out of loop without
waiting to get back to condition
Continue
Continue:
main( )
{
int i, j ;
for ( i = 1 ; i <= 2 ; i++ )
{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j )
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
}
main( )
{
int x = 4, y = 0, z ;
while ( x >= 0 )
{
if ( x == y )
break ;
else
printf ( “\n%d %d”, x, y ) ;
x-- ;
y++ ;
}
}
Predict Output

int main()
{
int i=0;
for(;;)
printf("hello");
return 0;
}
Predict Output

main( )
{
int i ;
for ( i = 1 ; i <= 5 ; printf ( "\n%d", i ) ) ;
i++ ;
}
Predict Output

main( )
{
int i ;
for ( i = 1 ; i <= 5 ; printf ( "\n%d", i ) ) ;
i++ ;
}
Predict Output

main( )
{
int i = 1, j = 1 ;
for ( ; ; )
{
if ( i > 5 )
break ;
else
j += i ;
printf ( "\n%d", j ) ;
i += j ;
}
}

Output:- 2 5
Predict Output

main( )
{
int i ;
for ( i = 1 ; i <= 5 ; printf ( "\n%c", 65 ) ) ;
i++ ;
}
Nesting of Loops
/* Demonstration of nested loops */
main( )
{
int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
{
sum = r + c ;
printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;
}
}
}
{do-while} loop

do
{
this ;
and this ;
and this ;
and this ;
} while ( this condition is true ) ;
main( ) main( )
{ {
while ( 4 < 1 ) do
printf ( "Hello there {
\n") ; printf ( "Hello there \n")
} ;
}while ( 4 < 1 );

}
Which of the following is not an infinite
loop.
1. int i = 1 ; 3. int True = 0, false ;
while ( 1 ) while ( True )
{ {
i++ ; False = 1 ;
} }
_______________ ____________________
_

2. for ( ; ; ) ; 4. int y, x = 0 ;
do
{
y=x;
} while ( x == 0 ) ;
GO TO Statement

• Goto: take the control where you want.


•If the condition is satisfied the goto
statement transfers control to the label
‘sos’, causing printf( ) following sos to be
executed.
•The label can be on a separate line or on the same line
as the statement following it, as in
sos : printf ( "To err is human!" ) ;

• Any number of gotos can take the control to the same


label.

• The exit( ) function is a standard library function which


terminates the execution of the program. It is necessary
to use this function since we don't want the statement
printf ( "To err is human!" ) to get executed after
execution of the else block.
#include <stdio.h>
int main()
{
int sum=0;
for(int i = 0; i<=10; i++){
sum = sum+i;
if(i==5){
goto addition;
}
}

addition:
printf("%d", sum);

return 0;
}
#include <stdio.h>
int main () {
int a = 10;
LOOP:do {
if( a == 15) {
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;

}while( a < 20 );

return 0;
}
Practice Questions

• To check whether a given number is perfect or not.

• Write a C program to print all even numbers between 1 to 100.

• Write a C program to enter a number and print its reverse.

• Program to print strong numbers in given range


Strong number is a special number whose sum of
factorial of digits is equal to the original number. For
example: 145 is strong number. Since, 1! + 4! + 5! = 145
Thanks

You might also like