Computer Programming
Computer Programming
PPT Booklet
BITS Pilani
Pilani Campus
Computer Programming
Topicsto beCovered:
Computers& Programming,ProgrammingLanguages
BITSPilani
Pilani Campus Types,ProblemSolvingusingComputers
3 4
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
What is programming? Programming Languages-1
5 6
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
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
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
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
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).
34
BITS Pilani, Pilani Campus
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=?
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=?
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))
• 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
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
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
• 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
69 70
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Data Types
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.
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!
BITSPilani
Pilani Campus
Thank You!
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
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
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]
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
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens
BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens
BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Learning Objectives BASICS in C – Input and Output
46
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
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
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
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.
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
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
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).
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
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
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.
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
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
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]
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
Computer Programming, Lecture 2 BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens
BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
BASICS in C - Tokens
BITS Pilani, Pilani Campus Computer Programming, Lecture 2 BITS Pilani, Pilani Campus
Learning Objectives BASICS in C – Input and Output
46
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
48
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
BASICS in C
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
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.
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
67 68
Computer Programming, Lecture 3 BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
Logical expression
• Logical operators are used to combine more than one • Sample program biggest of two numbers
relational expressions . • Biggest of three numbers
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).
OR Not
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
86
BITS Pilani, Pilani Campus Computer Programming, Lecture 3 BITS Pilani, Pilani Campus
89
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
COMPUTER PROGRAMMING
FUNCTIONS
BITS Pilani Contactsession4 [Link]
Pilani Campus
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.
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
17 18
Computer Programming BITS Pilani, Pilani Campus Computer Programming BITS Pilani, Pilani Campus
FUNCTIONS FUNCTIONS
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
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
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);
}
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
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
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
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
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
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
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
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
73 74
Computer Programming, Session 6 BITS Pilani, Pilani Campus Computer Programming, Session 6 BITS Pilani, Pilani Campus
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
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
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
Start
Statement(s)
False
Test
True
Statement(s)
Statement(s)
a b t
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
int main()
{
float celsius, fahrenheit;
return 0;
}
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.
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…
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
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”)
Example Example
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.
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).
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
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
69
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
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.
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
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
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
}
// if the first condition does not hold
else{
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
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
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.
Simple calculator
43 44
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Use of If statements in function
Use of If statements in function
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
8
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
For Loop
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
(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
1
12
123
1234
12345
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
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
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
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, 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:
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
Forgettingthebasecase→Leadstoinfiniterecursion.
Forgetting the base case → Leads to infinite recursion.
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
int sumIterative(int n) {
int total = 0;
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
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
// 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
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
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
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
17 18
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
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
21 22
BITS Pilani, Pilani Campus BITS Pilani, Pilani Campus
Searching
BITS Pilani
Pilani Campus
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
• 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
• 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
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
Thank You!
Computer Programming
CS_10 Topics to be Covered:
Operations on Arrays: Sorting
BITS Pilani
Pilani Campus [Link] Bubble Sort, Insertion Sort
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.
•In this way, the largest element is moved to the rightmost end at
first.
5
BITS Pilani, Pilani Campus
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
Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands.
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
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
BITS Pilani
Pilani Campus
Thank You!
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];
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
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
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;
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
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
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
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
➢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
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;
}
• 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;
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
/* 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");
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
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
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
#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 arr[5];
int *p[5]=&arr; // Variable p of type pointer is pointing to the
address of an integer array arr.
Pointertostructure Pointertoafunction
Advantageofpointer NULLPointer
• Itwillprovideabetterapproach.
Pointer Program to swap two numbers Pointer Arithmetic
without using the 3rd variable.
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
• 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
#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
3
Pointers to Pointers Pointers to Pointers
printf(“%d”,V); printf(“%d”,***D);
printf(“%d”,*P); =101
printf(“%d”,**Q);
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
Value 1 2 3 4 5
❑ Relationship between Array and pointer.
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
❑ 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));
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]);
Array of Pointers,
1D Array as Parameter
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
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
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
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
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;
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
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
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
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
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)
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
/* 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
❑ 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))
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
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
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;
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.
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));
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
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.
BITS Pilani, K K Birla Goa Campus BITS Pilani, K K Birla Goa Campus
realloc()
Arrays in C
No bounds checking!
Allowed – usually causes no error
array[10] may overwrite b
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));
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.
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.
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.
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:
Tobecalledfrommain()functionas:
Whatistobedone?
• Herealsowearerequiredtodeleteaspecified void
{
delete (node **head)
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;
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
insert
Link to Data Link to
the prev the next
node node
delete
size
Circularlinkedlist
head Tail
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.
•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;
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
temp->next=temp->next->next;
Search an Element on a Linked List Sort Elements of a Linked List
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.
Forexample,ifafunctionhasthedeclaration int(*pointer)(int);//functionpointerdeclaration
floatfoo(int,int); intareaSquare(int);//functiondeclaration
DeclarationofafunctionpointerinCforthefunction foo willbe pointer=areaSquare;
#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;
}
#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;
}
#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;
}
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.
❖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
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
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
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.
#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()
givenstreamandstorestheminthestringstr. printf("\nThefilecouldnotbeopened");
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 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
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
Casestudy
CaseStudy–
SimpleCalculator
Toprintdiamondshape
Studentmanagementsystem
Toprintdigitalclock
ElectricityBillCalculator
RockPaperScissorinC
ElectricityCostCalculator ElectricityCostCalculator
•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
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