0% found this document useful (0 votes)
3 views268 pages

Computer Programming

The document provides an overview of computer programming concepts, including the definition of computers, programming languages, and problem-solving methodologies. It discusses various number representations, including binary and signed magnitude, as well as arithmetic operations in binary. Additionally, it covers techniques for converting decimal to binary and performing binary addition and subtraction.

Uploaded by

Disha Khurana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views268 pages

Computer Programming

The document provides an overview of computer programming concepts, including the definition of computers, programming languages, and problem-solving methodologies. It discusses various number representations, including binary and signed magnitude, as well as arithmetic operations in binary. Additionally, it covers techniques for converting decimal to binary and performing binary addition and subtraction.

Uploaded by

Disha Khurana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Programming

PPT Booklet
BITS Pilani
Pilani Campus

Computer Programming
Topicsto beCovered:
Computers& Programming,ProgrammingLanguages
BITSPilani
Pilani Campus Types,ProblemSolvingusingComputers

What is aComputer? What is programming?


• Instructing a computer to execute a sequenceof
• Computer is a computing device steps (each step represents a “built-in”
– Facilitate computation of anything that iscomputable instruction) is called “Programming”
• Can we store all possible computations? • Different computers have different instruction sets
– Answer: NO – May varied in terms of types as well as levelof
• Then how it performs allcomputations? instructions (e.g. Simple or Complex)
– Having facility to execute basic computation steps. – [Link] instruction in x86 and ADDV instruction in Cray
Called as “instruction set” computer

3 4
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
What is programming? Programming Languages-1

• Instruction set must be complete suchthat • Computer is an electronic device, made of


– any computation can be expressed as a sequence electronic components
of steps – An electronic component can have two possible
– each step is achieved by an instruction available in states either ON (1) or OFF(0)
the instruction set – Instructions must be represent in the form, inwhich
a machine can understand i.e. “Machine Language”
• Any Drawbacks?

5 6
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Programming Languages-2 Programming Languages-3


• In the place of long sequence of 1s and 0s, • Tomake program development process easier
computer operations can be represented by (i.e. Machine Independent)
mnemonic codes-- “Assembly Language” – a language which is similar to natural language like
– e.g. ADD for addition, SUBfor subtraction… English is preferred, called as “High Level Language”
– Requires “Assembler”(i.e. converts assembly • More user friendly than so called lowlevel
instructions into corresponding machine languages (i.e. Machine andAssembly)
instructions) – Requires “Compiler Program”to translate into the
• Any Drawbacks? target computer’smachine language
– e.g. C, C++, Java,C#
• Any Drawbacks?
7 8
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
How to solve aproblem? Example Problem
• Basic Steps • Problem statement
1. Specify the problem requirements – Convert currency value given in Dollars to Rupees
2. Analyze the problem and display the result
3. Design the algorithm to solve theproblem
4. Implement the algorithm
5. Test and verify the problem solution (i.e.
“Program”)
6. Maintain/update the Program

9 10
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Numbersand Representations-1
BITSPilani
Pilani Campus

• Roman numerals
– Totalsevensymbolsareused(i.e.I,V,X,L,C,D, M)
– Numbersareformedbycombining symbols
– Symbolsareplacedinorderof value
– e.g.MMXII(equalsto 2012)

Topicsto beCovered:
Numbers&Representations,NumberRepresentationin
Computers,UnsignedBinaryRepresentationand
Arithmetic Operations 12
BITS Pilani, Pilani Campus
Numbersand Representations-2 Numbersand Representations-3
• Howtoperformthearithmetic operations?
• Arabic numerals
– V*V= XXV
– Total0to9,tensymbols(digits)are used
– VI*VIII=XXXXVIII
– Numbersarerepresentedinasequenceof digits
– 5*5= 25
– e.g.578,“readasaFiveHundredandSeventy
Eight” – 6*8= 48
• Canwedefinethestepsof multiplication?

13 14
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Numbersand Representations-4 Binary Numbers


• Lookingforarepresentationthatallows • Twosymbols(digits)areused(i.e.0and 1)
operationsinefficientmanner • Examples: 1001,0110,1111, 1010
• Naturalnumbersarerepresentedinbase 10 • ThedecimalequivalentofaBinarynumber
• Whatisgoodfor computers? dn-1dn-2 …. d0 isgivenas:
– Answer:Base2(Binary). Why? dn-1*2n-1+dn-2 * 2n-2 +…..d0* 20
• Decimalequivalentof 10101?

15 16
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
DecimaltoBinary Conversion DecimaltoBinary Conversion
• HowtoconvertadecimalnumberNtoits • Exercise:
equivalentBinary number? – Findthebinaryequivalentofthedecimalnumber 25
1. DividethenumberNby 2
• theremainderbecomestheLeastSignificantBit (LSB)
2. Dividethequotientby2(ifitisnot 0)
• theremainderbecomesthenextbittothe left
3. Repeatthestep2untilthequotientis 0

17 18
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Questions BinaryAddition Table


• UsingKbits,whatistherangeofdecimal
Cin A B S Cout
numbersonecan represent?
0 0 0
0 0 1
0 1 0
• GivenadecimalnumberN,howmanybitsare 0 1 1
requiredtorepresentitin binary? 1 0 0
1 0 1
1 1 0
1 1 1
19 20
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Arithmetic Operations 4-Bit Adder B0 A0
• Howtoaddtwounsignedbinarynumbers?
• Procedure Cout
FA
Cin
– Rightalignthe numbers
– Addthetwocorrespondingbitandacarry-in bit(if any)
togetasinglesumbitandacarry-out bit S0
• Example: B3 A3 B2 A2 B1 A1 B0 A0
110011
+10011100 C2 C1 C0 Cin
FA FA FA FA

Cout
21 S3 S2 S1 S0 13
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Overflow
BITS Pilani
Pilani Campus

• Therearefinitenumberofbitsavailablein
computerstorepresentthe numbers
– Fora8bitcomputer,themaximumnumber(unsigned
binary) which canberepresentedis(28– 1)or 255
• Let’saddthetwo8bitbinary numbers:
11110000
+ 00010001 Topicsto beCovered:
Signed Binary Representations (Signed Magnitude , 1’s
Complement, 2’s Complement) andArithmetic Operations,
14 Character DataRepresentations
BITS Pilani, Pilani Campus
Signed Magnitude
Signed Binary Representations Representation

• Todothesubtraction,weneedtorepresent
negativenumbersas well • Appendanextrabitasanleftmost bit
• Needtostorethesignofthe number • 0forPositive and1for Negative
• Unsignedrepresentationcanbeextendedto • Example:
storethesigninformationalongthe value • 01111(+15)and
• Howtodo it? • 11111 (-15)

25 26
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Signed Magnitude Binary


Representation
Number/Repr Signed
e sentation Magnitude
000 0
001 1
010 2
011 3
100 -0
101 -1
110 -2
111 -3
27
BITS Pilani, Pilani Campus
Ifthesignbitis“0”,thismeansthenumberispositiveinvalue.Ifthesignbitis“1”,then
the number is negative in value.

For example,
• For range of 6 bit Sign-Magnitude form binary number is from to
which is equal from minimum value -31 (i.e., 1 11111) to maximum value +31 (i.e.,
0 11111).

• And zero (0) has two representation, -0 (i.e., 1 00000) and +0 (i.e., 0 00000).

The range of Sign-Magnitude form is from (2(n-1)-1) to


(2(n-1)-1).
signed-magnitude representation. Arithmetic: Signed Magnitude Representation
• a number consists of a magnitude and a symbol which indicates
whether the magnitude is positive or negative. • Let’sconsidertwonumbers(signedmagnitude)
• + 79, - 82, - 25.2 etc Aand B
– TosubtractBfromA,addB’snegativeto A
– i.e.A+ (-B)
• Let’stryarithmeticforsignedmagnitude?

34
BITS Pilani, Pilani Campus

Binary and decimal Binary Subtraction

1101
- 0101
_____
Binary Subtraction

1010
1101 (-) 101
________
- 0101
_____
1000

Practice questions

1010
(-) 101 1. 1011011−10010=?
________
0101 2. 1010110−101010=?

3. 1000101−101100=?

4. 101101−100111=?
Practice question 1 Practice questions

1. 1011011−10010=1001001

2. 1010110−101010=?

3. 1000101−101100=?

4. 101101−100111=?

Practice question 2 Practice questions

1. 1011011−10010=1001001

2. 1010110−101010=101100

3. 1000101−101100=?

4. 101101−100111=?
Practice question 3 Practice questions

1. 1011011−10010=1001001

2. 1010110−101010=101100

3. 1000101−101100=11001

4. 101101−100111=?

Practice question 4 Practice questions

1. 1011011−10010=1001001

2. 1010110−101010=101100

3. 1000101−101100=11001

4. 101101−100111=110
1’sComplement
1’sComplement Representation

• Negativenumbersarerepresentedbyflipping
thebits(1to0and0to1)ofcorresponding Theone’scomplementforthebinaryno:
110010 → 001101
positivenumber representation.
• Examplewith3 bits
– Representationof+2 is:
• 010
– Representationof-2 is:
• 101

49
BITS Pilani, Pilani Campus

Whatistheone’scomplementof7.
Decimal Binary 1’s
number number complement
7 → 0111
0 000 111
1’scomplementof0111→ 1000
1 001 110
2 010 101
3 011 100
1’sComplement Representation

Number/ 1’s
Representation Complement
000 0 Whatistherepresentationof0?
001 1
010 2
011 3
100 -3
101 -2
110 -1
111 -0

53
BITS Pilani, Pilani Campus

Whatistherepresentationof0?
What is the range of numbers can be represented using
Nbitsin1’scomplementform?
00000000 (positive zero (+0))
11111111 (negative zero (-0))

An N-bit ones' complement numeral system can only represent


integers in the range −(2N−1−1)to2N−1−1
Arithmetic: 1’sComplement Binarysubtractionusing1’s
Representation complement

• Let’strythearithmeticfor1’scomplement i)Towritedown1’scomplementofthesubtrahend.
numbers?
ii) To add this with the minuend.

iii) If the result of addition has a carry over then it is dropped and
an 1 is added in the last bit. Else take 1's complement of the
result which will be negative

iv)Ifthereisnocarryover,then1’scomplementoftheresultof
addition is obtained to get the final result and it is negative.

57
BITS Pilani, Pilani Campus

Binary Subtraction

Example 1: 10101 - 00111

We take 1's complement of subtrahend 00111, which comes out 11000. Now, sum
1101 1101
them. So,
- 0101 + 1010
1’scomplement
10101+11000 =1 01101.
_____ ______
In the above result, we get the carry bit 1, so add this to the LSB of a given result, i.e.,
01101+1=01110, which is the answer.
1000 10111
Add carry 1

01000
Practice questions

Example 2: 10101 – 10111

We take 1's complement of subtrahend 10111, which comes out 01000. Now, add both
1. 1011011−10010=1001001
of the numbers. So,
2. 1010110−101010=101100
10101+01000 =11101.
3. 1000101−101100=11001
In the above result, we didn't get the carry bit. So calculate the 1's complement of the
result, i.e., 00010, which is the negative number and the final answer.
4. 101101−100111=110

2’sComplement Representation 2’sComplement Representation


What is the representation of 0?
• Positivenumbersarerepresentedasunsigned Number/Re
pr
2’s
Compleme
What is the range of numbers can be represented
binary numbers esentation nt
using N bits
000 0
• Howtorepresentanegative number? 001 1
in 2’scomplement form?

– Take1’scomplementof+ive number 010 2


– Add1togetthenegativeof that 011 3
– Example: 100 -4
• 011 (+3) 101 -3
• 100(1’s complement)
110 -2
• 101(2’s complement)
111 -1
63 64
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Arithmetic: 2’sComplement BinaryRepresentationusing2’s
Representation complement

• Let’stryarithmeticfor2’scomplementnumbers:
1101
+ 0101

• Representabovenumbersin6bitsandperform
the addition

65
BITS Pilani, Pilani Campus

Practice questions

1. 1011011−10010=1001001

2. 1010110−101010=101100

3. 1000101−101100=11001

4. 101101−100111=110
Overflow: 2’s Complement Overflow: 2’s Complement

• Let’strythefollowing operation: • Let’strythefollowing operation:

011010 (+26) 011010 (+26)


+001010 (+10) +001010 (+10)
100100(+36)

69 70
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Data Types

• Observations: • ADataTypeinprogrammingrefers to:


– Signofboth numbers – asetofvaluesassociatedwithacommonrepresentation
and operations
– Signof result
• e.g.IntegerinC(32bit machine)
– Setofvalues(-231to0to231- 1)
– 2’sComplement Representation
– Possibleoperations(+,-,*,/, %)
• Question
– Whataboutunsigned int?
72
BITS Pilani, Pilani Campus
Range for Unsigned /signed integers

• [0to 65,535] or [0 to 4,294,967,295] → 2 to 4 bytes –


Whataboutunsignedint? Unsigned

Unsigned int is a data type that can store the data values from zero to • A 2-byte signed integer can have a range from -32,768
positive numbers whereas signed int can store negative values also. It is usually to 32,767.
more preferable than signed int as unsigned int is larger than signed int.

• A signed integer is a 32-bit datum that encodes an integer


in the range [-2147483648 to 2147483647]

Character Representation

• Characterscanalsorepresentedbynatural
numbers
• Charactersarerepresentedusingunsigned int
inC language
– Rangeis0to255(8 bits)
– ASCIIcodesareusedtorepresentthe characters
– Englishalphabets(Uppercaseandlowercase),
ArabicNumerals,Punctuation,specialcharacters
aremaptothesetof unsigned int values(i.e.0 to
255)
75
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Doubts clarification

Thank You!

BITS Pilani, Pilani Campus

BITSPilani
Pilani Campus

Thank You!

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

COMPUTER PROGRAMMING
C LANGUAGE – Basic Concepts
BITS Pilani Contact Session 2 Prof.A. Jaya
Pilani Campus

Learning Objectives
➢ History of C language
➢ Data types
➢ Advantages of C language
➢ Input and Output functions
➢ Structure of a C Program
➢ Expressions and its types
➢ Character set of a C Program
➢ Type conversion
➢ Tokens and their classifications
- Constants
- Identifiers
- Variables
- Operators
- Strings
- Special Symbols

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BASICS in C BASICS in C

- It is a middle level language i.e. it supports high level as 2) Efficient and fast
well as low-level programming Due to its variety of data types and powerful operators.
- Developed by Dennis Ritchie at Bell Labs, 1972. Limited no of keywords(only 32 keywords)
- The UNIX OS was totally written in C. 3) Portable
Advantages of C Language It means that a C program written for one type of the computer
1) Robust language can be run on another type of the computer with little or no
▪ It has rich set of operators and built in functions modification.
▪ It can be used to write any complex program. 4) Expandability (Re-usability)
▪ The language is well suited for writing system software and Existing program or function may be included into another
business packages, because it combines the capabilities of program. No need for building from scratch i.e. new modules
an assembly language and an high level language need not be created every time.

5
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

BASICS in C BASICS in C –
STRUCTURE OF A C PROGRAM

5) Modularity
It Supports modular programming. The property of dividing
a big problem into sub problems is called as modularity.
The sub problems are called as modules or functions or.
Advantages of modularity
a) Workload can be divided and shared by more than one
programmers.
b) Errors can be identified and corrected easily.
c) Time is minimized

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C – BASICS in C - Structure of C Program
STRUCTURE OF A C PROGRAM
// subprogram section
A C program has the following format:
function header 1( )
Documentation section
{
Link section
variable declaration;
Data Definition section
statement 1;
Global declaration section
statement 2;
main() function section

{

Local declaration part
statement n;
Statement 1;
}
Statement 2;
function Header 2()
….Executablestatements/proceduralstatements
{
….
..
Statement m; }
}
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

Sample‘C’Program
Sample‘C’Program

#include <stdio.h> Program : To add Two numbers


int main()
{ printf("Hello world"); #include <stdio.h>
return 0; Void main()
} {
int a , b;
[Link] a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BASICS in C – Parts of a C Program Sample‘C’Program

1. Documentation section Program : To add Two numbers


Set of comment lines can be given to specify the name of the
program, like the author and the other details which the programmer
#include <stdio.h>
would like to use later.
There are two formats to enter the comments Void main()
(i) Starts with // if the comment is of a single line {
(ii)Starts with /* and ends with */ if the comment is of multiple lines // addition of two numbers documentation section
2. Linkage section int a , b;
It is used to link functions from the system library or from another C
a = 5;
program.
The format is b = 10;
#include Header file name / C program name c = a + b;
Enclosed in double quotes Printf(“Additionoftwono%d”,c);
Computer Programming Lecture 2 BITS Pilani, Pilani Campus } BITS Pilani, Pilani Campus

Sample‘C’Program BASICS in C – Parts of a C Program


3. Data Definition section
Program : To add Two numbers The symbolic constants are to be declared in this section. Some of
the values of the variables are constant throughout the program. This
#include <stdio.h> Linkage section type of constant is called as the Symbolic constant.
Void main()
{
// addition of two numbers documentation section
int a , b;
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
} BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Sample‘C’Program BASICS in C – Parts of a C Program
3. Data Definition section
Program : To add Two numbers The symbolic constants are to be declared in this section. Some of
the values of the variables are constant throughout the program. This
#include <stdio.h> Linkage section type of constant is called as the Symbolic constant.
4. Global declaration section
Void main()
The variables which are used in more than one functions are called
{
global variables. They should be declared in this section before all
// addition of two numbers documentation section the functions.
int a , b; data definition section
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
} BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

Sample‘C’Program- Program
: To add Two numbers BASICS in C – Parts of a C Program
5. main() function section
#include <stdio.h> Linkage section It is a subroutine / function that consists of one or more statements
Void main() designed to perform a specific task
Float pi = 3.14 global variable definition Each main function consists of two parts. They are
(i) Declaration part - It declares all the local variables used in the
{
function.
// addition of two numbers documentation section
(ii) Executable part : It is for defining the executable / procedural
int a , b; data definition section statements.
a = 5; • The two parts appear between the opening and the closing
b = 10; braces.
• All the procedural statements and declaration statements end
c = a + b; with semicolon.
Printf(“Additionoftwono%d”,c); • Every C program must have a main() function section from
} which the program starts it execution.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Sample‘C’Program- Program
: To add Two numbers BASICS in C – Parts of a C Program

#include <stdio.h> Linkage section


Void main() 6. Subprogram section
Contains all the user-defined functions that are called in the main
int pi = 3.14 global variable definition
function.
{ Note :-All sections, except the main function are optional. It means
// addition of two numbers documentation section that those section may not be present when they are not required.
int a , b; data definition section
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
}
22
BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

BASICS in C - Tokens BASICS in C - Tokens


CHARACTER SET USED IN C CONSTANTS
A set of characters, which are used to write the program The fixed values that do not change during the execution of a
- Alphabet(a..z, A..Z) program are called constants.
- Numeric digits(0-9) There are two types of constants.
- Special characters (+,-,*,% etc.,) They are Numeric constants and Non – Numeric constants
TOKENS (i) Numeric constant
A C program consists of various tokens. A token is classified into the It is a collection of numeric digits with optional + or - sign . There are
following: 1. A constant two types of numeric constants. They are
2. An identifier – a) Integer constant
3. A variable – Itreferstoasequenceofdigits,doesn’thaveanydecimalpoint.
Example: 15, +25, -32 are the Integer constants.
4. A keyword
– b) Float constant
5. An operator
– It refers to a sequence of digits with a decimal point. Example: 7.52,
6. A string +16.543, -23.14 are float constants.
7. A special symbol
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens BASICS in C - Tokens
Note:- A float constant can be expressed in the following form also.
IDENTIFIER -
7.52 can be expressed as .752e1 or .752E1 or .752E+1 or .752e+1
• It is a name used to identify a variable, function, or any other
(ii) Non Numeric constants user-defined item.
It is a collection of one or more characters. They are • An identifier starts with a letter A to Z, a to z, or an underscore '_'
– a) Single character constant followed by zero or more letters, underscores, and digits (0 to 9).
– Contains a single character enclosed within a pair of single
quotemarks.Example:‘X’,‘e’,‘5’,‘*’ Area_Triangle , Interest_rate , Sum
– b) String constant
– Sequence of characters enclosed within double quotes. The
– character may be letters, numbers and special characters. For
– example:“Hello1”,“[Link]'sschoolofmanagementstudies”,
– “?….!”,“5+3”

25 26
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

VARIABLE
BASICS in C - Tokens

• It is a quantity whose value can be changed during the The Rules for forming the identifiers/variable names are:-
execution of the program. • Must begin with an alphabet
• It is a data name used to store data value. • Maximum length of 36 characters.
• Uppercase and lowercase are significant. The variable Total is
• A variable may take different values at different different from the variable total.
situations during execution. • Should not be a keyword. The keywords are the words reserved
• A variable name can be chosen by the programmer in for doing some operations such as printf, scanf, etc.
meaningful way, i.e. it reflects the function or nature of • White space is not allowed.
the program.
• For example: amount, height, salary.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
#include <stdio.h>
int main() According to the availability in the parts of a program,
{
the variables are divided into two types. They are local
int number1, number2, sum;
float res;
and global variable.
printf("Enter the First Number to find = "); Local variable
scanf("%d",&number1);
printf("Enter the Second Number to find = ");
If a variable is used within a function only , the variable is
scanf("%d",&number2); a local variable. The variable should be declared
sum = number1 + number2; inside the function.
res = sum/2; //(float)sum/2;
printf("The Sum of %d and %d = %d\n", number1, number2, sum);
Global variable
printf("The Average of %d and %d = %.2f\n", number1, number2, res); If a variable is used in all the functions then the variable
return 0;
is called Global variable.
}
[Link]

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Sample‘C’Program- To add Two


BASICS in C - Tokens
numbers

KEYWORDS
#include <stdio.h> Linkage section Keywords are reserved words or tokens that have a special meaning
Void main() C has a set of 32 keywords
int pi = 3.14 global variable definition
{
// addition of two numbers documentation section
int a , b,c; local variable
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
}
BITS Pilani, Pilani Campus
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens Arithmetic operators
OPERATORS
An operator is a symbol that is used to perform arithmetic
calculations and logical comparisons such as Operator Meaning of Operator
A = B + C; // + is the operator for arithmetic calculation + additionorunaryplus
A > B // > is the operator for logical comparisons
- subtractionorunaryminus
* multiplication
/ division
remainderafterdivision
%
(modulodivision)

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Program- use of arithmetic


operations Output

// Working of arithmetic operators


a+b = 13
#include <stdio.h>
int main() a-b = 5
{
a*b = 36
int a = 9,b = 4, c;
c = a+b; a/b = 2
printf("a+b = %d \n",c); Remainder when a divided by b=1
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
STRINGS Declarations of Strings in C:
• Strings are nothing but an array of characters that end charstring[20]={‘s’,’a’,‘m’,‘p’,‘l’,‘e’,‘\0’};
with a null charstring[20]=“sample”;
• character(‘\0’).Thisnullcharacterindicatestheendof charstring[]=“sample”;
the string. Note :
• Strings are always enclosed in double-quotes. (i) whenwedeclarecharas“string[20]”,20bytesof
Whereas, a character is enclosed in single quotes in C memory space is allocated in the memory for holding
and C++. the string value.
(ii)Whenwedeclarecharas“string[]”,memoryspace
will be allocated as per the requirement during the
execution of the program.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C - Tokens BASICS in C - Tokens


• Parentheses(): These special symbols are used to indicate
SPECIAL SYMBOLS function calls and function parameters.
The following special symbols are used in C having some • Braces{}: These opening and ending curly braces mark the start
special meaning and thus, cannot be used for some and end of a block of code containing more than one executable
statement.
other purpose.[] () {}, ; * = #
• Comma (, ): It is used to separate more than one statements like
• Brackets[]: Opening and closing brackets are used as for separating parameters in function calls and variable
array element reference. These indicate single and declarations.
multidimensional subscripts. • Colon(:): It is an operator that essentially invokes something
called an initialization list.

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens

• Semicolon(;): It is known as a statement terminator. It SYMBOLIC CONSTANTS


indicatestheendofonelogicalentity.That’swhyeach If the value of a variable is not altered throughout the program,
individual statement must be ended with a semicolon. the constant is the symbolic constant.
• Asterisk (*): It is used to create a pointer variable. For example, the value of pi is always 22/7.
General format for defining a symbolic constant
• Assignment operator(=): It is used to assign values.
#define symbolic_name value_of_constant
• Pre-processor (#): The preprocessor is a macro
processor that is used automatically by the compiler to
transform your program before actual compilation.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

BASICS in C - Tokens

Rules for defining the symbolic constants are Examples:


(i) There is no space between # and define # define PI 3.14127
#defineCOMPANY“HCL”
(ii) There is a space between define and symbolic_name
#defineOPEN‘{‘
and also between symbolic_name andvalue_of_constant
#defineCLOSE‘}’
(iii) A program may have more than one symbolic constant
(iv) Only one symbolic constant can be defined using a single
#define
(v) It should not end with semicolon
(vi) For differentiating symbolic name and the variable the
symbolic_name may be given in upper case characters.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Learning Objectives BASICS in C – Input and Output

➢ Data types INPUT AND OUTPUT FUNCTIONS


➢ Input and Output functions • In C Language , there are no input and output statements.
• Functions are used for input and output Called I/O functions.
➢ Expressions and its types
• The function which is used to give the value of variable through
➢ Type conversion keyboard is called input function.
• The function which is used to display or print the value on the
screen is called output function.

46
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C - Formatting the Input


and Output
The control sting specifies the field format in which the data is to be
• In C language we use two built in functions, one is used entered.
for reading and another is used for displaying the %d –integer
result on the screen. %f – float
• These are scanf() and printf() functions. %c- char
%s – string
• They are stored in the header file named stdio.h.
% ld – long integer
• General format for scanf( ) function
%u – Unsigned Integer
scanf(“controlstring”,&variable1,
&variable2,……)

48
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C
Formatted input - We can specify the field width when we are
Example: reading the value.
1)scanf(“%d”,&x)– reading an integer value, the value The field speciation for reading the number is %wd, where w – is
will be stored in x the field width of the number to be read .
Example
2)scanf(“%d%f”,&x,&a)- reading a integer and a float scanf(“%2d%5d”,&num1,&num2);Iftheinputisgivenas:5031425
value. the value 50 is assigned to num1 and 31425 is assigned to num2.
Intheabovescanf()function,wedon’tuseanyformat.
This type of Input is known as Unformatted Input.

50
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C
Output Function : The output functions are used to print the value
• Suppose the input data is given as 31425 50 , then the
on the screen or to store the value on the file.
variable num1 will be assigned 31 and num2 will be
printf() is the function which is used to display the output on the
assigned to 425 and 50 is unread.
screen.
• An input field may be skipped by specifying * in the The General format of the printf() function is
place of field width. printf(“controlstring”,variable1,variable2,…..)
• Example the statement scanf(“%d%*d%d),&a,&b); Example
• Will assign the data 123 456 789 as follows: 123 is printf(“%d”,x);//printingtheintegervaluex.
assigned to a , 456 skipped because of * and 789 to b printf(“%d%f”,x,a);//printingaintegerandfloatvalueusinga
single printf function
.

52
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C

Formatted output - Some of the escape sequence characters are


• Output can be formatted using control strings as well \a – Producing bell sound
\n – new line
• The control string consists of three types of items.
\b – back space
• Characters that will be printed on the screen as they
\f – form feed
appear ,
\r – carriage return
• The control strings as specified in the input statements \t - horizontal tab
and Escape sequences- \v – vertical tab
• Escape sequences represent non-printable and special
characters in character and literal strings.

54
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C BASICS in C

Examples DATATYPES
printf(“a=%f\nb=%f”,a,b); Data type specifies the type of data which is going to be assigned or
printf(“”sum=%d“,1234); stored in a variable. There are four data type
printf(“%6d”,9876) 1. Primary data type – Available in most of the computer languages.
printf(“%-6d”,9876) 2. User-defined data types – Data type created by the user
printf(“%06”,9876); 3. Structured data types (arrays and structures) – Data type to be
printf(“%7.2f”,y); used for grouping more than one data.
printf(“%-7.2f”,y); 4. Special Data type - They are Pointer data type for declaring
printf(“%10.2e”,y); pointer variable and Empty data set (void) – Data type which has
printf(“%11.4e”,-y); nothing.
1.

55 56
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C

Primary data type 1) Integer data type


The data type which is available in most of the languages • Signed int – 16 bits, both +ve and –ve values, range –32768 to
32767
is called as the primary data type. It is also called as
• Unsigned int –16 bits, only positive values, range 0 to 655535
the standard data type.
• Signed short int – 8 bits , both +ve and –ve values, range –128 to
127
• Unsigned short int – 8 bits, only positive values, range 0 to 255
• Signed long int – 32 bits, both +ve and –ve values, range –
214748364 to 2147483647
• Unsigned long int – 32 bits, only positive values, range 0 to
4294966295
2) Floating data type (float, double, long double)
3) Char data type (signed char, unsigned char)

58
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C BASICS in C
2. User defined data type
A data type which is created by the user is called as the user defined The general format is
data type. enumidentifier{value1,value2,…..valuen};
There are two types of user defined data types. They are The enumerated variables v1,v2,..vn can only have one of the values
a) Typedef - It is used to give a name to the available data type. value1,value2..valuen. the assignments of the following types are
The general format is valid.
typedef datatype name; v1=value3
E.g. typedef int x; v5=value1
Now we can declare the integer variables a and b as follows:
x a,b; // which is equivalent to int a,b;
b) Enumerated data type
Which can be used to declare variables that can have one of the
values enclosed within the braces(known as enumeration constants).

59 60
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
Example Note:-
enum day {Monday, Tuesday, Wednesday, Thursdat, • The compiler automatically assigns integer digits
Friday, Saturday, Sunday}; beginning with 0 to all the enumeration constants.
enum day week_st, week_end; • That is value1 is assigned to 0
week_st=Monday; • value2 is assigned to 1 and so on.
week_end=Friday; • The automatic assignments can be overridden by
assigning values explicitly to the enumeration
constants.
• enumday{Monday=1,Tuesday,…..Sunday};
• The remaining constants are assigned values that
increase successively by 1.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C BASICS in C
Declaration of Variables: The general format for declaring a variable is
• A variable is a holder of values. Datatype v1, v2, v3, ...... vn; where v1 , v2 ,.... vn are the
• All the variables used in the program should be declared variables
in the declaration part. Datatype specifies which type of data can be assigned to the
• The declaration specifies what type of data is going to be held by variables v1, v2, .... vn.
the variable. More than one variables with the same datatype can be declared
using a single statement.

63 64
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C
Operators and Expressions
Example : It is a collection of variables, constants and operators.
int x , y , z; [ the variables x , y and z are integer type There are three types of expressions. They are
variables and the values assigned for the variables 1. Arithmetic expression : An arithmetic expression is an
must be integer constants ] expression in which the variables and constants are combined with
the arithmetic operators. The arithmetic operators are
float a , b; [ the variables x , y and z are the float
* - Multiplication
variables and the values assigned for the variables
/ - Division
must be float constants ]
+ - Addition
char c; [ the variables c is the character variables and
- - Subtraction
the values assigned for the variables must be
%- Modulo divisor
character constant ]
Examples for arithmetic expression
a + b % 35, z – 25 + 45

66
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C BASICS in C

Relational expression : A relational expression is an expression in Examples for relational expression :


which the variables and constants are combined with the relational (a) a >= b [ true if the value of a is greater than or equal
operators. The resultant value of a relational expression is either true to the value of b. otherwise it is false ]
or false. The relational operators are (b) b = = c [ true if the value of b is equal to the value of c,
< - Lesser than otherwise the value is false]
> - Greater than (c) a < ( b + c ) [ true if the value of a is lesser than the value of b +
<= - Less than or equal to c , otherwise the value of the expression is false]
>= - Greater than or equal to
== - Equal to
!= - Not Equal to

67 68
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
• Logical expression : A Logical expression is an General format of a Logical Expression is
expression in which the variables and constants are Relational expression 1 logical operator relational
combined with the Logical operators. expression 2
• The logical operators are E.g. (a<b)&&(c>d);
• && - AND
• || - OR
• ! - NOT

• Logical operators are used to combine more than one • Sample program biggest of two numbers
relational expressions . • Biggest of three numbers

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C

The result of the relational expression is also either true or false. Examples for Logical expression :
The relational expression is evaluated as follows: a. ( (a > b ) && ( a > c ) )
(a) If more than one relational expressions are combined with the
&& operators , the logical expression is true only if all the b. ( ( Mark1 > 50 ) | | ( Mark2 > 50 ) )
relational expressions are true.
(b) If more than one relational expressions are combined with the
| | operators , the logical expression is true only if any one of the
relational expressions is true.
(c) ! is the negated operator. If the relational expression followed by
this operator is false, the logical expression is true and vice
versa.

71
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Program – logical operator OR
And
(a == b) && (c > 5) (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
evaluates to 1 because both operands (a != b) || (c < b) evaluates to 0 because both operand (a !=
(a == b) and (c > b) is 1 (true). b) and (c < b) are 0 (false).

(a == b) && (c < b) evaluates to 0 because operand


(c < b) is 0 (false).

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Not BASICS in C
Evaluation of an expression - If an arithmetic expression is given,
!(a != b) evaluates to 1 because operand (a != b) is 0 there are some rules to be followed to evaluate it.
(false). Hence, !(a != b) is 1 (true). These rules are called as the priority rules.
They are also known as hierarchy rules or Operator precedence and
associativity.
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence,
!(a == b) is 0 (false).

76
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
Expression rules

Rule 1 :- If an expression contains parentheses , the


expression within the parentheses will be performed
first. Within the parentheses , the priority is to be
followed.
Rule 2 :- If it has more than parentheses , the inner
parenthesis is performed first.
Rule 3:- If more than one symbols of same priority , it
will be evaluated from left to right.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C
Example for evaluating an expression
7 * (5 + 15) / (2 * 5) - 3;
Let X = 2 , Y =5 then the value of the expression
((( Y - 1 ) / X ) * ( X + Y ) ) is calculated as:-
First evaluation is done on the innermost parenthesis First step :
( Y - 1) = ( 5 - 1 ) = 4 = T1 7 * (20) / (2 * 5) - 3;
Second evaluation in done on next outer parenthesis
Next
( T 1 / X ) = ( 4 / 2 ) = 2 = T2
7 * (20) / (10) - 3;
Third evaluation is made on the next set parenthesis
( X + Y ) = ( 2 + 5 ) = 7 = T3 Next
Last evaluation is for finding the value of whole expression 140/ (10) - 3;
( T2 * T3 ) = ( 2 * 7 ) = 14 Next
The evaluations are made according to the priority rule.
14 – 3
Ans : 11
79
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
1
Symbol Typeofoperation Associativity

BASICS in C [ ] ( ) . ->
++ -- (postfix)
Expression Lefttoright

sizeof & * + - ~ ! Unary Righttoleft


++ -- (prefix)

Type conversion typecasts Unary Righttoleft


*/% Multiplicative Lefttoright
The process of converting the data from one type to another type is
+- Additive Lefttoright
called type conversion. There are two types of type conversion. They << >> Bitwiseshift Lefttoright
are < > <= >= Relational Lefttoright
• Implicit type conversion == != Equality Lefttoright
& Bitwise-AND Lefttoright
• Explicit type conversion.
^ Bitwise-exclusive-OR Lefttoright
| Bitwise-inclusive-OR Lefttoright
• Int a = 5
&& Logical-AND Lefttoright
• Int a = 5.3
|| Logical-OR Lefttoright
• Float a = 5.0
?: Conditional-expression Righttoleft
= *= /= %= Simpleandcompound Righttoleft
2
+= -= <<= >>= &= assignment
^= |=
, Sequentialevaluation Lefttoright
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Implicit type conversion

The conversion which is automatically done by the When a mixed data type expression is found in the
compiler is called expression, the compiler converts the result of the
automatic type conversion. expression into the data type of the operands which
Example: If a statement is given as c=a/b; takesmorenumberofbytes.Since‘b’isofintegerdata
type, the value is automatically converted into float
Where a is a float and b is an integer. Then the expression though‘b’isinteger.
is the mixed data type expression.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


BASICS in C BASICS in C
Explicit type conversion
Instead of automatic type conversion , the user can change type of Example
the data in an expression. It is called as the explicit data type Assume that 10 and 3 are the values of two integers a and b
conversion. respectively.
It is also called as the type casting. After the statement c=a/b; is evaluated , the value of c
For type casting the general format is is 3.0, even though c is float .
(datatype) operand; Instead , if the type casting is made
where the operand may be either a variable or a constant as follows:
c=(float)a/b;
the value of c is 3.3333.
Note:-
Type conversion is not changing the type of variable. Instead it
changes the datatype for the value of the variable.

85 86
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

Thanks

87
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

COMPUTER PROGRAMMING
C LANGUAGE – Basic Concepts
BITS Pilani Contact Session 3 Prof.A. Jaya
Pilani Campus

Learning Objectives
➢ History of C language
➢ Data types
➢ Advantages of C language
➢ Input and Output functions
➢ Structure of a C Program
➢ Expressions and its types
➢ Character set of a C Program
➢ Type conversion
➢ Tokens and their classifications
- Constants
- Identifiers
- Variables
- Operators
- Strings
- Special Symbols

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BASICS in C BASICS in C

- It is a middle level language i.e. it supports high level as 2) Efficient and fast
well as low-level programming Due to its variety of data types and powerful operators.
- Developed by Dennis Ritchie at Bell Labs, 1972. Limited no of keywords(only 32 keywords)
- The UNIX OS was totally written in C. 3) Portable
Advantages of C Language It means that a C program written for one type of the computer
1) Robust language can be run on another type of the computer with little or no
▪ It has rich set of operators and built in functions modification.
▪ It can be used to write any complex program. 4) Expandability (Re-usability)
▪ The language is well suited for writing system software and Existing program or function may be included into another
business packages, because it combines the capabilities of program. No need for building from scratch i.e. new modules
an assembly language and an high level language need not be created every time.

5
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

BASICS in C BASICS in C –
STRUCTURE OF A C PROGRAM

5) Modularity
It Supports modular programming. The property of dividing
a big problem into sub problems is called as modularity.
The sub problems are called as modules or functions or.
Advantages of modularity
a) Workload can be divided and shared by more than one
programmers.
b) Errors can be identified and corrected easily.
c) Time is minimized

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C – BASICS in C - Structure of C Program
STRUCTURE OF A C PROGRAM
// subprogram section
A C program has the following format:
function header 1( )
Documentation section
{
Link section
variable declaration;
Data Definition section
statement 1;
Global declaration section
statement 2;
main() function section

{

Local declaration part
statement n;
Statement 1;
}
Statement 2;
function Header 2()
….Executablestatements/proceduralstatements
{
….
..
Statement m; }
}
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

Sample‘C’Program
Sample‘C’Program

#include <stdio.h> Program : To add Two numbers


int main()
{ printf("Hello world"); #include <stdio.h>
return 0; Void main()
} {
int a , b;
[Link] a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BASICS in C – Parts of a C Program Sample‘C’Program

1. Documentation section Program : To add Two numbers


Set of comment lines can be given to specify the name of the
program, like the author and the other details which the programmer
#include <stdio.h>
would like to use later.
There are two formats to enter the comments Void main()
(i) Starts with // if the comment is of a single line {
(ii)Starts with /* and ends with */ if the comment is of multiple lines // addition of two numbers documentation section
2. Linkage section int a , b;
It is used to link functions from the system library or from another C
a = 5;
program.
The format is b = 10;
#include Header file name / C program name c = a + b;
Enclosed in double quotes Printf(“Additionoftwono%d”,c);
Computer Programming Lecture 2 BITS Pilani, Pilani Campus } BITS Pilani, Pilani Campus

Sample‘C’Program BASICS in C – Parts of a C Program


3. Data Definition section
Program : To add Two numbers The symbolic constants are to be declared in this section. Some of
the values of the variables are constant throughout the program. This
#include <stdio.h> Linkage section type of constant is called as the Symbolic constant.
Void main()
{
// addition of two numbers documentation section
int a , b;
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
} BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Sample‘C’Program BASICS in C – Parts of a C Program
3. Data Definition section
Program : To add Two numbers The symbolic constants are to be declared in this section. Some of
the values of the variables are constant throughout the program. This
#include <stdio.h> Linkage section type of constant is called as the Symbolic constant.
4. Global declaration section
Void main()
The variables which are used in more than one functions are called
{
global variables. They should be declared in this section before all
// addition of two numbers documentation section the functions.
int a , b; data definition section
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
} BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

Sample‘C’Program- Program
: To add Two numbers BASICS in C – Parts of a C Program
5. main() function section
#include <stdio.h> Linkage section It is a subroutine / function that consists of one or more statements
Void main() designed to perform a specific task
Float pi = 3.14 global variable definition Each main function consists of two parts. They are
(i) Declaration part - It declares all the local variables used in the
{
function.
// addition of two numbers documentation section
(ii) Executable part : It is for defining the executable / procedural
int a , b; data definition section statements.
a = 5; • The two parts appear between the opening and the closing
b = 10; braces.
• All the procedural statements and declaration statements end
c = a + b; with semicolon.
Printf(“Additionoftwono%d”,c); • Every C program must have a main() function section from
} which the program starts it execution.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Sample‘C’Program- Program
: To add Two numbers BASICS in C – Parts of a C Program

#include <stdio.h> Linkage section


Void main() 6. Subprogram section
Contains all the user-defined functions that are called in the main
int pi = 3.14 global variable definition
function.
{ Note :-All sections, except the main function are optional. It means
// addition of two numbers documentation section that those section may not be present when they are not required.
int a , b; data definition section
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
}
22
BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

BASICS in C - Tokens BASICS in C - Tokens


CHARACTER SET USED IN C CONSTANTS
A set of characters, which are used to write the program The fixed values that do not change during the execution of a
- Alphabet(a..z, A..Z) program are called constants.
- Numeric digits(0-9) There are two types of constants.
- Special characters (+,-,*,% etc.,) They are Numeric constants and Non – Numeric constants
TOKENS (i) Numeric constant
A C program consists of various tokens. A token is classified into the It is a collection of numeric digits with optional + or - sign . There are
following: 1. A constant two types of numeric constants. They are
2. An identifier – a) Integer constant
3. A variable – Itreferstoasequenceofdigits,doesn’thaveanydecimalpoint.
Example: 15, +25, -32 are the Integer constants.
4. A keyword
– b) Float constant
5. An operator
– It refers to a sequence of digits with a decimal point. Example: 7.52,
6. A string +16.543, -23.14 are float constants.
7. A special symbol
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens BASICS in C - Tokens
Note:- A float constant can be expressed in the following form also.
IDENTIFIER -
7.52 can be expressed as .752e1 or .752E1 or .752E+1 or .752e+1
• It is a name used to identify a variable, function, or any other
(ii) Non Numeric constants user-defined item.
It is a collection of one or more characters. They are • An identifier starts with a letter A to Z, a to z, or an underscore '_'
– a) Single character constant followed by zero or more letters, underscores, and digits (0 to 9).
– Contains a single character enclosed within a pair of single
quotemarks.Example:‘X’,‘e’,‘5’,‘*’ Area_Triangle , Interest_rate , Sum
– b) String constant
– Sequence of characters enclosed within double quotes. The
– character may be letters, numbers and special characters. For
– example:“Hello1”,“[Link]'sschoolofmanagementstudies”,
– “?….!”,“5+3”

25 26
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

VARIABLE
BASICS in C - Tokens

• It is a quantity whose value can be changed during the The Rules for forming the identifiers/variable names are:-
execution of the program. • Must begin with an alphabet
• It is a data name used to store data value. • Maximum length of 36 characters.
• Uppercase and lowercase are significant. The variable Total is
• A variable may take different values at different different from the variable total.
situations during execution. • Should not be a keyword. The keywords are the words reserved
• A variable name can be chosen by the programmer in for doing some operations such as printf, scanf, etc.
meaningful way, i.e. it reflects the function or nature of • White space is not allowed.
the program.
• For example: amount, height, salary.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
#include <stdio.h>
int main() According to the availability in the parts of a program,
{
the variables are divided into two types. They are local
int number1, number2, sum;
float res;
and global variable.
printf("Enter the First Number to find = "); Local variable
scanf("%d",&number1);
printf("Enter the Second Number to find = ");
If a variable is used within a function only , the variable is
scanf("%d",&number2); a local variable. The variable should be declared
sum = number1 + number2; inside the function.
res = sum/2; //(float)sum/2;
printf("The Sum of %d and %d = %d\n", number1, number2, sum);
Global variable
printf("The Average of %d and %d = %.2f\n", number1, number2, res); If a variable is used in all the functions then the variable
return 0;
is called Global variable.
}
[Link]

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Sample‘C’Program- To add Two


BASICS in C - Tokens
numbers

KEYWORDS
#include <stdio.h> Linkage section Keywords are reserved words or tokens that have a special meaning
Void main() C has a set of 32 keywords
int pi = 3.14 global variable definition
{
// addition of two numbers documentation section
int a , b,c; local variable
a = 5;
b = 10;
c = a + b;
Printf(“Additionoftwono%d”,c);
}
BITS Pilani, Pilani Campus
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens Arithmetic operators
OPERATORS
An operator is a symbol that is used to perform arithmetic
calculations and logical comparisons such as Operator Meaning of Operator
A = B + C; // + is the operator for arithmetic calculation + additionorunaryplus
A > B // > is the operator for logical comparisons
- subtractionorunaryminus
* multiplication
/ division
remainderafterdivision
%
(modulodivision)

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Program- use of arithmetic


operations Output

// Working of arithmetic operators


a+b = 13
#include <stdio.h>
int main() a-b = 5
{
a*b = 36
int a = 9,b = 4, c;
c = a+b; a/b = 2
printf("a+b = %d \n",c); Remainder when a divided by b=1
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
STRINGS Declarations of Strings in C:
• Strings are nothing but an array of characters that end charstring[20]={‘s’,’a’,‘m’,‘p’,‘l’,‘e’,‘\0’};
with a null charstring[20]=“sample”;
• character(‘\0’).Thisnullcharacterindicatestheendof charstring[]=“sample”;
the string. Note :
• Strings are always enclosed in double-quotes. (i) whenwedeclarecharas“string[20]”,20bytesof
Whereas, a character is enclosed in single quotes in C memory space is allocated in the memory for holding
and C++. the string value.
(ii)Whenwedeclarecharas“string[]”,memoryspace
will be allocated as per the requirement during the
execution of the program.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C - Tokens BASICS in C - Tokens


• Parentheses(): These special symbols are used to indicate
SPECIAL SYMBOLS function calls and function parameters.
The following special symbols are used in C having some • Braces{}: These opening and ending curly braces mark the start
special meaning and thus, cannot be used for some and end of a block of code containing more than one executable
statement.
other purpose.[] () {}, ; * = #
• Comma (, ): It is used to separate more than one statements like
• Brackets[]: Opening and closing brackets are used as for separating parameters in function calls and variable
array element reference. These indicate single and declarations.
multidimensional subscripts. • Colon(:): It is an operator that essentially invokes something
called an initialization list.

Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens

• Semicolon(;): It is known as a statement terminator. It SYMBOLIC CONSTANTS


indicatestheendofonelogicalentity.That’swhyeach If the value of a variable is not altered throughout the program,
individual statement must be ended with a semicolon. the constant is the symbolic constant.
• Asterisk (*): It is used to create a pointer variable. For example, the value of pi is always 22/7.
General format for defining a symbolic constant
• Assignment operator(=): It is used to assign values.
#define symbolic_name value_of_constant
• Pre-processor (#): The preprocessor is a macro
processor that is used automatically by the compiler to
transform your program before actual compilation.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus

BASICS in C - Tokens

Rules for defining the symbolic constants are Examples:


(i) There is no space between # and define # define PI 3.14127
#defineCOMPANY“HCL”
(ii) There is a space between define and symbolic_name
#defineOPEN‘{‘
and also between symbolic_name andvalue_of_constant
#defineCLOSE‘}’
(iii) A program may have more than one symbolic constant
(iv) Only one symbolic constant can be defined using a single
#define
(v) It should not end with semicolon
(vi) For differentiating symbolic name and the variable the
symbolic_name may be given in upper case characters.

BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Learning Objectives BASICS in C – Input and Output

➢ Data types INPUT AND OUTPUT FUNCTIONS


➢ Input and Output functions • In C Language , there are no input and output statements.
• Functions are used for input and output Called I/O functions.
➢ Expressions and its types
• The function which is used to give the value of variable through
➢ Type conversion keyboard is called input function.
• The function which is used to display or print the value on the
screen is called output function.

46
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C - Formatting the Input


and Output
The control sting specifies the field format in which the data is to be
• In C language we use two built in functions, one is used entered.
for reading and another is used for displaying the %d –integer
result on the screen. %f – float
• These are scanf() and printf() functions. %c- char
• They are stored in the header file named stdio.h. %s – string
% ld – long integer
• General format for scanf( ) function
%u – Unsigned Integer
scanf(“controlstring”,&variable1,&variable2,……)

48
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C

• Formatted input - We can specify the field width when we are


Example:
reading the value.
1) scanf(“%d”,&x) – reading an integer value, the value
• The field speciation for reading the number is %wd, where w –
will be stored in x is the field width of the number to be read .
2) scanf(“%d%f”,&x,&a) - reading a integer and a float
value. Example
In the above scanf ( ) function , we don’t use any format. • scanf(“%2d%5d”,&num1,&num2);Iftheinputisgivenas:50
31425
This type of Input is known as Unformatted Input. • the value 50 is assigned to num1 and 31425 is assigned to num2.

50
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C
• Output Function : The output functions are used to print the
• Suppose the input data is given as 31425 50 , then the value on the screen or to store the value on the file.
variable num1 will be assigned 31 and num2 will be • printf() is the function which is used to display the output on the
assigned to 425 and 50 is unread. screen.
• An input field may be skipped by specifying * in the • The General format of the printf() function is
place of field width. printf(“controlstring”,variable1,variable2,…..)
• Example the statement scanf(“%d%*d%d),&a,&b); Example
• Will assign the data 123 456 789 as follows: 123 is • printf(“%d”,x); // printing the integer value x.
assigned to a , 456 skipped because of * and 789 to b • printf(“%d%f”,x,a); // printing an integer and float value using a
• single printf function

52
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
Formatted output
BASICS in C

• Output can be formatted using control strings as well Some of the escape sequence characters are
• The control string consists of three types of items. \a – Producing bell sound
\n – new line
• Characters that will be printed on the screen as they
\b – back space
appear
\f – form feed
• The control strings as specified in the input statements
\r – carriage return
and Escape sequences-
\t - horizontal tab
• Escape sequences represent non-printable and special \v – vertical tab
characters in character and literal strings.

54
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C BASICS in C

Examples DATATYPES
printf(“a=%f\nb=%f”,a,b); Data type specifies the type of data which is going to be assigned or
printf(“”sum=%d“,1234); stored in a variable. There are four data type
printf(“%6d”,9876)
printf(“%-6d”,9876) 1. Primary data type – Available in most of the computer languages.
printf(“%06”,9876); 2. User-defined data types – Data type created by the user
printf(“%7.2f”,y); 3. Structured data types (arrays and structures) – Data type to be
printf(“%-7.2f”,y); used for grouping more than one data.
printf(“%10.2e”,y); 4. Special Data type - They are Pointer data type for declaring
printf(“%11.4e”,-y); pointer variable and Empty data set (void) – Data type which has
nothing.

55 56
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C

Primary data type 1) Integer data type


The data type which is available in most of the languages • Signed int – 16 bits, both +ve and –ve values, range –32768 to
32767
is called as the primary data type. It is also called as
• Unsigned int –16 bits, only positive values, range 0 to 655535
the standard data type.
• Signed short int – 8 bits , both +ve and –ve values, range –128 to
127
• Unsigned short int – 8 bits, only positive values, range 0 to 255
• Signed long int – 32 bits, both +ve and –ve values, range –
214748364 to 2147483647
• Unsigned long int – 32 bits, only positive values, range 0 to
4294966295
2) Floating data type (float, double, long double)
3) Char data type (signed char, unsigned char)

58
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C BASICS in C
2. User defined data type
A data type which is created by the user is called as the user defined The general format is
data type. enumidentifier{value1,value2,…..valuen};
There are two types of user defined data types. They are The enumerated variables v1,v2,..vn can only have one of the values
a) Typedef - It is used to give a name to the available data type. value1,value2..valuen. the assignments of the following types are
The general format is valid.
typedef datatype name; v1=value3
E.g. typedef int x; v5=value1
Now we can declare the integer variables a and b as follows:
x a,b; // which is equivalent to int a,b;
b) Enumerated data type
Which can be used to declare variables that can have one of the
values enclosed within the braces(known as enumeration constants).

59 60
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
Example Note:-
enum day {Monday, Tuesday, Wednesday, Thursdat, • The compiler automatically assigns integer digits
Friday, Saturday, Sunday}; beginning with 0 to all the enumeration constants.
enum day week_st, week_end; • That is value1 is assigned to 0
week_st=Monday; • value2 is assigned to 1 and so on.
week_end=Friday; • The automatic assignments can be overridden by
assigning values explicitly to the enumeration
constants.
• enumday{Monday=1,Tuesday,…..Sunday};
• The remaining constants are assigned values that
increase successively by 1.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C BASICS in C
Declaration of Variables: The general format for declaring a variable is
• A variable is a holder of values. Datatype v1, v2, v3, ...... vn; where v1 , v2 ,.... vn are the
• All the variables used in the program should be declared variables
in the declaration part. Datatype specifies which type of data can be assigned to the
• The declaration specifies what type of data is going to be held by variables v1, v2, .... vn.
the variable. More than one variables with the same datatype can be declared
using a single statement.

63 64
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C
Operators and Expressions
Example : It is a collection of variables, constants and operators.
int x , y , z; [ the variables x , y and z are integer type There are three types of expressions. They are
variables and the values assigned for the variables 1. Arithmetic expression : An arithmetic expression is an
must be integer constants ] expression in which the variables and constants are combined with
the arithmetic operators. The arithmetic operators are
float a , b; [ the variables x , y and z are the float
* - Multiplication
variables and the values assigned for the variables
/ - Division
must be float constants ]
+ - Addition
char c; [ the variables c is the character variables and
- - Subtraction
the values assigned for the variables must be
%- Modulo divisor
character constant ]
Examples for arithmetic expression
a + b % 35, z – 25 + 45

66
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C BASICS in C

Relational expression : A relational expression is an expression in Examples for relational expression :


which the variables and constants are combined with the relational (a) a >= b [ true if the value of a is greater than or equal
operators. The resultant value of a relational expression is either true to the value of b. otherwise it is false ]
or false. The relational operators are (b) b = = c [ true if the value of b is equal to the value of c,
< - Lesser than otherwise, the value is false]
> - Greater than (c) a < ( b + c ) [ true if the value of a is lesser than the value of b +
<= - Less than or equal to c , otherwise the value of the expression is false]
>= - Greater than or equal to
== - Equal to
!= - Not Equal to

67 68
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
Logical expression

• Logical expression : A Logical expression is an General format of a Logical Expression is


expression in which the variables and constants are Relational expression 1 logical operator relational
combined with the Logical operators. expression 2
• The logical operators are E.g. (a<b)&&(c>d);
• && - AND
• || - OR
• ! - NOT

• Logical operators are used to combine more than one • Sample program biggest of two numbers
relational expressions . • Biggest of three numbers

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C

The result of the relational expression is also either true or false. r.e1 r.E 2 And Or
The relational expression is evaluated as follows: True True true True
(a) If more than one relational expressions are combined with the True False false True
&& operators , the logical expression is true only if all the False True False True
relational expressions are true. False false false False
(b) If more than one relational expressions are combined with the
| | operators , the logical expression is true only if any one of the
relational expressions is true.
(c) ! is the negated operator. If the relational expression followed by
this operator is false, the logical expression is true and vice
versa.

71
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Program – logical operator
And
Examples for Logical expression : (a == b) && (c > 5)
a. ( (a > b ) && ( a > c ) ) evaluates to 1 because both operands
b. ( ( Mark1 > 50 ) | | ( Mark2 > 50 ) ) (a == b) and (c > b) is 1 (true).

(a == b) && (c < b) evaluates to 0 because operand


(c < b) is 0 (false).

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

OR Not

(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true). !(a != b) evaluates to 1 because operand (a != b) is 0


(a != b) || (c < b) evaluates to 0 because both operand (a != (false). Hence, !(a != b) is 1 (true).
b) and (c < b) are 0 (false).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence,
!(a == b) is 0 (false).

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


BASICS in C Expression rules
Evaluation of an expression - If an arithmetic expression is given,
there are some rules to be followed to evaluate it. Rule 1 :- If an expression contains parentheses , the
These rules are called as the priority rules. expression within the parentheses will be performed
They are also known as hierarchy rules or Operator precedence and first. Within the parentheses , the priority is to be
associativity. followed.
Rule 2 :- If it has more than parentheses , the inner
parenthesis is performed first.
Rule 3:- If more than one symbols of same priority , it
will be evaluated from left to right.

77
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BASICS in C
Example for evaluating an expression
Let X = 2 , Y =5 then the value of the expression
((( Y - 1 ) / X ) * ( X + Y ) ) is calculated as:-
First evaluation is done on the innermost parenthesis
( Y - 1) = ( 5 - 1 ) = 4 = T1
Second evaluation in done on next outer parenthesis
( T 1 / X ) = ( 4 / 2 ) = 2 = T2
Third evaluation is made on the next set parenthesis
( X + Y ) = ( 2 + 5 ) = 7 = T3
Last evaluation is for finding the value of whole expression
( T2 * T3 ) = ( 2 * 7 ) = 14
The evaluations are made according to the priority rule.

80
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C

7 * (5 + 15) / (2 * 5) - 3; Type conversion


The process of converting the data from one type to another type is
called type conversion. There are two types of type conversion. They
First step :
are
7 * (20) / (2 * 5) - 3; • Implicit type conversion
Next • Explicit type conversion.
7 * (20) / (10) - 3;
• Int a = 5
Next
• Int a = 5.3
140/ (10) - 3;
• Float a = 5.0
Next
14 – 3
Ans : 11
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

Implicit type conversion


Symbol Typeofoperation Associativity
[ ] ( ) . -> Expression Lefttoright
++ -- (postfix)
sizeof & * + - ~ ! Unary Righttoleft
++ -- (prefix)
typecasts Unary Righttoleft
The conversion which is automatically done by the
*/% Multiplicative Lefttoright
+- Additive Lefttoright compiler is called
<< >> Bitwiseshift Lefttoright automatic type conversion.
< > <= >= Relational Lefttoright
== != Equality Lefttoright
Example: If a statement is given as c=a/b;
& Bitwise-AND Lefttoright Where a is a float and b is an integer. Then the expression
^ Bitwise-exclusive-OR Lefttoright is the mixed data type expression.
| Bitwise-inclusive-OR Lefttoright
&& Logical-AND Lefttoright
|| Logical-OR Lefttoright
?: Conditional-expression Righttoleft
= *= /= %= Simpleandcompound Righttoleft
2
+= -= <<= >>= &= assignment
^= |=
, Sequentialevaluation Lefttoright
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BASICS in C
Explicit type conversion
When a mixed data type expression is found in the Instead of automatic type conversion , the user can change type of
expression, the compiler converts the result of the the data in an expression. It is called as the explicit data type
expression into the data type of the operands which conversion.
takesmorenumberofbytes.Since‘b’isofintegerdata It is also called as the type casting.
type, the value is automatically converted into float For type casting the general format is
though‘b’isinteger. (datatype) operand;
where the operand may be either a variable or a constant

86
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus

BASICS in C Conditional operator


Conditional Operators : Also known as ternary operator
Example It is a decision making operator. These operators are also called as
Assume that 10 and 3 are the values of two integers a and b the ? : operator. The general format of the operator is
respectively. Variable = Condition ? a.e 1 : a.e 2;
After the statement c=a/b; is evaluated , the value of c where Condition is either a relational Expression or a Logical
is 3.0, even though c is float . Expression which evaluates to either True or False, And a.e 1 and a.e
Instead , if the type casting is made 2 are arithmetic expressions.
as follows: If the condition is true , the value of the a.e. 1 is assigned to the
c=(float)a/b; variable on the L.H.S. Otherwise , the value of the a.e. 2 is assigned
to variable.
the value of c is 3.3333.
Example: big = (x > y )? x : y;
Note:-
For the above statement if the values of x and y are 10 and 12 , then big = 12
Type conversion is not changing the type of variable. Instead it because the condition is false, so the value of the expression 2 ( that is the
changes the datatype for the value of the variable. value of y ) is assigned to big. If the values of x and y are 100 and 10 , then
big = 100 because the condition is true, so the value of the expression 1 (
that is the value of x ) is assigned to big.
87 88
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Thanks

89
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

COMPUTER PROGRAMMING
FUNCTIONS
BITS Pilani Contactsession4 [Link]
Pilani Campus

Learning Objectives FUNCTIONS

➢What are functions? • If a large or complex problem is given to be


solved, it is difficult to maintain , test and
➢ Advantages of Functions debug the code of the program.
➢ Types of functions • If this program is divided into different parts,
a. Built in functions then they can be tested, debugged and
maintained separately and these operations
b. User defined functions are very easy.
➢Different types of user defined functions • Each part may be independently processed
and are combined into a single unit to get the
solution for the complex problem.

3 4
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
Advantages:

• The sub parts are known as Modules. 1. It supports the top-down programming approach. That is after defining
• They are also known as subroutines or functions. the overall logic of the program in the calling function, we can define the
• The functions in C can be easily defined and used. called functions.
2. The code is reduced.
3. Errors or faults can be identified easily.
4. A function in another program can be called to our current program. This
property is known as Expandability.
5. Time and space are saved.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

TYPES OF FUNCTIONS
TYPES OF FUNCTIONS
The functions of C are divided into two categories. They are
• Built-in-Functions
• User Defined Functions I. Built-in-Functions :- The procedures of the functions are
defined previously.
1. The user need not write the procedure for them.
2. They are written by the manufacturer of compiler.
3. Each built-in-function is stored in a filed called as the HEADER
FILE
4. If a built-in-function is to be called, the corresponding header
file is to be linked into the current program in the linkage
section.

8
BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
BUILT-IN FUNCTIONS :
FUNCTIONS
b) User Defined Functions :- The procedures for these functions are
not defined already. • The functions which are not written by the user are called as the Built-in-
The user has to create his / her own function. functions.
Since the functions is developed by the user, the function is called as • These functions are predefined functions and available is header files.
the User Defined functions.
• Some of the header files and built-in functions in C are
It is created at the time of writing the program.
The main() function is one of the user defined function because the
statements within the main() function are to be written by the
user.

9
Computer Programming BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Header files in C Header files in C


No. Name Description
Asetoffunctionformanipulatingcomplex
No. Name Description 13 complex.h
numbers
1 stdio.h Input/Output Functions Forqueryingandspecifyingthealignmentof
14 stdalign.h
2 conio.h console input/output objects
3 assert.h DiagnosticsFunctions 15 errno.h Fortestingerrorcodes
4 ctype.h Character Handling Functions Foratomicoperationsondatasharedbetween
16 stdatomic.h
threads
5 locale.h LocalizationFunctions 17 stdnoreturn.h Forspecifyingnon-returningfunctions
6 math.h Mathematics Functions TypesandfunctionsformanipulatingUnicode
18 uchar.h
7 setjmp.h NonlocalJumpFunctions characters
8 signal.h SignalHandlingFunctions Asetoffunctionsforcontrollingthefloating-point
29 fenv.h
environment
9 stdarg.h VariableArgumentListFunctions
20 wchar.h Defineswidestringhandlingfunctions
10 stdlib.h GeneralUtilityFunctions 21 tgmath.h Type-genericmathematicalfunctions
11 string.h String Functions Accessingavaryingnumberofargumentspassedto
12 time.h DateandTimeFunctions 22 stdarg.h
functions
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
23 stdbool.h Definesabooleandatatype
Input output functions FUNCTIONS - <math.h>
Frequently used input output functions in <stdio.h> Function Usage
sqrt(x) To find the Square Root of X
Function Description
sin(x) To find the sine (x)
scanf readcharacter,string,numericdatafromakeyboard cos(x) To find cosine(x)
tan(x) To find tangent(x)
printthe“character,string,float,integer,octalandhexadecimal
printf exp(x) To calculate exponent value of x
values”ontotheoutputscreen
log(x) To calculate logarithmic value of x
getchar readsacharacterfromtheterminalandreturnsitasaninteger fabs(x) To have the Absolute value of X
pow (x,y) To find x y
putchar displaysthecharacterpassedtoitonthescreen floor(x) To round down x to its nearest integer
ceil(x) To round up x to its nearest integer
gets readsalinefrom stdin(standardinput)intothebuffer
acos(x) To find cos -1 (X)
puts writesthestring str andatrailingnewlineto stdout. asin(x) To find sin -1 (X)
atan(x) To find tan -1 (X)
14
BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

Simple program using mathematical


Output
function
#include<stdio.h> 4.000000
#include <math.h>
int main(){ 4.000000
printf("\n%f",ceil(3.6)); 3.000000
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
3.000000
printf("\n%f",floor(3.2)); 4.000000
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
2.645751
printf("\n%f",pow(2,4)); 16.000000
printf("\n%f",pow(3,3));
27.000000
printf("\n%d",abs(-12));
return 0; 12
}

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


FUNCTIONS - <string.h> FUNCTIONS
• strcat() – It is a function to concatenate one string to another.
String Functions :
The general format is
• These functions are used for processing the strings. A string is an array of characters. strcat (st1,st2)
• These functions are stored in a header file, string.h. if any function is to be called , the where st1 is the destination string and st2 is the source string.
header file is to be included as the function is used , the content of st2 is concatenated to content of
#include <string.h> st1 and the new string is stored in st1.
The string functions are
• strlen () – It is a function to find the length of the string. Example : Assume that st=”BALA”,then strlen(st) is returning 4.
• strcpy() – It is a function to copy the content of one string to
The general format is
another. The general format is
strlen(st)
strcpy(st1 , .st2)
where st is the string whose length is to be found where st1 is the destination string and st2 is the source string.
Example :- Assumethatst2=”BALA”,then strcpy(st1,st2) is copying
thestring“BALA”tost1.

17 18
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

FUNCTIONS FUNCTIONS

Example :- Assumethanst1=”BALA”andst2=”RAMAN”.Ifweuse • strrev() – It is a function to reverse a string. Its general format is


strcat(st1,st2),st1=“BALARAMAN”. strrev(st1)
• strcmp() – It is a function to compare two strings. Its general where st1 is a string to be reversed. The function returns
format is strcmp(st1,st2) Example :- Assumethanst1=”BALA”.Afterthefunctionstrrev(st1);
where st1 and st2 are the strings to be compared. The function thevalueofst1is“ALAB”.
returns • strcat() – It is a function to concatenatee two strings. Its general
0 - if both the strings are equal format is strcat(st1,st2)
+ ve - if st1 is greater than st2 where st1 and st2 are the strings to be concatenated and the
- ve - if st1 is lesser than st2. resulatant string is store in st1.
Example :- Assumethanst1=”BALA”andst2=”RAMAN”.The Example :- Assumethanst1=”BALA”andst2=”RAMAN”.Afterthe
function strcmp(st1,st2) returns –ve value. functionstrcat(st1,st2);iscalled,st1=“BALARAMAN”.

19 20
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
Functions <ctype.h>
Program using string functions [Link] Function & Description

1 intisalnum(intc)-checkswhetherthepassedcharacterisalphanumeric.

2 intisalpha(intc)-checkswhetherthepassedcharacterisalphabetic.
#include <stdio.h> intiscntrl(intc)-checkswhetherthepassedcharacteriscontrolcharacter.
3
#include <strings.h>
4 intisdigit(intc)Thisfunctioncheckswhetherthepassedcharacterisdecimaldigit.
int main()
{ char s1[30],s2[30];
5 intisgraph(intc)-checkswhetherthecharacterhasgraphicalrepresentationusinglocale.
printf("Hello World");
strcpy(s2,"welcome"); intislower(intc)-checkswhetherthepassedcharacterislowercaseletter.
6
strcpy(s1,"welcome");
7 intisprint(intc)-checkswhetherthepassedcharacterisprintable.
printf("\n compare the string %d",strcmp(s1,s2)); strcat(s1," to C class");
8 intispunct(intc)-checkswhetherthepassedcharacterisapunctuationcharacter.
printf("\n copy %s",s1);
printf("\nlength of the string %d", strlen(s1));
9 intisspace(intc)Thisfunctioncheckswhetherthepassedcharacteriswhite-space.
printf("\n compare the string %d",strcmp(s1,s2));
return 0;} 10 intisupper(intc)-checkswhetherthepassedcharacterisanuppercaseletter.

11 intisxdigit(intc)-checkswhetherthepassedcharacterisahexadecimaldigit.
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Functions <ctype.h> Functions <conio.h>

The library also contains two conversion functions that accepts and returns an
"int". Functions Description
clrscr() usedtocleartheoutputscreen
[Link] Function&Description
. getch() Itreadscharacterfromthekeyboard
1 inttolower(intc)This function converts uppercase letters to lowercase. readscharacterfromkeyboardand
getche()
echoestoo/pscreen
2 inttoupper(intc)This function converts lowercase letters to uppercase.
textcolor() usedtochangethetextcolor
textbackground() usedtochangetextbackground

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


FUNCTIONS
USER DEFINED FUNCTIONS
#include <stdio.h> • A function which is written by the user is called as the User
defined function.
#include <conio.h>
• The function main() is also an user defined function because the
main() statements within it are written by the user.
{ • Whenafunctionisdesignedandpacked,itistreatedasa‘black
box’.
textcolor(RED);
• The function takes a data from another function and returns a
cprintf("C programming"); value. To give the data to a function, a call is made to call the
getch(); function.
• The function which sends the data to the function is called as
return 0;
• the Calling Function and the function which is called by the
} calling function is called as the Called Function.

26
BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

FUNCTIONS FUNCTIONS
The general format of a User defined Function is
Function 1 Function 2 Return type Function name (argument list)
………….. ………….. {
…………… ………….. Declaration part;
Statement 1;
…………..Calling is made ………….. Statement 2;
………….. Finds Some -------------
-------------
………….. Return the value found Value --------------
………….. ………….. --------------
………….. ………….. Statement n;
return(e);
}

Function 1 is the Calling Function and Function 2 is the Called


Function

27 28
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
FUNCTIONS FUNCTIONS

where The rules for developing the user defined functions are
- argument list consists of a variable or a collection of more than one The rules followed for forming variables are used for forming a
variables separated by commas function name.
- Declaration Part 2 is for declaring the local variable(s) used in the – The arguments must be enclosed within the parenthesis.
function. – A function is returning only integer value by default.
- e is an arithmetic expression which may be a value/a variable or an – If a function returns a value which is other than integer, must de
arithmetic expression. – declared in the calling function explicitly. This method is called as the
- Statement1,Statement2,…..StatementnareCExecutable Functional prototyping.
statements. – The type specifier is to be given for the user defined function if it
- All parts are not essential. returns a non-integer value. If a function does not return any value , the
type specifier must be void.
- A function can be written without any argument. A function returns
– The‘plain’returncanbegivenforthefunctionifitdoesnotreturnany
the value by means of return statement.
value.

29 30
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

FUNCTIONS

• A function is called by using the function name in the statement.


• Sometimesafunctionmaynotreturnavalue.Ifso,thefunctiondoesn’thavereturn
statement.
• If a function is returning a value , the function is called by using the
following format • A function returns only one value at a time.
• Local variables which are used within the function are not valid outside the function.
Variable = function name (arguments list ); • A program may contain more than user defined functions.
where
the datatype for the variable and the return datatype must be same.

• If a function is returning a value , the function is called by using


the following format function name (arguments list )

• A function should be used on the right hand side of the


assignment statement.

31
Computer Programming BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
FUNCTIONS
TYPES OF FUNCTIONS
According the arguments and the returning value , functions are 1. FUNCTION WITH NO ARGUMENTS AND RETURN NO VALUE
divided into three categories. If a function does not have any arguments , it is getting any value from the
1. A function with no arguments and no return value calling function. Also if it does not return any value , the called function is
2. A function with an argument or arguments and returning no receiving any vale from the function when it is called. That is , there is no
value
data transfer between the calling function and the called function.
3. A function with argument(s) and returning a value.

33
Computer Programming BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

FUNCTIONS FUNCTIONS

Function 1 Function 2 Example :


………….. ………….. main( )
…………… ………….. {
…………..No Input is sent to the function ………….. callwecome( );
………….. Finds Some }
………….. No output is returned Value void callwelcome( )
………….. ………….. {
………….. ………….. printf(“\nWELCOME”);
}
In the program, main( ) function is the calling function and
No data is transferred between the functions callwelcome( ) is the called function. Between the functions , no data
is transferred.

35 36
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
Sample Program FUNCTIONS
2. A FUNCTION WITH AN ARGUMENT OR ARGUMENTS AND
#include <stdio.h> RETURNING NO VALUE
void wel(); A function which gets one or more values from the calling function
void main() May not return a value.
{ Function 1 One or more Inputs Function 2
wel(); ………….. …………..
} …………… …………..
void wel() …………..…………..
{ ………….. Finds Some
printf("\n welcome to C class"); …………..No output is returned Value
} ………….. …………..

One or more values is / are sent from the calling function to called
function but the called function does not return any value

38
BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

Functions with arguments FUNCTIONS


3. A FUNCTION WITH AN ARGUMENT OR ARGUMENTS AND
#include <stdio.h> RETURNING A VALUE
void add(int ,int ); A function which gets one or more values from the calling function
void main()
returns a value.
{
Function 1 One or more Inputs Function 2
int x,y,z;
scanf("%d%d”,&x,&y);
………….. …………..
add(x,y); …………… …………..
} …………..…………..
void add(int a,int b) ………….. Finds Some
{ …………..Anoutput is returned Value
int c; ………….. …………..
c=a + b;
printf("%d",c);
One or more values is / are sent from the calling function to the
}
called function and the called function returns a value

40
BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
FUNCTIONS
FUNCTIONS
Example
#include <stdio.h>
main() void add(int ,int );
{ void main()
int x,y,z; {
scanf(“%d%d”,&x,&y); int x,y,z;
z=add(x,y); scanf("%d%d”,&x,&y);
printf(“\nResultantvalueis%d”,z); printf(“addition%d”,add(x,y));
} }
void add(int a, int b)
int add(int a,int b)
{
{
int c;
int c; c=a + b;
c=a+b; return c
return( c ); }
}
41
Computer Programming BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

FUNCTIONS
Function prototyping :- If the called function returns an non integer void main()
value or not returning any value, has to be declared in the calling {
function. Only function header can be declared. It is called as the float x,y,z;
function prototyping. float div ( float , float );
scanf(“%f%f”,&x,&y);
Example
z=div(x,y);
printf(“\nResultantvalueis%f”,z);
}
float div(float a, float b)
{
float c;
c=a / b;
return( c );
}

43
Computer Programming BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
FUNCTIONS - Example
FUNCTIONS
main()
{
In the above example , int a,b,res;
scanf(“%d%d”,&a,&b);
• a type specifier is given for the called function div ( ) . res=difference(a,b); // calling the function difference
• Also the function header is declared in the calling function. printf(“\n Difference is %d”,res);
}
Note 1 :- A function can call any function. Again the called function difference(int x,int y)
{
may call another function. The functions are called as the Nesting of int dif;
functions. big=biggest(x,y); // calling the function biggest //
if (big==x) dif=x-y;
else dif=y-x;
return(dif);
}
biggest(int x,int y)
{
if (x>y) return(x);
else return(y);
}

45 46
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

FUNCTIONS Learning Objectives


➢Actual and Formal Parameters
Note 2:- Nesting of function calls also possible in C as
➢Storage classes
c = div( div(a,b),c) // which is equivalent to a / b / c.
Note 3:- A function calls itself is called as the Recursion (i) Automatic variable
(ii) Global variable
(iii) Register variable
(iv) static variable
➢Recursive functions [Recursion ]
- What are recursive functions?
- Example for recursion
- Advantages of recursion
➢ Revisiting arrays
47 48
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
FUNCTIONS - Actual and Formal
Parameters FUNCTIONS
A parameter is a variable in amethod’sdefinition.Itisalsoknownas void main()
Formal parameters {
When a method is called, the arguments are the data you pass into the float bpay,revisedpay;
method's parameters. These are also known as Actual parameters. printf(“\nEntertheBASICPAYoftheEMPLOYEE..”);
Parameter is a variable in the declaration of a function scanf(“%f”,&bpay);
Argument is the actual value of this variable that gets passed to function. revisedpay=bpay+increment(bpay); Argument or Actual parameter
Assume that a C program has the following functions as printf(“\mTheRevisedSALARYis%f”,revisedpay);
}
#include <stdio.h>
In the above program,
float increment(float basic) Parameter or Formal parameter
main() function is the calling function. Increment(float basic) is the
{ called function.
float inc=0; We know that parameter used in the calling function is the actual
if(basic<=250000)return(basic*0.25); parameter.
else if (basic<=50000)return(basic*0.10); So here , bpay is the actual parameter.
else if (basic<=50000)return(basic*0.10); The parameter of the called function (increment( ) function) in basic
} is known as the formal parameter.
49 50
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

FUNCTIONS - Call By Value and Call by


reference FUNCTIONS – Call by value
Call By Value and Call by reference void swap(int x,int y)
{
When a called function is called with the normal int t=x;
variable(s), the calling statement is known as Call by x=y;
Value and the parameter is known as the Value y=t;
parameter. }
Why it is called as the value parameter? void main()
{
Because , only the value(s) of the actual parameter(s) int a=10,b=30;
is/are sent to the called function (not the variable). printf(“\nBeforeswapfunctioniscalled,a=%db=%d”,a,b);
The formal parameter gets the value(s) and is/are used swap(a,b);
in the called function. printf(“\nAfterswapfunctioniscalled,a=%db=%d”,a,b);
}
So if the called function alters the value , it does not
The output of the above program is
affect the value of the actual parameter. Before swap function is called , a=10 b=20
After swap function is called , a=10 b=20

51 52
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
FUNCTIONS FUNCTIONS
If the called function has pointer variable(s) as its Example:
parameter(s) and the calling function calls the function void swap(int *x,int *y)
with the address / addresses [the value of a pointer {
variable], the process is known as Call by reference and
int t=*x;
the parameters are known as variable parameters.
*x=*y;
Why they are called as the variable parameters? *y=t;
Because the address of the actual parameter of the calling }
function is sent to the called function. void main()
When the address (refence) is sent, any alteration in the {
called function will affect the variable in the calling int a=10,b=30;
function.
printf(“\n Before swap function is called , a=%d b=%d,a,b);
swap(&a,&b);
printf(“\n After swap function is called , a=%d b=%d,a,b);
}
53 54
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

FUNCTIONS Storage classes- Scope of variables


SCOPE OF VARIABLES OR STORAGE CLASS
The scope of the variable specifies the part / parts in which the variable
The output of the above program is is alive.
Before swap function is called , a=10 b=20 Depending on the place of the variable declared, the variables are
After swap function is called , a=20 b=10 classified into two broad categories as Global and Local variables.
In some languages like BASIC, all the variables are global and the vales
are retained throughout the program.
Here the memory location or the address of the variable But in C language , the availability of value of the variable depends on
is sent to the called function and the process accesses the‘storage‘classofvariable.
the memory location of the variables directly and In C , there are four types of storage classes. They are
hence swaps the values in the specified memory 1. Local or Automatic variables
2. Global variables
locations.
3. Static Variables
4. Register Variables.

55 56
BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
Storage classes- Scope of variables Storage classes- Scope of
variables
1. Automatic variable: - An Automatic variable is a local variable 2. Global variable: - Global variable is a variable which is declared
which is declared inside the function. before all the functions.
The memory cell is created at the time of declaration statement is The memory cell is created at the time of declaration and is not
executed and is destroyed when the flow comes out of the function. destroyed when the control comes out of the function.
These variables are also known as internal variables. Global variables can be accessed by any function in the same
A variable which is declared inside the function without using any program.
storage class is assumed as the local variable because the default
storage class is automatic. A global variable can be declared externally in the global variable
A variable can be declared automatic explicitly by using the declaration section.
keyword“auto”as int x = 100;//Global variable
main ( ) main ( )
{ {
auto int x; x = 200;

f1 ( );
…..
f2 ( );
}
57
} 58
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

Storage classes- Scope of variables Storage classes- Scope of variables


f1 ( ) 3. Static Variables : These variables are alive throughout the
{ program.
x = x + 1; Avariablecanbedeclaredasstaticbyusingthekeyword“static ”
} as static int x ;
f2 ( ) A static variable can be initialized only once at the time of
declaration .
{
The initialization part is executed only once and retain the value
x = x + 100; through the remainder of the program.
}
The variable x is declared above all the functions. It can be accessed
by all the functions as main( ) , f1 ( ) and f2 ( ). The final value of x is
301.

59 60
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
Storage classes- Scope of variables Storage classes- Scope of variables
Example Program – static variable
main ( ) The above program produces the following output
{ The Value of X is 1
void f1 ( ); The Value of X is 2
f1 ( ); The Value of X is 3.
f1 ( ); [Link] Variables :- If we want to store the variable in a register
f1 ( ); instead of memory, the variable can be declared as register
} variablesbyusingthekeyword“register”as
void f1 ( ) register int x;
{ If the variables are stored in the registers, they can be accessed
faster than a memory access.
static int x = 0;
So the frequently accessed variables can be declared as register
x = x + 1;
variables.
printf(“\nTheValueofXis%d“,x);
}
61 62
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

Storage classes- Scope of variables Storage classes- Scope of variables

Example Program: A static variable is a variable that can keep its value between different
#include <stdio.h> function calls.
void main ( ) A static variable remains in memory while the program is running.
{
A global variable is defined outside of all functions and can be called from
register int x=10;
any function.
register float y=2.35;
char z='A'; A global variable can be declared static if it is to be made visible only in the
printf("\n Data are x=%d y=%f z=%c",x,y,z); current C file.
} The extern modifier is most commonly used when there are two or more files
In the above program , all the variables are stored in the registers sharing the same global variables or functions
instead of memory.

63
Computer Programming BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
FUNCTIONS FUNCTIONS
... .. ...
RECURSION / RECURSIVE FUNCTION
recurse();
A function that calls itself is known as a recursive function. And, this
... .. ...
technique is known as recursion.
}
How recursion works?
void recurse()
{
... .. ...
recurse();
... .. ...
}

void main()
{
65 66
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

FUNCTIONS FUNCTIONS
The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if .. Else statement (or similar approach) result = sum(number);
can be used where one branch makes the recursive call, and the
other does not. printf("sum = %d", result);
Example: Sum of Natural Numbers Using Recursion return 0;
#include <stdio.h> }
int sum(int n);
int sum(int n) {
int main() { if (n != 0)
int number, result; // sum() function calls itself
return n + sum(n-1);
printf("Enter a positive integer: "); else
scanf("%d", &number); return n;
}
67 68
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
FUNCTIONS FUNCTIONS

Output
Enter a positive integer:3
sum = 6

Initially, the sum() is called from the main() function with number
passed as an argument
Suppose, the value of n inside sum() is 3 initially. During the next
function call, 2 is passed to the sum() function. This process continues
until n is equal to 0.
When n is equal to 0, the if condition fails and the else part is
executed returning the sum of integers ultimately to
the main() function.

69 70
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus

FUNCTIONS FUNCTIONS – Revisiting Arrays

Advantages of Recursion Passing array to function using call by reference


• Recursion makes program elegant. When we pass the address of an array while calling a
• However, if performance is vital, use loops instead as recursion is function then this is called function call by reference.
usually much slower.
• That being said, recursion is an important concept. When we pass an address as an argument, the function
• It is frequently used in data structures and algorithms. declaration should have a pointer as a parameter to
• For example, it is common to use recursion in problems such as receive the passed address.
tree traversal. #include <stdio.h>
void display (char *x) // x is a pointer variable
{
printf(“%c“,*x);//valueattheaddressisprinted
}
71 72
Computer Programming BITS Pilani, Pilani Campus Computer Programming, Session 6 BITS Pilani, Pilani Campus
FUNCTIONS – Revisiting Arrays FUNCTIONS – Revisiting Arrays

void main() How to pass an entire array to a function as an


{ argument?
chararray[]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’}; In the above example, we have passed the address of
for(i=0;i<6;i++) // Total no :- of characters is 7 each array element one by one using a for loop in C.
display(&array[i]); // address is sent to the function However you can also pass an entire array to a function
} like this:
The output of the program is Note: The array name itself is the address of first element
Welcome of that array.
For example if array name is arr then we can say that
arr is equivalent to the &arr[0].

73 74
Computer Programming, Session 6 BITS Pilani, Pilani Campus Computer Programming, Session 6 BITS Pilani, Pilani Campus

FUNCTIONS – Revisiting Arrays FUNCTIONS – Revisiting Arrays

Example program x[j]=temp;


PROGRAM TO DO BUBBLE SORT Using a Function }
void Bubble_sort(int x[50],int m) printf(“\nTheSortedListis….\n”);
{ for(i=0;i<=m-1;i++)printf (“%f\t”,x[i]);
int temp.i.j; }
for(i=0;i<=m-2;i++) // Calling Function
for(j=i+1;j<=m-1;j++) void main()
if(x[i]>x[j]) {
{ float A[50];
temp=x[i]; int i,j,n;
x[i]=x[j]; printf(“\nEnterhowmanyelementstoSort”);

75 76
Computer Programming, Session 6 BITS Pilani, Pilani Campus Computer Programming, Session 6 BITS Pilani, Pilani Campus
FUNCTIONS – Revisiting Arrays

scanf(“%d”,&n);
printf(“\nEnterElementstoSort”);
for(i=0;i<=n-1;i++)scanf(“%f”,&A[i]);
Bubble_sort(A,n) //Here array A is passed to a function
}
Thanks
Program Execution
Enter how many elements to Sort 8
Enter Elements to Sort
23 34 7 56 -100 45 2 50
TheSortedListis….
-100 2 7 23 34 45 50 56
77 78
Computer Programming, Session 6 BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
SystemsProgramming-V3.0

➢It is important to know that just login to the session does not CONTROL STATEMENTS-
guarantee the attendance. Flow of Execution in a C program

➢Once you join the session, continue till the end to consider you
as present in the class.
➢IMPORTANTLY, you need to make the class more interactive by
responding to Professors queries in the session.
➢ Whenever Professor calls your number / name ,you need to
respond, otherwise it will be considered as ABSENT

SystemsProgramming-V3.0 BITS Pilani, Pilani Campus


CONTROL STATEMENTS-
Types of Flow of execution Flow of Execution in a C program
A C program is a collection of different C statements in which each statement ends with a
Sequential Structure semicolon. According to the flow of execution of the statements, it has three types of
Selective structure structures.

Repetitive structures
[Link] Structure : It is a structure in which the statements are executed sequentially one
after another. It means that the flow of execution goes to statement i + 1 after the ith
statement is executed. The statements are normally executed in the order in which they
appear in the program

6
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Sequential flow
Example

• C program control tends to flow


sequentially.
• The program which flows only from
top to bottom without changing the
flow of control are known as
sequence control structure.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Example program for flow of execution Average of three numbers

// volume of the cylinder int main( )


int main( ) {
{ float a, b, c, av;
float pi=3.14, r, h, v; printf(“Enterthreenumber”);
printf(“Enterradiusandheight”); scanf(“%f%f%f”,&a,&b,&c);
scanf(“%f%f”,&r,&h); av = (a+b+c)/3;
v = pi*r*r*h; printf(“Averageis%d”,av);
printf(“Areais%d”,a); return 0;
return 0; }
}

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

C program to input day and convert it into year,


Statements in C: Sequential
month and days.
int main( ) • Statements are sequenced by default in C
{ • Instructions are executed one after the other
int day, y, m, d, rd; • The next instruction that is executed by default is the one that is the
printf(“Enterday”); next in memory location
scanf(“%d”,&day); • Example:
y = day/365; X = 10;
Y = x+5
rd = day%365;
• The default sequential execution order can be changed by using
m = rd/30;
Conditional Statement
d = rd%30;
printf(“Year=%dMonth=%dDays=%d”,y,m,d);
return 0;

BITS Pilani, Pilani Campus BITS Pilani, K K Birla Goa Campus


Control Statements if statement
Control or decision making statements Syntax:
– if statement if (expression)
– switch statement {
– goto statement statement/ statements;
}
statement x;

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Start

Statement(s)

False
Test
True
Statement(s)

Statement(s)

BITS Pilani, K K Birla Goa Campus BITS Pilani, Pilani Campus


Swaping values

• Consider the sequence of statements


• Assume (a=10 and b=5)
t=a;
a=b;
b=t;
a b t

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Example: Sequential Statement


Execution

• Sequence of statements to swap the values of two integers a and b


a = a + b;
b = a – b;
a = a – b;

a b t

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Working model for swamping two values Flow Charting: Sequential Statements

a=5;b=3 • Flow charts are used as a visual aid for program design
a = a + b; → a = 5+3 → 8 • Sequence of statements are indicated by a sequence of boxes
b = a – b; → b= 8-3 →5 • Sequence of statements to swap two integer values
a = a – b; → a = 8 – 5 → 3

Now the value of a becomes 3 and value of b becomes 5

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Flowchart for Simple Interest

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Program to convert Fahrenheit to
Flow chart for Fahrenheit to Centigrade
centigrade
#include <stdio.h>

int main()
{
float celsius, fahrenheit;

/* Input temperature in fahrenheit */


printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);

/* Fahrenheit to celsius conversion formula */


celsius = (fahrenheit - 32) * 5 / 9;

/* Print the value of celsius */


printf("%.2f Fahrenheit = %.2f Celsius", fahrenheit, celsius);

return 0;
}

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Practice problems How to write program

1. Enter marks of five subjects and calculate total,average and percentage Enter marks of five subjects and calculate total,average and percentage
2. Find out the gross salary and net salary of an employee.
3. Convert centimetre into Meter and kilometre Input : ?
4. Write a C program to enter radius of a circle and find its diameter, circumference Output : ?
and area. Process: ?
5. Write a C program to enter any number and calculate its square root.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Find out the gross salary and net salary
of an employee.

Input : Marks of five subjects Input : basic salary, allowance, deductions


Output : Total, Average and percentage Output : gross salary
Process : Process : gross salary → ( add basic with all allowance)
Total : Addition of F subjects Net salary → ( add basic with all allowance –
Average : total/5 deductions)
Percentage : total/5

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Control Structures Conditional Statements


• Controls the flow of execution C allows decisions to be made by evaluating a given expression
• Control structures enable us to combine individual instructions into a single logical – true (non zero)
unit with one entry point and one exit point. – false (zero)
• Compound statement: group of statements bracketed by { and } and each
statement executed sequentially
Entry
• Condition : condition an expression that is either false or true

False
Test expression ?

True
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Contd… Contd…

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Contd… Contd…

Important Note: 0-9 48 - 57


A – Z 65 – 90
a – z 97 -122

True TRUE
True TRUE
True FALSE
False FALSE
False FALSE
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Contd… Short Circuit Evaluation

Assuming x = 15.0 and y = 25.0. State what value each condition generates • C evaluates only part of the expression
• x != y • Example : a || b
• x<x • Example : !flag || (y + z >= x - z)
• x >= y - x • Example : a && b
• x == y + x – y
• x=y

Program Name: relational Operator.c


Document : Worksheet for [Link] Exercise 2.1 and 2.2

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

[Link] structure :

Also known as Decision making statement , It is a structure in which the check whether given number is positive
statements are not executed sequentially.
It means that the flow of execution goes to statement k (which is not equal to i
ifno>0printf(“givenispositive”)
+ 1) after the ith statement is executed.
Else
The statements are not executed in the order in which they appear in the
program. printf(“givenisnegative”)

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Syntax: if / if-else Statement

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Syntax: if / if-else Statement

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Flow Charting: Conditional Statements Example

• Conditional statement is indicated by diamond with two branches


• Flow chart to find max and min of two numbers

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Example Example

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Example
Practice problems

1. Find the given number is odd or even using the conditional operator in c
2. Find the biggest among three numbers using the conditional operator in C
3. Write a C program to find whether a given year is a leap year or not.
4.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

CONTROL STATEMENTS
Quadratic Equation
Flow of Execution in a C program
#include <stdio.h>
#include <math.h>
void main() [Link] / Decision making Structures
{
int a,b,c,d;
float x1,x2;
These structures are used for doing the decision making operations, like choosing one
printf("Input the value of a,b & c : ");
among two or more choices.
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c; For example
if(d==0)
{ (a) Which is greater, whether A or B?
printf("Both roots are equal.\n");
x1=-b/(2.0*a);
x2=x1;
(b) Who has got more marks among the persons P1, P2 ,... , Pn?
printf("First Root Root1= %f\n",x1);
printf("Second Root Root2= %f\n",x2); (c) What action is to be done if some condition becomes false occurs?
}
else if(d>0)
{
These structures are also called as the decision making structure.
printf("Both roots are real and diff-2\n");
x1=(-b+sqrt(d))/(2*a); The statement which selects what action is to be done among the
x2=(-b-sqrt(d))/(2*a);
printf("First Root Root1= %f\n",x1); actions is known as control statement.
printf("Second Root root2= %f\n",x2);
}
else
printf("Root are imeainary;\nNo Solution. \n");
}

52
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Selective / Decision making / Conditional
CONTROL STATEMENTS
control Structures
C programming language provides the following types of decision
There are two types of control statements. They are making or conditional control statements.
a) Conditional control statements : The flow is altered according
to a condition where the condition is a statement whose value will [Link]. Statement & Description
be either TRUE or FALSE. It is also called as the Selective Structure. 1 if statement :An if statement consists of a boolean expression followed by one or more
The Relational and Logical expressions are the conditions. statements.
The conditional control statements are
2 if...else statement :An if statement can be followed by an optional else statement,
(i) if statement
which executes when the Boolean expression is false.
(ii) switch ... case statement
b) Unconditional control statement : The flow is altered without 3 nested if statements :You can use one if or else if statement inside another if or else
any condition. if statement(s).

The unconditional control statement is 4 If..elseif ladder or Multi-way if statement


goto

5 switch statement :A switch statement allows a variable to be tested for equality


against a list of values. Nested switch statement
53 54
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

CONTROL STATEMENTS Common if

1. Selective Structure with If statement:


The if statement has the following types.
i. Common If
ii. If . . else
iii. Nested If
iv. Multi alternative
i. The Common IF has the following format
Statement x;
If ( condition ) statement y / {block of statements} ;
Statement z
Where the condition may be a relational or logical expression and
the block may have a single statement or more than one
statement. The block opens with { and closes with }.

55
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
CONTROL STATEMENTS

#include<stdio.h>
FALSE Checks the TRUE
condition int main(){
int number=0;
printf("Enter a number:");
Executing the Block scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0;
Statement X
}

57
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

CONTROL STATEMENTS CONTROL STATEMENTS


ii. The if.. else has the following format
Case 1 : The block or statement y is selected for the execution only if the if ( condition ) block 1;
condition is true. After executing the statement / statements within the block, else block 2;
the flow comes to the next statement z.
where the condition may be a relational or logical expression and
Case 2 : The block/statement y is not selected for the execution if the
condition becomes false. Without executing the statement y/ statements blocks may have a single or more than one statements opens with {
within the block, the flow comes to the next statement z which immediately and closes with }. In the format ,
follows the if structure. Case 1 (condition True): The block is selected for the execution only if the
condition is true.
Example: After executing the statement / statements within the block, the flow comes to
if(marks>=80)printf(“\nPerformanceGood”) the next statement after block 2. Block 2 is not executed.
printf(“PrepareWellforthefinalexam”); Case 2 (condition False): The block2 is selected for the execution if the
condition becomes false.
After executing the statement / statements within the block 2 , the flow comes to
The flow of execution is represented in the flow chart as the next statement following block2. Block 1 is not executed.
59 60
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
CONTROL STATEMENTS If ..Else ..Odd or even

Example: #include <stdio.h>


if(marks>=50)printf(“\nPerformanceGood,KeepitUP”); int main()
{
else
int x = 11;
printf(“\nPerformancenotGood,PrepareWellforthenextexam”); if(x%2 == 0)
The flow of execution is represented in the flow chart as {
printf("%d is an even number", x);
FALSE TRUE }
else
Condition {
printf("%d is an odd number", x);
Block 2 Block 1
}
return 0;
}
Statement after Block 2

61
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

List of programs
/* C program to check whether a character is alphabet or not */
• Check if the given number is an even or an odd number in C #include <stdio.h>
int main()
• Check if the given character is an alphabet in C {
• Check if the given year is a leap year in C char ch;
/* Input a character from user */
• Find the larger of two numbers in C printf("Enter any character: ");
• Find the largest of three numbers in C scanf("%c", &ch);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("Character is an ALPHABET.");
}
else
{
printf("Character is NOT ALPHABET.");
}
return 0;
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Nested if Sample pgm – nested if
elseif(x<10)
#include <stdio.h>
if (condition1) { {
int main()
printf("%disapositivenumber.",x);
/* code to be executed if condition1 is true */ { printf("\nThevalueislessthan10");
int x = 11;
if (condition2) { }
elseif(x>10&&x<100)
/* code to be executed if condition2 is true */ if(x<0) {
{ printf("%disapositivenumber.",x);
} else {
printf("%d is a negative printf("\nThevalueisgreaterthan10butlessthan100");
/* code to be executed if condition2 is false */ number", x); }
} else
} else if(x == 0) {
} else { { printf("%disapositivenumber.",x);
printf("%d is zero", x); printf("\nThevalueisgreaterthan100.");
/* code to be executed if condition1 is false */ } }
}
return0;
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Check whether given character is vowel


Practice
or not
#include <stdio.h> Create a simple calculator using a C program.. Based on the choice , select the
int main()
{ operations (add/subtract/multiply/division)
char ch;

/* Input a character from user */


printf("Enter any character: ");
scanf("%c", &ch);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("Character is an ALPHABET.");
if ((ch=='a')||(ch=='e'))
{
printf("Character is vowel.");
}
} else
{
printf("Character is NOT ALPHABET.");
}
return 0;
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
CONTROL STATEMENTS
b) Un conditional control statement using go to
The flow is altered without checking any condition. The general
format of go to is
go to label name;
where label name is a label given for the statement for which the
flow is sent. The rules for defining the variables are to be used for
labeling the statement.
The label for a statement should be given in the format
Label name : statement – X;

69
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Example program for goto CONTROL STATEMENTS


// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are displayed.
#include <stdio.h>
Example : main()
int main() { {
const int maxInput = 100;
int i; int a,b , c = 1000;
double number, average, sum = 0.0; a = 100;
for (i = 1; i <= maxInput; ++i) {
printf("%d. Enter a number: ", i); b = 20;
scanf("%lf", &number); go to lab;
c = -1000;
// go to jump if the user enters a negative number
if (number < 0.0) { printf(“\nDummy”);
goto jump; lab: print(“\n C value is %d”,c);
}
}
sum += number;
} The output for the above program is C value is 1000.
jump: Here,
average = sum / (i - 1); The statements c = - 1000;andprintf(“\nDummy”);arenotexecuted
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average); because as soon as the flow reaches to go to statement , the flow will
return 0; be transferred to the
} printf(“\n C value is %d”,c); which has the label (lab).
72
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Sample program using go to

#include <stdio.h> Lab resources


int main() [Link]
{
int sum=0;
for(int i = 0; i<=10; i++){
sum = sum+i;
if(i==5){
goto addition;
Thanks
}
}

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

return 0;
}

74
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Contactsession6

SystemsProgramming-V3.0

CONTROL STATEMENTS-
Flow of Execution in a C program
A C program is a collection of different C statements in which each statement ends with a
➢It is important to know that just login to the session does not guarantee semicolon. According to the flow of execution of the statements, it has three types of
the attendance. structures.
[Link] Structure : It is a structure in which the statements are executed sequentially one
➢Once you join the session, continue till the end to consider you as present
after another. It means that the flow of execution goes to statement i + 1 after the ith
in the class. statement is executed. The statements are normally executed in the order in which they
appear in the program
➢IMPORTANTLY, you need to make the class more interactive by
responding to Professors queries in the session. [Link] structure : Also known as Decision making statement , It is a structure in which the
➢ Whenever Professor calls your number / name ,you need to respond, statements are not executed sequentially. It means that the flow of execution goes to statement
k (which is not equal to i + 1) after the ith statement is executed. The statements are not
otherwise it will be considered as ABSENT executed in the order in which they appear in the program.

4
SystemsProgramming-V3.0 BITS Pilani, Pilani Campus
[Link] / Decision making
CONTROL STATEMENTS
Structures
Flow of Execution in a C program

[Link] structures : Some statements within a program are executed more than
once. That means , the execution of the statements i to m are done more than once.
These structures are used for doing the decision-making operations,
The statements are normally executed as long as a condition is true. It exits only if like choosing one among two or more choices. For example
the condition becomes false.

(a) Which is greater, whether A or B?


(b) Who has got more marks among the persons P1, P2 ,... , Pn?
(c) What action is to be done if some condition becomes false occurs?

These structures are also called as the decision making structure. The statement
which selects what action is to be done among the actions is known as
control statement.

5
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Selective / Decision making / Conditional


CONTROL STATEMENTS
control Structures
There are two types of control statements. They are C programming language provides the following types of decision
making or conditional control statements.
a) Conditional control statements : The flow is altered according to a condition where the condition is a [Link]. Statement & Description

statement whose value will be either TRUE or FALSE. It is also called as the Selective Structure. 1 if statement :An if statement consists of a boolean expression followed by one or more
statements.
The Relational and Logical expressions are the conditions.
The conditional control statements are 2 if...else statement :An if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.
(i) if statement
(ii) switch ... case statement
3 nested if statements :You can use one if or else if statement inside another if or else
if statement(s).
b) Unconditional control statement : The flow is altered without
any condition. 4 If..elseif ladder or Multi-way if statement
The unconditional control statement is
goto 5 switch statement :A switch statement allows a variable to be tested for equality against a list
of values. Nested switch statement

7 8
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
CONTROL STATEMENTS CONTROL STATEMENTS
1. Selective Structure with If statement: Case 1 : The block or statement y is selected for the execution only if the condition is true. After
The if statement has the following types.
i. Common If
executing the statement / statements within the block, the flow comes to the next statement z.
ii. If . . else
iii. Nested If Case 2 : The block/statement y is not selected for the execution if the condition becomes false.
iv. Multi alternative
Without executing the statement y/ statements within the block, the flow comes to the next
i. The Common IF has the following format statement z which immediately follows the if structure.

Statement x;
If ( condition ) statement y / {block of statements} ;
Example:
Statement z if(marks>=80)printf(“\nPerformanceGood”)
Where the condition may be a relational or logical expression and printf(“PrepareWellforthefinalexam”);
the block may have a single statement or more than one
statement.
The flow of execution is represented in the flow chart as
The block opens with { and closes with }.

9 10
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

CONTROL STATEMENTS CONTROL STATEMENTS


ii. The if.. else has the following format
FALSE Checks the TRUE if ( condition ) block 1;
condition
else block 2;
where the condition may be a relational or logical expression and blocks may have a single or
Executing the Block
more than one statements opens with { and closes with }.
In the format ,
Case 1 (condition True): The block is selected for the execution only if the condition is true.
After executing the statement / statements within the block, the flow comes to the next statement
Statement X
after block 2. Block 2 is not executed.
Case 2 (condition False): The block2 is selected for the execution if the condition becomes
false.
After executing the statement / statements within the block 2 , the flow comes to the next
statement following block2. Block 1 is not executed.

11 12
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
CONTROL STATEMENTS CONTROL STATEMENTS

Example: iii. The Nested if is an if structure in which more than one if structures are overlapped.
if(marks>=50)printf(“\nPerformanceGood,KeepitUP”); That is , if an if lies within another if , then such a structure is called the nested if. The
general format of nested if is
else
printf(“\nPerformancenotGood,PrepareWellforthenextexam”);
if ( condition 1 )
The flow of execution is represented in the flow chart as
{
if (condition 2 ) block 1;
FALSE TRUE else block 2;
Condition }
else
Block 2 Block 1 {
if (condition 3 ) block 3;
else block 4;
Statement after Block 2 }

13 14
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Sample programs for nested if Nested if statement


//check if the first condition holds
if (condition 1) {

//if the second condition holds


if (condition 2) {
do something
}
//if the second condition does not hold
else {
do something else
}

}
// if the first condition does not hold
else{

//if the third condition holds


if (condition 3) {
do something
}
//if the third condition does not hold
else {
do something else
}

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


CONTROL STATEMENTS CONTROL STATEMENTS
In the above format, the condition 1 is checked first.
In the example, bonus=1000 if customer category is A and getting salary less than 2500.
(i) If it is true, then condition 2 is checked Or bonus=750 if customer category is A and getting salary greater than or equal to 2500.
if it is also true, block1 is executed. Or bonus=1000 if customer category is not A and getting salary less than 5000 . No bonus is given
other wise (condition 2 is false) , block2 is executed. if customer category is not A and getting salary greater than or equal to 2500.
(ii) If condition 1 is false, then condition 3 is checked
if it is also true, block3 is executed.
Otherwise (condition 3 is false) , block4 is executed. The following diagram represents how the blocks are executed for a nested if statement

Example if(cust_cat==’A’)
if ( salary < 2500 ) bonus = 1000;
else bonus= 750;
else
if (salary<5000)bonus=1500;
else bonus=0;

17 18
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Biggest of three numbers

CONTROL STATEMENTS #include <stdio.h>


int main() {
// variables to store the three numbers
int a, b, c;
//take input from the user
TRUE FALSE scanf("%d %d %d", &a, &b, &c);
//if else condition to check whether the first number is greater than the second
Condition1 if (a > b) {
//nested if else condition to check if a>c
if (a > c) {
TRUE FALSE TRUE FALSE //a is greatest
printf("%d", a);
Condition 2 Condition 3 } else {
//c is the greatest
printf("%d", c);
}
} else {
//nested if else condition to check if b>c
Block 1 Block 2 Block 3 Block 4 if (b > c) {
//b is greatest
printf("%d", b);
} else {
//c is the greatest
printf("%d", c);
}
Statement after if }
return 0;
19 }
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
To check whether students are pass or fail
CONTROL STATEMENTS
#include <stdio.h>
int main() {
// variable to store the marks of the student
int marks;
The Multi alternative if structure also known as if..else if ladder has the following format
//take input from the user
scanf("%d", &marks);
if ( condition 1 ) block1;
//if else condition to check whether the student is pass
if (marks >= 35) {
else if (condition 2) block2;
//nested if else condition to determine the grade of the student
if (marks >= 90) {
else if (condition 3) block 3;
//A grade
printf("A");
.................
} else if (marks >= 80) {
//B grade
.................
printf("B");
} else if (marks >= 70) {
else block n;
//C grade
printf("C");
statement – X;
} else if (marks >= 60) {
//D grade
In the above format, block 1 is executed only if the condition 1 is true. After the execution , the
printf("D"); flow goes to the statement – X. If the condition 1 is false, it checks whether the condition 2 is
} else {
//E grade true.
printf("E");
} If it is true , block 2 is executed. After the execution , the flow goes to the statement – X and so
} else {
//the student didn't pass
on. If no condition is true , block n is executed.
printf("F");
}
return 0; } 22
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

CONTROL STATEMENTS
Condition1
TRUE
FALSE Block 1

Condition 2
TRUE
FALSE
Block 2

Condition 3
TRUE
FALSE Block 3

Condition n-1

Block n-1
Block n

Statement after if

23
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Program to Print Day Names using Else


If Ladder Practice programming
// Print Day name for number
#include <stdio.h> 1. Write a C program Print a word for vowel
int main() { 2. WriteaCprogramPrintcolournamefor“vibgyor”
int day;
printf( "Enter Day Number: "); 3. WriteaCprogramtoinputmonthnumberandprintnumberofdaysinthatmonth.
scanf("%d",&day);
printf( "Day is "); 4. WriteaCprogramtoinputmarksoffivesubjectsPhysics,Chemistry,Biology,
if (day == 1)
MathematicsandComputer.Calculatepercentageandgradeaccordingto
printf("Sunday \n"); following:
else if (day == 2)
printf("Monday \n");
Percentage>=90%:GradeA
else if (day == 3) Percentage>=80%:GradeB
printf("Tuesday \n");
else if (day == 4)
Percentage>=70%:GradeC
printf("Wednesday \n"); Percentage>=60%:GradeD
else if (day == 5)
printf("Thursday \n");
Percentage>=40%:GradeE
else if (day == 6) Percentage<40%:GradeF
printf("Friday \n");
else
printf("Saturday \n");
return 0;
} BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
CONTROL STATEMENTS CONTROL STATEMENTS
2. Selection with switch ... case structure In the above format ,
This structure is used for doing multi way decisions such as else if
- expression may be an arithmetic expression/character or integer variable or
ladder. It is an alternate structure to else .. if ladder.
enumerated type.
The general format for the switch .. case structure is - The value 1, value 2, ...... are the constant values that the expression is evaluated to.
switch ( expression ) - Each block except block n has a break statement.
{
case value 1: block 1; The block 1 is executed if the value of expression is equal to value1. After the block is
case value 2 : block 2; executed , the flow moves to the statement – x by means of the break statement in the
block.
case value 3: block 3;
The block 2 is executed if the value of expression is equal to value 2. After the block is
........... executed , the flow moves to the statement – x by means of break statement in the
default: block.
block n; And so on……
}
Statement x;
29 30
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

CONTROL STATEMENTS
if the value of expression does not match with any optional values value1, or value2,
..... . Or value n-1, then the block n is executed . After the block is executed, the flow switch (expression)
moves to the statement – x automatically. Example ௙{
case constant1:
switch (cust_cat )
// statements
{ break;
case‘A’:discount=price*10.0/100;
break; case constant2:
// statements
case‘B’:discount=price*7.5/100; break;
break; .
case‘C’:discount=100; .
break; .
default:
default:printf(“\nInvalidcustomerCategory”); // default statements
discount=0 }
}
31
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Flow chart

• The expression is evaluated once and compared with the values of each
case label.

• If there is a match, the corresponding statements after the matching label are
executed.

• For example, if the value of the expression is equal to constant2, statements


after case constant2: are executed until break is encountered.

• If there is no match, the default statements are executed.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Simple calculator

// Program to create a simple calculator


Notes: #include <stdio.h>
int main() {
If we do not use the break statement, all statements after the matching label are char operation;
double n1, n2;
also executed. printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter two operands: ");
The default clause inside the switch statement is optional. scanf("%lf %lf",&n1, &n2);
switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Print a number Print a word for vowel

#include <stdio.h> #include <stdio.h>


int main()
int main() { {
int n1; char c;
printf("enter number"); printf("enter a character\n");
scanf(“%d”,&n1); scanf(“%c”,&c);
switch (c) {
switch (n1) { case'a':
case 7: printf("a for apple");
printf("Value is Seven"); break;
case 'e':
break; printf("e for elephant");
case 8: break;
printf("Value is Eight"); case'i':
printf("I for ink");
break; break;
case 9: case'o':
printf("Value is Nine"); printf("o for oil");
break; break;
case'u':
default: printf("u for umbrella");
printf("Out of range"); break;
break; default:
printf("not a vowel");
} break;
return 0; }
} return 0;
}

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Practice program Nesting of Switch case

• WriteCprogramtoprintnumberofdaysinamonthusingswitchcase. Nested-Switch statements refers to Switch statements inside of another Switch


• WriteCprogramtoprintdayofweeknameusingswitchcase. Statements.
• WriteCprogramtocreatecalculatorusingswitchStatement.
• WriteCprogramtocheckevenoroddnumberusingswitchcase.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


switch(n)
{
//codetobeexecutedifn=1;

Nested Switch case statements


case1:
 //Nestedswitch
switch(num)
{
//codetobeexecutedifnum=10
case10:
statement1;
break; • Choice1…>alphabets(vowels)
//codetobeexecutedifnum=20
case20:
statement2;
• Choice2…>Numbers(0to9)
break;
//codetobeexecutedifnum=30
case30:
statement3;
break;
//codetobeexecutedifnum
//doesn'tmatchanycases
default:
}
 break;
//codetobeexecutedifn=2;
case2:
statement2;
break;
//codetobeexecutedifn=3;
case3:
statement3;
break;
//codetobeexecutedifndoesn'tmatchanycases
default:
}

CONTROL STATEMENTS CONTROL STATEMENTS

b) Un conditional control statement using go to b = 20;


The flow is altered without checking any condition. The general go to lab;
format of go to is c = -1000;
go to label name; printf(“\nDummy”);
where label name is a label given for the statement for which the lab: print(“\n C value is %d”,c);
flow is sent. The rules for defining the variables are to be used for }
labeling the statement.
The output for the above program is C value is 1000.
The label for a statement should be given in the format
Here,
Label name : statement – X;
The statements c = - 1000;andprintf(“\nDummy”);arenotexecuted
Example : main()
{ because as soon as the flow reaches to go to statement , the flow will
int a,b , c = 1000; be transferred to the
a = 100; printf(“\n C value is %d”,c); which has the label (lab).

43 44
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Use of If statements in function
Use of If statements in function

// Online C compiler to run C program online #include <stdio.h>


void disp (int);
#include <stdio.h> int main()
void disp (char str[]);
{
int main()
{ int num;
int num; num=1;
num =2; disp(num);
if (num==1) return 0;
disp("Sunday"); }
if (num==2) void disp(int no)
disp("Monday");
{
if (no==1)
return 0;
} printf("Sunday");
void disp(char str[]) if (no==2)
{ printf("Monday");
printf("%s",str);
} }

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Function , if statement, Switch case

Lab resources
• Printing Employee details [Link]
• Printing invoice of the product
• Calculator

Thanks

48
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Contact session 7
IMP Note to Self

Repetitve Statements
BITS Pilani
Pilani Campus Systems Programming - V
3.0

Learning Objectives
IMP Note to Students ➢ What are Repetitive statements?
➢ How they are different from control statements?
➢ It is important to know that just login to the session
➢ Different types of repetitive statements
does not guarantee the attendance.
while statement
➢ Once you join the session, continue till the end to
do .. While statements
consider you as present in the class.
for statements
➢ IMPORTANTLY, you need to make the class more
looping with go to statement
interactive by responding to Professors queries in the
➢ Jump Statements
session. break statement
➢ Whenever Professor calls your number / name ,you continue statement
need to respond, otherwise it will be considered as
Systems Programming - V
ABSENT 3.0

4
BITS Pilani, Pilani Campus
LOOPING STATEMENTS Repetitive structure
Repetitive Structure : It is a structure in which a block is to be
executed more than once.
This structure is also known as Looping structure or Iterative
structure .
The block may be a single statement or a collection of more than one
statements begins with { and ends with }.
There are four types of repetitive structures. They are
(i) While Loop
(ii) Do .. while Loop
(iii) For Loop
(iv) Looping with go to statement

5
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Syntax for For ..loop LOOPING STATEMENTS


When the FOR loop is executed , the following steps are done.
Step 1: Initialization part is performed first
Step 2: The condition is verified.
Step 3: If the condition is True ,
– Block is executed
– The incremental or decremental part is done
Again , the control goes to step (2). It is continued as long as the
condition is true.
If the condition is False ,
The control goes to the statement which lies after the for loop
without executing the block.

8
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
For Loop

for ( init; condition; increment ) Printing sequence of numbers from 1 to n


{
statement(s); Starting number is 1
}
The number till to be printed n

The increment value is 1

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

LOOPING STATEMENTS For Loop --decrement

Examples:
1. for(i=1;i<=8;i++)printf(“%d\n”,i); for ( init; condition; decrement )
printf(“\nOK..”); {
The output of the above segment is statement(s);
1
}
2
3
4
5
6
7
8
OK..
11
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
LOOPING STATEMENTS LOOPING STATEMENTS
2. for(i=10;i<=8;i++)printf(“%d\n”,i);
Examples:
printf(“\nOK..”);
1. for ( i =8 ; i>=1 ; i--)printf(“%d\n”,i);
The output of the above segment is
printf(“\nOK..”);
OK..
The output of the above segment is
8
Note :All the parts are optional. So the following for loops are valid
7
6
5
4
3
2
1
OK..
13 14
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

LOOPING STATEMENTS- For loop without Final


For loop without initial value value

(a) i = 1; (b) i = 1;
for(;i<=10;i=i+3)printf(“%d\n”,i); for ( ; ; i = i + 3)
{
printf(“OK..”);
printf(“%d\n”,i);
The output will be if ( i > 10 ) go to xyz;
1 }
4 xyz:printf(“OK..”);
7 The output will be
1
10
4
OK.. 7
10
13
OK.. 16
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
LOOPING STATEMENTS – Listed program
Without any conditions
(c) i = 1;
1. Factorial of a number
for ( ; ; )
2. Print a multiplication table
{
3. Write a program to print right angle triangle using asterisk
printf(“%d\n”,i);
4. Sum of first n even numbers.
i = i + 3;
5. Square roots of 1 to 9 numbers.
if ( i > 10 ) go to xyz;
6. Numbers not divisible by 2, 3, 5.
}
xyz:printf(“OK..”);
The output will be
1
4
7
10
OK..
17
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Listed program For loop with if condition

1
12
123
1234
12345

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


For loop and If statement Practice Program
#include <stdio.h>
int main() [Link] zero, odd & even digits
{ 2. Print total marks of student who have passed
int i; 3. Program to calculate the sum of numbers (10
for(i=1;i<10;i++) numbers max) If the user enters a negative
{ number, it's not added to the result
if (i%2 ==0 )
printf("%d even numbers\n",i);
else

printf("%d odd numbers\n",i);


}
return 0;
}
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Nested Loop Nested loop

• A loop within another loop is called a nested


loop. Nested loop means a loop statement inside another
loop statement. That's why nested loop are also called as loop
inside loop.
• Execution of statement within the loop flows in a way that the
inner loop of the nested loop gets declared, initialized and
then incremented.
• Once all the condition within the inner loop gets satisfied and
becomes true it moves for the search of the outer loop. It is
often called a loop within a loop.

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Nested loop

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

LOOPING STATEMENTS Looping using goto


Note :- A for loop within another for loop is known as the Nested for
loop. (iv)Looping with Go to : Repetitive structure can be
for ( i =1 ; i <= 5; i++) formed by
for ( j = 10; j<=50 ; j = j + 10) using the go to statement as
printf(“%d\t”,i*j); i=1;
xyz:printf(“%d\n”,i);
The output of the above segment is
i = i + 3;
10 20 30 40 50 20 40 60 80
.. .. .. 50 100 150 200 250

27
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
LOOPING STATEMENTS JUMP STATEMENTS
The jump statements are the statements which can be used inside
if ( i <= 10 ) go to xyz; the looping structure. The Jump statements are
printf(“\nOK..”);
1. break statement
The output of the above statement 2. continue statement
1
4
7
10

29 30
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

break statement
JUMP STATEMENTS

When the break statement inside the looping structure is The output of the above code is
executed, the control comes out of the loop immediately 1 2 3 4 5
without checking the condition. Reason: break statement is executed when the condition becomes
This statement is used for premature exit from the loop. true. The condition is true when the value of i becomes 6
(6%6==0). Though the loop is framed to be executed for 20 times,
Example: Sample code with break statement
the control comes out of the looping structure prematurely.
for(i=1;i<=20;i++)
{
if (i%6==0)break;
printf(“%d\t”,i);
}

32
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
JUMP STATEMENTS
Continue statement Example: Sample code with continue statement
When the continue statement inside the looping structure for(i=1;i<=20;i++)
is executed, the control does not come out of the loop like {
a break statement. if (i%6==0)continue;
printf(“%d\t”,i);
The loop is continued as long as the condition is true but
}
the statement(s) that lie after the continue statement is
The output of the above code is
ignored.
1 2 3 4 5 7 8 9 10
The example for using continue statement is given below: 11 13 14 15 16 17 19 20
The continue statement is executed when the condition becomes true.
The condition is true when the value of i becomes 6 , 12, and 18
(6%6==0,12%6==0 and 18%6==0).
When it is true, the printf() statement is not executed.

34
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Using Continue statement

// Program to calculate the sum of numbers (10 numbers max)


// If the user enters a negative number, the loop terminates
#include <stdio.h> Lab resources
int main() { [Link]

int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i) {
printf("Enter n%d: ", i);
Thanks
scanf("%lf", &number);
// if the user enters a negative number, break the loop
if (number < 0.0) {
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
return 0;
} 36
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
IMP Note to Self
IMP Note to Self

Lecture - 8
Recursion in C
BITS Pilani
Pilani|Dubai|Goa|Hyderabad

Agenda Introduction to Recursion

• Recursion is a process where a function calls itself to solve a


Introduction to Recursion
problem.
Recursion vs. Iteration • It breaks down a problem into smaller subproblems, solving
each recursively.
Tips & Common Programming Errors
• Requires a base case to stop the recursion.
Programming Examples & Exercises
❖ Key Concepts
✓ Base Case: The stopping condition to prevent infinite
recursion.
✓ Recursive Case: The part of the function that calls itself.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Recursion Introduction to Recursion
General Syntax: Recursion Flowchart: Start

void recursiveFunction()
{ Initiate Function
if (base_condition)
return; Recursive Call
else False True
Base Case
{
// Recursive call
recursiveFunction(); Recursive Case Return Statement
}
}
Stop

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Introduction to Recursion Code Explanation


Example: Factorial Calculation Header File Inclusion
#include <stdio.h> # include <stdio.h>
int factorial(int n)
{
✓ This includes the standard input-output library in C.
if (n == 0) // Base case ✓ Required for functions like printf() and scanf().
return 1;
return n * factorial(n - 1); // Recursive case Recursive Function Definition
}
int factorial(int n) {
int main()
{
int num = 5; ✓ Declares a recursive function named factorial.
printf("Factorial of %d is %d\n", num, factorial(num)); ✓ Takes an integer n as input and returns an integer.
return 0;
} BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Code Explanation Code Explanation
Base Case: Recursive Case:

if (n == 0) // Base case return n * factorial(n - 1); // Recursive case


return 1;

✓ Calls factorial(n - 1), reducing n by 1.


✓ If n == 0, the function returns 1 (since 0! = 1).
✓ Multiplies n with the factorial of n - 1.
✓ Prevents infinite recursion by stopping the function calls. ✓ This breaks down the problem into smaller parts until n == 0.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Code Explanation Code Explanation

Entry point of the program. printf("Factorial of %d is %d\n", num, factorial(num));

int main() { ✓ Calls the factorial() function with num = 5.


✓ printf() prints the result to the console.

Declares an integer num and initializes it to 5.


return 0;
int num = 5;
✓ Indicates successful execution of the program.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
How Recursion Works in this Case? How Recursion Works in this Case?

For factorial(5), the function calls occur like this: Now, returning values step by step:

factorial(5) → 5 * factorial(4) factorial(1) = 1 * 1 = 1


factorial(4) → 4 * factorial(3) factorial(2) = 2 * 1 = 2
factorial(3) → 3 * factorial(2) factorial(3) = 3 * 2 = 6
factorial(2) → 2 * factorial(1) factorial(4) = 4 * 6 = 24
factorial(1) → 1 * factorial(0) factorial(5) = 5 * 24 = 120
factorial(0) → 1 (Base case)
Final Output
Factorial of 5 is 120
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Recursion vs Iteration Recursion vs Iteration

Feature Recursion Iteration Fibonacci Series (Recursion vs Iteration)


Recursion:
Function Calls Uses function calls Uses loops (for, while)
int fibonacci(int n)
Memory Usage High (stack frames) Low
{
Performance Slower due to overhead Faster if (n <= 1)
return n;
More readable for some
Readability More efficient
problems return fibonacci(n - 1) + fibonacci(n - 2);
}

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Tips for Writing Recursive
Recursion vs Iteration Functions:
Fibonacci Series (Recursion vs Iteration)
Iteration: Always define a base case.
int fibonacciIterative(int n)
{ Ensure that recursive calls reduce the problem size.
int a = 0, b = 1, temp;
for (int i = 2; i <= n; i++) Use recursion only when necessary (avoid excessive stack
{
temp = a + b;
usage).
a = b;
b = temp;
Prefer tail recursion (if applicable) for better optimization.
}
return b;
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Common Mistakes in Recursion

Forgettingthebasecase→Leadstoinfiniterecursion.
Forgetting the base case → Leads to infinite recursion.

Recursive calls not reducing problem size → Stack Problem:


overflow. • If we forget to define a base case, the function will keep
Using recursion when iteration is more efficient → calling itself indefinitely, leading to a stack overflow.

Wastes memory.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example: Incorrect Factorial Function (No Base Case)

#include <stdio.h>
int factorial(int n) { Issue:
return n * factorial(n - 1); // No base case
• The function never stops calling itself because there’s no
}
base case.
int main() {
int num = 5; • This results in infinite recursion and a stack overflow
printf("Factorial of %d is %d\n", num, factorial(num)); error.
return 0;
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

RecursiveCallsNotReducingProblemSize→Stack
Fix: Overflow
int factorial(int n) { Problem:
if (n == 0) // Base case • If the problem size does not decrease, recursion never
return 1; reaches the base case, causing a stack overflow.
return n * factorial(n - 1);
}

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example: Incorrect Countdown Function (Doesn't Reduce Input)
#include <stdio.h>
void countdown(int n) {
if (n == 0) {
printf("Blast off!\n");
Issue:
return; } • The function keeps calling countdown(n) with the same
printf("%d\n", n);
value of n.
countdown(n); // Problem: n is never decreasing!
} • n is not decreasing, so the base case is never reached.
int main() {
countdown(5);
return 0; }
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Fix:
void countdown(int n) { UsingRecursionWhenIterationisMoreEfficient→
if (n == 0) { Wastes Memory
printf("Blast off!\n"); Problem:
return; • Some problems are better solved using loops instead of
} recursion.
printf("%d\n", n); • Using recursion unnecessarily increases memory usage
countdown(n - 1); // Decrease problem size and function call overhead.
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example: Sum of First N Natural Numbers (Inefficient Recursion)
#include <stdio.h>
int sum(int n) {
if (n == 0)
return 0;
Issue:
return n + sum(n - 1); // Recursively summing numbers • This function makes n recursive calls, leading to stack
}
memory consumption.
int main() {
int num = 10000; // Large input • For large values of n, it may cause a stack overflow.
printf("Sum of first %d numbers is %d\n", num, sum(num));
return 0;
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Fix: Use Iteration (More Efficient)

int sumIterative(int n) {

int total = 0;

for (int i = 1; i <= n; i++)

total += i;
Examples
return total;

}
Why is iteration better?
• Uses a single loop instead of multiple function calls.
• Saves stack memory and prevents stack overflow.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example- Sum of Digits Using Recursion Advanced Example - Tower of Hanoi
#include <stdio.h> #include <stdio.h>
int sumOfDigits(int n) { // Function to solve Tower of Hanoi
if (n == 0) // Base case
void towerOfHanoi(int n, char source, char destination, char auxiliary)
return 0;
{
return (n % 10) + sumOfDigits(n / 10); // Recursive case
if (n == 1)
}
int main() { { // Base Case: Only one disk to move
int num = 1234; printf("Move disk 1 from %c to %c\n", source, destination);
printf("Sum of digits of %d is %d\n", num, sumOfDigits(num)); return;
return 0; }
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Advanced Example - Tower of Hanoi Advanced Example - Tower of Hanoi

Problem Statement Example 1:


The Tower of Hanoi, is a mathematical problem which Input: N = 3,
consists of three rods and multiple disks. Initially, all the disks Output:
are placed on one rod, one over the other in ascending order of Move disk 1 from rod A to rod C
size similar to a cone-shaped tower. Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
The objective of this problem is to move the stack of disks Move disk 3 from rod A to rod C
from the initial rod to another rod, following these rules: Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
• Move one disk at a time. Move disk 1 from rod A to rod C
• No disk can be placed on top of smaller disk. Explanation: Moving disks from one rod to another using an
• Only the top disk may be moved. auxiliary rod takes these steps.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Advanced Example - Tower of Hanoi Advanced Example - Tower of Hanoi

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Advanced Example - Tower of Hanoi Advanced Example - Tower of Hanoi

// Step 1: Move n-1 disks from source to auxiliary using destination int main() {
towerOfHanoi(n - 1, source, auxiliary, destination);
int num_disks = 3; // Change this for more disks

printf("Tower of Hanoi solution for %d disks:\n", num_disks);


// Step 2: Move nth disk from source to destination
printf("Move disk %d from %c to %c\n", n, source, destination); towerOfHanoi(num_disks, 'A', 'C', 'B’);

// 'A' is source, 'C' is destination, 'B' is auxiliary


// Step 3: Move n-1 disks from auxiliary to destination using source
return 0;
towerOfHanoi(n - 1, auxiliary, destination, source);
} }
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Example - Reverse a String Using Recursion Example - Reverse a String Using Recursion
#include <stdio.h> int main() {
#include <string.h>
// Function to reverse a string using recursion char str[] = "hello"; // Input string
void reverseString(char str[], int left, int right)
{ int length = strlen(str);
if (left >= right) // Base case: When pointers cross
reverseString(str, 0, length - 1); // Call recursive function
return;
// Swap characters at left and right
printf("Reversed string: %s\n", str);
char temp = str[left];
str[left] = str[right]; return 0;
str[right] = temp;
reverseString(str, left + 1, right - 1); // Recursive call for the remaining substring }
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Summary

Homework Examples
✓ Write a recursive function to find the Greatest Common Divisor ✓ Recursion simplifies problem-solving for divide-and-conquer
(GCD) of two numbers. problems.
✓ Implement a recursive function to check if a number is a ✓ Base cases are crucial to avoid infinite loops.
palindrome. ✓ Choose recursion wisely; sometimes iteration is more efficient.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Q&A
IMP Note to Self

Any questions?

46

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Pilani Campus

47

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Computer Programming
ARRAYS (CS_9) Topics to be Covered:
Random Access Lists
BITS Pilani
Pilani Campus IntegerArrays: Declaration, Indexing, Iterating
PassingArrayasa functionargument
BITS Pilani, Pilani Campus

Introduction Arrays: List of Items


• Simpledatatypes(i.e.int,float,double)usesingle
• Acollectionofhomogeneous(i.e.similartype)
memory cell to store avariable.
– e.g.intage<allocates4bytesofmemorycellona32bit
data items under same name iscalled an Array
machine> – e.g.want to store marks of100 students
• Consider aprogram that processes exam marks for a •Allocates100contiguousmemorycellsofequalsize
class of100students marks→ 0th cell
1st cell
– Needtodeclare100differentvariablestostorethemarks

for allthe students

• Ifwecanstoretheminonearea …
ofmemoryandcanaccessasa …
98th cell
groupthen the job becomes easy
99th cell
3 4
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Array Declaration and
Accessing Array Elements
Initialization
Array declaration: marks[0]→ 50 RandomAccess:
marks[0]→ 50 <data_type><array_name>[SIZE] marks[4] = marks[4]+2;
marks[1]→ 60
marks[1]→ 60 Example: int marks[10], float marks[10];
marks[2]→ 45
marks[2]→ 45 Array Initialization: Sequential Access:
int marks[10]; marks[3]→ 55 int marks[10];
marks[3]→ 55
marks[10] = {50, 60, 45, 55, 35, 67, 89, 88, 76,90}; marks[4]→ 35 for(index=0;index<10;index++){
marks[4]→ 35
marks[10] = {0}; marks[5]→ 67 if(marks[index]>= 60)
marks[5]→ 67 marks[] = {50,60, 45, 55, 35,67, 89,88, 76,90}; printf(“First Division”); }
marks[6]→ 89
marks[6]→ 89
marks[7]→ 88
marks[7]→ 88
marks[8]→ 76
marks[8]→ 76
marks[9]→ 90
marks[9]→ 90
5 6
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Iterating Array Elements Iterating Array Elements


Average Calculation:
t1 t2 totM t1 t2 totM
int t1[10],t2[10],totM[10],sum,avg;
50 60 110 50 60 110
Array Addition: sum =0;
60 50 110 60 50 110 for (index=0; index<10; index++)
int t1[10], t2[10], totM[10];
45 44 89 45 44 89 {totM[index]=t1[index]+t2[index];
for (index=0; index<10; index++)
55 55 110 55 55 110 sum = sum+ totM[index];
totM[index] = t1[index] + t2[index];
}
35 35 70 35 35 70
avg = sum/index;
67 77 144 67 77 144
89 89 178 89 89 178
88 80 168 88 80 168
76 56 132 76 56 132
90 49 139 7
90 49 139 8
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
PassingArrayasaFunction Returning Array From a
Argument Function
int main() { int FindMean (int List[], int size) int main() { void FindDev(int size, int mean, int
int list[10],i,mean_val; { int i, mean, sum=0; intlist[10],devlist[10],i,mean_val; List[], int DevList[])
for(i=0;i<10;i++) for(i=0; i<size; i++) for(i=0 ; i<10 ; i++) { int i;
scanf(“%d”,&list[i]); sum=sum+List[i]; scanf(“%d”,&list[i]); for(i=0;i<size;i++)
mean_val=FindMean(list,10); mean = sum/size; mean_val=FindMean(list,10); DevList[i] = List[i] - mean;
printf(“Mean = %d”,mean_val); return mean; } FindDev(10,mean_val,list,devlist); }
return 0; for(i=0 ; i<10 ; i++)
} printf(“%d”,devlist[i]);
return 0;
}

9 10
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Summary

• A group ofelements can be stored under asingle name • A collection/group of characters also can be stored
using Arrays under asingle name like numbers using Arrays in C
– Individual items can be randomly accessed usingthe index – Array of characters
value – The corresponding ASCII value is stored in the memory
• Arrays can bepassed asan argument to the functions
– An array ispassed as anargument toa function,by reference
• In C, Array boundary should be protected by the
programmer

11 12
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Character Array Declaration and
Initialization Character Array I/O

• Reading array elements from user input


grade[0]→ A Array declaration: int i; char arr[10];
grade[1]→ <data_type><array_name>[SIZE] Alternate method
B for(i=0; i<10; i++)
Example: char grade[10]; arr[i]=getchar();
grade[2]→ C scanf(“%c”,&arr[i]);
grade[3]→ A Array Initialization: • Displaying array elements to the standard output
grade[4]→ B char grade[10]= {‘A’, ‘B’, ‘C’, ‘A’, ‘B’, ‘C’, ‘A’, ‘B’, ‘C’, ‘D’};
for(i=0; i<s10; i++)
Alternate method
grade[5]→ C printf(“%c”,arr[i]); arr[i]=putc(arr[i],stdout);
grade[6]→ A
grade[7]→ B
grade[8]→ C
grade[9]→ D
13 14
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Accessing Character Array


Elements Strings

marks[0]→ 50 grade[0]→ A Sequential Access: • String is an array of characters which is terminated by a


marks[1]→ 75 grade[1]→ B int marks[10], grade[10]; specialcharacter i.e. NULL (‘\0’)
marks[2]→ 45 grade[2]→ C for(index=0;index<10;index++){ – Example: charstr[8]={‘P’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘\0’};
if(grade[i]==‘A’)
marks[3]→ 85 grade[3]→ A – char str[8]=“Program”
printf(“Marks= %d”,marks[i];
marks[4]→ 35 grade[4]→ B } – char str[]=“Program”;
marks[5]→ 67 grade[5]→ C
marks[6]→ 89 grade[6]→ A
marks[7]→ 88 grade[7]→ B
marks[8]→ 40 grade[8]→ C
marks[9]→ 20 grade[9]→ D
15 16
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
String Input and Output Example Problem

• Reading string using scanf() function • Writeaprogramwhichreadsthecharactersfromtheuseruntil


– scanf(“%s”,&str) thereturnkeyispressedandfindsoutthenumberofvowels
and consonants entered by theuser. Assume usercan enter any
• Readingstring using gets()function character.Theprogramshoulddisplaythecharactersenteredby
– gets(str) theuseralongwiththenumberofvowelsandconsonants.
• Displaying string using printf() function Programshouldconsiderbothuppercaseandlowercase
characters for vowel/consonants count.
– printf(“%s”,str)
• Displaying string using puts() function
– puts(str)

17 18
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Implementation String Handling Functions

int main() {
char text[100],ch; text[i++]=ch;
• String handling functions are used to carry out various
int i=0,vowel=0,consonant=0; } string manipulations like:
while ((ch=getchar())!='\n') { text[i]='\0';
if(ch>=65 &&ch<=90 || ch>=97 && ch<=122) { printf("Userinputis:%s\n",text);
– To find the lengthof a string [strlen(s1)]
switch(ch) {
case 'a':
printf("No. of vowels are: %d\n",vowel); – To copy onestring to another [strcpy(s1,s2)]
printf("No.ofconsonantsare:%d",consonant);
case'A': return 0; – To concatenatetwo strings [strcat(s1,s2)]
case 'e':
} – To comparetwostrings [strcmp(s1,s2)]
case'E':
case 'i':
case 'I': • These functions are packaged in string.h header file
case 'o':
case 'O':
case 'u':
case'U':vowel++; break;
default: consonant++;
}
}
19 20
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Implementation of strcat() Summary

//concatenates the contents of str2to the str1


• Strings are defined as NULL terminated character arrays
– Total (N+1) byte space is required to store N character string
void String_Concatenate(char str1[], char str2[])
{ inti=0,j=0; • Passing strings as an function argument is same as passing
while(str1[i++]!='\0'); integer arrays
i--; – Here size is not required to pass for boundary protection as an
argument like integer arrays because NULL character is used as
while(str2[j] != '\0')
termination of the string
str1[i++] = str2[j++];
• Strings are also passed by reference
str1[i]='\0‘;
}
as an function argument

21 22
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Searching
BITS Pilani
Pilani Campus

• How to search an item in alist…with N items?


– Iterateover the list and compare each element of the
list withkey
– Whento stop the process…?
• If key matches with an item at pos x (0<=x<N) inthelist
• List is exhaustedwithout matching key
– Called as simple search or LinearSearch
Operations on Arrays:
Searching: Linear search & Binary search
Insertion and Deletion
24
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Linear Search in an Array[1] Linear Search in an Array[2]

Problem Statement: Find the index of thefirst occurrence of the key Problem Statement: Find numberof occurrences of the key
int LinearSearch(int List[], int size, int key) int LinearSearch(int List[], int size, int key)
{ int i; { inti,count=0;
for(i=0;i<size;i++) for(i=0 ; i<size; i++)
if(key==List[i]) return i; if(key==List[i]) count++;
return -1; return count;
} }

25 26
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Searching in an Ordered List Binary Search: Example-1

• How search operation can be improved, if the items in • Assume key = 8
start mid end
the list are sorted
3 4 6 8 9 12 14 18 20 22 24 Key < A[5]
• Pick a random element in the list and compare with the
start mid end
key. Three possibilities
– Key == random element (Done!!!) 3 4 6 8 9 12 14 18 20 22 24 Key > A[2]
– Key < random element (key ispresent in lefthalf ofthe list) mid start end
– Key>randomelement(keyispresentintherighthalfofthe
3 4 6 8 9 12 14 18 20 22 24 Key == A[3]
list )

27 28
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Binary Search: Example-2 Binary Search Implementation

• Assume key = 7 mid end int binary_search(int list[], int key, int size)
start
{ intfound=0,end=size-1,start=0,mid;
3 4 6 8 9 12 14 18 20 22 24 Key < A[5]
mid=(end+start)/2;
start mid end
while(end>=start) {
3 4 6 8 9 12 14 18 20 22 24 Key > A[2] if(key==list[mid]) return mid;
mid start end else
{ if(key<list[mid]) end=mid-1;
3 4 6 8 9 12 14 18 20 22 24 Key < A[3]
end mid start else start=mid+1;
}
3 4 6 8 9 12 14 18 20 22 24
mid=(end + start)/2; }
Key NOT Found return -1;
29 } 30
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Insertion Operation Insert at First Position

• Assume alist ofstudent marks are stored in anarray 3 4 6 8 9 12 14 18 20 22

• A new student is registered in the course hence his int InsertAtStart(int marks[], int cur_size,int val)
marksneeds to beinsert in the list { inti;
Increase Size by 1
if(cur_size!=0) { &
• How toinsert…? Shift Right
for(i=cur_size-1;i>=0; i--)
– Insert at the end of the list
marks[i+1]=marks[i]; 3 3 4 6 8 9 12 14 18 20 22
– Insert at the start of the list
}
– Insertat a specified position
marks[0]=val;
return cur_size+1;
}

31 32
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Insert at Last Position Insert at Specified Position

intInsertAtEnd(int marks[],intcur_size, int val) int InsertAtRandomPos(int marks[], int cur_size, int val, int index)
{ int i; { int i;
marks[cur_size]=val; for(i=cur_size-1;i>=index;i--)
return cur_size+1; marks[i+1]=marks[i];
} marks[index]=val;
return cur_size+1;
}

33 34
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Delete First Element From an


Deletion Operation Array

• Assume alist ofelements are stored in an array. One 3 4 6 8 9 12 14 18 20 22

element needs to be deleted from thelist. int DeleteFirst(int marks[],int cur_size)


• We need to know which element has to be delete. The { inti;
Shift Left and ReduceSize
possible options are: if(cur_size==0) { by one

– Delete first element of the list printf("NoelementintheList");


– Delete last element of the list return cur_size;
3 4 6 8 9 12 14 18 20 22
– Delete elementfrom a specified position from the list }
for(i=0;i<cur_size-1;i++)
marks[i]=marks[i+1];
return cur_size-1;
}
35 36
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Delete Last Element of an Array Delete from a Specified Position

intDeleteLast(int marks[], int cur_size) int DeleteAtPos(int marks[], intcur_size, int pos)
{ return cur_size-1; { int i;
} for(i=pos; i<cur_size; i++)
marks[i]=marks[i+1];
return cur_size-1;
}

37 38
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Delete a Specified Element Summary

int DeleteElement(int marks[], int cur_size, intkey) • We learnedfollowing operations onthearrays


{ int i, new_size;
– Search an array element
for(i=0; i<cur_size; i++) {
if(marks[i]==key) {
– Insert an arrayelement
new_size = DeleteAtPos(marks, cur_size, i); – Delete anarrayelement
return new_size;
} • KeyPoints to remember
}
– Howto iterate over the array
return cur_size;
}
elements
– Keep track of array boundary
39 40
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Thank You!

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Computer Programming
CS_10 Topics to be Covered:
Operations on Arrays: Sorting
BITS Pilani
Pilani Campus [Link] Bubble Sort, Insertion Sort

BITS Pilani, Pilani Campus

Introduction BubbleSort

• Many times we need to arrange the data in the desired • Bubble Sort is a simple algorithm which is used to sort a
manner to getprecise information given set of n elements provided in form of an array with
n number of elements.
– Arranging students marks in ascending/descending order
– Arranging price of items from lowest to highest or viceversa
• Bubble Sort compares all the element one by one
– Searching a data item in a sorted list takes less time (Binary and sort them based on their values.
Search Vs. LinearSearch)
• Bubble Sort works by repeatedly swapping the adjacent
elements if they are in the wrong order.

• This algorithm is not suitable for large data sets as its


average and worst-case time complexity is quite high.
3 4
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
BubbleSort Bubble Sort

•Traverse from left and compare adjacent elements and the


higher one is placed at right side.

•In this way, the largest element is moved to the rightmost end at
first.

•This process is then continued to find the second largest and


place it and so on until the data is sorted.

5
BITS Pilani, Pilani Campus

At the end of the first iteration, the highest


element placed its position in the array.
Iteration2

During the Second Iteration, the second largest element is placed in its place.

Iteration 3

During the third iteration, third largest element placed at its place.
Iteration 4 Attheendoftheiteration

Bubble Sort Implementation


void SortList_Ascending(int List[], int size)
13 10 8 6 12 13>10 [ TRUE: Swap] { int temp,i,j;
for(i=0; i<size-1; i++) {
10 13 8 6 12 10>8 [TRUE:Swap] for(j=i+1; j<size;j++) {
if(List[i]>List[j]) {
8 13 10 6 12 8>6 [TRUE:Swap]
temp=List[i];
6>12 [FALSE: No Swap]
List[i]=List[j];
6 13 10 8 12
List[j]=temp;
}
Ist Iteration is shown here }
}
}
15 16
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
InsertionSort InsertionSort

Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands.

The array is virtually split into a sorted and an unsorted part.

Values from the unsorted part are picked and placed at the correct position in the
sorted part.

To sort an array of size N in ascending order iterate over the array and compare
the current element (key) to its predecessor, if the key element is smaller than its
predecessor, compare it to the elements before.

Move the greater elements one position up to make space for the swapped
element.

InsertionSort
Insertionsort Implementation
void SortList_Insertion(int List[], int size)
13 10 8 6 12
{ int temp, i, j;
10 13 8 6 12
for(i=1; i<size; i++) {
temp=List[i];
8 10 13 6 12
j = i;
while(j>0 && List[j-1] > temp) {
List[j] = List[j-1];
6 8 10 13 12
j = j -1;
}
6 8 10 12 13
List[j] = temp;
}
}
23 24
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Summary
BITS Pilani
Pilani Campus
• We learned how to arrange the array elements
• Two Methods or Algorithms
– Bubble Sort
– Insertion Sort
• Exercise
– Takeanarrayof100elementsandrunboththealgorithmsto
findwhichalgorithmisbestintermsofnumberor
swapping/comparison operations. Topics to be Covered:
Two Dimensional Arrays:
Representation, Uses and Processing
25
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Introduction Two Dimensional Arrays


• An instructor wants to store the marks of three exams i.e. ex1,
ex2 and ex3 for 100 students. Also, he wants to store the total
• How to represent two dimensional arrays…?
marks (i.e. total=ex1+ex2+ex3) for each of the student. int A[3][2] = {2,4,6,8,10,12};
– Which data structure is suitable for storing such kind of data? • MemoryLayout of 2-D arrays:
– Choice-1
• Four one dimensional arrays can beused; ex1[100], ex2[100], A[0][0] 2 A[0][0] 2
ex3[100] and total[100] A[0][1] 4 A[1][0] 6
– Choice-2 A[1][0] 6 A[2][0] 10
ex1 ex2 ex3 total A[1][1] 8 A[0][1] 4
Student-1 A[2][0] 10 A[1][1] 8
Stuent-2 A[2][1] 12 A[2][1] 12
……
Student-99
27 28
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Accessing 2-D Array Elements Example
• Requires two nested loops: • Total 100 students marks for ex1,ex2 and ex3 are stored. The
for(i=0;i<3;i++) { 4th column will store the totalmarks.
for(j=0;j<2;j++) void Read_marks(int stu_marks[][4], int size) {
printf("%d ",a[i][j]); introw, col;
printf("\n"); for(row=0; row<size; row++)
} for(col=0; col<3; col++)
• Populating array elements: scanf(“%d”,&stu_marks[row][col]);
for(i=0;i<3;i++) { }
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
printf("\n");
}
29 30
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

FillingTotalMarksColumnfor
Find Average Marks in EachCourse
Each Student
void Average_MarksPerExam(int stu_marks[][4], int size) {
void Total_Marks(int stu_marks[][4], int size) {
int row, col, ctot; floatavg;
introw, col,tot;
for(col=0; col<3; col++) {
for(row=0; row<3; row++) {
ctot = 0;
tot=0;
for(row=0; row<size; row++)
for(col=0; col<3; col++) ctot =ctot + stu_marks[row][col];
tot = tot + stu_marks[row][col] avg = ctot/size;
stu_marks[row][col] = tot; printf(“Average of Course %d is : %f”,col,avg);
} // }
} }
Sample Function Call: Sample Function Call:
Total_Marks(marks,100); Average_MarksPerExam(marks,100);
31 32
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Array of Strings Memory Layout

• To store thenames of students oremployees, anarray name[0] M P A \0


of strings can be used. O I \0
H T
– e.g. char name*4+*10+ = ,“MOHAN”, “KALPIT”, “LAKSHYA”,.
A \0
“KARAMVEER”,-;
N name[3] K
– Alternate way to initialize string arrays: \0 A
• strcpy(name*0+, “MOHAN”); R
• strcpy(name*1+,“KALPIT”); name[2] L A
• strcpy(name*2+, “LAKSHYA”); A M
• strcpy(name*3+, “KARAMVEER”); K V
name[1] K S E
A H E
L Y R
33 34
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Processing Array of Strings: Processing Array of Strings:


Sorting Searching (Case Sensitive)
void SortNames(char names[][20], int size) int SearchName(char names[][20], char search[], int size)
{ int i,j; char temp[20];
{ int i;
for(i=0; i<size-1; i++) {
for(i=0; i<size; i++) {
for(j=i+1; j<size; j++) {
if(strcmp(search,names[i]) == 0)
if(strcmp(names[i],names[j])>0) {
strcpy(temp,names[i]); return i; //returns pos
strcpy(names[i],names[j]); }
strcpy(names[j],temp); return -1;
} }
} Sample function call:
} charnamelist[10][20],str[20];
} SearchName(namelist, str, 10);
35 12
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
ProcessingArrayofStrings:
Summary
Searching (Case Insensitive)
int SearchCaseInsensitive(char names[ ][20], char search[ ], int size) • Two dimensional arrays aredefined asan Arrayof Arrays
{ int i, j, k;
for(i=0; i<size; i++) {
• Alist of names is represented by an array of NULL
j = k =0; terminatedcharacter arrays
while(search[j] != NULL && names[i][k] != NULL) { • Two dimensional arrays are stored linearly in thememory
if(toupper(search[j]) != toupper(names[i][k]))
break;
like one dimensional arrays
j++; k++; – Either row wise or column wise order
} //while close
if(search[j] == NULL &&names[i][k] == NULL)
return i;
} //forclose
return -1;
}
37 38
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

BITS Pilani
Pilani Campus

Thank You!

BITS Pilani, Pilani Campus


BITS Pilani
Pilani|Dubai|Goa|Hyderabad

Computer Programming
Contactsession11
:
1. User Defined Types
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Department of Computer Science and Information Systems
Birla Institute of Technology and Science, Pilani
2. Tuples in C (Struct)
3. Unions
1 2
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Structures
UserdefinedDatatypes
WhereStructuresareUsed?

➢Callowscustomdatatypestobecreatedinvariousways. ➢Asweknow,simplevariablescanbeusedtoholdonepieceofinformationata
timeandArrayscanbeusedtoholdmorethanonepieceofinformationofthesame
➢OneofthedatatypeisStructure. datatype.

➢AStructureisagroupofvariablesunderonenameandisalsocalleda ➢Thesetwostoragemechanismscanhandlemanyasituations.
conglomeratedatatype.
➢However,theremaybecase,wheretheprogrammermaywishtooperateupon
➢Anotheruser-defineddatatypeisUnion,whichenablesthesamepieceof dataitemsofdifferenttypestogetherasaunit.
memorytobedefinedastwoormoredifferenttypesofvariables.
➢Inthiscase,neitheravariablenoranarrayisadequate.
➢Thefinaltype,whichisenumeration,whichisalistofsymbols.

3 4
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Structures
Structures WhereStructuresareUsed? WhereStructuresareUsed?
➢Forexample,supposeaprogramiswrittentostoredataconcerningacatalogueof
books.Thefollowingmayrequiredandstored. ➢ButtheseArraysarenoteasytohandletogether.
name of each book (a character array)
author’s name (another character array) ➢ThisiswhereaStructuremakesthethingssimpler.
the edition number (an integer)
price of the book (a float) ➢AStructureconsistsofanumberofdataitems,whichneednotbeofthesame
type,groupedtogether.
➢Amulti-dimensionalArraycannotbeusedtodothis,asanArraymustbeofthe
sametype. ➢Inthepreviousexample,aStructurewouldconsistsofthe book’s name, the
author name, the edition name, and the price of the book.
➢SeveraldifferentArrays-a character Array for name of the book, an integer Array
for the edition of the book, andsooncanbeusedtorepresentthecharacteristics ➢TheStructureasmanyoftheseitemsasdesired.
relatingtoasingleentry.

5 6
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Structures Structure
• Structure is a user-defined data type. It works similarly struct[structuretag]{
like arrays.
• memberdefinition;
• Structures help you in grouping items of different types in a
single group. Structures (also called structs) are a way to memberdefinition;
group several related variables into one place. ...
memberdefinition;
• a structure can contain many different data types (int, float,
char, etc.).It stores the collection of different data types. }[oneormorestructurevariables];

• Each variable in the structure is known as a member of the


structure.

7 8
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Memoryallocation
structemployee
{intid;
charname[20];
floatsalary;
};

9 10
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Structure example

structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
strcpy([Link],"CProgramming");
intbook_id;
strcpy([Link],"NuhaAli");
}book; strcpy([Link],"CProgrammingTutorial");
Book1.book_id=6495407;

structMyStructure{//Structuredeclaration
intmyNum;//Member(intvariable)
charmyLetter;//Member(charvariable)
};//Endthestructurewithasemicolon

11 12
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
StructureDeclaration Program2:ForAssigningstring

//CreateastructurecalledmyStructure struct myStructure {


structmyStructure{ int myNum;
intmyNum; char myLetter;
charmyLetter; char myString[30]; // String
};
};
intmain(){ int main() {
//CreateastructurevariableofmyStructurecalleds1 struct myStructure s1;
structmyStructures1;
//Assignvaluestomembersofs1 // Assign a value to the string using the strcpy function
[Link]=13; strcpy([Link], "Some text");
[Link]='B';
//Printvalues //Printthevalue
printf("Mynumber:%d\n",[Link]); printf("My string: %s", [Link]);
printf("Myletter:%c\n",[Link]);
return 0;
return0; }
}
13 14
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Assigningvaluesinsingleline Structureoperations-Structure
example
//Createastructure
structmyStructure{
intmyNum;
charmyLetter;
charmyString[30];
};

intmain(){
//Createastructurevariableandassignvaluestoit
structmyStructures1={13,'B',"Sometext"};

//Printvalues
printf("%d%c%s",[Link],[Link],[Link]);

return0;
}

15 16
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Assignment and comparison Assignment and comparison

How to compare??
Let Rectangle R1,R2;
-Field by Field comparison
[Link]=4; [Link]=5;
Boolean equals(Rectangle R1, Rectangle R2)
R2 =R1 ? ?
{
if(([Link]==[Link]) &&
Can we compare: R1==R2 ?? ([Link]==[Link])
Assignment is OK { return TRUE;}
But not equality test return FALSE;
}
17 18
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Operations Comparisonofstructure

How tocompute area?? #include<stdio.h>


structPoint{
intcomputeArea(Rectangle R1) intx;
inty;
{ };
intmain()
return [Link]*[Link]; {
} structPointp1={10,20};
structPointp2=p1;//works:contentsofp1arecopiedtop2
int main(){ if(p1==p2)//compilererror:cannotdoequalitycheckfor
//wholestructures
Rectangle R; int Area;R={3,4}; {
…… printf("p1andp2aresame");
}
Area=computeArea(R); getchar();
return0;
….. }

19 20
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Passingstructureasfunction Structures
StructureDefinition
structBooks{ ➢AStructuredefinitionformsatemplatethatisusedtocarrystructurevariables.
chartitle[50]; Thevariablesthatmakeupthestructurearecalledstructure variablesorStructure
elementsorStructure members.
charauthor[50];
➢Generallyallelementsinastructurearelogicallyrelatedbecausetheyarerelated
charsubject[100]; toasingleentity.
intbook_id; ➢ThedefinitionofaStructureisbestunderstood structbook
}; voidprintBook(structBooksbook)
 byanexample. {
charbk_name[25];
{ charauthor[25];
printf("Booktitle:%s\n",[Link]);
➢Theabovestatementdefinesanewdatatype intedn;
printf("Bookauthor:%s\n",[Link]);  calledstruct book. floatprice;
printf("Booksubject:%s\n",[Link]); };
printf("Bookbook_id:%d\n",book.book_id); ➢Eachvariablesofthistypeconsistsoffourelements–bk_name, author, edn and
} price.

21 22
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Structures Structures
StructureVariables
StructureDefinition
➢Onceanewdatatypehasbeendefined,oneormorevariablesofthattypecanbe
➢Thestatementdoesnotdeclareanyvariableofthetypebook,andsoitdoesnot declared.Thiscanbedoneasfollows:
setasideinmemory.Ittellsthecompilerwhatastructurebook lookslike. struct book books1;
➢Thisstatementwillsetasideenoughmemorytoholdallitemsinthestructure.
➢Thekeywordstructtellsthecompilerthatastructureisbeingdefined.
➢Theabovevariabledeclarationperformsafunctionsimilartovariabledeclarations
➢Thetagbook isnotavariablename,sinceavariableisnotbeingdeclared.Itisa likeint numandfloat amount.
type name.
structbook ➢Ittellsthecompilertosetasidestorageforavariableofspecifictypeandgivesa
➢Theelementsofthestructurearesurroundedby { nametothevariable.
 bracesandtheentiredefinitionisterminatedby charbk_name[25];
charauthor[25];
 asemicolon. ➢Aswithint, floatandotherdatatypestherecanbeanynumberofvariablesofa
intedn;
floatprice;
givenstructuretype.
};

23 24
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Structures Structures
StructureVariables StructureVariables
➢Inaprogramtwovariablesbooks1andbooks2ofthestructuretypebookcanbe ➢Thegeneralsyntaxforaccessingastructureelementsis,thestructurevariable
declared.Thiscanbedoneinanyofthefollowingways. namefollowedbyaperiodandtheelementnamereferencesthatindividual
structureelement.
structbook
{ structure_variable.element_name
charbk_name[25];
charauthor[25]; struct book books1 ➢Thereforetoreadthenameofthe‘book’,thecodewouldbe
struct book books1, books2;
intedn; struct book books2; scanf(“%s”, books1.bk_name);
floatprice;
}books1,books2;  andtoprintthesameitwouldbe
printf(“%s”, books1.bk_name);
➢Individualstructureelementsarereferencedthroughtheuseofthedot
operator(.),whichisalsoknownasthemembership operator.  andtoprintthesamewithanstringexpressionexplainingthevalue
displayed
➢Forexample,bk_nameofthestrucutrevariablebooks1canbereferredas printf(“The name of the book is %s”, books1.bk_name);
books1.bk_name;
25 26
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Structures Structures
InitializingStructures AssignmentinStructures
➢LikeVariablesandArraysstructurevariablescanbeinitializedatthebeginningofa
program.Theformatissimilartotheoneusedtoinitializearrays.
➢Onestructurevariablecanbeassignedtoanothervariableofthesametype.
➢Considerthefollowingstructure: structemployee
 Variablesemp1 andemp2ofthetypeemployeecanbe { ➢Thatis,ifbooks1andbooks2arestructurevariablesofthesametype,the
initializedwhenitisdeclared. intno; followingstatementisvalid.
struct employee emp1 = { 346, “ Dennis”}; charname[20];
struct employee emp1 = { 347, “ Ritchie”}; }; books2 = books1;

➢Aftertheusualdeclarationofthestructuretype,thetwo-structurevariablesemp1 ➢Thein-builtfunctionmemcopy( )canbeusedtoassignonestructuretoanother.


andemp2 aredeclaredandinitialized. Theprototypeforthisis
  memcopy(char*destn,char*source,intnbytes);
➢TheinitializationofastructureissimilartothatofanArray-thevariabletype,
 -thevariablename,andtheassignmentoperatorfollowedbybraces **this topic will be cleared whenever pointers is finished.
enclosingalistofvalues,withthevaluesseparatedbycommas.

27 28
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Structures Structures
StructureswithinStructures StructureswithinStructures

➢ItispossibletohaveoneStructurewithinanotherstructure. ➢Astructureliketheabovecanbeinitializedas:
➢However,aStructurecannotbenestedwithinitself. struct issue iss1 = { “Arun”, “28/29/13”, {“Programming”, “Dennis Ritchie”,
➢Havingonestructurewithinanotherismanytimesaparticularrequirement. 250.00} }
➢For example, where, a record of the person borrowing the book and details of the
books borrowed has to be maintained. ➢Itcanbenotedthatnestedbracesareusedtoinitializestructurewithin
struct issue structures.
{
char borrower[20]; ➢Toaccesstheelementsofthestructuretheformatwillbesimilartotheoneused
char dt_of_issue[8]; withnormalstructures,thatistoaccessnameofborrower,thecodeis
struct book borrowedbook;  [Link]
} iss1;
➢This declares borrowedbook to be a component of the structure [Link] component itself ➢Howevertoaccesselementsofthestructurebook,whichisapartofanother
is a structure of type struct book (defined earlier). structureissue,thefollowingexpressionwillbeused:
[Link]

29 30
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Structures Structures
StructureswithinStructures PassingStructuresasArguments
➢Astructurevariablecanbepassedasanargumenttoafunction.

➢Thisreferstotheelementauthorinthestructureborrowedbookinthestructure ➢Thisisausefulfacilityanditisusedtopassgroupsoflogicallyrelateddataitems
iss1. togetherinsteadofpassingthemonebyone.

In the following example, a structure is declared for the customer name, the
➢Thelevelofnestingstructuresisrestrictedonlybytheavailabilityofmemory.For
customer number and the principal amount deposited by the customer.
example, 
[Link] The data is accepted in the main( ) function and is then passed to another funciton
intcal( ), where the payable interest is calculated. This information along with the
entered data is printed.
➢Also,rememberthatifastructureisnestedwithinanother,ithawstobedeclared
priortothestructure,whichusesit. Notethatatagisnotusedwhenthestructureisdefined.Thisisbecausethe
variablesofthattypeisdeclaredalongwiththestructuredefinitionitself.

31 32
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Structures Structures
PassingStructuresasArguments ArrayofStructures
#include<stdio.h> intcal(struct{ ➢OneofthemostcommonuseofstructuresisasanArrayofstructures.
voidmain()  charcust_name[20];
{  intcust_numb; ➢TodeclareanArrayofStructures,astructureisfirstdefined,andthenanArray
 struct  floatamt;
 }bill)
variableofthattypeisdeclared.
 {
 charname[20]; {
 intnumb; floatsi; ➢For example, to declare a 3 element array of structures, of the type book (declared
 floatpurchase_amt; floatrate=5.5; earlier), the statement would be:
 }customer1; floatyrs=2.5; struct book lost_books[3];
si=(([Link])*rate*yrs)/100;
printf("EnterCustomername:");
gets([Link]); printf("\nCustomernameis%s",bill.cust_name); ➢LikeallArrayvariables,ArrayofStructuresbeginindexingat0.
printf("EnterCustomernumber:"); printf("\nCustomernumberis%d",bill.cust_numb);
scanf("%d",&[Link]); printf("\nTheamountis%f",[Link]); ➢SimilarlytheArraynamefollowedbyitssubscriptenclosedinsquarebrackets
printf("EnterPrincipalAmount:"); printf("\nTheInterestis%f",si);
scanf("%f",&customer1.purchase_amt); return; standforanelementofthatArray.
} }

33 34
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Structures Structures
ArrayofStructures InitializationofStructureArrays
➢Aftertheabovedeclaration,eachelementoftheArrayisastructurebyitself.
➢AnArrayofanytypeisinitializedbyenclosingthelistofvaluesofitselements
➢Soalltherulesofreferencingfieldsapplythereafter. lostbooks[0].bk_name withinpairofbraces.
lostbooks[0].author ➢Thisruleremainssameeveniftheelementsarestructures.
lostbooks[0].edn ➢Theeffectiveinitializationcontainsnestedbraces.
lostbooks[0].price structunitseries[3]=
  lost_books[1].author structunit {
lostbooks[1].bk_name {
 willrefertothefieldauthorofthe1stelementofthe  {‘a’,100}
lostbooks[1].author charch;  {‘b’,200}
 arraylost_books.
lostbooks[1].edn inti;  {‘c’,300}
}; };
lostbooks[1].price
lostbooks[2].bk_name ➢Thisdeclaresseries tobeanarrayofstructures,eachofthetypestruct unit.
lostbooks[2].author ➢Sowheninitializing,eachelementisinitializedasastructureisbeinginitialized.
lostbooks[2].edn ➢Thewholelististhenenclosedwithinbracestoindicatethatthearrayisbeing
initialized.
lostbooks[2].price
35 36
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Structures Usingtypedef
ThingstoRemember
typedef keyword to allow users to provide
✓AStructureisusuallyusedwhenwewishtostoredissimilardatatogether. alternativenamesfortheprimitive(e.g.,௙int)
and user-defined௙(e.g struct) data types.
✓Structureelementscanbeaccessedthroughastructurevariableusinga(.)
operator.

✓AllelementsofaStructurevariablecanbeassignedtoanotherstructurevariable
usingtheassignment(=)operator.

✓Itispossibletopassastructurevariabletoafunctioneitherbyvalueorby
address.

✓ItispossibletocreateanArrayofStructures.

37 38
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Types for Re-use


• Types classify (data) values Typedef →which you can use to give a
• So, each type is a set of values type a new name
– e.g. int = { m | -2n-1 <= m <2n-1 }
– e.g. char = {c | c is an ASCII value } To define a term BYTE for one-byte numbers
• int and char are basic (primitive) types
typedef unsigned char BYTE;
• Arrays are structured (non-primitive) types
BYTE b1,b2;

39 40
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Tuple Data – More C Details User Defined Type Declaration
• Syntax
• Declarations (Type and variable) e.g. typedef type identifier
typedef struct { int x; int y; } Point;
Point p1, p2;
• Example
• Usage and assignment (by fields selection) typedef int marks;
p1.x = 5; //fieldsareassigned one-by-one
p1.y = p1.x + 1;
• Here marks symbolizes int. So later itcan be
if (p1.x == p1.y) … used to declare variables
marks cp[60];
41 4 42
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Example Tuple Types - Motivation


• Consider storing a rectangle
typedef int Celsius;
• First attempt: 2 lists (i.e. arrays)
Celsius c1, c2;
– length array, width array
– Problems: Consider add / delete operations.
typedef int Celsius; • Shifting to be done in 2 arrays separately.
typedef Celsius WeeklyTemps[7]; • 2 arrays arethe 2 element values passed as
WeeklyTemps t1; parameters.
• Data representation “does notsay” the 2 things arerelated.
• Better Solution: 1 list of pairs
typdef int Matrix[100][100];
– Each pair is of the form:
Matrix M; (length, breadth)

43 44
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Tuples in C Tuples in C
• C Provides structures to represent tuples. • C provides structures to represent tuples.
struct tag
{
member 1; {
member 2; declaration member 1;
no structure tag!
……… member2;
………
member n;
member n;
}; } Element;

Defines atypenamed
Element which is a structure.
45 46
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Example Initialization
• Define a structure type without tag-name • To store tuple (“VVK Ramesh”,23,9.4) in
• typedef struct { Ramesh,method is as follows:
char name[30]; student Ramesh;
intage; strcpy([Link],“VVK Ramesh”); //string
→created a struct type student.
float cgpa; [Link]=23; // int
[Link]=9.4; // float
} student;

• Syntax: struct_var.member=val;
47 48
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Toreadandprint Structureandtypedef
#include <string.h>
typedef struct Books { #include<stdio.h>
char title[50]; structPoint{
char author[50];
char subject[100];
intx;
int book_id; inty;
} Book; };
int main( ) {
intmain(){
Book book; structPointp1;
strcpy( [Link], "C Programming"); p1.x=1;
strcpy( [Link], "Nuha Ali"); p1.y=3;
strcpy( [Link], "C Programming Tutorial");
book.book_id = 6495407;
printf("%d\n",p1.x);
printf("%d\n",p1.y);
printf( "Book title : %s\n", [Link]); return0;
printf( "Book author : %s\n", [Link]);
printf( "Book subject : %s\n", [Link]); }
printf( "Book book_id : %d\n", book.book_id);

return 0;
}
49 50
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Typedef….. Tuple Data – More C Details


• Assignment by Copying
#include<stdio.h>
#include<stdio.h> p2 = p1; // fields of p1 are copied into p2.
structPoint{
intx;
typedefstructPoint{ • Initialization
intx;
inty; Point p3 = { 5, 7 } // initialized: p3.x=5; p3.y=7;
inty;
};
}Point;
typedefstructPointPoint;
intmain(){ • Parameters
intmain(){
Pointp1; void bump (Point p) { p.x += 1; p.y+=1; }
Pointp1;
p1.x=1;
p1.x=1;
p1.y=3;
p1.y=3; // Will bump(p1) change p1?
printf("%d\n",p1.x);
printf("%d\n",p1.x);
printf("%d\n",p1.y);
// Recall C parameters are passed by value I.e. by copying!
printf("%d\n",p1.y);
return0;
return0; // So p1 will not be changed outside.
}
}

51 52
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Tuple Data – More C Details
Togivesymbolicname

#include<stdio.h>
• Structures as return values #defineTRUE1
Point bump(Point p) #defineFALSE0
{ intmain(){
Point p1 = p; printf("ValueofTRUE:%d\n",TRUE);
p1.x += 1; p1.y += 1; printf("ValueofFALSE:%d\n",FALSE);
return p1; return0;
} }
• What will this do?
p2 = bump(p1);

53 54
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

BITS Pilani
Union
Pilani|Dubai|Goa|Hyderabad

Constructing generic types


• Union
• Memory that contains different type of
objects over time
• Members share space
• Allocation: Only one member
:
1. Generic Types
UNION

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Unions
WhyUnionsareused
• Aunionisauser-definedtypesimilarto structsin ➢AUnion isamemorylocationthatissharedbytwoormorevariables,generallyof
differenttypes,atdifferenttimes.
C exceptforonekeydifference.
• Structuresallocateenoughspacetostorealltheir ➢AUnionisaspecialdatatypeavailableinCthatenablesyoutostoredifferent
datatypesinthesamememorylocation.
members,whereas unions can only hold one
➢Thatis,aUnionisawayforasectionofmemorytobetreatedasavariableofone
member value at a time. typeononeoccasionandavariableofanothertypeonanotheroccasion.

➢Wecandefineaunionwithmanymembers,butonlyonemembercancontaina
valueatanygiventime.

➢Unionsprovideanefficientwayofusingsamememorylocationformulti-purpose.

58
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Unions Unions
WhyUnionsareused WhyUnionsareused
➢Aunioncanbepicturedasachunkofmemorythatisusedtostorevariablesof ➢Theabovedefinitiondoesnotdeclareanyvariables,thatis,nomemoryspaceis
differentdatatypes. allocatedafterthisdefinition.

➢Onceanewvalueisassignedtoafield,theexistingdataisoverwrittenwiththe ➢Variablesofthistypecanbedeclaredbyeitherplacingthemattheendofthe
newdata. definitionorbyusingaseparatedeclarationstatement.
➢DefiningaUnionissimilartodefiningastructure.
➢AUnionvariabletemp1ofthetypetempcandeclaredas
   union temp temp1;
uniontag
uniontemp In Union temp1, both integer i and character ch share the same memory
{
{ location. At any point, the data stored in temp1 can be referred to as either an
typevar_1;
inti; integer or a character.
typevar_1;
charch;
…..
};
}unionvariables;

59 60
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Unions Unions
WhyUnionsareused WhyUnionsareused
➢WhenaUnionisdeclared,thecompilerautomaticallycreatesavariablelong ➢AUnioncanalsobeusedinthefunctiontostoretheincomingdata.
enoughtoholdthelargestvariabletypeintheUnion.
➢AUnioninwhichvaluesofanydatatypeisacceptablecanbedefinedasfollows:
➢Inthiscase,twobytes,asrequiredbytheinteger,isallocatedtotheUniontemp.

➢ThesyntaxforaccessingaUnionelementissimilartothatusedtoaccessstructure
elements. unionnumber
{
➢Unionsareusedfrequentlywhentypeconversionsareneeded,asthedataheldin doublednum;
theunioncanbereadindifferentways. floatfnum;
longlnum;
intinum;
➢AnotheruseofUnioniswhenasinglevariablenameistobeusedtopassdataof
charcnum;
differenttypes. };

61 62
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Structures Enumerations
ThingstoRemember Enumerationdefinition
✓AUnionisamemorylocationthatissharedbytwoormorevariables,generallyof ➢Inventourowndatatypeanddefinewhatvaluesthevariablecantake.
differenttypesatdifferenttimes.
➢AnEnumerationisasetofnamedintegerconstantsthatspecifyallthelegal
✓AUnionisdefinedinthesamewayaslikeStructures. valuesavariableofthattypemayhave.

➢Theformatofenumissimilartothatofastructureinwhichthedeclarationhas
✓ItispossibletonestUnionswithinUnions,UnionsinStructures,andStructuresin twoparts.
Unions. Thefirstpartdeclaresthedatatypeandspecifies
 itspossiblevalues.ThesevaluesarecalledEnumerators. enumtag{
Thesecondpartdeclaresvariablesofthisdatatype. enumerationlist
}variable_list;
➢Enumerationsaredefinedmuchlikestructures.Thekeywordenumsignalsthe
startofanenumerationtype.

63 64
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Enumerations Enumerations
Enumerationdefinition EnumerationUsage
✓Forexample,anEnumerationofthemetrotownsofIndiais: ➢Wecan’tgivevaluesthataren’tintheoriginaldeclaration.Thusthefollowing
  Bombay,Delhi,Madras,Calcutta expressionwouldcauseanerror.
   town = Pune; or town = Chennai;
➢Here,boththeenumerationtagandvariablelistareoptional.
➢Given this definition and declaration, the following types of statements are
➢Aswithstructures,theenumerationtagnameisusedtodeclarevariablesofits perfectly valid:
type. town = Bombay;
➢Theenumerationlistcontainsvalues,whicharecalledenumerators. if( town = = Madras)
printf(“This town is Madras \n”);
➢The following code defines an enumeration called metro and declares town to be
of that type. ➢However,values,whicharenotpresentintheoriginaldeclaration,cannotbe
assignedorreferredto.

enum metro {Bombay, Delhi, Madras, Calcutta}; ➢Doing this, results in an error. For example, the following is erroneous.
enum metro town; town = Bangalore;

65 66
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Enumerations Enumerations
EnumerationUsage EnumerationUsage
➢Internallythecompilertreatsenumeratedvariablesasintegers.Eachvalueonthis ➢Thevalueofoneormoreofthesymbolscanbespecifiedbyusinginitializers.
listofpermissiblevaluescorrespondstoaninteger,startingwith0.
➢Thisisdonebywritingthesymbolfollowedwithanequalsignandaninteger
➢Thus in town example, Bombay is stored as 0, Delhi as 1, Madras as 2 and Calcutta value.
as 3.
printf (“%d %d”, Bombay, Madras); ➢Thesymbolthatappearaftertheinitializersareassignedvaluesgreaterthanthe
0 2 previousinitializationvalue.
➢Thisdefaultassignmentcanalsobeoverriddenbytheprogrammerbyinitializing
theenumeratorstodifferentintegervalues. ➢For example, the following code assigns the value of 13 to Madras.

enummetro ➢Now,thevaluesofthesesymbolsare:
{ enum metro {Bombay, Delhi, Madras=13, Calcutta};
Bombay=0, Delhi=1, Madras=13, Calcutta=14
Bombay=100,Delhi=200,Madras=300,Calcutta=400
};
enummetrotown1,town2;
67 68
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Enumerations Enumerations
EnumerationUsage EnumerationUsage
➢Enumeratorscannotactasinputandoutputdirectly.For example, the following ➢Theweaknessofusingenumvariableisthatthereisnootherwaytousethe
code fragment will not perform as desired. enumeratedvaluesdirectlybyprintf( ).
town = Bombay
printf(“%s”, town); ➢Forthatweneedtowriteacode.For example, the following code is needed to
display, in other words the kind of metro that town contains:
➢Remember,Bombay issimplyanameforaninteger.ItisnotaString.Forthesame
reasonthefollowingcodecannotbeused. switch(town)
   gets(s); {
strcopy(town,s); caseBombay : printf(“Bombay”);
caseDelhi : printf(“Delhi”);
➢AStringthatcontainsthenameofasymbolisnotautomaticallyconvertedtothat caseMadras : printf(“Madras”);
symbol. caseCalcutta : printf(“Calcutta”);
}
➢Creatingcodetoinputandoutputenumerationsymbolsisquitecumbersome. ➢AnotherwayofusingenumerationsisbydeclaringanArrayofStringsandusing
theenumerationvalueasanindextotranslateanenumerationvalueintoits
correspondingstring.

69 70
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956 BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956

Enumerations How to define a union?


EnumerationUsage
➢For example, the following code will output proper string.
  char name[ ] = {“Bombay”, “Delhi”, “Madras”, “ Calcutta”}; unioncar
printf(“%s”, name[town]);
{
➢ThiswillworkonlyifnosymbolisinitializedbecausethestringArraymustbe
indexedstartingat0. charname[50];
➢Enumeratedvariablescanbetreatedasintegersasintegersandusedfor
intprice;
arithmeticoperations. };

71
BITS Pilani,DeemedtobeUniversityunderSection3ofUGCAct,1956
Unionprogram DifferencebetweenstructureandUnion
#include<stdio.h>
#include<string.h>
unionData{
inti;
floatf;
charstr[20];
};
intmain(){
unionDatadata;
data.i=10;
data.f=220.5;
strcpy([Link],"CProgramming");
printf("data.i:%d\n",data.i);
printf("data.f:%f\n",data.f);
printf("[Link]:%s\n",[Link]);

return0;
}

Functions and Similarities Between Union and Structure DifferencebetweenstructureandUnion


• Theyarebothuser-defineddatatypes,andtheystoredifferentsortsof
datatogetherasasingleunit.

• Bothoftheirmemberscanbeanytypeofobject.Itmayincludedifferent
structuresandunions/arrays.Itsmemberscanalsocontainabitfield.

• AUnionoraStructurecaneasilypassbyvaluetofunctionsandalso
returntothevaluebyfunctions.Everyargumentmustpossessthesame
parametersasthatofthefunctionparameter.

• AUnionorStructurepassesbythevaluejustlikeanyscalarvariableinthe
formofacorrespondingparameter.

• Youcanusethe“.”operatorforaccessingthemembers.
Structurewithinstructure

Structure structstu_address
{
I I I I C C C` C C C intstreet;
char*state;
Int=2;c=hi
char*city;
char*country;
2 I I I h i C` C C C };
structstu_data
{
2 H i I C C C` C C C Union intstu_id;
intstu_age;
2 0 H i C C C` C C C char*stu_name;
structstu_addressstuAddress;
};

Arrayofstructures
Programforstructurewithinstructure
Arrayofstructures

structstudent{ Programmeforarrayofstructures
charname[60];
introllNum;
charaddress[60];
floatmarks;
}stu[5];
Stu[1].rollNum=5;

Type definitions for players


#define MAX 30
typedef struct{
typedef char CountryName[MAX]; CountryName Name;
struct Bowler { int age;
structBatsman{ CountryName
CountryName Name; Name;int float Bat_Avg;
age;
int age; } Batsman;
float Bat_Avg;
float Bow_Avg; };
};
typedef struct Bowler Bowler; typedef struct Batsman Batsman;

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Tuple Player..
typedef enum{BOWLER=-1, KEEPER, BATSMAN} PlayerKind;
structWicketKeeper{ typedefstruct{
CountryName Name; typedef struct{
CountryName Name;
int age; int age; PlayerKind Kind;
int catches; int catches; union
int stumpings; int stumpings;
}; {
}Keeper;
typedef struct Bowler bowler;
WicketKeeper Keeper;
Batsman batsman;
Keeper keeper;
}playertype;
}Player;
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

int main() switch( (PlayerKind) type )


{
{ case BOWLER:
[Link]=BOWLER;
Player P1, P2, P3; printf("Enter the country of the bowler \n");
scanf("%s", [Link]);
int type;
printf("Enter the Player type \n"); printf("Enter the Age of the bowler \n");
scanf("%d", &[Link]);
printf(" -1:Bowler,1: Batsman, 0:Keeper \n");
printf("Enter the Bowling Avg of the bowler\n");
scanf("%d", &type); scanf("%f", &[Link].Bow_Avg);

/* break; */

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
case KEEPER: case BATSMAN:
[Link]=KEEPER; [Link]=BATSMAN;
printf("Enter the country of the keeper \n"); printf("Enter the country of the batsman \n");
scanf("%s", [Link]); scanf("%s", [Link]);

printf("Enter the Age of the keeper \n"); printf("Enter the Age of the batsman \n");
scanf("%d", &[Link]); scanf("%d", &[Link]);

printf("Enter the number ofcatches taken by him\n"); printf("Enter the Batting Avg ofthe batsman\n");
scanf("%d", &[Link]); scanf("%f", &[Link].Bat_Avg);

/* break; */ /* break; */

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

BITS Pilani
Pilani|Dubai|Goa|Hyderabad

case default:
printf(“You have entered invalid type\n");
break; }// end of switch
printf("Details of the player you entered are \n");

}// end of main

92
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad

Computer Programming

ContactSession12

BITS Pilani Introduction to Pointers, Pointer Arithmetic, Pointers to Structures,


S
Pilani|Dubai|Goa|Hyderabad [Link] Tips and common programming errors, Programming examples and
Exercise

Whatispointers? Whatispointers?

• ThepointerinClanguageisavariablewhichstores
theaddressofanothervariable. a
• Thisvariablecanbeoftypeint,char,array,function,
oranyotherpointer. 5
• Thesizeofthepointerdependsonthearchitecture.
• However,in32-bitarchitecturethesizeofapointer
1000
is2byte.
Int*pv,a
a=5;
Inta
a=5; *pv=a
&→addressofthevariable
Pv=&a
Usageof AddressOf(&)Operator
pointer

The address of operator '&' returns the address of a


Dynamic memory allocation variable. But, we need to use %u to display the address
In c language, we can dynamically allocate memory using malloc() and of a variable.
calloc() functions where the pointer is used.
Arrays, Functions, and Structures If you have a variable var in your program, &var will give
Pointers in c language are widely used in arrays, functions, and you its address in the memory.
structures. It reduces the code and improves the performance.
Pointers (pointer variables) are special variables that are
used to store addresses rather than values.

Assigning addresses to Pointers

Int*p;-→apointerpofinttype. int*pc,c;
c=5;
int*p1; pc=&c;
int*p2;
(or) Here,5isassignedtothe c variable.And,the
int*p1,p2; addressof c isassignedtothe pc pointer.
Get Value of Thing Pointed by Pointers Get Value of Thing Pointed by Pointers

int*pc,c; normalvariable Pointervariable


c=5;    
pc=&c;
printf("%d",*pc); C *pV
//Output:5 (normalvalue)
&C pv(addressofthe
pointervariable)

Changing Value Pointed by Pointers SampleProgram

#include<stdio.h>
intmain()
int*pc,c;
int*pc,c; int*pc,c,d; { Addressofc:2686784
c=5; c=5; int*pc,c; Valueofc:22
c=5; pc=&c;
pc=&c; d=-15; c=22;
*pc=1; printf("Addressofc:%p\n",&c); Addressofpointerpc:2686784
c=1; printf("%d",*pc);//Output:1 printf("Valueofc:%d\n\n",c);//22 Contentofpointerpc:22
printf("%d",c);//Output:1 pc=&c;printf("%d",*pc);
printf("%d",c);//Output:1 //Output:5 pc=&c;
Addressofpointerpc:2686784
printf("%d",*pc);//Output:1 printf("Addressofpointerpc:%p\n",pc); Contentofpointerpc:11
pc=&d;printf("%d",*pc);
printf("Contentofpointerpc:%d\n\n",*pc);//22
 //Ouptut:-15 c=11; Addressofc:2686784
printf("Addressofpointerpc:%p\n",pc); Valueofc:2
printf("Contentofpointerpc:%d\n\n",*pc);//11
*pc=2;
printf("Addressofc:%p\n",&c);
printf("Valueofc:%d\n\n",c);//2
return0;
}
Sampleprogram

c=11; #include<stdio.h>
int*pc,c; intmain(){
intnumber=50;
printf("valueofnumberis%d,addressofnumberis
c=22;
*pc=2;
%u",number,&number);
return0;
}
pc = &c;

Pointingtoaddressoftheinteger Declaringapointer

int *a;//pointer to int


int n = 10; char *c;//pointer to char
int* p = &n; // Variable p of type pointer is pointin
g to the address of the variable n of type integer
Pointerandaddress Pointertoarray

int arr[5];
int *p[5]=&arr; // Variable p of type pointer is pointing to the
address of an integer array arr.

Pointertostructure Pointertoafunction

struct st { void show (int);


void(*p)(int) = &display; // Pointer p is pointing to the a
char name[10]; ddress of a function
introll;
float mark;
}ref;
struct st *p = &ref;
Memory Using Pointers
Addresses
Memory Sequential
• Memory can be conceptualized as a linear set #include <stdio.h> 0x1017 …
Addresses Memory
of data locations. int main (void)
. 0x1020 ptr2: 0x344A
. • Variables reference the contents of a location. {
. • Pointers have a value of the address of a given int i1; 0x10A1 …
location. int i2;
0x10BC ptr1: 0x344A
1000
• Pointers are variablesthat contain memory int *ptr1;
1001
addresses as their values. int *ptr2; 0x2204 i2: 23
1002 i1 = 1; 0x344A i1: 31
1003 i2 = 2;
1004 ptr1 = &i1; *:"dereferencing
&: "address operator"
1005 ptr2 = ptr1;
operator"which
which gives or produces
1006 For example: *ptr1 = 3;
i2 = *ptr2;
provides the address
the memory contentsofin
. inta;//SimpleVariable the memory
a data location
variable.
. return (0)
. int *a; //Pointer Variable } specified by a pointer
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Advantageofpointer NULLPointer

• Pointer reduces the code and improves the performance, it is • ApointerthatisnotassignedanyvaluebutNULL


used to retrieving strings, trees, etc. and used with arrays,
structures, and functions. isknownastheNULLpointer.
• We can return multiple values from a function using the
pointer. • If you don't have any address to be specified in
• It makes you able to access any memory location in the the pointer at the time of declaration, you can
computer's memory. assignNULLvalue.

• Itwillprovideabetterapproach.
Pointer Program to swap two numbers Pointer Arithmetic
without using the 3rd variable.

#include<stdio.h> • A pointer may be incremented or decremented.


intmain()
{
• An integer may be added to or subtracted from a pointer.
inta=10,b=20,*p1=&a,*p2=&b;
printf("Beforeswap:*p1=%d*p2=%d",*p1,*p2);
*p1=*p1+*p2; • Pointer variables may be subtracted from one another.
*p2=*p1-*p2;
*p1=*p1-*p2; • Pointer variables can be used in comparisons, but usually
printf("\nAfterswap:*p1=%d*p2=%d",*p1,*p2); only in a comparison to NULL.

return0;
}

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Arithmeticoperations Pointer Arithmetic

Memory Sequential
•Increment #include <stdio.h>
int main (void)
Addresses Memory

1997
{
•Decrement int i, *ptr1;
1998
1999
int ch, *ptr2;
•Addition i = 255; 2000
ch = ‘C’; 2001

•Subtraction ptr1 = &i; 2002


ptr2 = &ch; 2003

•Comparison ptr1++; //ptr1--


ptr1+=4;
2004
2005
i = ptr2-ptr1;
2006
if (ptr1 <= ptr2)
2007
printf (“GREATER”);
else 2008
printf(“smaller”); 2009
} BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
IncrementingPointerinC IncrementingPointervariables

• If we increment a pointer by 1, the pointer will start pointing to the immediate #include<stdio.h>
next location. int main()
• This is somewhat different from the general arithmetic since the value of the
{
pointer will get increased by the size of the data type to which the pointer is int number=50;
pointing. int *p;//pointer to int
p=&number;//stores the address of number variable
• We can traverse an array by using the increment operation on a pointer which
will keep pointing to every element of the array, perform some operation on
that, and update itself in a loop.
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n"
new_address= current_address + i * size_of(data type) ,p); // in our case, p will get incremented by 4 bytes.
For32-bitintvariable,itwillbeincrementedby2bytes.
For64-bitintvariable,itwillbeincrementedby4bytes.
return 0;
}

Traversinganarrayusingpointers DecrementingPointerinC

//withpointers
//withoutpointers
#include<stdio.h> If we decrement a pointer, it will start pointing to the previous
#include<stdio.h>
void main ()
void main ()
{
location.
{ int arr[5] = {1, 2, 3, 4, 5};
int arr[5] = {1, 2, 3, 4, 5}; int *p = arr;
int i; int i; new_address= current_address - i * size_of(data type)
printf("printing array elements...\n"); printf("printing array elements...\n");
for(i = 0; i< 5; i++)
for(i = 0; i< 5; i++)
{ 32-bit
printf("%d ",*(p+i));
{ } For 32-bit int variable, it will be decremented by 2 bytes.
}
printf("%d ",arr[i]); } 64-bit
} For 64-bit int variable, it will be decremented by 4 bytes
Decrementingpointers PointerAddition

#include<stdio.h> • Wecanaddavaluetothepointervariable.
voidmain(){
• Theformulaofaddingvaluetopointerisgivenbelow

intnumber=50;
new_address= current_address + (number * size_of(data type))
int*p;//pointertoint
p=&number;//storestheaddressofnumbervariable 32-bit
For 32-bit int variable, it will add 2 * number.
printf("Addressofpvariableis%u\n",p);
64-bit
p=p-1; For 64-bit int variable, it will add 4 * number.
printf("Afterdecrement:Addressofpvariableis%u\n",p);//Pwillnowpointtotheimmidiate
previouslocation.
}

Pointer
Addition

#include<stdio.h>
int main(){ the address of p is 3214864300. But after adding 3 with p variable, it
int number=50; is 3214864312,
int *p;//pointer to int i.e., 4*3=12 increment. Since we are using 64-bit architecture, it
p=&number;//stores the address of number variable increments 12.
printf("Address of p variable is %u \n",p); But if we were using 32-bit architecture, it was incrementing to 6
p=p+3; //adding 3 to pointer variable only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-
printf("After adding 3: Address of p variable is %u \n",p); bit OS
return 0;
}
PointerSubtraction PointerSubtraction

• we can subtract a value from the pointer variable. Subtracting any number from a #include<stdio.h>
pointer will give an address. int main(){
• The formula of subtracting value from the pointer variable is given below: int number=50;
new_address= current_address - (number * size_of(data type)) int *p;//pointer to int
32-bit
p=&number;//stores the address of number variable
For 32-bit int variable, it will subtract 2 * number.
64-bit printf("Address of p variable is %u \n",p);
For 64-bit int variable, it will subtract 4 * number. p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}

Pointersubtraction

• Youcanseeaftersubtracting3fromthepointervariable,itis12 #include<stdio.h>
(4*3)lessthanthepreviousaddressvalue. void main ()
• However,insteadofsubtractinganumber,wecanalsosubtract {
anaddressfromanotheraddress(pointer).
int i = 100;
int *p = &i;
int *temp;
temp = p;
p = p + 3;
printf("Pointer Subtraction: %d - %d = %d",p, temp, p-
temp);
}
Illegalarithmeticwithpointers Pointerstostructures

•Address+Address=illegal • Pointer to structure holds the add of the entire


•Address*Address=illegal structure.
• It is used to create complex data structures such
•Address%Address=illegal as linked lists, trees, graphs and so on.
•Address/Address=illegal • The members of the structure can be accessed
•Address&Address=illegal using a special operator called as an arrow
operator ( -> ).
•Address^Address=illegal
•Address|Address=illegal
•~Address=illegal

Declaration - declarationforpointersto Accessing


structures

how to access the pointers to structures


structtagname*ptr;
Ptr-> membername;

 structstudent*s s->sno, s->sname, s->marks;


Pointertostructureprogram
Example2

#include<stdio.h>
#include<stdio.h>
struct student{
structperson{
int sno;
intage;
char sname[30];
floatweight;
float marks; };
};
main ( ){
intmain(){
struct student s;
structperson*personPtr,person1;
struct student *st;
personPtr=&person1;
printf("enter sno, sname, marks:");
printf("Enterage:");
scanf ("%d%s%f", & [Link], [Link], &s. marks);
scanf("%d",&personPtr->age);
st = &s;
printf("Enterweight:");
printf ("details of the student are");
scanf("%f",&personPtr->weight);
printf ("Number = %d\n", st ->sno);
printf("Displaying:\n");
printf ("name = %s\n", st->sname);
printf("Age:%d\n",personPtr->age);
printf ("marks =%f\n", st ->marks);
printf("weight:%f",personPtr->weight);
getch ( );
return0;}
}

Pointers to Structures:
“->”Operator BITS Pilani
Pilani|Dubai|Goa|Hyderabad
#include <stdio.h>
int main (void)
{
struct book
{
intpage;
float price;
char author[20];
};
struct book c_lang;
structbook*ptr; ptr
=&c_lang;
c_lang.page = 600;
c_lang.price = 277.90;
strcpy (c_lang.author,"Jerry R Hanly");
printf ("Pages = %d\n”,c_lang.page);
printf ("Price = %f\n“,c_lang.price);
puts (c_lang.author);
} BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
IMP Note to Self

Topics to be Covered:
Pointers and arrays
Pointers and Functions
Pointer to Structures
2
Dynamic Memory Allocation,Pass by reference BITS Pilani, Pilani Campus

IMP Note to Students BITS Pilani


K K Birla Goa Campus

➢ It is important to know that just login to the session does


not guarantee the attendance.
➢ Once you join the session, continue till the end to consider
you as present in the class.
➢ IMPORTANTLY, you need to make the class more interactive
by responding to Professors queries in the session.
➢ Whenever Professor calls your number / name ,you need to
Pointers and arrays
respond, otherwise it will be considered as ABSENT

3
Pointers to Pointers Pointers to Pointers

❑ A pointer can also point to another pointer Example:


Memory Memory
❑ But the pointer must be of that type intV=101;
Q P V D Q P V
int*P=&V; 
Example: f104 f20 101 f134 f104 f20 101
0 int**Q=&P; 0
intV=101; f10 f20 f13 f10 f20
4 0 int***D=&Q; 4 4 0
int*P=&V; Pointertopointer pointer Variable Pointertopointer pointer Variable

int**Q=&P;

printf(“%d”,V); printf(“%d”,***D);

printf(“%d”,*P); =101
printf(“%d”,**Q);

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Arrays Why pointers?


Array elements are stored in contiguous memory locations. Grades[0] Grades[1] Grades[2] Grades[3] Grades[4]
int arr[10];
starting address of the array ➔ &arr[0]
➔ arr

Starting address Offset = Address of


of the array +
Grade[3]

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Why pointers? Pointers and One Dimensional Array
g_ptr
Address of Elements x[0] x[1] x[2] x[3] x[4]
Grades[0]
Value 1 2 3 4 5
Grades[0] Grades[1] Grades[2] Grades[3] Grades[4]
Address 1000 1002 1004 1006 1008

Base address

*(g_ptr + 3) p = &x[0];
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Elements x[0] x[1] x[2] x[3] x[4] Arrays and Pointers,

Value 1 2 3 4 5
❑ Relationship between Array and pointer.

Address 1000 1002 1004 1006 1008


intP[]={23,38,56,69,74};

P p = &x[0] 1000
p+1= &x[1] 1002
p+2= &x[2] 1004
p+3= &x[3] 1006
p+4= &x[4] 1008
BITS Pilani, Pilani Campus
Pointer Arithmetic, Pointer Arithmetic,

Characterpointer

char*ptr;

980 1000

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Pointer increment / decrement, Arrays and Pointers,

❑ Pointer Addition
Integerpointer
intP[]={3,5,6,7,9};

10051006
1007 int*ptr; int*ptr=P; 01234

printf(“%d”,ptr[2]);

printf(“%d”,*(ptr+2));
ptr++:incrementby
onelocation(4bytes) printf(“%d”,*(P+2));

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Arrays and Pointers, Array of Pointers,

intarr[]={10,20,30,40,50};

int*ptr=arr; intp=40,q=60,r=90;

ptr
int*arr[3];

ptr+1
arr[0]=&p;
arr[1]=&q;
ptr+2
arr[2]=&r;
ptr+3
printf(“%d”,*arr[1]);
ptr+4
printf(“%d”,*arr[2]);

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Array of Pointers,

1D Arrays and Pointers


❑ int A[5] - A is the address where the array starts (first element), it is
equivalent to &(A[0])
❑ A is in some sense a pointer to an integer variable
❑ To determine the address of A[x] use formula:
– (addressofA+x*bytestorepresentint)
– (addressofarray+elementnum*bytesforelementsize)
❑ The + operator when applied to a pointer value uses the formula above:
– A+xisequivalentto&(A[x])
– *(A+x)isequivalenttoA[x]

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


1D Array and Pointers Example

DMA float A[6] = {1.0,2.0,1.0,0.5,3.0,2.0};


❑ Arrays and Pointers,
float *theMin = &(A[0]);
❑ Dynamic Memory Allocation,
float *walker = &(A[1]);
❑ Pass by Reference while (walker < &(A[6])) {
❑ Linked List: Implementation of Linked List if (*walker < *theMin)
theMin = walker;
walker = walker + 1;
}
printf("%.1f\n",*theMin);

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

1D Array as Parameter

Limits of Static Allocation


❑ Whatifwedon’tknowhowmuchspacewewillneedaheadoftime?
❑ When passing whole array as parameter use syntax ParamName[], but can
also use *ParamName ❑ Example:
❑ Still treat the parameter as representing array: – askuserhowmanynumberstoreadin
int totalArray(int *A, int N) { – readsetofnumbersintoarray(ofappropriatesize)
int total = 0;
– calculatetheaverage(lookatallnumbers)
for (I = 0; I < N; I++)
– calculatethevariance(basedontheaverage)
total += A[I];
return total; ❑ Problem: how big do we make the array??
} – usingstaticallocation,havetomakethearrayasbigastheusermightspecify
(mightnotbebigenough)
❑ For multi-dimensional arrays we still have to use the
ArrayName[][Dim2][Dim3]etc. form

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


What is the output? Important note
int m, n, *p; Following notations are same
m=10; n=20; num[x]
p = &m; *(num+x)
printf(“%d%d”,*p,m,n); *(x+num)
*p = &n; x[num]
printf(“%d%d%d%d”,*p,m,&n,n);
Note the difference
*(num+x) and *num+x

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Important note Important note


Note the difference ++*ptr and *++ptr where ptr is pointer to num
*(num+x) and *num+x
++*num and *++num

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Pointers and Two-Dimensional Arrays Example
Two dimensional array is a collection of single dimensional
array

2000 2002 2004 2006 2008 200A


X 1 2 3 4 5 6

ROW 0 ROW 1 ROW 2


BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Example
Example 1. What is the address of individual elements?
2000 2002 2004 2006 2008 200A 2000 2002 2004 2006 2008 200A
X 1 2 3 4 5 6 X 1 2 3 4 5 6

ROW 0 ROW 1 ROW 2


ROW 0 ROW 1 ROW 2
Element 0: &x[0][0]
Answer the following:
Element 1: &x[0][1]
1. What is the address of individual elements? Element 2: &x[1][0]
2. What is the starting address of each row? Element 3: &x[1][1]

3. Is it possible to access individual elements of row using row Element 4: &x[2][0]


address? Element 5: &x[2][1]

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Example
Example
What is the starting address of each row? Is it possible to access individual elements of row using row
2000 2002 2004 2006 2008 200A address?
X 2000 2002 2004 2006 2008 200A
X 1 2 3 4 5 6
1 2 3 4 5 6

ROW 0 ROW 1 ROW 2


ROW 0 ROW 1 ROW 2

Row 0: &x[0][0] = x[0]


*(Row address + column number)
Row 1: &x[1][0] = x[1] For Example:
Row 2: &x[2][0] = x[2] Element 6: *(x[2]+1)
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Example Array of Pointers


Use of pointers to access individual elements

X 2000 2002 2004 2006 2008 200A


1 2 3 4 5 6

ROW 0 ROW 1 ROW 2

Step1: Assign starting address of array to pointer variable


Step2: Use formula *(Row address + column number) to access
individual elements.

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Pointers and Character Array What is the output?
Write a program to find the length of a string using pointers. int num1[5] = { 1, 2, 3, 4, 5 }, i;
(H.W.) int num2[5];

num1 = num2;

printf(" \n Contents of num1 array\n");


for (i = 0; i < 5; i++)
printf(" %d\n", num1[i]);

printf(" Contents of num2 array\n");


for (i = 0; i < 5; i++)
printf(" %d\n", num2[i]);

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Pointers and Functions Pointers with Functions: pass by value


• Pointers can be used to pass addresses of variables to #include <stdio.h> void swap( int a, int b )
void swap ( int a, int b ) ; {
functions, thus allowing the called function to alter
int main ( ) int temp;
the values stored there.
{ temp= a; a= b; b = temp ;
int a = 5, b = 6; printf ("a=%d b=%d\n", a, b);
• Similarly, functions can return a pointer. printf("a=%d b=%d\n",a,b) ; }
swap (a, b) ; Results:
printf("a=%d b=%d\n",a,b) ; a=5 b=6
return 0 ; a=6 b=5
} a=5 b=6

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Pointers with Functions:
Pointers to Structure
Pass by reference
#include <stdio.h> void swap( int *a, int *b )
void swap ( int *a, int *b ) ; {
int main ( ) int temp;
{ temp= *a; *a= *b; *b = temp ;
int a = 5, b = 6; printf ("a=%d b=%d\n", *a, *b);
printf("a=%d b=%d\n",a,b) ; }
swap (&a, &b) ; Results:
printf("a=%d b=%d\n",a,b) ; a=5 b=6
return 0 ; a=6 b=5
} a=6 b=5 -> arrow operator or member selection operator
Pointer -> membervariable
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, K K Birla Goa Campus

Pointers to Structure Pointers to array of structure


Exercise8:Identifytheerrorifany.
#include<stdio.h>
#include<string.h>
structbook1{
charname[10];
floatprice;
intpages;
};
main()
{
structbook1*b1,b2;
b1=&b2;
strcpy(b1->name,"CBook");
b1->price=145.50;
b1->pages=100;

printf("Name:%s",b1->name);
printf("Price:%f",b1->price);
printf("pages:%d",b1->pages);
}
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Structure variable within a structure Passing structure to a function
Exercise9

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Conceptual View of Storage Contd…

• Permanent memory or Static memory


– For global variables
Memory
• Stack
– For local variables
– For parameters passed to / from functions
ProgramMemory DataMemory
• Dynamic memory
– For dynamic variables (not part of language but provided through library of
functions)
main() Other Global Stack Heap
functions

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
DynamicMemoryAllocation
Contd…
• Static memory has a fixed size, computed by the The process of allocating memory at runtime is called
compiler, and is always used in full Dynamic Memory Allocation

• Heap and stack have a maximum size, are initially


empty and then filled and released as needed. It is
therefore possible to exceed the space available (stack
overflow, memory overflow system errors)

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Dynamicmemoryscenario Staticmemoryexample
#define MAX 1000
struct student
{
int id;
char name[20];
char surname[20]; Student dimension is 42 bytes.
}; v dimension is 42000 bytes.
struct student v[MAX];

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Limits of Static Allocation Dynamic Memory Allocation

❑ Whatifwedon’tknowhowmuchspacewewillneedaheadoftime? ❑ Allow the program to allocate some variables (notably arrays), during the
program, based on variables in program (dynamically)
❑ Example:
– askuserhowmanynumberstoreadin ❑ Previous example: ask the user how many numbers to read, then allocate
array of appropriate size
– readsetofnumbersintoarray(ofappropriatesize)
❑ Idea: user has routines to request some amount of memory, the user then
– calculatetheaverage(lookatallnumbers) uses this memory, and returns it when they are done
– calculatethevariance(basedontheaverage) – memoryallocatedintheDataHeap
❑ Problem: how big do we make the array??
– usingstaticallocation,havetomakethearrayasbigastheusermightspecify
(mightnotbebigenough)

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

Memory Management Functions Array Allocation with calloc

1. calloc - routine used to allocate arrays of memory ❑ prototype: void * calloc (size_t num, size_t esize)
2. malloc - routine used to allocate a single block of memory
– size_tisaspecialtypeusedtoindicatesizes,generallyanunsignedint
3. realloc - routine used to extend the amount of space allocated previously
– numisthenumberofelementstobeallocatedinthearray
4. free - routine used to tell program a piece of memory no longer needed – esizeisthesizeoftheelementstobeallocated
– note:memoryallocateddynamicallydoesnotgoawayattheendoffunctions,you • generally use sizeof and type to get correct value
MUSTexplicitlyfreeitup
– anamountofmemoryofsizenum*esizeallocatedonheap
– callocreturnstheaddressofthefirstbyteofthismemory
– generallywecasttheresulttotheappropriatetype
– ifnotenoughmemoryisavailable,callocreturnsNULL

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


calloc Example Releasing Memory (free)

float *nums; ❑ prototype: void free(void *ptr)


int N;
int I;
– memoryatlocationpointedtobyptrisreleased(sowecoulduseitagaininthe
future)
printf(“Readhowmanynumbers:”);
scanf(“%d”,&N);
– programkeepstrackofeachpieceofmemoryallocatedbywherethatmemory
nums = (float *) calloc(N, sizeof(float));
starts
/* nums is now an array of floats of size N */ – ifwefreeapieceofmemoryallocatedwithcalloc,theentirearrayisfreed
for (I = 0; I < N; I++) { (released)
printf(“Pleaseenternumber%d:“,I+1);
– resultsareproblematicifwepassasaddresstofreeanaddressofsomethingthat
scanf(“%f”,&(nums[I]));
wasnotallocateddynamically(orhasalreadybeenfreed)
}
/* Calculate average, etc. */

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

free Example The Importance of free

float *nums; void problem() {


int N; float *nums;
int N = 5;
printf(“Readhowmanynumbers:”);
scanf(“%d”,&N); nums = (float *) calloc(N, sizeof(float));
nums = (float *) calloc(N, sizeof(float)); /* But no call to free with nums */
} /* problem ends */
/* use array nums */

/* when done with nums: */ ❑ When function problem called, space for array of size N allocated, when
free(nums);
function ends, variable nums goes away, but the space nums points at (the
array of size N) does not (allocated on the heap) - furthermore, we have no
/* would be an error to say it again - free(nums) */ way to figure out where it is)
❑ Problem called memory leakage

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Array Allocation with malloc
Increasing Memory Size with realloc

❑ prototype: void * malloc(size_t esize) ❑ prototype: void * realloc(void * ptr, size_t esize)

– similartocalloc,exceptweuseittoallocateasingleblockofthegivensizeesize – ptrisapointertoapieceofmemorypreviouslydynamicallyallocated
– aswithcalloc,memoryisallocatedfromheap – esizeisnewsizetoallocate(noeffectifesizeissmallerthanthesizeofthe
– NULLreturnedifnotenoughmemoryavailable memoryblockptrpointstoalready)
– memorymustbereleasedusingfreeoncetheuserisdone – programallocatesmemoryofsizeesize,
– canperformthesamefunctionascallocifwesimplymultiplythetwoarguments – thenitcopiesthecontentsofthememoryatptrtothefirstpartofthenewpiece
ofcalloctogether ofmemory,
– finally,theoldpieceofmemoryisfreedup
• malloc(N * sizeof(float)) is equivalent to
• calloc(N,sizeof(float))

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

realloc Example Dynamically Allocating 2D Arrays

float *nums;
int I;

nums = (float *) calloc(5, sizeof(float)); Can not simply dynamically allocate 2D (or higher) array
/* nums is an array of 5 floating point values */
Idea - allocate an array of pointers (first dimension), make each
for (I = 0; I < 5; I++)
nums[I] = 2.0 * I; pointer point to a 1D array of the appropriate size
/* nums[0]=0.0, nums[1]=2.0, nums[2]=4.0, etc. */ 0 1 2 3
Can treat result as 2D array
nums = (float *) realloc(nums,10 * sizeof(float));
0
/* An array of 10 floating point values is allocated, the first 5 floats
from the old nums are copied as the first 5 floats of the new nums, 1
then the old nums is released */ A 2
3
4

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus


Non-Square 2D Arrays
Dynamically Allocating 2D Array

float **A; /* A is an array (pointer) of float


pointers */
int I;
No need to allocate square 2D arrays:
A = (float **) calloc(5,sizeof(float *)); float **A; 0 1 2 3 4
/* A is a 1D array (size 5) of float pointers */ int I;

for (I = 0; I < 5; I++) 0


A = (float **) calloc(5,
A[I] = (float *) calloc(4,sizeof(float)); sizeof(float *)); 1
/* Each element of array points to an array of 4 float variables */
A 2
/* A[I][J] is the Jth entry in the array that the Ith member of A points
for (I = 0; I < 5; I++)
A[I] = (float **) 3
to */
calloc(I+1, 4
sizeof(float));

BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus

malloc()
DynamicMemoryAllocation
• ‘C’hasfourlibraryroutines(Memory • malloc reserves a block of memory of specified size
Management Functions) to do this for us during the program execution .
– malloc • Syntax:
ptr = (cast-type *) malloc (byte-size);
– calloc
• Returns void pointer: we can assign it to any type of
– free pointer
– realloc – returns NULL if no more memory is available

• Needs to type cast the appropriate pointer type


• They allocate and release memory during
program execution.

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Example
Examples
1) x = (int *) malloc (100*sizeof(int));
• The following declaration allocates memory space for the
2) cptr = (char *) malloc (10); ‘pointer’p
– int *p;

3) ptr = (int *) malloc (j * sizeof(int)); • Allocation of memory is made later


– p = (int *) malloc(sizeof(int));
4) st_var = (struct store *) malloc (sizeof( struct store));
• Then the variable is initialized
Note: – *p = 20;

• malloc allocates a block of contiguous bytes.


• if heap is not sufficient to satisfy the request, malloc
returns a NULL.
• free(ptr) releases the used space.
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

Example malloc() example


Request memory
allocation for n
int *p; integers. Write a program to store values in an integer array and
int n; print the same.
scanf(“%d”,&n);
p= (int *) malloc(n * sizeof(int));
if (p == NULL)
{
printf (“Errorinallocation\n”);
exit();
Transforms the
}
Check if memory is generic pointer (void *) into an
… available for int pointer (int *)
allocation.
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Solution
Releasememory:free()
• The system function free is used to release a memory area
dynamically when not in use:
syntax: free(ptr);

• ptr is a pointer to a memory block which has already been


created by malloc or calloc
• Example:
• int *xPtr;
• xPtr = (int *) malloc(100*sizeof(int));
• ....
• free(xPtr);
• It frees the memory pointed by the parameter, which have
been allocated with malloc.
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

free() DynamicAllocationofstrings
Important note: • In C strings are stored as char arrays, using '\0‘aslast
1. Use of invalid pointer in the call can cause the system character to represent the end of the string.
to crash.
• Two ways to store a string made of n chars:
• Use an array statically allocated of length N>n or
2. It is not the pointer that is being released but rather
• Dynamically allocate an array of n+1 bytes.
what it points to.

3. To release an array of memory that was allocated by


calloc we need only to release the pointer once. It is an
error to attempt to release elements individually.

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Anothermemoryallocation calloc()example
function:calloc() number of size of an
blocks element
calloc() reserves the memory during program execution
Syntax:
ptr = (cast-type *) calloc(n, elem-size);
– Example:
bb = (char *) calloc( j, sizeof(char));

calloc() allocates multiple blocks of storage space, each of


same size, and sets all bytes to zero.
(malloc allocates a single block of space)

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

calloc() Vs malloc() Altering the Size of a Block


malloc() Calloc()
Sometimes we need to alter the size of some
takesasingleargument(memory needstwoarguments previously allocated memory block.
requiredinbytes) ➢ More memory needed.
➢ Memory allocated is larger than necessary.
ptr=(cast-type*)malloc(byte- ptr=(cast-type*)calloc(n,elem-
•How?
size); size);
using the realloc function.
doesnotinitializethememory initializestheallocatedmemory
allocated toZERO •Iftheoriginalallocationisdoneas:
ptr = malloc (size);
malloc isfasterthan calloc calloc takes little longer
than malloc because of the extra then reallocation of space may be done as:
step of initializing the allocated ptr = realloc (ptr, newsize);
memorybyzero

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Contd…
Reallocate
• Syntax: The new memory block may or may not begin at the same
ptr = realloc (ptr, newsize) place as the old one.

If it does not find space, it will create it in an entirely


• Note: newsize may be larger or smaller than earlier size. different region and move the contents of the old block
into the new block.
• returns NULL if unsuccessful. ➢ The function guarantees that the old data
remains intact.

➢ If it is unable to allocate, it returns NULL and frees the original block.

BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus

realloc()
Arrays in C

• All elements of same type – homogenous


• Suppose each element takes k bytes,
then an array of m data values is a
int array[10]; sequence of m*k bytes.
int b;
First element (index 0)
array[0] = 3; Last element (index size - 1)
array[9] = 4;
array[10] = 5;
array[-1] = 6;

No bounds checking!
Allowed – usually causes no error
array[10] may overwrite b

BITS Pilani, K K Birla Goa Campus


Pointers and Arrays Pointers and Arrays
#include <stdio.h>
int main (void)
{ int myNumbers[4] = {25, 50, 75, 100};
int array[10]; int i;
//Initialize the Array Elements
for (i = 0; i < 4; i++) {
printf ("Array block starts from address\n");
printf ("%u\n",array); printf("%d\n", myNumbers[i]);
printf ("%u\n",&array[0]); }

printf ("First Element of Array\n"); int myNumbers[4] = {25, 50, 75, 100};
printf ("%d\n",array[0]); int i;
printf ("%d\n",*(array+0));
for (i = 0; i < 4; i++) {
printf ("Fourth Element of Array\n"); printf("%p\n", &myNumbers[i]);
printf ("%d\n",array[3]); }
printf ("%d\n",*(array+3));

Pointers and Arrays Pointers and Arrays

// Create an int variable #include<stdio.h>


int myInt; void main()

// Get the memory size of an int {


printf("%lu", sizeof(myInt)); int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;
int myNumbers[4] = {25, 50, 75, 100}; for (i = 0; i < 4; i++)
// Get the size of the myNumbers array {
printf("%lu", sizeof(myNumbers)); printf("%d\n", *(ptr + i));
}
}
Memory management overview Memory management overview

• Stack memory • Heap-allocated memory


– When a function is called, memory is allocated for all of its – This is used for persistent data, that must survive
parameters and local variables. beyond the lifetime of a function call. For
– Each active function call has memory on the stack (with the current example:
function call on top) • global variables
– When a function call terminates, • dynamically allocated memory – C statements can
the memory is deallocated (“freed up”) create new heap data (similar to new in Java/C++)
g() – Like stack-allocated memory, the underlying
• Ex: main() calls f(), system determines where to get more memory –
f() the programmer doesn’t have to search for free
f() calls g() memory space!
main()

Allocating new heap memory Deallocating heap memory

void free(void *pointer);


• void *malloc(size_t size);
• Given a pointer to previously allocated
• Allocate a block of size bytes, return a pointer to the block (NULL
memory,
if unable to allocate block)
– put the region back in the heap of unallocated
memory
• void *calloc(size_t
* element_size bytes, num_elements, size_t
element_size);
• Allocate a block of num_elements initialize every byte to zero,
return pointer to the block (NULL if unable to allocate block)
Pointers and Functions Pointers with Functions:
pass by value
• Pointers can be used to pass addresses of variables to #include <stdio.h>
void swap( int a, int b )
functions, thus allowing the called function to alter {
void swap ( int a, int b ) ;
the values stored there. int temp;
int main ( ) temp= a; a= b; b = temp ;
{ printf ("a=%d b=%d\n", a, b);
• Similarly, functions can return a pointer. int a = 5, b = 6; }
printf("a=%d b=%d\n",a,b) ; Results:
swap (a, b) ; a=5 b=6
• How to pass array to a function ? printf("a=%d b=%d\n",a,b) ; a=6 b=5
return 0 ; a=5 b=6
}

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Pointers with Functions:Pass by


reference

#include <stdio.h> void swap( int *a, int *b )


void swap ( int *a, int *b ) ; {
int main ( ) int temp;
{ temp= *a; *a= *b; *b = temp ;
int a = 5, b = 6; printf ("a=%d b=%d\n", *a, *b); Thank You
printf("a=%d b=%d\n",a,b) ; swap }
(&a, &b) ; printf("a=%d Results:
b=%d\n",a,b) ; return 0 ; a=5 b=6
} a=6 b=5
a=6 b=5

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, K K Birla Goa Campus
BITSPilani
Pilani|Dubai|Goa|Hyderabad

Computer Programming
:
Prof.A.Jaya 1. Linked List
BITSPilani 2. Operations on Linked list
Pilani|Dubai|Goa|Hyderabad

Linked List

A linked list is a linear data structure that includes a series of
connected nodes. Here, each node stores the data and
the address ofthenextnode.

Linked list Data Structure

A linked list is a linear data structure that includes a series of connected nodes. Here,
each node stores the data and the address of the next node. For example,

Note: You might have played the game Treasure Hunt, where each
clue includes the information about the next clue. That is how the
linked list operates.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Representation of Linked List

Let's see how each node of the linked list is represented. Each node
consists:

A data item
You have to start somewhere, so we give the address of the first node An address of another node
a special name called HEAD. Also, the last node in the linked list Understanding the structure of a linked list node is the key to
can be identified because its next portion points to NULL. having a grasp on it.
Linked lists can be of multiple types: singly, doubly, and circular
linked list. In this lecture, we will focus on the singly linked list.

Each struct node has a data item and a pointer to another struct node.
Let us create a simple Linked List with three items to understand how
this works.

Introduction
Representation of Linked List
Alinkedlistisadatastructurewhichcanchange
struct node
duringexecution.
{
Successiveelementsareconnectedbypointers.
int data
LastelementpointstoNULL.
struct node *next;
Itcangroworshrinkinsizeduringexecutionofaprogram.
}
Itcanbemadejustaslongasrequired.
Itdoesnotwastememoryspace.
head
Understanding the structure of a linked list node is the key to having a
grasp on it.

Each struct node has a data item and a pointer to another struct A B C
node. Let us create a simple Linked List with three items to
understand how this works.
Illustration:Insertion
Keepingtrackofalinkedlist:
A B C
Mustknowthepointertothefirstelementofthelist(called
start,head,etc.).
Item to be
Linkedlistsprovideflexibilityinallowingtheitemstobe tmp X inserted
rearrangedefficiently.
Insertanelement.
Deleteanelement. A B C

curr
X

Pseudo-codeforinsertion Illustration:Deletion
Item to be deleted
typedef struct nd {
struct item data; A B C
struct nd * next;
} node;
tmp
void insert(node *curr) curr
{
node * tmp; A B C

tmp=(node *) malloc(sizeof(node));
tmp->next=curr->next;
curr->next=tmp;
}
Pseudo-codefordeletion Inessence...
typedef struct nd { Forinsertion:
struct item data; Arecordiscreatedholdingthenewitem.
struct nd * next; Thenextpointerofthenewrecordissettolinkitto
} node;
theitemwhichistofollowitinthelist.
void delete(node *curr) Thenextpointeroftheitemwhichistoprecedeit
{ mustbemodifiedtopointtothenewitem.
node * tmp;
tmp=curr->next; Fordeletion:
curr->next=tmp->next; Thenextpointeroftheitemimmediatelypreceding
free(tmp);
theonetobedeletedisaltered,andmadetopoint
}
totheitemfollowingthedeleteditem.

ArrayversusLinkedLists TypesofLists
Arraysaresuitablefor: Dependingonthewayinwhichthelinksareusedtomaintainadjacency,several
Inserting/deletinganelementattheend. differenttypesoflinkedlistsarepossible.
Randomlyaccessinganyelement.
Linearsingly-linkedlist(orsimplylinearlist)
Searchingthelistforaparticularvalue. Onewehavediscussedsofar.

Linkedlistsaresuitablefor:
Insertinganelement. head
Deletinganelement.
Applicationswheresequentialaccessisrequired.
Insituationswherethenumberofelementscannotbe A B C
predictedbeforehand.
Circularlinkedlist Doublylinkedlist

Thepointerfromthelastelementinthelistpointsbacktothefirstelement. Pointersexistbetweenadjacentnodesinbothdirections.
Thelistcanbetraversedeitherforwardorbackward.
Usuallytwopointersaremaintainedtokeeptrackofthelist,headandtail.

head

head tail
A B C
A B C

BasicOperationsonaList ListisanAbstractDataType

Whatisanabstractdatatype?
• Creatingalist Itisadatatypedefinedbytheuser.
• Traversingthelist Typicallymorecomplexthansimpledatatypeslikeint,float,
etc.
• Insertinganiteminthelist
• Deletinganitemfromthelist Whyabstract?
Becausedetailsoftheimplementationarehidden.
• Concatenatingtwolistsintoone Whenyoudosomeoperationonthelist,sayinsertan
element,youjustcallafunction.
Detailsofhowthelistisimplementedorhowtheinsert
functioniswrittenisnolongerrequired.
ConceptualIdea Example:Workingwithlinkedlist

Considerthestructureofanodeasfollows:

struct stud {
int roll;
char name[25];
Insert int age;
List struct stud *next;
implementation };
Delete
and the
/* A user-defineddatatypecalled“node”*/
related functions
Traverse typedef struct stud node;
node *head;

Howtobegin?

Tostartwith,wehavetocreateanode(thefirstnode),andmakeheadpointtoit.


CreatingaList head = (node *) malloc(sizeof(node));

head
roll

name next
age
Contd.
Iftherearennumberofnodesintheinitiallinkedlist: node *create_list()
{
Allocatenrecords,onebyone. int k, n;
node *p, *head;
Readinthefieldsoftherecords.
printf ("\n How many elements to enter?");
Modifythelinksoftherecordssothatthechainisformed. scanf ("%d", &n);
for (k=0; k<n; k++)
{
if (k == 0) {
head = (node *) malloc(sizeof(node));
p = head;
}
else {
p->next = (node *) malloc(sizeof(node));
head p = p->next;
}
scanf ("%d %s %d", &p->roll, p->name, &p->age);
}

A B C p->next = NULL;
return (head);
}

Tobecalledfrommain()functionas:

   node *head;


……… TraversingtheList
head = create_list();
Whatistobedone?

Oncethelinkedlisthasbeenconstructedand void display (node *head)


{
headpointstothefirstnodeofthelist, int count = 1;
node *p;
p = head;
• Followthepointers. while (p != NULL)
{
• Displaythecontentsofthenodesasthey printf ("\nNode %d: %d %s %d", count,
p->roll, p->name, p->age);
aretraversed. count++;
p = p->next;
• StopwhenthenextpointerpointstoNULL. }
printf ("\n");
}

Tobecalledfrommain()functionas:

   node *head;


……… InsertingaNodeinaList
display (head);
Howtodo? Contd.
When a node is added at the beginning,
Theproblemistoinsertanodebefore a specified node. Onlyonenextpointerneedstobemodified.
Specifiedmeanssomevalueisgivenforthenode headismadetopointtothenewnode.
(calledkey). Newnodepointstothepreviouslyfirstelement.
Inthisexample,weconsiderittoberoll. When a node is added at the end,
Twonextpointersneedtobemodified.
Lastnodenowpointstothenewnode.
Conventionfollowed: NewnodepointstoNULL.
Ifthevalueofrollisgivenasnegative,thenodewill
beinsertedattheendofthelist. When a node is added in the middle,
Twonextpointersneedtobemodified.
Previousnodenowpointstothenewnode.
Newnodepointstothenextnode.

void insert (node **head) else


{ {
int k = 0, rno; while ((p != NULL) && (p->roll != rno))
node *p, *q, *new; {
q = p;
new = (node *) malloc(sizeof(node)); p = p->next;
}
printf ("\nData to be inserted: "); The pointers
scanf ("%d %s %d", &new->roll, new->name, &new->age); if (p == NULL) /* At the end */ q and p
printf ("\nInsert before roll (-ve for end):"); { always point
scanf ("%d", &rno); q->next = new; to consecutive
new->next = NULL; nodes.
p = *head; }
else if (p->roll == rno)
if (p->roll == rno) /* At the beginning */ /* In the middle */
{ {
new->next = p; q->next = new;
*head = new; new->next = p;
} }
}
}
Tobecalledfrommain()functionas:

   node *head;


……… Deletinganodefromthelist
insert (&head);

Whatistobedone?

• Herealsowearerequiredtodeleteaspecified void
{
delete (node **head)

node. int rno;


node *p, *q;
• Say,thenodewhoserollfieldisgiven.
printf ("\nDelete for roll :");
• Herealsothreeconditionsarise: scanf ("%d", &rno);
• Deletingthefirstnode. p = *head;
• Deletingthelastnode. if (p->roll == rno)
/* Delete the first element */
• Deletinganintermediatenode. {
*head = p->next;
free (p);
}
FewExercisestoTryOut
else
{
while ((p != NULL) && (p->roll != rno)) Writeafunctionto:
{
q = p;
p = p->next; • Concatenatetwogivenlistintoonebiglist.
} • node*concatenate(node*head1,node*head2);
• Insertanelementinalinkedlistinsortedorder.The
if (p == NULL) /* Element not found */ functionwillbecalledforeveryelementtobeinserted.
printf ("\nNo match :: deletion failed"); • voidinsert_sorted(node**head,node*element);
else if (p->roll == rno) • Alwaysinsertelementsatoneend,anddeleteelements
/* Delete any other element */ fromtheotherend(first-infirst-outQUEUE).
{ • voidinsert_q(node**head,node*element)
q->next = p->next; • node*delete_q(node**head)/*Returnthedeleted
free (p); node*/
}
}
}

AFirst-inFirst-out(FIFO)List ALast-inFirst-out(LIFO)List

In Out
In Out
C B A B C

B A
C B A

Also called a
Also called a QUEUE STACK
Example1::Complexnumbers
struct cplx {
float re;
float im;
Structure
} definition
AbstractDataTypes typedef struct cplx complex;

complex *add (complex a, complex b);


complex *sub (complex a, complex b);
complex *mul (complex a, complex b);
Function
complex *div (complex a, complex b);
complex *read(); prototypes
void print (complex a);


add
Example2::Setmanipulation
struct node {
int element;
sub struct node *next;
Structure
} definition
typedef struct node set;
mul Complex
Number set *union (set a, set b);
div set *intersect (set a, set b);
set *minus (set a, set b); Function
void insert (set a, int x); prototypes
read void delete (set a, int x);
int size (set a);

print
union
Doublylinkedlist

intersect NULL Data Link to Link to Data Null


the next the prev
node node
minus
Set head Tail

insert
Link to Data Link to
the prev the next
node node
delete

size

Circularlinkedlist

Link to Data Address Linkedlistscanbeofmultipletypes: singly, doubly,


Address Data Link to
of the the next the prev of the and circular linked list.
tail node node node head
node

head Tail

Link to Data Link to


the prev the next
node node

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


. Linked List implementation

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Linkedlistoperations

E.g.ifyouwantedtoputanelement4between1and2,
thestepswouldbe:
[Link]listinsertion
[Link]listdeletion
•Createanewstructnodeandallocatememorytoit. [Link]listtraversal
•Additsdatavalueas4 [Link]listsearch
•Pointitsnextpointertothestructnodecontaining2as
thedatavalue [Link]listsorting
•Changethenextpointerof"1"tothenodewejust
created.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Suppose data LinkedList: Node Linkedlistinsertion
isa single
integer DATA
struct node;
typedefstructnode NODE;
struct node typedefNODE *link;
{ struct node
int data; {
structnode *next; intdata;
20 Null
}; link next;
intmain (void) };
intmain (void)
{
{
structnoden; NODE n;
[Link] =20; [Link]= 20;
[Link]= NULL; [Link]= NULL;
} }

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


LinkedlistInsertionatthebeginning Linkedlistattheend

•Procedure structnode*newNode;
•Allocatememoryfornewnode newNode=malloc(sizeof(structnode));
•Storedata newNode->data=34;
•Allocatememoryfornewnode structnode*newNode; •Traversetolastnode newNode->next=NULL;
•Storedata newNode=malloc(sizeof(structnode)); •Changenextoflastnodetorecentlycreated
•Changenextofnewnodetopointtohead newNode->data=34; node structnode*temp=head;
•Changeheadtopointtorecentlycreated newNode->next=head; while(temp->next!=NULL){
node head=newNode; temp=temp->next;
}

temp->next=newNode;

Insertioninthemiddle Traverse a Linked List

• Displaying the contents of a linked list is very simple. We keep moving


the temp node to the next one and display its contents.
structnode*newNode;
newNode=malloc(sizeof(structnode));
newNode->data=34; • When temp is NULL, we know that we have reached the end of the
linked list so we get out of the while loop.
structnode*temp=head;
structnode*temp=head;
•Allocatememoryandstoredatafornew for(inti=2;i<position;i++){
printf("\n\nListelementsare-\n");
node if(temp->next!=NULL){
while(temp!=NULL){
•Traversetonodejustbeforetherequired temp=temp->next;
printf("%d--->",temp->data);
positionofnewnode }
temp=temp->next;
•Changenextpointerstoincludenewnode }
}
inbetween newNode->next=temp->next;
temp->next=newNode;
Deletion of a node from the linked list
Deletionfromthebeginning

Step1: Start

Step 2: If deletion from the beginning, then point head to the second node

Step 3: If deletion at the end, then traverse to second last element and change its pointer
to null

Step 4: If deletion at the middle, then traverse list and identify before the element to be
deleted and change next pointers to exclude the node from the list 1. Delete from beginning
•Pointheadtothesecondnode

head=head->next;

DeletionfromtheEnd DeletionfromtheMiddle

•Traversetosecondlastelement structnode*temp=head; Delete from middle


•Changeitsnextpointertonull while(temp->next->next!=NULL){ •Traversetoelementbeforetheelementtobe
temp=temp->next; deleted
} •Changenextpointerstoexcludethenode for(inti=2;i<position;i++){
temp->next=NULL; fromthechain if(temp->next!=NULL){
temp=temp->next;
}
}

temp->next=temp->next->next;
Search an Element on a Linked List Sort Elements of a Linked List

[Link] the head as the current node and create


• Makeheadasthecurrentnode.
• RunaloopuntilthecurrentnodeisNULLbecausethelast another node index for later use.
elementpointstoNULL. [Link] head is null, return.
• Ineachiteration,checkifthekeyofthenodeisequaltoitem.
[Link], run a loop till the last node (i.e. NULL).
Ifitthekeymatchestheitem,returntrueotherwisereturn
false. [Link] each iteration, follow the following step 5-6.
//Searchanode
boolsearchNode(structNode**head_ref,intkey){
structNode*current=*head_ref;
[Link] the next node of current in index.
while(current!=NULL){
[Link] if the data of the current node is greater
if(current->data==key)returntrue;
current=current->next;
than the next node. If it is greater,
}
returnfalse;
swap current and index.
}

Sort Elements of a Linked List Function Pointers

// Sort the linked list


void sortLinkedList(struct Node** head_ref) { • Function pointers in C are variables that can store the memory address of
struct Node *current = *head_ref, *index = NULL;
int temp; functions and can be used in a program to create a function call to functions
pointed by them.
if (head_ref == NULL) {
return;
• Function pointers in C need to be declared with an asterisk symbol and
} else {
while (current != NULL) { function parameters (same as the function they will point to) before using
// index points to the node next to current them in the program.
index = current->next;

while (index != NULL) { • Declaration of function pointers in C includes the return type and data type of
if (current->data > index->data) { different function arguments.
temp = current->data;
current->data = index->data;
index->data = temp;
• An asterisk symbol before the pointer name differentiates the function pointer
} from a usual function declaration.
index = index->next;
} • Functions can aspect function pointer as a function argument and later call it
current = current->next;
} inside the function body. Such passed functions are called callback functions.
}
}
Function Pointers Declaring a Function Pointer in C

• Like variables, instructions of a function are also stored in memory and have
an address.
Function add() istoaddtwointeger
• A pointer pointing to the address of a function is called function pointer. numbers.
Here,thefunctionnamepointstothe
• A function pointer in C can be used to create function calls to the function addressofthefunctionitselfsoweare
they point to just like a normal function. usingafunctionpointer fptr thatstores
theaddressofbeginningofthe
function add(a,b) thatin1001inthis
case.

Calling a Function Through a Function


Syntax of Function Pointer in C Pointer in C

return_type (* pointer_name) (datatype_arg_1, datatype_arg_1, ...); Callingafunctionusingapointerissimilartocallingafunctionintheusualway


usingthenameofthefunction.
DeclaringafunctionpointerinCiscomparabletodeclaringafunctionexceptthatwhena Supposewedeclareafunctionanditspointerasgivenbelow.
functionpointerisdeclared,we prefix its name which is an Asterisk * symbol.

Forexample,ifafunctionhasthedeclaration int(*pointer)(int);//functionpointerdeclaration
floatfoo(int,int); intareaSquare(int);//functiondeclaration
DeclarationofafunctionpointerinCforthefunction foo willbe pointer=areaSquare;

//functionpointerdeclaration Here,pointer *foo_pointer isa


float(*foo_pointer)(int,int); functionpointerandstoresthe
/*assigningtheaddressofthefunction(foo)to memoryaddressofa
functionpointer*/ function foo thattakestwo
foo_pointer=foo; argumentsoftype int andreturns
avalueofdatatype float.
Function Pointer in C

#include<stdio.h>
Tocallthefunction areaSquare,wecancreateafunctioncallusinganyofthe //functiondeclaration
threeways intareaRectangle(int,int);
intmain(){
intlength,breadth,area;

intlength=5; //functionpointerdeclaration//notethatourpointerdeclarationhasidentical
//argumentsasthefunctionitwillpointto
int(*fp)(int,int);
//Differentwaystocallthefunction 
printf("Enterlengthandbreadthofarectangle\n");
scanf("%d%d",&length,&breadth);
//1.usingfunctionname 
intarea=areaSquare(length); //pointingthepointertofunctionsmemoryaddress
fp=areaRectangle;

//2.usingfunctionpointer(a) //callingthefunctionusingfunctionpointer
area=(*fp)(length,breadth);
intarea=(*pointer)(length); 
printf("Areaofrectangle=%d",area);
return0;
//3.usingfunctionpointer(b) }
intarea=pointer(length);
//functiondefinition
intareaRectangle(intl,intb){
intarea_of_rectangle=l*b;
returnarea_of_rectangle;
}

Relationship Between Arrays and


Pointers

Anarrayisablockofsequentialdata.Let'swriteaprogramtoprintaddressesofarray There is a difference of 4 bytes between two consecutive elements of


elements. array x. It is because the size of int is 4 bytes (on our compiler).

#include<stdio.h> Notice that, the address of &x[0] and x is the same. It's because the
intmain(){ variable name x points to the first element of the array.
intx[4];
inti;
Fromtheaboveexample,itisclearthat &x[0] isequivalentto x.
for(i=0;i<4;++i){ And, x[0] isequivalentto *x.
printf("&x[%d]=%p\n",i,&x[i]); Similarly,
}
•&x[1] isequivalentto x+1 and x[1] isequivalentto *(x+1).
printf("Addressofarrayx:%p",x); •&x[2] isequivalentto x+2 and x[2] isequivalentto *(x+2).
•...
return0;
}
•Basically, &x[i] isequivalentto x+i and x[i] isequivalentto *(x+i).
PointersandArrays
#include<stdio.h>
intmain(){

inti,x[6],sum=0;

printf("Enter6numbers:");
Fromtheaboveexample,itisclearthat &x[0] isequivalentto x.
And, x[0] isequivalentto *x. for(i=0;i<6;++i){
//Equivalenttoscanf("%d",&x[i]);
Similarly, scanf("%d",x+i);
•&x[1] isequivalentto x+1 and x[1] isequivalentto *(x+1).
•&x[2] isequivalentto x+2 and x[2] isequivalentto *(x+2). //Equivalenttosum+=x[i]
sum+=*(x+i);
•... }
•Basically, &x[i] isequivalentto x+i and x[i] isequivalentto *(x+i).
printf("Sum=%d",sum);

return0;
}

Arrays and Pointers Function Pointers

#include<stdio.h> • definedafunction areaRectangle() thattakestwointegerinputsandreturnsthe


intmain(){
areaoftherectangle.
intx[5]={1,2,3,4,5};
int*ptr; • Tostorethereferenceofthefunction,weareusingfunctionpointer (*fp) that
hasasimilardeclarationtothefunctionitpointsto.
//ptrisassignedtheaddressofthethirdelement
ptr=&x[2]; • Topointthefunctionaddresstothepointerwedon'tneedtouse & symbolas
thefunctionname areaRectangle alsorepresentsthefunction'saddress.
printf("*ptr=%d\n",*ptr);//3
printf("*(ptr+1)=%d\n",*(ptr+1));//4 • Tocallthefunction,wepassparametersinsidetheparenthesis((*fp)(length,
printf("*(ptr-1)=%d",*(ptr-1));//2
breadth)),andthereturnvalueisstoredinthevariable area.
return0;
}
Pass Addresses to Functions Passing Pointers to Functions

#include<stdio.h> #include<stdio.h>
voidswap(int*n1,int*n2);
intmain()
{ voidaddOne(int*ptr){ Here, the value stored at p, *p, is 10
intnum1=5,num2=10; (*ptr)++;//adding1to*ptr initially.
//addressofnum1andnum2ispassed } We then passed the pointer p to
swap(&num1,&num2);
Theaddressof num1 and num2 are
passedtothe swap() function the addOne() function. The ptr pointer gets
intmain()
printf("num1=%d\n",num1); this address in the addOne() function.
printf("num2=%d",num2);
using swap(&num1, &num2);. {
Inside the function, we increased the
int*p,i=10;
return0; Pointers n1 and n2 acceptthese p=&i; value stored at ptr by 1 using (*ptr)++; .
}
voidswap(int*n1,int*n2)
argumentsinthefunction addOne(p); Since ptr and p pointers both have the
{ definition. same address, *p inside main() is also 11.
inttemp; printf("%d",*p);//11
temp=*n1; return0;
*n1=*n2; }
*n2=temp;
}

Array of function pointers

• Arraysaredatastructurethatstorescollectionofidenticaldatatypes.Likeany #include<stdio.h> result=(*operation[2])(a,b);


printf("Multiplication(a*b)=%.1f\n",result);
otherdatatypeswecancreateanarraytostorefunctionpointersinC. floatadd(int,int); 
floatmultiply(int,int); result=(*operation[3])(a,b);
floatdivide(int,int); printf("Division(a/b)=%.1f\n",result);
• Functionpointerscanbeaccessedfromtheirindexeslikeweaccessnormalarray floatsubtract(int,int); 
return0;
values arr[i]. intmain(){ }
inta,b;
float(*operation[4])(int,int); floatadd(inta,intb){
• Thiswaywearecreatinganarrayoffunctionpointers,whereeacharrayelement operation[0]=add;
returna+b;
}
storesafunctionpointerpointingtodifferentfunctions. operation[1]=subtract;
operation[2]=multiply; floatsubtract(inta,intb){
operation[3]=divide; returna-b;
 }
printf("Entertwovalues");
scanf("%d%d",&a,&b); floatmultiply(inta,intb){
 returna*b;
floatresult=(*operation[0])(a,b); }
printf("Addition(a+b)=%.1f\n",result);
 floatdivide(inta,intb){
result=(*operation[1])(a,b); returna/(b*1.0);
printf("Subtraction(a-b)=%.1f\n",result); }

BITSPilani
Pilani|Dubai|Goa|Hyderabad
BITS Pilani
Pilani|Dubai|Goa|Hyderabad

Contactsession-15
:
1. File handling in C
BITS Pilani Prof.A.Jaya
Pilani|Dubai|Goa|Hyderabad 2. File I/O
3. File Operations

File handling in C
• We frequently use files for storing information which can be processed
by our programs. In order to store information permanently and retrieve • File handing in C is the process in which we create, open,
it we need to use files. read,write,andcloseoperationsonafile.
• Files are not only used for data. Our programs are also stored in files.
• The editor which you use to enter your program and save it, simply • C language provides different functions such as fopen(),
manipulates files for you. fwrite(), fread(), fseek(), fprintf(), etc. to perform input,
• The Unix commands cat, cp, cmp are all programs which process your output,andmanydifferentCfileoperationsinourprogram.
files.
• In order to use files we have to learn about File I/O i.e. how to write
information to a fileand how to read information from a file.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


File File

❖Discretestorageunitfordataintheformofastreamofbytes.
- Afileissequenceofbytes.
- It can be thought of a data container – gets stored on a
❖Durable:storedinnon-volatilememory.
storagedevice
❖Startingend,sequenceofbytes,andendofstream(orendoffile).
------
❑Datainmemoryisephemeral ------
❖Sequentialaccessofdatabyapointerperformingread/write/ ❑Needpersistenceandabilityto ------
deletion/insertion. preserve File
❑Dataissohugethatitcannotbe StorageDevice
❖Meta-data(informationaboutthefile)beforethestreamofactual accommodatedinmemory
data. ❑Needtheabilitytomovedata

File TypesofFiles
- Broadlyclassifiedas
- TextfilesandBinaryFiles

Head Tail
MetaData 40 65 87 90 24 67 89 90 0 0 - Textfiles
- A text file is a named collection of characters saved in
secondarystorage,andhasnofixedsize.
▪ Normallycreatedusingatexteditor;
File Pointer ▪ Containsplainandreadabletext(ASCII)
▪ Usuallyverylargeinsize–needcompression
▪ Easytoaccessandmaintain

7
File handling in C

- Binaryfiles
- A binary file is a file created by executing a program that
stores directly in the  file the computers representation of
eachfilecomponent.

▪ Createdusinganapplicationsoftware(OfficeS/W,MultimediaS/W)
▪ Containscharactersfromnon-ASCIIcharactersets
▪ NeedspecificS/Wtoreadandedit

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Text File Processing [Link]Files

• Since there can be multiple files in the disk, to


Atextfilecontainsdatainthe formofASCIIcharacters and
process files via C programs we need to: isgenerallyusedtostoreastreamofcharacters.
– Specify which file we wish to use, i.e. open the file
– Specify the modein which the file is to be opened, i.e. 1. Each line in a text file ends with a new line character
(‘\n’).
read or write
2. Itcanbereadorwrittenbyanytexteditor.
– Perform operations on the file, i.e. reading, writing, or 3. Theyaregenerallystoredwith .txt fileextension.
appending. 4. Textfilescanalsobeusedtostorethesourcecode.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


2.BinaryFiles CFileOperations

Cfileoperationsrefertothedifferentpossibleoperationsthatwe
Abinaryfilecontainsdatain binaryform(i.e.0’sand1’s) instead
canperformonafileinCsuchas:
of ASCIIcharacters.They contain data that is stored in a similar
mannertohowitisstoredinthemainmemory. [Link] a new file – fopen()withattributesas“a”or“a+”or“w”or
• Thebinaryfilescanbecreatedonlyfromwithinaprogram “w+”
andtheircontentscanonlybereadbyaprogram. [Link] an existing file – fopen()
• Moresecureastheyarenoteasilyreadable. [Link] from file – fscanf() or fgets()
[Link] to a file – fprintf() or fputs()
• Theyaregenerallystoredwith .bin fileextension. [Link] to a specific location in a file – fseek(), rewind()
[Link] a file – fclose()

FileBasics(SpecifictoUnix) FilePermissions

- Everyfilehas: - Afilehasasetofpermissions
- Aname(max.255characters) - Todeterminewhocandowhatwithagivenfile
- Apath–filelocationinahierarchyofdirectories - Threetypesofpermissions–read,writeandexecute
- Anowner–whocreatedthefile - Threetypesofusers–owner,groupandothers
- Agroup–whichtheauthorbelongsto - read–4,write–2andexecute–1
- Amode–whocanwrite,readandexecute - Max.permission–4+2+1=7
- Timestamps–creation,modification,access,etc. Example:
- Inode–Uniqueindexthatidentifiesafile 777 – read/write/execute permission to owner, group and others
- Links–shortcutstofile 644 – read/write to owner and read to group and others
755 – write/read/execute to owner and read/execute to group and others
GenericFileOperations GenericFileOperations

•Creatinganewfile
• Usedforcreatinganewfile
•Openinganexistingfile Create
•Readingdatafromanexistingfile • Usedforopeninganexistingfileorcreatinganewfile
•Writingdatatoafile Open

•Movingdatatoaspecificlocationonthefile • Usedforreadingcontentsfromanopenfile
Read
•Closingthefile
• Usedforwritingdatatoafilethatisopen
Write

• Usedforclosing(saving)anopenfile
Close

FileFunctions FileSystemCalls

Open Read Write Close


• creat() • read() • write() • close()
• open() • fscanf() • fprintf() • fclose()
• fopen() • fgetc() • fputc()
• fgets() • fputs() - SystemcallsarecallstosubroutinesbuiltintheOS.
• getc() • putc() - Offerbettercontroloveraccessingsystemresources
• fread() • fwrite() - Runinkernelmode
- Usefulinsystemprogramming
MODE DESCRIPTION
STREAMSINCcontd.

r Open a text file for reading. If the stream (file) does not exist then an error will be reported.
Standard input (stdin): Standard input is the stream KEYBOARD stdin
Open a text file for writing. If the stream does not exist then it is created otherwise if the file already
w exists, then its contents would be deleted
fromwhichtheprogramreceivesitsdata.Theprogram
requests transfer of data using the read operation. PROGRAM stderr
a Append to a text file. if the file does not exist, it is created.
However, not all programs require input. Generally,
Open a binary file for reading. B indicates binary. By default this will be a sequential file in Media 4
rb unlessredirected,inputforaprogramisexpectedfrom
format SCREEN stdout

wb Open a binary file for writing thekeyboard.


ab Append to a binary file
Standard output (stdout): Standard output is the stream where a program writes its output
Open a text file for both reading and writing. The stream will be positioned at the beginning of the file.
r+ When you specify "r+", you indicate that you want to read the file before you write to it. Thus the file data.Theprogramrequestsdatatransferusingthewriteoperation.However,notallprograms
must already exist.
generateoutput.
Open a text file for both reading and writing. The stream will be created if it does not exist, and will be Standard error (stderr): Standard error is basically an output stream used by programs to
w+ truncated if it exist.
reporterrormessagesordiagnostics.Itisastreamindependentofstandardoutputandcanbe
Open a text file for both reading and writing. The stream will be positioned at the end of the file
a+ redirectedseparately.Nodoubt,thestandard outputandstandard errorcanalsobedirectedto
content.
r+b/ rb+ Open a binary file for read/write thesamedestination.
w+b/wb+ Create a binary file for read/write Astreamislinkedtoafileusinganopenoperationanddisassociatedfromafileusingaclose
a+b/ab+ Append a binary file for read/write operation.

BUFFERASSOCIATEDWITHFILESTREAM 
Whenastreamlinkedtoadiskfileiscreated,abufferisautomaticallycreatedandassociatedwiththestream.Abufferis
nothingbutablockofmemorythatisusedfortemporarystorageofdatathathastobereadfromorwrittentoafile.
Buffers areneeded because disk drives areblock oriented devices as they can operate efficiently when data has to be
read/writteninblocksofcertainsize.Thesizeofidealbuffersizeishardwaredependant.Thebufferactsasaninterface
betweenthestream(whichischaracter-oriented)andthediskhardware(whichisblockoriented).Whentheprogramhas
towritedatatothestream,itissavedinthebuffertillitisfull.Thentheentirecontentsofthebufferarewrittentothe
diskasablock.

Datafromthebufferiswrittentothediskfile
Programwritesdatatobuffer

PROGRAM
BUFFER DISK

Similarly, whenreading data from a diskfile, the data is read as a block from the file and written into the buffer. The
programreadsdatafromthe buffer.Thecreationandoperationofthebuffer isautomaticallyhandled bytheoperating
system. However, C provides some functions for buffer manipulation. The data resides in the buffer until the buffer is
flushedorwrittentoafile.
OPENININGAFILEcontd.  CLOSINGAFILEUSINGFCLOSE() 
Thefopen()canfailtoopenthespecifiedfileundercertainconditionsthatarelistedbelow:
• Tocloseanopenfile,thefclose()functionisusedwhichdisconnectsafilepointerfroma
Openingafilethatisnotreadyforusage
file.Afterthefclose()hasdisconnectedthefilepointerfromthefile,the pointercanbe
Openingafilethatisspecifiedtobeonanon-existentdirectory/drive
Openinganon-existentfileforreading usedtoaccessadifferentfileorthesamefilebutinadifferentmode.
Openingafiletowhichaccessisnotpermitted
• The fclose() function not only closes the file but also flushed all the buffers that are
maintainedforthatfile
FILE*fp;
fp=fopen("[Link]","r");
if(fp==NULL) • If you do not close a file after using it, the system closes it automatically when the
{ programexits.However,sincethereisalimitonthenumberoffileswhichcanbeopen
 printf("\nThefilecouldnotbeopened");
 exit(1); simultaneously;theprogrammermustcloseafilewhenithasbeenused.Theprototype
}
OR ofthefclose()functioncanbegivenas,
charfilename[30];
FILE*fp; intfclose(FILE*fp);
gets(filename);
fp=fopen(filename,"r+");
if(fp==NULL)
{ • Here,fpisafilepointerwhichpointstothefilethathastobeclosed.Thefunctionreturns
 printf("\nThefilecouldnotbeopened");
 exit(1); an integer value which indicates whether the fclose() was successful or not. A zero is
} returned if the function was successful; and a non-zero value is returned if an error
occurred.

Creatingoropeningfileusingfopen()
Parameters

• Thefopen()functionisusedtocreateanewfileoropenan
existingfileinC.Thefopenfunctionisdefinedinthestdio.h file_name − It is a string that specifies the name
headerfile. of the file that is to be opened or created using the
fopen method. mode:
• Now,letsseethesyntaxforcreationofanewfileoropening
afile It is a string (usually a single character ) that
specifies the mode in which the file is to be
• file=fopen(“file_name”,“mode”) opened.

• Thisisacommonsyntaxforbothopeningandcreatingafile There are various modes available to open a file in


inC. C, we will learn about all of them later in this
article.
SampleFileProgram
#include<stdio.h>
#include<stdio.h>
intmain(){
intmain(){
FILE*file;
FILE*file;
if(file=fopen("[Link]","rb")){
if(file=fopen("[Link]","r")){
printf("Fileopenedsuccessfullyinreadmode");
printf("Fileopenedsuccessfullyinreadmode");
}
}
else
else
printf("Thefileisnotpresent!cannotcreateanew
printf("Thefileisnotpresent!cannotcreateanew
fileusingrbmode");
fileusingrmode");
fclose(file);
fclose(file);
return0;
return0;
}
}
The file is not present! cannot create
Output a new file using rb mode
File opened successfully in read mode

#include<stdio.h> #include<stdio.h>
intmain(){ intmain(){
FILE*file; FILE*file;
if(file=fopen("[Link]","w")){ if(file=fopen("[Link]","a")){
printf("Fileopenedsuccessfullyin
printf("Fileopenedsuccessfullyin appendmodeoranewfileiscreated");
writemodeoranewfileiscreated"); }
} else
printf("Error!");
else fclose(file);
printf("Error!"); return0;
fclose(file); }
File opened successfully in
return0; append mode or a new file is
File opened successfully in write mode
} created
or a new file is created
READDATAFROMFILES 
READDATAFROMFILES 
Cprovidesthefollowingsetoffunctionstoreaddatafromafile. #include<stdio.h>
main()
{ FILE *fp;
• fscanf() char name[80];
• fgets() int roll_no;
• fgetc() fp = fopen("[Link]", "r");
• fread() if(fp==NULL)
{ printf("\n The file could not be opened");
exit(1);
fscanf() }
 Thefscanf()isusedtoreadformatteddatafromthestream.Thesyntax printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s %d", name, &roll_no); /* read from keyboard */
ofthefscanf()canbegivenas, printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
// READ FROM FILE- [Link]
fscanf(fp, "%s %d", name, &roll_no);
int fscanf(FILE*stream,constchar*format,…); printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
fclose(fp);
}
Thefscanf()isusedtoreaddatafromthestreamandstorethemaccordingtothe
parameterformatintothelocationspointedbytheadditionalarguments.

ReadingDataforfromanexistingfile
Sampleprogram
fscanf() #include<stdio.h>
intmain(){
Thefscanf()functionisusedtoreadcharacterseti.estrings FILE*file;
charstr[500];
fromthefile.ItreturnstheEOF,whenallthecontentofthefile if(file=fopen("[Link]","r")){
arereadbyit. while(fscanf(file,"%s",str)!=EOF){
printf("%s",str);
}
}
else
printf("Error!”);
fclose(file);
return0;
}
fgets() fgets()

• fgets()standsforfile get string.Thefgets()functionisusedtoget FILE*fp;


astringfromastream.Thesyntaxoffgets()canbegivenas:  char str[80];
• char*fgets(char*str,intsize,FILE*stream);  fp=fopen("[Link]","r");
• Thefgets()function readsatmostoneless than the numberof  if(fp==NULL)
characters specified by size (gets size - 1 characters) from the  {

givenstreamandstorestheminthestringstr.   printf("\nThefilecouldnotbeopened");

• Thefgets()terminates assoon asitencounterseitheranewline   exit(1);

characterorend-of-fileoranyothererror.However,ifanewline  }

character is encountered it is retained. When all the characters  while(fgets(str,80,fp)!=NULL)

are read without any error, a '\0' character is appended to end   printf("\n%s",str);
 printf("\n\nFileRead.Nowclosingthefile");
thestring.
  fclose(fp);

fgetc() fgetc()

• Thefgetc()functionreturnsthenextcharacterfromstream,orEOFiftheend FILE*fp;
charstr[80];
offileisreachedorifthereisanerror.Thesyntaxoffgetc()canbegivenas
int i,ch;
  intfgetc(FILE*stream);  fp=fopen("Program.C","r");
• fgetcreturnsthecharacterreadasanintorreturnEOFtoindicateanerroror  if(fp==NULL)
endoffile.  { printf("\nThefilecouldnotbeopened");
  exit(1);
• fgetc()readsasinglecharacterfromthecurrentpositionofafile(file  }
associatedwithstream).Afterreadingthecharacter,thefunctionincrements //Read79charactersandstoretheminstr
theassociatedfilepointer(ifdefined)topointtothenextcharacter.  ch=fgetc(fp);
• However,ifthestreamhasalreadyreachedtheendoffile,theend-of-file  for(i=0;(i<79)&&(feof(fp)==0);i++)
{ str[i]=(char)ch;
indicatorforthestreamisset.   ch=fgetc(stream);
 }
  str[i]='\0';
 printf("\n%s",str);
fclose(fp);
Files in C – Interfaces
Files in C – Explanations
/* stdio.h */
/* Pre-condition: f is open
• fgetc is morethan a read operation
Post-condition: – Itreadsthenextcharacteraswellasupdatesthe
- return the next character of f as a char or EOF if end of file occurs
current position in the FILE (that is why a pointerto a
*/
FILE is passed).
– In a sense, comparing it with queue data structure, it
int fgetc(FILE *f); is a combination of frontQ and deleteQ operations:
• returnthe front element and
/* Pre-condition: f is open • delete the front element from f
Post-condition: • But thisdelete does not physically delete it from the file,
- write the character c (as an unsigned int) on f only from the f that is updated.
- return c or EOF if there is an error
*/
int fputc(int c, FILE *f);
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

fread() fread()

• Thefread()functionisusedtoreaddatafromafile.Itssyntaxcanbegivenas Thefread()functionadvancesthefilepositionindicatorforthe
intfread(void*str,size_tsize,size_tnum,FILE*stream); streambythenumberofbytesread.
FILE*fp;
• Thefunctionfread()readsnumnumberofobjects(whereeachobjectissize charstr[11];
bytes)andplacesthemintothearraypointedtobystr.Thedataisreadfrom  fp=fopen("[Link]","r+");
thegiveninputstream.  if(fp==NULL)
 {
• Uponsuccessfulcompletion,fread()returnsthenumberofbytessuccessfully   printf("\nThefilecouldnotbeopened");
read.Thenumberofobjectswillbelessthannumifareaderrororend-of-file   exit(1);
 }
isencountered.Ifsizeornumis0,fread()willreturn0andthecontentsofstr
 fread(str,1,10,fp);
and the state of the stream remain unchanged. In case of error, the error
 str[10]='\0';
indicatorforthestreamwillbeset.  printf("\nFirst9charactersofthefileare:%s",str);
fclose(fp);
WRITINGDATATOFILES  WRITINGDATATOFILES 
• Cprovidesthefollowingsetoffunctionstoreaddatafromafile. FILE *fp;
int i;
• fprintf()  fputs()  fputc()  fwrite() char name[20];
float salary;
• fprintf() fp = fopen("[Link]", "w");
if(fp==NULL)
• Thefpritnt()isusedtowriteformattedoutputtostream.Itssyntaxcanbegiven { printf("\n The file could not be opened");
as, exit(1);
intfprintf(FILE*stream,constchar*format,...); }
for(i=0;i<10;i++)
• Thefunctionwritestothespecifiedstream,datathatisformattedasspecified { puts("\n Enter your name : ");
bytheformatargument.Aftertheformatparameter,the functioncanhaveas gets(name);
manyadditionalargumentsasspecifiedinformat. fflush(stdin);
• Theparameterformatinthefprintf()isnothingbutaCstringthatcontainsthe puts("\n Enter your salary : ");
textthathastobewrittenontothestream. scanf("%f", &salary);
fprintf(fp, " (%d) NAME : [%-10.10s] \t SALARY " %5.2f", i, name,
salary);
}
fclose(fp);

fputs() fputc()

Thefputs()isusedtowritealineintoafile.Thesyntaxoffputs()canbegivenas
• Thefputc()isusedtowriteacharactertothestream.
intfputs(constchar*str,FILE*stream);
Thefputs()writesthestringpointedtobystrtothestreampointedtobystream.Onsuccessful • intfputc(intc,FILE*stream);
completion,fputs()returns0.Incaseofanyerror,fputs()returnsEOF. • Thefputc()functionwillwritethebytespecifiedbyc(convertedtoan
#include<stdio.h> unsignedchar)totheoutputstreampointedtobystream. Uponsuccessful
main()
{ completion,fputc()willreturnthevalueithaswritten.Otherwise,incaseof
 FILE*fp; error,thefunctionwillreturnEOFandtheerrorindicatorforthestreamwill
 charfeedback[100];
fp=fopen("[Link]","w");
beset.
 if(fp==NULL)
 {
  printf("\nThefilecouldnotbeopened");
  exit(1);
 }
 printf("\nKindlygivethefeedbackontyhisbook:");
 gets(feedback);
 fflush(stdin);
 fputs(feedback,fp);
fclose(fp);
}
fputc() fwrite()

#include<stdio.h>
main() • Thefwrite()isusedtowritedatatoafile.Thesyntaxoffwritecan
{
 FILE*fp;
begivenas,
 charfeedback[100]; • intfwrite(constvoid*str,size_tsize,size_tcount,FILE*stream);
 inti;
fp=fopen("[Link]","w"); • Thefwrite()functionwillwrite,fromthearraypointedtobystr,
 if(fp==NULL)
 { uptocountobjectsofsizespecifiedbysize,tothestreampointed
  printf("\nThefilecouldnotbeopened");
tobystream.
  exit(1);
 } • Thefile-positionindicatorforthestream(ifdefined)willbe
 printf("\nKindlygivethefeedbackonthisbook:");
 gets(feedback); advancedbythenumberofbytessuccessfullywritten.Incaseof
 for(i=0i<feedback[i];i++)
  fputc(feedback[i],fp);
error,theerrorindicatorforthestreamwillbeset.
 fclose(fp);
}

fwrite() DETECTINGTHEEND-OF-FILE 
main(void) InC,therearetwowaystodetecttheend-of-file
{FILE*fp;
size_tcount; Whilereadingthefileintextmode,characterbycharacter,the
charstr[]="GOODMORNING";
programmercancomparethecharacterthathasbeenreadwiththe
fp=fopen("[Link]","wb");
if(fp==NULL) EOF,whichisasymbolicconstantdefinedinstdio.hwithavalue-1.
{ printf("\nThefilecouldnotbeopened"); while(1)
 exit(1); { c=fgetc(fp); //herecisanintvariable
}  if(c==EOF)
count=fwrite(str,1,strlen(str),fp);   break;
printf("\n%dbyteswerewrittentothefiles”,count);  printf("%c",c);
fclose(fp); }
}
fwrite()canbeusedtowritecharacters,integers,structures,etctoafile.However,fwrite()
canbeusedonlywithfilesthatareopenedinbinarymode .
DETECTINGTHEEND-OF-FILE  ERRORHANDLINGDURINGFILEOPERATIONS 
Theotherwayistousethestandardlibraryfunctionfeof()whichisdefinedin • It is not uncommon that an error may occur while reading
stdio.h.Thefeof()isusedtodistinguishbetweentwocases data from or writing data to a file. For example, an error may
 Whenastreamoperationhasreachedtheendofafile arise
• When you try to read a file beyond EOF indicator
 WhentheEOF("endoffile")errorcodehasbeenreturnedasageneric • When trying to read a file that does not exist
errorindicatorevenwhentheendofthefilehasnotbeenreached • When trying to use a file that has not been opened
• When trying to use a file in un-appropriate mode. That is, writing data to a file
 Theprototypeoffeof()canbegivenas:
that has been opened for reading
intfeof(FILE*fp); • When writing to a file that is write-protected
Feof()returnszero(false)whentheendoffilehasnotbeenreachedandaone • The function ferror() is used to check for errors in the stream. Its prototype
can be given as
(true)iftheend-of-filehasbeenreached. • int ferror ( FILE *stream);
 while(!feof(fp)
 { fgets(str,80,fp);
  printf("\n%s",str);
 }

ERRORHANDLINGDURINGFILEOPERATIONS  clearerr()
Itreturnsazeroifnoerrorshaveoccurredandanon-zerovalueif Thefunctionclearerr()isusedtoclearstheend-of-fileanderrorindicatorsforthestream.Itsprotoypecan
there is an error. In case of an error, the programmer can begivenasvoidclearerr(FILE*stream);

determinewhicherrorhasoccurredbyusingtheperror().
Theclearerr() clears the error for thestream pointed to bystream. Thefunction is used because error
indicatorsarenotautomaticallycleared;oncetheerrorindicatorforaspecifiedstreamisset,operations
FILE*fp;
 charfeedback[100]; onthatstreamcontinuetoreturnanerrorvalueuntilclearerr,fseek,fsetpos,orrewindiscalled.
 inti;  FILE*fp;
 fp=fopen("[Link]","w");
fp=fopen("[Link]","w");  if(fp==NULL)
 printf("\nKindlygivethefeedbackonthisbook:");  { perror("OOPSERROR");
  printf("\nerrorno=%d",errno);
 gets(feedback);   exit(1);
 for(i=0i<feedback[i];i++)  }
 printf("\nKindlygivethefeedbackonthisbook:");
  fputc(feedback[i],fp);  gets(feedback);
 if(ferror(fp))  for(i=0i<feedback[i];i++)
 { printf(“\nErrorwritinginfile”);  { fputc(feedback[i],fp);
  if(ferror(fp))
  exit(1);   { clearer(fp);
 }     break;
} }
 fclose(fp);  fclose(fp);
perror() perror()

• perror()standsforprinterror.Theperror()functionisusedto Ifacalltoperror()ismadewhennoerrorhasactuallyoccurred,thena“Noerror”
handleerrorsinCprograms.Whencalled,perror()displaysa willbedisplayed.Themostimportantthingtorememberisthatacalltoperror()
doesnothingtodealwiththeerrorcondition.
messageonstderrdescribingthemostrecenterrorthatoccurred #include<stdio.h>
#include<stdlib.h>
duringalibraryfunctioncallorsystemcall.Theprototypeof #include<errno.h>

perror()canbegivenas main()
{ FILE*fp;

• voidperror(char*msg); 

fp=fopen("[Link]","w");
if(fp==NULL)
• Theperror()takesoneargumentmsgwhichpointstoanoptional 

{

perror("OOPSERROR");
printf("\nerrorno=%d",errno);
user-definedmessage.Thismessageisprintedfirst,followedbya 


}
exit(1);

colonandtheimplementation-definedmessagethatdescribesthe  printf("\nKindlygivethefeedbackonthisbook:");
 gets(feedback);
mostrecenterror.  for(i=0i<feedback[i];i++)
  fputc(feedback[i],fp);
 fclose(fp);
}
OUTPUT
OOPSERROR:Nosuchfileordirectory
errno=2

Writeaprogramtoprinttherecordsinreverse
FUNCTIONSFORSELECTINGARECORDRANDOMLY  order
fseek() .Thefilemustbeopenedinbinarymode.Usefseek()
#include<stdio.h>
fseek()isusedtorepositionabinarystream.Theprototypeoffseek()canbegivenas, #include<conio.h>
intfseek(FILE*stream,longoffset,intorigin); main()
{ typedefstructemployee
fseek()isusedtosetthefilepositionpointerforthegivenstream.Offsetisanintegervaluethatgivesthe  { intemp_code;
charname[20];
numberofbytestomoveforwardorbackwardinthefile.Offsetmaybepositiveornegative,providedit inthra;
intda;
makessense.Forexample,youcannotspecifyanegativeoffsetifyouarestartingatthebeginningofthe intta;
file.  };
 FILE*fp;
Theoriginvalueshouldhaveoneofthefollowingvalues(definedinstdio.h):  structemployeee;
 intresult,i;
SEEK_SET:toperforminputoroutputonoffsetbytesfromstartofthefile  fp=fopen("[Link]","rb");
 if(fp==NULL)
SEEK_CUR:toperforminputoroutputonoffsetbytesfromthecurrentpositioninthefile  { printf("\nErroropeningfile");
  exit(1);
SEEK_END:toperforminputoroutputonoffsetbytesfromtheendofthefile  }
SEEK_SET,SEEK_CURandSEEk_ENDaredefinedconstantswithvalue0,1and2respectively.  for(i=5;i>=0;i--)
 { fseek(fp,i*sizeof(e),SEEK_SET);
Onsuccessfuloperation,fseek()returnszeroandincaseoffailure,itreturnsanon-zerovalue.For   fread(&e,sizeof(e),1,fp);
  printf("\nEMPLOYEECODE:%d",e.emp_code);
example,ifyoutrytoperformaseekoperationonafilethatisnotopenedinbinarymodethenanon-zero   printf("\nName:%s",[Link]);
  printf("\nHRA,TAandDA:%d%d%d",[Link],[Link],[Link]);
valuewillbereturned.  }
 fclose(fp);
fseek()canbeusedtomovethefilepointerbeyondafile,butnotbeforethebeginning.  getch();
 return0;
}
//Theprogramopensafileandreadsbytesatseveral
differentlocations.

#include<stdio.h>
rewind() main()
rewind()isusedtoadjustthepositionoffilepointersothatthenextI/Ooperationwilltakeplaceatthe {
 FILE *fp;
beginningofthefile.It’sprototypecanbegivenas  fpos_tpos;
voidrewind(FILE*f);  char feedback[20];
rewind()isequivalenttocallingfseek()withfollowingparameters:fseek(f,0L,SEEK_SET);  fp=fopen(“[Link]”,“rb”);
 if(fp==NULL)
fgetpos()  {
Thefgetpos()isusedtodeterminethecurrentpositionofthestream.It’sprototypecanbegivenas   printf(“\nErroropeningfile”);
  exit(1);
 intfgetpos(FILE*stream,fpos_t*pos);  }
Here,streamisthefilewhosecurrentfilepointerpositionhastobedetermined.posisusedtopointtothe  //Readsomedataandthenchecktheposition.
 fread(feedback,sizeof(char),20,fp);
locationwherefgetpos()canstorethepositioninformation.Theposvariableisoftypefops_twhichis  if(fgetpos(fp,&pos)!=0)
definedinstdio.handisbasicallyanobjectthatcanholdeverypossiblepositioninaFILE.  {
  printf(“\nErrorinfgetpos()");
Onsuccess,fgetpos()returnszeroandincaseoferroranon-zerovalueisreturned.Notethatthevalueof   exit(1);
posobtainedthroughfgetpos()canbeusedbythefsetpos()toreturntothissameposition.  }
 fread(feeback,sizeof(char),20,fp);
fsetpos()  printf("\n20bytesatbyte%ld:%s",pos,feedback);
Thefsetpos()isusedtomovethefilepositionindicatorofastreamtothelocationindicatedbythe  
 //Setanewpositionandreadmoredata
informationobtainedin"pos"bymakingacalltothefgetpos().Itsprototypeis  pos=90;
intfsetpos(FILE*stream,constfops_tpos);  if(fsetpos(fp,&pos)!=0)
 {
Here,streampointstothefilewhosefilepointerindicatorhastobere-positioned.pospointstopositioning   printf(“\nErrorinfsetpos()");
informationasreturnedby"fgetpos".   exit(1);
 }
Onsuccess,fsetpos()returnsazeroandclearstheend-of-fileindicator.Incaseoffailureitreturnsanon-zero  fread(feedback,sizeof(char),20,fp);
value  printf("\n20bytesatbyte%ld:%s",pos,feedback);
 fclose(fp);
}

ftell() remove()
Theftellfunctionisusedtoknowthecurrentpositionoffilepointer.ItisatthispositionatwhichthenextI/Owillbeperformed.Thesyntaxof
Theremove()asthenamesuggestsisusedtoeraseafile.Theprototypeofremove()asgiveninstdio.hcanbegivenas,
theftell()definedinstdio.hcanbegivenas:
longftell(FILE*stream); intremove(constchar*filename);
Onsuccessful,ftell()functionreturnsthecurrentfileposition(inbytes)forstream.However,incaseoferror,ftell()returns-1. Theremove()willerasethefilespecifiedbyfilename.Onsuccess,thefunctionwillreturnzeroandincaseoferror,itwill
Whenusingftell(),errorcanoccureitherbecauseoftworeasons: returnanon-zerovalue.

First,usingftell()withadevicethatcannotstoredata(forexample,keyboard)
Second,whenthepositionislargerthanthatcanberepresentedinalonginteger.Thiswillusuallyhappenwhendealingwithverylargefiles RenamingtheFile
Therename()asthenamesuggestsisusedtorenamesafile.Theprototypeis:
FILE *fp; intrename(constchar*oldname,constchar*newname)
char c;
int n; Here,theoldnamespecifiesthepathname ofthe filetoberenamedandthenewnamegivesthenewpathnameofthe
fp=fopen("abc","w");
if(fp==NULL) file.
{ printf("\n Error Opening The File");
exit(1); Onsuccess,rename()returnszero.Incaseoferror,itwillreturnanon-zerovaluewillsettheerrnotoindicatetheerror.
}
while((c=getchar())!=EOF)
putc(c,fp);
n = ftell(fp); CREATINGATEMPORARYFILE
fclose(fp); The tmpfile() function is used to create a temporary file. The tmpfile() opens the corresponding stream with access
fp=fopen("abc","r");
if(fp==NULL) parameterssetas“w+”.Thefilecreatedwithtmpfile()will beautomaticallydeletedwhenall referencestothe file are
{ printf("\n Error Opening The File");
exit(1); closed.Thatis,thefilecreatedwillbeautomaticallyclosedanderasedwhentheprogramhasbeencompletelyexecuted.
}
while(ftell(fp)<n) Theprototypeoftmpfile()asgivenisstdio.hheaderfileis,
{ c= fgetc(fp);
printf('%c", c); FILE*tmpfile(void);
}
fclose(fp); Onsuccess,tmpfile()willreturnapointertothestreamofthefilethatiscreated.Incaseoferror,thefunctionwillreturn
anullpointer[andseterrnotoindicatetheerror.
#include<stdio.h>
intmain(){
FILE*file;
charstr[500];
if(file=fopen("[Link]","r")){
printf("%s",fgets(str,50,file));
}
fclose(file);
return0;
}

#include<stdio.h>
intmain(){
FILE*file;
charstr;
if(file=fopen("[Link]","r")){
while((str=fgetc(file))!=EOF)
printf("%c",str);
}
fclose(file);
return0;
}
WritingDatatoafileinC

#include<stdio.h>
intmain(){
FILE*file;
if(file=fopen("[Link]","w")){
if(fprintf(file,"tutorialsPoint”)>=0)
printf("Writeoperationsuccessful");
}
fclose(file);
return0;
}
A Simple Program
#include <stdio.h>
int main (void) Since we can use a number of
{ files in our program, we will
FILE*fp; require to specify while reading
char ch;
or writing which file we wish to
fp = fopen ("prog.c”,"r");
if (fp == NULL)
use. This is accomplished by
{ using a variable called a file
printf ("Error in opening the pointer.
file");
return (0);
}
ch=fgetc(fp);
while (ch != EOF)
printf ("%c",ch);
fclose(fp);
return (0);
}

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Function fopen () Function fopen ()


/* stdio.h */
• fopen() is more than a create operation – it is a
/* type definition for FILE */
customizable initializer for FILE elements.
/* Pre-condition: – Initialization can set the mode to read, write, or read-
- name is a string and a valid filename (as defined by the OS) write.
- mode is a string and must be one from
– Initialization can set the mode to open (existence is a
{ “r”, “w”, “a”, “r+”, “w+”, “a+” }
Post-condition:
pre-condition) or to create (over-writing is a pre-
- text file named name is open in the appropriate mode
condition).
“r” – open for reading; “w” – create for (over)writing; • fopen returns a pointer to a FILE which points to the
“a” – open or create for writing (at the end); current position in physical file.
“+” – for updating (reading and writing)
*/

FILE *fopen(char *name, char *mode);

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
File Opening Modes File Opening Modes

• When you open afile, you must specify how itis to be opened. This means Adding + to the filemode creates three new modes:
whether to create it from new, overwrite it, or append to it. • "r+"Opensthefileforbothreadingandwriting.(Thefilemust
• Thisisdoneusingoneormorefilemodespecifierswhicharesingleletters"r", exist.)
"b", "w", "a" and + (in combination with the other letters).
• "w+"Opensthefileasanemptyfileforbothreadingand
• "r" - Opens the file for reading. This fails if the file does not exist or cannot
be found. writing. If the file exists, its contents are destroyed.
• "w" - Opens the file as an empty file for writing. If the file exists, its contents • “a+" Opens the file for reading and appending; the appending
are destroyed. operation includes the removal of the EOF marker before new
• "a" - Opens the file for writing at the end of the file (appending) without data is written to the file and the EOF marker is restored after
removing the EOF marker before writing new data to the file; this creates writing is complete; creates the file first if it doesn't exist.
the file first if it doesn't exist.

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Program Files in C – Interfaces


#include <stdio.h> /* stdio.h */
int main (void) /* Pre-condition: f is open
{
FILE*fp; Post-condition:
char ch; - f is closed;return 0 if no error else EOF.
fp = fopen ("prog.c”,"r");
- any buffer is cleared
if (fp == NULL)
{ */
printf ("Error in opening the file"); int fclose(FILE *f);
return (0); /* Pre-condition: f is open in write (or overwrite) mode
}
ch=fgetc(fp); ?????? Post-condition:
while (ch != EOF) - any buffered but unwritten data is written
printf ("%c",ch);
fclose(fp); - return 0 if no error else EOF
return (0); */
} int fflush(FILE *f);

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Files in C – Explanations Copyfilesfromone
toanother
• fclose is the finalization operator – counterpart of fopen, the
initializer
– fclose releases any OS resources being used by the file

• Buffering
– Files are usually stored in persistent storage such as disk
(hard, floppy, compact) or tape – i.e. largebut slow devices
– Most of them have latency (time to rotate head, rewind
tape) that is constant i.e. does not depend on number of
characters reador written.
– Buffers (or temp. storage) in memory is used for speedup

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

Casestudy
CaseStudy–

SimpleCalculator
Toprintdiamondshape
Studentmanagementsystem
Toprintdigitalclock
ElectricityBillCalculator
RockPaperScissorinC

ElectricityCostCalculator ElectricityCostCalculator

The Electricity Cost Calculator project is an application- #include<stdio.h>


#include<stdlib.h>
voidUrban()
{
based micro project that predicts the following month’s #include<conio.h> intamount=0;
#include<string.h> [Link];
electricitybillbasedontheappliancesorloadsused.Visual #include<Windows.h> if([Link]<=30&&[Link]>=0)
#include"MainElectricityBill.h" {
studiocodewasusedtowritethecodeforthisproject.This amount=[Link]*3.25;//3.25isrupees
}
voiddetails()
project employs a multi-file and multi-platform strategy {
elseif([Link]>=31&&[Link]<=100)
{
printf("Enteryourareaname:\n");
People who do not have a technical understanding of  scanf("%s",[Link]);
amount=[Link]*4.70;
}

calculating power bills can use this program to forecast 



printf("Enteryourname:\n");
scanf("%s",[Link]);
elseif([Link]>=101&&[Link]<=200)
{
amount=[Link]*6.25;
their electricity bills for the coming months; however, an 

printf("EnteryourMeterNumber:\n");
scanf("%d",&[Link]);
}
else
electricitybillcalculatormusthavethefollowingfeatures: printf("Enterunitsconsumed:\n"); {
 scanf("%d",&[Link]); amount=[Link]*7.30;
•Allloads’powerrating printf("EnteremailID:\n"); }
scanf("%s",[Link]);
•Unitconsumedperday printf("Enterthepermanentaddress:\n");
printf("****ElectricityBill****\n\n");
printf("Name:%s\n",[Link]);
•Unitsconsumedpermonth,and scanf("%s",[Link]);
printf("Enterthephonenumber:\n");
printf("InUrban,yourelectricitybillis:%d\n",amount);
printf("Unitsyouconsumedpermonth:%d\n",[Link]);

•Totalloadcalculation scanf("%s",[Link]);
}
}
ElectricityCostCalculator
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
voidRural()
{
intamount=0;
[Link];
if([Link]<=30&&[Link]>=0)
{
amount=[Link]*3.15;//3.25isrupees
}
elseif([Link]>=31&&[Link]<=100)
{ 1. Command LineArguments
amount=[Link]*4.40;
} 2. Text File Processing
elseif([Link]>=101&&[Link]<=200)
{
amount=[Link]*5.95;
}
else
{
amount=[Link]*6.80;
}
printf("****ElectricityBill****\n\n");
printf("Name:%s\n",[Link]);
printf("InUrban,yourelectricitybillis:%d\n",amount);
printf("Unitsyouconsumedpermonth:%d\n",[Link]);
}

ACCEPTINGCOMMANDLINEARGUMENTS  ACCEPTINGCOMMANDLINEARGUMENTS 
• Command-lineargumentsaregivenafterthenameofaprogramincommand- The array of character pointers, argv contains the list of all the
lineoperatingsystemslikeDOSorLinux,andarepassedintotheprogramfrom
arguments.argv[0]isthenameoftheprogram,oranemptystringif
theoperatingsystem.
the name is not available. argv[1] to argv[argc – 1] specifies the
• Themain()canaccepttwoarguments,
• Firstargumentisanintegervaluethatspecifiesnumberofcommandline command line argument. In the C program, every element in the
arguments argvcanbeusedasastring.
• Secondargumentisafulllistofallofthecommandlinearguments.
• Thefulldeclarationofmain()canbegivenas, intmain(intargc,char*argv[])
• intmain(intargc,char*argv[]) {inti;
• Theinteger,argcspecifiesthenumberofargumentspassedintotheprogram printf("\nNumberofargumentspassed=%d",argc);
for(i=0;i<argc;i++)
fromthecommandline,includingthenameoftheprogram. printf("\narg[i]=%s",argv[x]);
}
Command Line Arguments Command Line Arguments
#include <stdio.h> • It is possible to pass arguments #include <stdio.h> • The previous program is equivalent
int main(int argc,char *argv[]) int main(int argc, char argv[]) to the unix command:
{ to C programs when they are { cat <filename>
FILE *fp;char ch; executed. int nof = argc-1; • Modify the same program which is
fp = fopen (argv[1],"r"); while (nof > 0)
if (fp == NULL)
• The brackets which follow main {
equivalent to the unix command:
{ are used for this purpose. argc FILE *fp;char ch; cat <filename1> <filename2> …
printf ("Error"); refers to the number of fp = fopen (argv[nof],"r");
return(0); ch = fgetc (fp);
} arguments passed, and argv[]
while (ch != EOF)
ch = fgetc (fp); is a pointer array which points {
while (ch != EOF) to each argument which is printf ("%c",ch);
{ ch = fgetc(fp);
printf ("%c",ch);
passed to main.
}
ch = fgetc(fp); nof--;
} fclose (argv[nof]);
fclose (fp); }
} }

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956

File-Copy Program File-Copy Program


(using functions)
• In Unix, cp command copies the file #include <stdio.h> • You can (and in fact “should”) use
#include <stdio.h>
from source to destination. Its int main(int argc, char *argv[]) functions where ever possible and
int main(int argc, char argv[])
syntax is { required for modular programming.
{
FILE *fp1, *fp2; • Write the same filecopy program
FILE *fp1, *fp2; cp <source filename> <destination char c; using function.
char c; filename> fp1 = fopen( argv[1],"r" );
fp1 = fopen( argv[1],"r" ); • Write aC program to achieve this. fp2 = fopen( argv[2], "w" );
fp2 = fopen( argv[2], "w" );
filecopy (fp1, fp2);
c = getc(fp1) ;
fclose ( fp1 );
while ( c != EOF)
fclose ( fp2 );
{
}
putc( c,fp2);
filecopy(FILE *ifp, FILE *ofp)
c = getc( fp1 ) ;
{
}
char c;
fclose ( fp1 );
while ((c=fgetc(ifp)) != EOF)
fclose ( fp2 );
fputc(c,ofp);
}
}

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956 BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Summary
▪ Fileisasequenceofbytesorganizedonastoragedevice
▪ Filesareclassifiedintotextandbinaryfiles
▪ Filescanbecreatedusingsystemcallsandlibraryfunctions
inC
▪ Everyfilehascertainpropertiescalledmetadata
▪ Basicoperationsonfilesare:create,open,read,writeand
close
▪ Filerelatedsystemcallsare:creat, open, read, write and
close

You might also like