UNIT 2-5 PST-NOTES
UNIT 2-5 PST-NOTES
INTRODUCTION
Objective
● To understand the basic components of C Programming Language.
● To learn the primitive data types.
● To learn the various operators
● To understand the library functions
Outcome
● Able to understand the structure of C program
● Able to write the programming expressions.
● Able to write executable expression to solve the problem
Introduction
The basics of any programming language is knowing the letters and symbols used in it. The
next level is forming the statements from the character set with proper grammar. The
grammar in programming language is said to be a syntax. The ordered sequence of
syntactically correct statement forms an executable program. All the above related to the C
programming language is covered in this module.
1. C Fundamentals
The translators of other high-level programming languages such as PHP, PYTHON, PERL were
also developed using C programming language.
1.1 Features
1
1.2 Character Set
The language needs a set of letters and symbols to form an instruction. The C language
supports following set to of character
• Alphabets : A-Z, a-z
• Numbers : 0-9
• Special characters :
, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
- \ ~ + (space)
The character can be used separately or combined with other characters to form a
syntactically and semantically correct instruction.
1.3 Keywords
Keywords are predefined reserved words. Each keyword is associated with a specific feature.
These are used as part of syntax with other characters and symbols provided. All the
keywords in the C program are in lower case. There are totally 32 keywords supported here.
These words can be used as user defined identifiers.
doub
auto int struct
le
break else long switch
enu regist
case typedef
m er
exter
char return union
n
contin signe
for void
ue d
do if static while
default goto sizeof volatile
unsign
const float short
ed
1.4 Identifiers
Identifier is an entity used to denote values and functions in a program. The name of
identifiers is case sensitive. Few examples of identifiers are Name, Mark. Not the first letter
2
of each identifier is given in capital letters. Denoting identifier ‘mark’ will be different from
‘Mark’, because these two differ in case. The rules must be followed while naming the
identifiers.
• Identifier can have all the characters (upper case and lower case) in the alphabet.
• Identifier can have all the numbers but not as the first letter of the identifier.
• No special character other than underscore (_) is allowed.
• Underscore can be in any position of identifier.
• No space is allowed in the identifier.
• No keyword can be identifier
3
Documentation Section
Documenting is a very good quality practice that should be followed in all the programs. The
documentation given on top of the program is used to give the description of the program.
It is a non-executable section. The documentation can also be done in other parts of the
program wherever it is necessary. Documentation is incorporated using a comment
statement.
Comment statements are non-executable statements. There are two types of comment
statements.
• Single Line Comment: Line preceded by double forward slash (//).
• Multiline Comment: More than one lines covered using /*…….*/
The component used to include built-in library files. The library functions are grouped under
the header file. The file with extension (.h). The line preceded by hash (#) and uses the
keyword ‘include’.
Syntax
# include <headerfile.h>
Example
# include <stdio.h>
Pre-processor Directives
The pre-processor directive session used to define the symbolic constants. The programming
statements referring to these constants are processed in the first phase of program
compilation. The directive line preceded by hash symbol (#) and uses the keyword ‘define’.
Syntax
# define ConstantIdentifier value
Example
# define PI 3.14
The constant PI defined in the pre-processor directive can be used anywhere in the program.
Global declaration
The identifiers required for all the modules/functions of the program can be declared in this
section. The declaration is similar to the identifier declaration in the program module.
4
Syntax
ReturnType FunctionName (Parameters);
main() Function
The main() function is the statement from where the execution of the program begins. Each
executable C program should have one main function. The function can receive and return
a value.
Syntax
ReturnType main() // Without parameter
{
}
The first argument is about the number of values passed and the second parameter is an
array type to collect all the values passed.
The identifiers used in the function have to be declared in the beginning of the module. It is
applicable to all the functions in the C program. The function can have other programming
statements next to the identifier declaration.
ReturnType main()
{
Identifier Declaration;
Programming Statements
Syntax
ReturnType FunctionName (Parameter) // Function Header
{
5
Programming Statements (Function Body)
}
The user function declaration and function definition can be combined, in such cases the
definition of the function can be given in the user function declaration section itself.
Void Type
Void means nothing. The Void data type is used when no value is specified. It is mostly used
in return type of function and in pointers which can be given a type later. The keyword is
‘void’.
Basic Data Types
Basic data type is used to allocate the memory and to represent the single values of
Numerical and Character type of data.
6
The character type is used to handle single character values. The value should be covered
within single quotes(‘a’). The character value will be given 1 Byte memory. The character
value is associated with the ASCII value. So, the character identifier can be given a respective
character or can be given a corresponding ASCII character.
Integer Type
The whole number is represented using Integer data type. It is allowed to have both negative
and positive values. Four Bytes of memory is allocated to integer values in the latest version
of C. In the early version it was only 2 Bytes.
Short Type
Short type is used to store the shorter range of integer values. It has been allocated only 2
bytes of memory.
Float Type
The float type is used to handle the real numbers. Four Bytes of memory is allocated to it.
Data Type Keywor Format
d Specifier
Float float %f
Double Type
7
The double type is also to store positive and negative real numbers. Eight bytes of memory
is allocated to it. It is double the size of float type.
Data Type Keywor Format
d Specifier
Double double %lf
Long Type
Long type is used to increase the range of values allowed and also to increase the memory
allocated. Long is combined with Integer and Double data type. Long Integer is allocated 4
Bytes of memory and Long Double is allocated 16 bytes of memory.
Data Type Keyword Format Specifier
8
Figure 1.4: Derived Data type
Array is a collection of values of homogeneous data type. All the values are stored in a
continuous location in memory. The values are accessed using the index position.
The pointer is an address of location stores value of basic data type or user defined data
type. These two data types are discussed more in later modules.
1.7 Constants
Constant is an identifier used to refer to fixed value. The value of the constant identifier has
to be given while declaring that it cannot be assigned a new value. The keyword ‘const’ is
used to denote the constant identifier.
Syntax
Keyword DataType IdentifierName = value;
Example
const int Mark = 97; // Constant definition
9
Assigning a new value to the constant identifier is an error, in another way that the
assignment operator can not be applied on a constant other than the definition statement.
Mark = 100; // Error, cannot assign new value to constant
More than one constant of the same type can be defined in a single statement. In this
identifier are separated by commas. All the constant identifiers must be given a value then
and there.
Syntax
Keyword DataType IdentifierName1 = Value1, IdentifierName2 = Value2;
Example
const int Rate = 10, Code = 5; // Two constants of type integer
1.8 Variables
Variable is an identifier used to refer to a value which can be assigned a new value anywhere
is the programming statement. The variable declared in the declaration statement can be
assigned an initial value or it may be given a value later anywhere in the program.
Syntax
DataType VariableName; // single variable
DataType VariableName = 10; // Variable with initial value
Example
int Amt;
int Mark=97;
The variables of the same type can be declared in a single declaration statement in which
the identifiers are separated by comma (,) operator. Here also the variable may be given a
value if needed.
Syntax
DataType Variable1, Variable2=10; // Multiple variable declaration
Example
int Amt=400, Mark;
1.9 Expression
The evaluable programming statements are called expressions. It contains operators and
operands. The operands may be a constant or variable. Expressions are classified based on
10
the type of value it returns as result of evaluation and types of operators involved in it. The
figure shows all types of expressions.
11
Relational Expression
The expression with relational operators and produces Boolean value as result is called
Relational Expression. There are two values in Boolean type, that are True and False. The
True indicates Boolean value 1 and False indicates Boolean value 0.
Example
10 > 20 // False, Returns 0
Logical Expression
The expression containing logical operator(s) and produces Boolean results is called a Logical
expression. The expression may contain more than one relational expression
Example
40 > 3 && 5<2 // && is logical operator
Pointer Expression
Pointer is a concept in C programming language to access memory location directly. There
are operators (&, *) associated with it. The expression with the pointer operators is called
pointer expression.
Example
int x;
int *a = &x; // Pointer operators
Bitwise Expression
Expression with Bitwise operators and works on bit level of value is called Bitwise operators.
Example
10 << 4 //Left shift bit values of 10 by 4 times
1.10 Statements
Executable part of the program. Each statement is associated with some semantics based on
the operation it performs and the result it produces.
Types
o Declaration Statement
o Input Statement
o Output Statement
o Condition Statement
o Loop Statement
o Evaluation Statement
Declaration Statement
12
The statement declaring the identifier or function is called a declaration statement.
The declaration statement should be terminated with semicolon (;).
Input Statement
The user can give a value during an execution of the program. The statement used to
receive value from the user is called an input statement. Some of the library functions are
used in C programs to get user input. The functions are
o getch()
o getche()
o gets()
o scanf()
Output Statement
The execution result of the program must be shown to the user. The statement used
to display the result of evaluation is called an output statement. The in-built library functions
are used to display the result. The functions are
o printf()
o puts()
Conditional Statement
The statements used to check the condition are called conditional statements. The
statement combines relational expression, conditional expression and in some criteria
arithmetic expression.
Loop Statement
The statement(s) that evaluate the expression and execute the statement(s) repeatedly is
called as loop statement. The number of iterations is depending on the conditional
statement checked either in the beginning or end of the loop statement.
Evaluation statement
The calculatetable expressions are called evaluation statements. All the expressions fall
under the category of evaluation statement.
1.11 Operators
Operators are symbols used to perform some evaluation on values. Based on the number of
operands evaluated the operators are classified as
● Unary operators: operate on one operand
● Binary Operators: operate on two operands
● Ternary Operators: operate on three operands
13
● Increment Operator
● Decrement Operator
● Assignment Operator
● Arithmetic operators
● Arithmetic Assignment Operator
● Relational Operators
● Logical Operators
● Bitwise Operators
● Conditional Operator
Sign Operators
The operator is used to assign a sign value. There two are unary operators.
Operator Example Description
Increment operator
The operator used to increase the value of operand by 1. It is a unary operator. There are
two types of increment, that are post increment and pre-increment
Operator Example Description
++ A = 10; Pre-increment operator. The value of A is
B = ++A; incremented by one and assigned to B.
After the execution value of A is 11 and value of B is
also 11.
A = 10; Post increment operation. The value of A is assigned
B = A++; to B before incrementing. Then the value of A is
increased. After evaluation value of A is 11, B is 10
Decrement Operator
The operator used to decrease the value of operand by 1. It is a unary operator. There are
two types of decrement, that are post decrement and pre-decrement
Operator Example Description
-- A = 10; Pre-decrement operator. The value of A is decreased
B = --A; by one and assigned to B.
14
After the execution value of A is 9 and value of B is
also 9.
A = 10; Post decrement operation. The value of A is assigned
B = A--; to B before decrementing. Then the value of A is
decreased. After evaluation value of A is 9, B is 10
Assignment operator
The operator used to assign the value to the identifier. It is a binary operator. The value on
the right of the operator is assigned to the identifier on the left.
A = 10;
The compound assignment is allowed. That is, more than one assignment operation can be
combined in a single statement.
int A=10;
int B, C;
B=C=A; //Compound Assignment
Arithmetic operator
The operators used to perform mathematical calculations are called arithmetic operators.
All the arithmetic operators are binary operators. It performs an operation on two operands.
Operator Example Description
+ C = 10 +20; Addition operation
- C = 20 -30; Subtraction Operation
* C = 10 * 20; Multiplication operation
/ C = 30 / 10; Division operation
% C = 30 % 4; Modulus operation, it returns the reminder
of an operation
15
*= C = 10; Value of C is multiplied with 20 and the result
C *= 20; 200 assigned to C.
/= C= 30; The value of C is divided by 10 and result 3 is
C /= 10; assigned to C.
%= C = 30; The value of C is divided by 4 and reminder 2 is
C %= 4; assigned to C
Relational Operators
The relational operator is used to compare two values. It is a binary operator. The operator
returns Boolean value as the result of compression.
Operator Example Description
== 10 == 10 Equal to operator. Return true (1) if both the
operands are equal else return false (0).
> 20 > 30 Greater than operator. Returns true (1) if the
first operand is greater than second operand
or else it returns false(0).
< 20 < 30 Less than operator. Returns true (1) if the first
operand is less than the second operand or
else it returns false (0).
>= 30>=40 Greater than or equal. Returns true (1) if the
first operand is greater or equal to the second
operand or else it returns false(0).
<= 30<=40 Less than or equal. Returns true (1) if the first
operand is less than or equal to the second
operand or else it returns false (0).
!= 30 != 40 Not equal. Returns true when both the
operands are not equal. Returns false when
both the operands are equal.
Logical Operators
The logical operators are used to compare two relational expressions. That is to check the
compound condition.
Operator Number of Example Description
Operators
&& Binary Operator (10 > 20) && (4 < 70) AND operator. Returns true
when both the relational
expression returns true. It
returns false when at least
one of the relational
expressions is false.
|| Binary Operator (10 > 20) || (4 < 70) OR operator. Returns true
when at least one of the
relational expressions
16
returns true. It returns false
when both the relational
expressions are false.
! Unary Operator ! (10>20) NOT operator. Returns the
negation of the result of
relational expression.
Bitwise Operators
The operator works on bit values of operand. The value of operands is converted into binary
format internally and applies to the operator. The result of the expression can be received
in any of the basic data types.
Operator Number of Example Description
Operators
& Binary Ans = 1 & 2; Bitwise AND. The binary of 1 is 001, binary of
2 is 010. The AND operation (001 & 010). So,
the result is 000. Final value in Ans is 0.
| Binary Ans = 1 | 2; Bitwise OR. The binary of 1 is 001, binary of
2 is 010. The AND operation (001 | 010). So,
the result is 011. Final value in Ans is 3.
^ Binary Ans = 1 ^ 2; Bitwise XOR. The binary of 1 is 001, binary of
2 is 010. The AND operation (01 | 10). So, the
result is 011. Final value in Ans is 3.
~ Unary Ans = ~5; Bitwise negation. The binary value of 5 is
010. Negated value is 101. Final value in Ans
is 6.
>> Binary Ans = 5 >> 2; Bitwise Right shift. The value in the left of
the operator is shifted to the right by the
number of times given in the right of the
operator.
<< Binary Ans = 5 << 2; Bitwise Left shift. The value in the left of the
operator is shifted to the left by the number
of times given in the right of the operator.
Conditional Operator
The operator used to check the condition. It operates on three operands so it is a ternary
operator. It consists of three components: one is condition, second is true part and third is
false part.
Operator Example Description
17
? : (10>20) ? Conditional operator
printf(“true”) : evaluates the conditional
printf(“false”); expression. If the result of
conditional expression is
True it executes the True
part or else it executes the
false part.
Operators Explanation
+a, -a, ~a Unary minus, unary plus, bitwise Not. All these are unary
operators.
^ Bitwise XOR
| Bitwise OR
18
&& Logical AND operator
|| Logical OR operator
= Assignment operator
Example
acosh()
asin()
19
ceil()
exp()
floor()
log()
ctype.h Character type functions isalnum()
isalpha()
isdigit()
islower()
isspace()
isupper()
tolower()
toupper()
string.h String handling functions strcat()
strcmp()
strcpy()
strlen()
time.h Date time functions setdate()
getdate()
clock()
time()
difftime()
Key Points
The character is set in the C programming language.
The keywords are reserved words.
Expression: Type of expressions,
Executable statements: Syntactically correct and executable statements.
Data Types: Primitive data types, user defined, derived data types.
Operators: Unary operators, binary operators, ternary operators, arithmetic operators,
relational, conditional operators.
20
The inbuilt functions in a header file.
Self Assessment
21
d) a % = 10;
8. Which of the following data type will throw an error on modulus operation(%)?
a) char
b) short
c)int
d) float
9. What is the result of logical or relational expression in C?
a) True or False
b) 0 or 1
c) 0 if an expression is false and any positive number if an expression is true
d) None of the mentioned
14. What is the Priority of C Logical Operators.? NOT (!), AND (&&) and OR (||)
a) NOT (!) > AND (&&) > OR (||)
b) NOT (!) > AND (&&) = OR (||)
c) AND (&&) > OR (||) > NOT (!)
d) AND (&&) = OR (||) > NOT (!)
22
15. What is the output of C program?
int main()
{
int a=9, b=6;
if(a==9 && b==6)
{
printf("Hockey");
}
else
{
printf("Cricket");
}
return 0;
}
a) Cricket Football
b) Hockey Football
c) Football
d) Compiler error
II.Descriptive
23
1. B
2. B
3. D
4. A
5. C
6. A
7. C
8. D
9. B
10. D
11. A
12. D
13. D
14. A
15. B
Summary
This module deals with the basic characters of C programming, constants, variables, different
types of expressions, operators and data types. Each of the above mentioned topics are
given with examples and explanations. The built-in header files and the method of including
the built-in functions are also explained. the program structure to write an executable
program also explained.
24
MODULE 2
OVERVIEW PROGRAMMING IN C
Objective
● To learn the simple program
● To learn the control structure.
● To learn the loop statements.
● To learn to write iterative programming statements.
Outcome
● Able to write interactive program
● Able to write a program with selection statements.
● Able to write a program to execute statement iteratively.
● Able to apply the conditional operators and relational operators to iterate statements.
Introduction
This module deals with primitive data types supported by the C programming language along
with the syntax to define the variables and constants of each type. The execution flow of the
program and the selection statements to change the program flow are also discussed in this
module. The repeated execution of programming statements are accomplished using the
looping statements. The loop statements of the C programming are discussed.
Getting value from the user is called input. The program will be interactive only when it
interacts with the user by getting value from the user and giving results to them. The
program can work on instant values instead of working on a fixed set of values, this is another
advantage of getting the value during the program execution. The programming statement
used to receive the input is called input statement.
The function scanf() is used to get any type of value from the user. It is available in the stdio.h
header file. The value received using this function is assigned to the variable given. This value
can be used further anywhere in the program. The input can be received using this function
at any required point. The execution flow of the program waits until receiving value from
the user.
The scanf() function contains two components one is to specify the format specifier of value
type and other one is to give an identifier. Single scanf() function can be used to get more
than one value. The default delimiter of the value is space ( ). Another delimiter is also
allowed. The variable in scanf() should be preceded by a pointer operator (& - Address of
Operator). It indicates to store the value received in memory location assigned for variable
identifier.
Syntax
25
scanf(“FormatSpecifier”, &VariableName); // To get one value
scanf(“FormatSpecifier1 FormatSpecifier2”, &Variable1, &Variable2); //To get two values
Example 1
int Mark;
scanf(“%d”, &Mark);
The above scanf() receives one value of type integer. So, the format specifier %d has been
specified.
Example 2
int Mark;
float Rate;
scanf(“%d%f”, &Mark, &Rate);
There are many other functions available in C programming to get an input. The respective
header file must be included in the linker/header section of the program to make use of
these functions.
The in-built printf() function available in the stdio.h header file is used to display value on
standard output devices. It takes 1 or more parameters. The parameters are separated using
comma (,). It is used to print string, result of expression and value of identifier.
Syntax
printf(“ ”); //print the content given in double codes
Example 1
printf(“First Output”);
Example 2
26
int a=10;
print(“%d”, a);
Example 3
int a=10;
float f=4.7;
printf("Value 1: %d \nValue 2: %f", a, f);
The simple program given here is to calculate a total of given 5 subject marks. The necessary
identifier is declared in the beginning of the main () function. The scanf() function used to
write the input statement through which the mark of 5 subjects are received. The total of
subject marks is evaluated using arithmetic expression. The output of the program has been
displayed using the output statement. The program used two in-built functions scanf() and
printf(), which are available in the stdio.h header file, that has been included in the header
file section of program structure.
The necessary documentation is done throughout the program using comment statements.
Example
//Program to find Total of 5 subject marks
#include<stdio.h> //Header file
void main ()
{
int M1, M2, M3, M4, M5; // Variable declaration
int Total;
printf("Enter 5 Subject Marks (Leave space between)"); // Output Statement
scanf("%d%d%d%d%d", &M1, &M2, &M3, &M4, &M5); //Input Statement
Total= M1 + M2 + M3 + M4 + M5; // Arithmetic Expression - Integer Expression
printf("Total :%d", Total); //Output Statement
27
Total :448
Control structure determines the flow control of a program. Flow control of a program is that
in what order or sequence, the program statements are executed. The control structure
contains a block of statement which is executed based on the control statement. The control
statement is a statement which contains a control or condition that yields either true or false
after evaluate the condition.
In programming languages, there are four types of flow controls such as
2. Sequential control
3. Selective control
4. Iterative control and
5. Jump control
Sequential control
In sequence control structure, the statements are executed line by line in the order they
appear. Most simple programs are following the sequence control program. These programs
executed starting from first line, then executed next line and finished at the last line without
any omission of lines.
Selection Control
The selection control executes any one block of statements based on the control statement’s
result. The other block of statement is not executed. Most languages support the control
statement with the Logical Expression.
28
Figure 2.2: Selection Statement Flow
A selection control statement is used to execute the selective part of the program. The
selection process of the statement is based on the result produced in the Logical and
Relational expression given in the conditional statement. The selection control statement is
implemented in three different structures. These statements are also referred to as decision
statements.
1. if statement
2. if.. else statement
3. if… else if…else statement
4. switch…case Statement
Iterative Control
The iterative control statement executes a block statement repeatedly. The repetition of
blocks is based on the condition in the control statement.
29
2. do…while loop
3. for loop
Jump Control
The jump control transfers the flow control of execution from one place to another place of
the program without any condition. The unconditional jump has been implemented using
the ‘goto’ statement in C programming Language.
2.5 if Statement
The if statement evaluates the Boolean expression given. If the result is true, the block of
statements is executed; otherwise (in case of False) the next statement after the if statement
block will be executed.
Syntax
if (Conditional Statement)
{
Statement(s) //True Block
}
30
if(num % 2 == 0)
printf(“%d is even.”, num); // True block statement
printf(“\nEnd of Program”);
return 0;
}
2.6 if… else statement
The if…else statement evaluates the conditional statement. If the result is true, the block of
statement(s) will be executed; otherwise (in case of False) the else part block will be
executed.
Syntax
if (Conditional Statement)
{
Statement (s) //True Block
}
else
{
Statement(s) //False Block
}
31
int num;
printf(“Enter an integer: “);
scanf(“%d”, &num);
return 0;
}
Syntax
if (condition1)
{
Statement(s) // Executed when condition1 is true
}
else if (Condition 2)
{
Statements(s) // Executed when condition 1 is false and condition 2 is true
}
else
{
Statements(s) // Executed when both condition1 and condition2 are false.
}
Example
//Checking the eligibility of age to work in an organization
# include <stdio.h>
int main()
{
32
int age;
if ( age < 18 )
{
printf(“Not Eligible to Work”);
}
else if (age >= 18 && age <= 60 )
{
printf(“You are Eligible to Work \n”);
}
else
{
printf(“You are too old to work!1\n”);
}
return 0;
}
The switch..case statement is another decision making statement. It used to check the
nested conditions. It checks the multiple values of one variable. It is used to avoid the
complicated nested ‘if’ and ‘else if’ statements. It can evaluate simple conditions /
expressions. The compound of condition checking is not possible in the switch case.
Syntax
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
33
Figure 2.6: Switch Case Statement Flow
The case statement can have character constant or numerical constant. The default part will
be executed when all the case statements are not matched for the resulting expression in
the switch statement.
Example
// Simple Calculator
// Program to create a simple calculator
# include <stdio.h>
int main() {
char operator;
double n1, n2;
switch(operator)
{
case ‘+’:
printf(“Addition\n”);
printf(“%.1lf + %.1lf = %.1lf”,n1, n2, n1+n2);
break;
case ‘-‘:
printf(“Subtraction \n”);
printf(“%.1lf - %.1lf = %.1lf”,n1, n2, n1-n2);
break;
case ‘*’:
34
printf(“Multiplication \n”);
printf(“%.1lf * %.1lf = %.1lf”,n1, n2, n1*n2);
break;
case ‘/’:
printf(“Division \n”);
printf(“%.1lf / %.1lf = %.1lf”,n1, n2, n1/n2);
break;
Label:
….
Goto Label:
Example
// Program to print Numerical table till 10th multiplication
#include <stdio.h>
int main()
{
int num, i=1;
35
printf(“Enter the number to print table till 10 :”);
scanf(“%d”, &num);
table:
printf(“%d x %d = %d\n”,num, I, num*i);
i++;
if(i<=10)
goto table;
}
2.10 While loop
While loop is being used to execute the continuous group of programming statements
repeatedly until the condition is true. The loop is executed only when the condition is true.
It is an entry control loop.
Syntax
while(condition)
{
statement(s);
}
#include <stdio.h>
int main () {
int n;
36
printf(“Enter the limit :”);
scanf(“%d”, &n);
37
do {
printf("value : %d\n", n);
n--;
}while( n>0);
return 0;
}
2.12 For loop
This loop is used to repeat a group of statements in the specified number of times. It is a
finite loop through which the number of iterations can be predicted in advance. The syntax
contains three components.
o Initialization: Contains assignment expression
o Condition: Contains logical and relational expression
o Increment: Contains arithmetic expression
Syntax
for (initialize; condition; increment) {
statement(s);
}
int main ()
38
{
int n,i;
printf("Enter the limit :");
scanf("%d", &n);
for (i=1;i<=n;i++)
printf("\nValue :%d",i);
return 0;
}
39
int i, j;
for(i=1;i<=n; i++) // outer loop
{
for(j=1;j<=i; j++) // inner loop
{
printf("%d\t", i); // printing the value.
}
printf("\n");
}
}
Example
// Program to print only till 5
#include<stdio.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ", i);
40
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
while{
statement(s)
continue; //takes the control to the beginning of loop
statement(s) // Skipped
}
Example
// Program to print till 20 and skips all the number multiples of 3
void main ()
{
int i;
for(i = 0; i<20; i++)
{
if(i%3==0)
continue;
printf("%d ",i);
}
41
}
Key terms
Data input, Data Output, Flow control, selection statement, loops, iteration, nested loops,
Self Assessment
I Multiple choice Questions
42
int main()
{
int k;
return 0;
}
a) 1 2 3 4 5
b) 1 2 3 4
c) 6
d) 5
4. What is the way to suddenly come out of or Quit any Loop in C Language.?
a) continue; statement
b) break; statement
c) leave; statement
d) quit; statement
43
8. If block always need to be assoicated with a else block?
a) True
b) False
9. If you have to make decision based on multiple choices, which of the following is best
suited?
a) if
b) if-else
c) if-else-if
d) All of the above
10. The continue statment cannot be used with ________
a) for
b) while
c) do while
d) switch
II Descriptive
1. Write an input statement to get one character input.
2. How to apply a ‘for’ loop to iterate statements?
3. Differentiate break and continue statements
4. How can the nested loop be used in a program?
5. Explain how switch statement can be used in place of nested if..else?
6. Write a program to find the sum of N numbers.
7. Write a program to find whether the person is eligible to get a grade in an exam?
Summary
The primitive data types supported by the C programming language along with the syntax to
define the variables and constants of each type are explained in this module. The selection
44
/ control statements used to change the execution flow of the program are also discussed.
The repeated execution of programming statements is accomplished using the looping
statements. The loop statements of the C programming are discussed.
45
MODULE – 3
FUNCTIONS & RECURSIONS
Objective
● To learn modularity in programming style.
● To learn the recursive function.
● To learn to write an efficient program.
Outcome
● Able to write user defined functions.
● Able to apply functions in problems which need modularity.
● Able to implement different level of storage to write optimal program
Introduction
The module deals with the concepts of functions. The detailed syntax of user defined functions
declaration, definition and function call are discussed. The concept of recursive function to execute
the function more than once by calling itself is discussed. The difference between storage classes to
maintain different visibility, accesses and scope of variables have been given in detail to write an
efficient and optimal program.
3.1 Functions
The functions are used to group the set of code under a single name. The set of programming
statements which have been used repeatedly are grouped as a single unit called function. The
functions are reusable codes. That avoids writing the same statements again and again. So it
reduces the size of the program.
The function has to be called explicitly to use it. Calling of the function is also known as
invoking the function. Functions are called by their name. There are two categories of
functions.
1. Built-in functions
2. User defined functions
Built-in functions
The C programming language provides a set of reusable functions as a Library. The functions
are grouped into separate header files based on the similarity of the functionality defined in
it. The respective header file has to be included in the linker/header section of the program to
make use of the built-in function.
46
● Function Definition
● Function Calling
The function prototype is a declaration statement to specify the details about the user
defined function. The function declaration statement has to be written in the Function
declaration part of program structure. The function prototype consists of three parts
o Function Return type
o Function Name
o Parameters / Arguments
Function Return Type: The result of function statements can be displayed within the
function itself using the output statement. In some cases, the function needs to return value
to the location from where it had been invoked.
Function Name: Function name is an identifier. The function is being invoked by its name.
The rules defined for identifier declaration are also applicable for function name declaration
also.
Parameter / Arguments: Parameters are the values passed to the function from the invoking
statement. The function declaration needs to specify the type of parameters to be passed.
More than one parameter is also allowed. In that the parameters are separated by comma
operator.
Syntax
The no parameter function can be specified explicitly using the ‘void’ keyword.
Example
47
3.3 Function Definition
The group of statements of function performing the task is specified in function definition.
The function defining consists two components
1. Function header: The function header should match with the function prototype. The
parameters have to be given along with identifiers. There should not be a semicolon at the
end of the statement.
2. Function body: The function statements covered within curly braces ({ }) is known as
function body.
Syntax
ReturnType FunctionName(ParameterType IdentifierName)
{
Function Body
}
The parameter in function definition is referred to as formal argument. More than one function
parameter is separated by comma operator.
Invoking the function is known as function call. The function is being called by its name.
Syntax
The value passed in the function call is called a formal argument. The value being returned
from the function will be received in a variable given along with the function call statement.
The execution flow will be sequential until the occurrence of selection or conditional
statement. In function components the control will be transferred to function definition
when the function call statement occurs. The control returns back to the function call after
executing all the statements of function or when the return statement occurs.
48
Figure 3.1: Function Execution Flow
Example
The program given here implements all the three components of function. The program is
to find the average of three numbers.
void Average()
{
int num1, num2, num3;
float avg;
printf("Enter three numbers :");
scanf("%d%d%d",&num1,&num2,&num3);
avg = num1 + num2 + num3;
printf("Average :%f", avg);
The main use of the function is reusability. The function statements can be applied on
49
different data for any number of times. Instead of getting the value in the function definition
statement the values can be sent from the function call. The calling statement can decide on
which data the function definition statements work. The value sent from the function calling
statements to the function definition is called parameter.
The function declaration should have the data type of values to be passed. The data types
have to be separated by comma when more than one value is passed.
The value passed from the function calling statement is being received in variables given in
the function header part of function definition.
Actual Argument: The value passed in function call is known as actual argument.
Formal Argument: The parameters in the header part of function definition is known as
formal argument
The actual argument and formal arguments are two different copies. The value of the actual
argument will be copied into variables in the formal argument. The changes in formal
argument will not be reflected in argument. The actual argument has to be passed as
reference or pointer to maintain the values of both the argument as single copy. In such
cases the changes in formal argument gets reflected in actual argument.
Example
The program is to find the average of three numbers. The values are passed as parameters
to function. The average is calculated as function definition and displayed. The different
values can be passed for each time of function call.
#include <stdio.h>
void Average(int, int, int); //Function Declaration
int main()
{
int num1, num2, num3;
printf("Find average of numbers");
printf("Enter three numbers :");
scanf("%d%d%d", &num1, &num2, &num3);
Average(num1, num2, num3); //Function call with parameter
return 0;
}
50
void Average(int n1, int n2, int n3) //function definition
{
float avg;
avg = n1 + n2 + n3;
printf("Average :%f", avg);
The actual parameter can be received as reference in function definition. In that both actual
parameter and formal parameter will refer to the same copy of value in memory. So, the
changes made in function definition will affect the value in the actual parameter also. The
function declaration should have the prototype to indicate the reference parameter by
giving address of operator(*). The formal parameters in function definition are preceded by
operator (*) to receive actual parameters as reference. The function call should have
operator (&) in front of parameters
Syntax
ReturnType FunctionName(DataType1 *, DataType2 *); // function declaration
Example
#include <stdio.h>
void Increment(int *);
int main()
{
int a=10;
printf("Before Function Call %d:",a); //10
Increment(&a);
51
printf("After Function Call %d:",a); //40
return 0;
}
a m
The actual parameter ‘a’ and formal parameter ‘m’ refers to the same memory location. The
formal parameter can access the value in the location only with value of operator(*). So the
changes done by one parameter will affect the other.
The function can return the value to the function calling statement. The ‘return’ statement.
The execution control will be transferred back to the function call whenever the ‘return’
statement occurred in function definition. The data type of the value being returned from
the function has to be given in function declaration and function definition header also. The
function can return a maximum of one value.
Example
The program contains the function Average to find the average of three numbers passed.
The calculated average is returned back to the function call using the ‘return’ statement.
#include <stdio.h>
float Average(int, int, int); //Function Declaration - Return
int main()
{
int num1, num2, num3;
float avg;
printf("Find average of numbers");
printf("Enter three numbers :");
scanf("%d%d%d",&num1,&num2,&num3);
52
avg = Average(num1,num2,num3); //Function call with parameter & Receive Value
printf("Average :%f", avg);
return 0;
}
float average;
average = n1 + n2 + n3;
return average; // return value
3.9 Recursions
The recursion problem solving divides the program into subprograms until there is no more
possibility of sub division. Each division reduces the problem size. In order to complete problem
solving one sub problem call the next and next and so on. Each call will execute the same set of
statements that are called instances. After each execution the control returns to the subprogram
which made a call.
The functional module that makes a conditional call to itself is called recursive function. The instance
of function will be created for each call of the function to itself. So, the instance is a copy of the same
function. As the definition is the same then it includes a function calling statement to itself. So, the
chain will go on. The un-terminatable recursive function call is called infinite recursive. The recursive
functions have to be designed in such a way to handle the infinite recursive. One prompt solution is
making the recursive call conditionally. That’s why the definition of recursive function given as “The
recursive is a function that have conditional call to itself”
53
The program to find the factorial of a given number is given here.
#include<stdio.h>
long int Factorial(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, Factorial(n));
return 0;
}
The identifiers declared in a program will have different visibility and different life space
based on the location where it is defined. By default, the life of identifier and visibility is only
within the block where it is defined. Memory space will be allocated to all the identifiers in
main memory. The content in register memory can be accessed more quickly than the
content in main memory. The lifetime, visibility and the storage allocation can be changed
and handled in the program explicitly to write optimal programs.
The storage classes are used to decide the variable features, that is life time, visibility, scope
and storage. There are four storage classes in programming in C.
● Auto
● Register
● Static
● Extern
Auto: The auto identifier visible only within the function where it is defined. The life and
scope of the auto identifier is only within the function. All the identifiers are auto by default.
54
The auto identifier will be allocated memory in main memory. The keyword ‘auto’ can be
used to mention the same explicitly.
Example
void main()
{
auto int i=10;
f1();
printf(“%d”, i) //10
}
void f1()
{
int i=40;
}
The identifier ‘I’ within main() and ‘i’ within the function f1() are different. Each has a scope
only within their own block. For each time of call to f1() new memory space will be allocated
and value 40 will be assigned.
Register: The register type identifier visible only within the function where it is defined. The
life and scope of the register identifier is only within the function. The register identifier will
allocate memory in the register. The keyword ‘register’ is mentioned in the identifier
declaration. It is good to register only important identifiers in register type because the
system will have a limited number of registers only. The system allocates main memory
when the register is not available. The address of operator & cannot be used.
Static: The identifiers in function will be allocated a memory newly for each function call and
the life of that variable will vanish when the function completes the execution and returns
the control back to the function calling statement. But the static identifiers are allocated a
memory only when the function is invoked, and the life of that exists until the completion of
the entire program. The visibility of static identifiers is only within the function. The
keyword ‘static’ has to be given in the identifier declaration.
55
static int i = 10;
Example
#include <stdio.h>
void f1();
int main()
{
int a = 10;
f1();
f1();
return 0;
}
void f1()
{
static int i=10;
i++;
int j=30;
printf("Static %d", i);
printf("Non Static %d", j);
}
The function f1() contains ‘i’ as static. So that is initialized only once when it is called for the
first time. The value increased will be kept as and continued from for the next function call
also. The output of above code is
Static 11
Non Static 30
Static 12
Non Static 30
External: The external identifier has lifetime, visibility and scope in the entire program. The
external identifier is accessible in another program by including a file in the header file. The
external variable can be defined only in the global declaration part of program structure. The
keyword’ extern’ has been mentioned explicitly to make an identifier as an external storage
class.
56
{
i = 10;
}
The user defined program can be included as a header file. Through which the function
defined in one file can be called from another file. The program included in the header file
should not have a main() function. The concept allows to make the user defined functions
as library functions. The user file should be given within double quotes(“”).
The identifiers in one file can be accessed in another page only when that is declared with
the ‘extern’ keyword.
File2.c
extern int I =10;
void function1()
{
I++;
}
File1.c
# include “File2.c”
extern int I; // defined in another file but referred here
void main()
{
Key term
Self Assessment
I Multiple choice questions.
1. Choose correct statement about Functions in C Language.
57
a) A Function is a group of c statements which can be reused any number of times.
b) Every Function has a return type.
c) Every Function may no may not return a value.
d) All the above.
2. The keyword used to transfer control from a function back to the calling function is
a) switch
b) goto
c) go back
d) return
58
d) volatile
II Descriptive
59
3. A
4. D
5. C
6. D
7. A
8. C
9. A
10. B
Summary
The module covers the concept of functions to implement the reusable coding structure. The
programming syntax of user defined functions declaration, definition and function call are discussed.
The different methods of passing values to the functions are explained. The concept of recursive
function to execute the function more than once by calling itself is discussed. The difference between
storage classes to maintain different visibility, accesses and scope of variables have been given in
detail to write an efficient and optimal program.
60
Module 4
ARRAYS, STRUCTURE and UNION
Objective
To learn derived data type an Array.
To learn user defined data types structure and union.
To implement structure to write application program
Outcome
Able to used array to handle homogeneous data
Able to use structure to write application programs.
Able to identify efficient data types to write a program.
Introduction
The module deals with two derived data types, an array and pointer. The method of
accessing array elements using pointers is discussed. The application program needs to
access more details of different types. The user defined data types structure and union
supports to group more than one different data type in a single group. The model covers the
programming statement to implement structure and union.
4.1 Arrays
Array is a derived data type. It is used to store more than one homogeneous type of values
in a single identifier. Elements in an array are identified by its position, it is referred to as the
index of an element. The index always starts from 0 and the last index is size-1. Single array
can hold any of the primitive data type values. The values of an array will be stored in a
continuous location. So, by knowing the location of the first element the remaining can be
assessed easily.
Value 1 2 3 4
0 0 0 0
Index 0 1 2 3
The index of operator square brackets([]) is used to access an element.
Array Declaration
The declaration of an array is like the declaration of a basic identifier, but the size of an array
has to be given using the index of operator. The size of an array can not be altered later.
Syntax
61
DataType ArrayIdentifierName[Size];
Example
int Marks[10];
The ‘Marks’ in an integer array can store a maximum of 10 elements from index 0 to 9.
The value of an array can be initialized during the declaration itself. The values are covered
within curly braces({}), within which the values are separated by comma(,).
Syntax
Example
Marks[0] = 100;
The value in the 0th position of the index will be changed with new value 100.
The given program receives 5 elements of an array and does the sum of all the elements.
This program can be simplified to a single ‘for’ loop, but to give more clarity about the use
of iteration separate loops are used to get the value and to do the sum of elements.
#include <stdio.h>
int main()
{
62
int Marks[5];
int i, sum=0;
for(i=0;i<5;i++)
{
printf("Enter element %d :", i);
scanf("%d", &Marks[i]);
}
for(i=0;i<5;i++)
{
sum += Marks[i];
}
printf("Total Marks :%d", sum);
return 0;
}
All the elements of an array can be passed as parameters to function. The array identifier
always points to the address of the first element. By knowing that remaining elements can
be accessed. The below ‘printf’ statement displays the address of ‘Marks’ identifier.
So the address of the array can be passed to a function or entire array. In both the
possibilities the changes made in the formal array parameter will be reelected into actual
array parameters.
In order to pass all the elements of an array to function the index of the operator has to be
given in function declaration and function definition. The values of the actual array will be
copied into a formal array.
Syntax
ReturnType FunctionName(DataType []); // Function Declaration
63
}
Example
#include <stdio.h>
void TotalMark(int[]); //Function Declaration
int main()
{
int Marks[5];
int i, sum=0;
for(i=0;i<5;i++)
{
printf("Enter element %d :", i);
scanf("%d", &Marks[i]);
}
TotalMark(Marks); //Function Call
printf("%d", Marks[4]); // 100 , Change in actual value
return 0;
}
void TotalMark(int M[]) // Function Definition
{
int i, sum=0;
for(i=0;i<5;i++)
{
sum += M[i];
}
M[4]=100; //Change mark in index 4
printf("Total Marks :%d", sum);
}
The changes made in formal argument M[4]=100 will be reflected in the actual argument.
The address of the array can be passed to function. In order to pass the address of an array
to function the pointer operator has to be given in function declaration and function
definition. The address of the actual array will be copied into a formal array pointer.
Syntax
64
ReturnType FunctionName(DataType *); // Function Declaration
Example
void TotalMark(int*); //Function Declaration
int main()
{
int Marks[5];
int i, sum=0;
for(i=0;i<5;i++)
{
printf("Enter element %d :", i);
scanf("%d",&Marks[i]);
}
TotalMark(Marks); //Function call
return 0;
}
void TotalMark(int *M) Function Definition
{
int i, sum=0;
for(i=0;i<5;i++)
{
sum += M[i];
}
printf("Total Marks :%d",sum);
}
The more than one dimension of homogenous values can be stored in an array. It consists
of row and column structure. The elements are accessed using row and column index. It uses
an index of operators separately for row and column, one is to specify the row and another
is to specify the column index.
65
5 3 6
8 40 5
0
25 30 8
This is a three rows and three columns array, mathematically it can be referred to as 3X3
matrix. The nested loop structure has to be used to iterate all the elements of an array. The
outer loop can be used to row and the inner loop can be used to access each column of the
row.
Declaration Syntax
DataType ArrayIdentifierName[RowSize][ColumnSize];
Example
int Mat[3][4]; //Three rows and 4 column array
Access Element
The row index and column index have to be specified to access an element. Row index ranges
from 0 to RowSize-1 and column index ranges from 0 to columnSize-1.
Example
The program to find the sum of all the elements in a two dimensional array.
#include <stdio.h>
void TotalMark(int[]);
66
int main()
{
int Mat[3][3];
int i,j, sum=0;
for(i=0;i<3;i++)
{
for(j=0; j<3; j++)
{
printf("Enter element %d %d:", i,j);
scanf("%d",&Mat[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0; j<3; j++)
{
sum += Mat[i][j];
}
}
4.5 String
Syntax
67
Example
char Name[10];
char Name1[10]={‘L’, ‘i’, ‘g’, ‘h’, ‘t’};
char Name2[10]={“Status”};
The individual characters can be accessed using index value. The entire array can be accessed
as string. The format specifier %s is used to access as string. The address of operator & is not
applicable while access as string. The scanf() function given here used to get the value as
string.
char Name[10];
scanf(“%s”, Name); //Get value as string
Example
The program is to find if the given string is palindrome or not. The string is received in a
character array and the library function from string.h are used to do the comparison.
#include <string.h>
#include <stdio.h>
int main()
{
char s1[1000],s2[1000];
int l,i,j;
printf("Enter the string: ");
scanf("%s", s1);
l=strlen(s1);
for(i=l-1, j=0;i>=0;i--,j++)
{
s2[j]=s1[i];
}
s2[j]='\0';
if(!strcmp(s1,s2))
printf("string is palindrome");
68
else
printf("string is not palindrome");
return 0;
}
4.6 Structure
Structure is a user defined data type. It groups more than one primitive data type to create
user defined data types. It represents a record. The storage size of the structure is the sum
of the size of all the data types in it. It is a good practice to define the structure in the global
declaration part of the program.
Define Structure
The keyword ‘struct’ is used to define the structure. All the members of the structure are
covered by curly braces ({}). The definition of structure has to be terminated by semicolon
(;).
Syntax
struct StructureName
{
DataType Identifier1;
DataType Identifier2;
};
Example
struct Book
{
int BookId;
char BookName[100];
};
The identifiers of structure can be defined as like the variable is being defined for primitive
data type. The structure identifier has a separate copy of the structure member.
69
Syntax
struct StructureName IdentifierName;
Example
struct Book b1;
The value for the structure identifier can be given along with the declaration itself. The
values have to be given within curly braces({}). The values are taken in the order of members
within the structure.
The structure members are accessed using the dot (.) operator along with the identifier of
structure.
Syntax
IdentifierName.member;
Example
b1.BookId = 40;
All the operations being performed on primitive type identifiers can also be performed on
structure members.
The structure variable can be defined as an array. This feature is highly applicable for
applications to handle the set of record values as a single unit.
70
Syntax
struct StructureName ArrayIdentifierName[size];
The value can be assigned to each record during the declaration. The value has to be covered
with curly braces.
Each internal curly braces are treated as one record. Individual records are accessed using
index position.
ArrayIdentifierName[index].member = value;
Example
The program here is to find the result of 5 students. The structure of Students has been
defined with necessary members. The structure identifier of size 5 has been defined in the
main() function.
#include <stdio.h>
struct Student
{
int RegNo;
char Name[100];
int m1,m2,m3,total;
float average;
char result;
};
int main()
{
struct Student S[5];
int i;
for (i=0; i<5;i++)
{
printf("Enter Student Register No :");
scanf("%d", &S[i].RegNo);
printf("Enter Student Name :");
71
scanf("%s", S[i].Name);
printf("Enter Mark1 :");
scanf("%d", &S[i].m1);
printf("Enter Mark2 :");
scanf("%d", &S[i].m2);
printf("Enter Mark3 :");
scanf("%d", &S[i].m3);
printf("\nResult of students");
printf("\nReg No\t\tName\t\t\tTotal\t\tAverage\t\tResult");
for (i=0; i<5;i++)
{
printf("\n%d\t\t%s\t\t%d\t\t%f\t\t%c",S[i].RegNo,S[i].Name,S[i].total,S[i].average,S[i].resul
t);
}
}
As like passing primitive data type values to functions, the structure identifiers can also be
passed as parameters to function. The parameter type in function declaration and function
definition should use structure name. The structure can also be passed as value or reference.
72
FunctionName(StructureIdentifier); //Function Call
Example
The program to find the result of student marks has been done in this program. The result
calculation is implemented in a functional module. The value received for the structured
identifier in main() is passed as parameter to the calculation function.
#include <stdio.h>
struct Student
{
int RegNo;
char Name[100];
int m1,m2,m3,total;
float average;
char result;
};
void ResultCalculation(struct Student);
int main()
{
struct Student S;
int i;
}
void ResultCalculation(struct Student STemp)
73
{
STemp.total = STemp.m1 + STemp.m2 + STemp.m3;
STemp.average = STemp.total/3;
printf("\n%d\t\t%s\t\t%d\t\t%f\t\t%c",STemp.RegNo,STemp.Name,STemp.total,STemp.av
erage,STemp.result);
The structure having the pointer type member to itself is known as self-referential structure.
The linked data structure can be formed using self-referential structure. structures pointing
to the same type of structures are self-referential in nature.
Syntax
struct StructureName
{
DataType MemberIdentifier;
struct StructureName *MemberIdentifier; //Self reference
};
Example:
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
74
}
The ‘link’ is a pointer member of type node. The pointer points to itself.
4.10 Union
Union is a user defined data type groups primitive data type into a single unit. The primitive
data identifiers declared within the union are called as members. The functionality of the
union is the same as the structure, but the only difference is that the size of the union is the
size of the data member with maximum size. All the members in the union share a single
storage space. The keyword ‘union’ is used to define the union data type.
Union Declaration
union UnionName
{
DataType Identifier;
DataType Identifier1;
};
UnionIdentifier.Member
Example
union Item
{
int Id;
float Price;
char Avail;
};
int main()
{
75
union Item Code;
Code.Id=1;
Code.Price=4.5;
printf("%f",Code.Price); //4.5000
printf("\n%d",Code.Id); // 1083179008 – Garbage value
return 0;
}
Among the data members of the union, the float member takes the highest storage. So the
union Item has been allocated a memory of 4 bytes. The values assigned to all the data
members will occupy the same space. The member a value assigned as latest only available
in memory. In above code Code.Price have been assigned as latest. It over writes the content
assignment Code.Id=1. So the printing of Code.Id=1 is showing garbage value.
Key Term
Array , homogeneous, index, multi dimensional, address, pointer, string, structure, record,
union, self-reference, member.
Self Assessment
I.Multiple Choice Questions
1. Which of the following are themselves a collection of different data types?
a) string
b) structures
c) char
d) all of the above
76
4. What is the correct syntax to declare a function Display() which receives an array of
structure in function?
a) void Display(struct *var);
b) void Display(struct *var[]);
c) void Display(struct var);
d) none of the above
9. The______ function returns the number of characters that are present before the
terminating null character.
a) strlength()
b) strlen()
c) strlent()
d) strchr()
10. In C, if you pass an array as an argument to a function, what actually gets passed?
a) Value of elements in array
b) First element of the array
77
c) Base address of the array
d) Address of the last element of array
II.Descriptive Questions
1. Define an Array.
2. How the elements of an array are accessed?
3. Write a program to find the determinant of matrix and matrix transpose.
4. In what factor does the union differ from Structure?
5. How can self referential structure be used to implement list data structure?
6. How are the array and address of memory related?
7. Write a program to swap two numbers by passing the address of variables to function.
8. Write a program to find the total marks of 10 students by using array of structures.
9. Write a program to implement library system using structures.
10. Write a program to compare two strings which are stored in character array.
Module 5
78
POINTERS and FILES
Objective
To learn the concepts of pointers.
To handle possible errors during program execution.
To use files in a program.
Outcome
Able to use pointer in program
Able to relate pointers and an array
Able to use files in a program to store content permanently.
Introduction
The module covers the concept of pointer, pointer declaration. The various operations in the
pointer and the relationship between pointers and an array has been given an explanation.
The content in a file is non-volatile. The programming syntax to do various operations in a
file and the built-in functions supporting the file operations are discussed in detail.
5.1 Pointers
Pointer is a variable that can store the memory address of another variable. The value of
another variable can be accessed using the pointer variable. It allows quick access of value
and also supports low level programming. The address operator (&) and value of operator
(*) used to point the address and value in that address respectively. The operator (*) used
to declare the pointer variable and also used to access the value from the location being
pointed by the pointer variable.
The address of a variable is accessed by mentioning the address of the operator in front of
the pointer variable. The value of operator is mentioned in front of the pointer variable to
access the value in a memory location being pointed by it.
The pointer variables are classified based on the value in a location being pointed by it.
• Integer pointer : The pointer identifier holds the address of location having
integer value.
• Float Pointer : The pointer identifier holds the address of location having float
type value.
• Character Pointer : The pointer identifier holds the address of location having
character type value.
• Structure Pointer : The pointer identifier holds the address of user defined
structure type identifier.
DataType *IdentifierName;
79
Example
int *pt;
The identifier ‘pt’ is a pointer that can point to a memory address having integer value. In
other words, the address of an integer variable can be assigned to an integer pointer.
int m=10;
int *pt;
pt = &m;
The value of the location being pointed pointer identifier can be accessed using value of
operator (*). After assigning an address of variable to pointer variable, both of them will
point to the same memory location. So the value being changed by either of that will reflect
in both.
Example
int m=10;
int *pt;
pt = &m;
printf(“%d”, *pt); // 10
(*pt) ++;
printf(“%d”, *pt); // 11
printf(“%d”, m); // 11
m++;
printf(“%d”, *pt); //12
The expression (*pt) ++ increases the value in a location being pointed by a pointer variable
pt.
Assume that X101 is the address located for variable ‘m’ and it is having a value 10.
m
X101 10
pt
X201 X101
The value in location X101 can be accessed using ‘m’ using ‘pt’ which has this address.
80
5.4 Passing Pointer to Function
The changes made on formal arguments within the function will be reflected in actual
pointer arguments. The actual pointer argument may have the address of another variable.
So the changes in formal argument also affect the value of the original variable.
Example
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
printf("%d",i); // 11
return 0;
}
Pointer ‘p’ points to the variable ‘i’. The pointer variable is passed as parameter to function,
so formal argument ‘ptr’ will also have the address of ‘i’. So the changes made through the
formal parameter ‘ptr’ will do the changes in value ‘i’.
i
X101 10
The statement p=&i assigns the address of ‘I’ (X101) to the location allocated for ‘p’.
p
X201 X101
After function call value in a location of ‘p’ will be assigned to the location allocated for
formal pointer parameter ‘ptr’.
ptr
X301 X101
81
An array is a homogeneous data structure. The values of an array will be stored continuously.
The array identifier contains only the address of starting location. So array itself a pointer
The value of operator (*) from an address X100 access the value in that location. Adding an
integer with integer pointer will add 4 bytes. In order to access the 3rd value that is the
value in index 2, either the index operator ([]) can be used or the index can be added with
an array variable. The expression a[2] is same as *(a+2).
The array identifier can be assigned to another pointer variable simply using an assignment
operator. Thereafter both will point to the same memory location. So the changes made
through one variable will affect another.
int a[5]={10,20,30,40,50};
int *p;
p=a; // Assign address of ‘a’ to pointer ‘p’
p[1]=44;
printf(“%d”, a[1]); //44 – Changed using pointer
Array of pointers is an array of pointer variables; it is also known as a pointer array. It stores
the address of pointer variables or memory locations.
Syntax
DataType *PointerIdentifier[size];
Example
82
int *ptr[3];
The pointer ‘ptr’ can store 3 addresses which are having integer values.
a
Xc120 10
b
Xd130 20
c
Xx310 30
ptr
Xssm2 X400
The pointer ‘ptr’ will be allocated 3 continuous locations and the starting address will be
assigned to ‘ptr’. Each location of the ‘ptr’ pointer array is stored with addresses of three
different integer variables. The values of all these three variables can be accessed using a
single pointer array ‘ptr’.
printf("%d",*ptr[0]); //10
printf("%d",*ptr[1]); //20
printf("%d",*ptr[2]); //30
Internally the expression gets evaluated faster than evaluating the direct variable. Accessing
the pointers is faster than accessing identifiers, because the pointer has a direct address, so
it reduces the address lookup time.
5.7 Files
83
The collection of information stored is known as a file. It is permanent. The content of the
file can be accessed in the C Program. The value given as an input and received as an output
from the program can be stored in file for later access.
The library functions available in the stdio.h header file are used to do all the file operations.
The functions and the descriptions are given in table.
Function Syntax Description
fopen() FilePointer = fopen(..) Function used to open a file
fclose() fclose(FilePointer) Function used to close the file
getc() int getc(FilePointer) Function to get one character
from file. The return value in
a form of ASCII.
putc() putc(Value, FilePointer) Writes one character into a
file at the location being
pointed by file pointer.
getw() int getw(FilePointer) The function returns an
integer value.
putw() putw(IntegerValue, The function writes the
FilePointer) integer value into file. The
value may be a constant or
variable.
fprintf() fprintf(FilePointer, Write the value into a file.
“FormatSpecifier”, Used to write any type of
Value) value. Value can be given
through the identifier. The
second parameter is used to
specify the format specifier of
value.
fscanf() fscanf(FilePointer, Read the value from the file.
“FormatSpecifier”, The type of value is specified
identifier) using the format specifier in
the second parameter. The
84
value read from the file will
be stored in a variable given
in the third parameter.
fseek() fseek(FilePointer, int The function used to move
offset bytes, int position) the file pointer. The second
parameter specifies the
number of bytes to be
moved. The third parameter
is to specify the position from
where the move to be taken.
Three position values are (0 –
From beginning, 1 – from
current, 2 – from end). Used
for random access of files.
ftell() long ftell(FilePointer) Function returns the current
position of file pointer. Used
for random access of files.
File Open
The file can be opened using FILE structure. The mode of opening a file has to be specified
while opening a file. The file should exist when opened in read mode. The file will be created
newly when it opens for write operation and also when it is not available. Opening an existing
file for write operation will clear previous content.
The file will contain read and write pointers. Both the pointers will be in the beginning of the
file when it is opened. The read pointer moves ahead when read operation is performed on
file. The write pointer will move ahead when the write operation is performed.
File Mode
The file can be opened in three modes, the respective symbolic character has to be given
while opening a file.
Read : r
Write : w
Append: a
Syntax
FILE *FilePointer = fopen(“FileName”, “Mode”);
Example
More than one mode of file open is allowed, the respective symbolic characters have to be
given together.
85
File close
The file has to be closed after completing all the operations. The file pointer pointing to the
file will be removed from the memory. The function close() is used to close the file.
FilePointer.close();
File Read
The content of the file can be read as character, line or record. The respective functions have
to be used. The file open mode has to give a symbolic constant as ‘r’. The file should already
exist to open in read mode. Opening a non-existing file is an error. The content of the file
can be read until it reaches the end of file (EOF).
Example
The program reads the content of the file. Each time it reads one character using the getc()
function. The reading operation continues until it reaches EOF.
#include <stdio.h>
void main()
{
char c;
FILE *fp;
fp = fopen(“File1.txt”, “r”);
while(c=getc(fp)!=EOF)
printf(“%c”, c);
fclose(fp);
}
File Write
The write operation allows to write the content into a file. The file has to be opened inwrite
mode. The symbolic constant for write operation is ‘w’. The non-existing file will be created
when it has been opened in write mode. The content of the existing file will be erased while
opening it in a write mode. The file can be opened in append mode to retain the existing
content and continue the write operation.
Example
The program writes the line received in the gets() function into a file using the fprintf()
function.
#include<stdio.h>
void main()
{
char c[100];
FILE *fp;
86
fp= fopen(“Sample.txt”, “w”);
printf(“Enter the string :”);
gets(c);
fprintf(fp,”%s”,c);
fclose(fp);
}
Key Terms
Pointe, File, Array, Array of Pointers, Open, Close, Write, Read, Seek, File Pointer, Sequential
access, random access, Record.
Self Assessment
I. Multiple Choice Questions
1. A pointer is
a) A keyword used to create variables
b) A variable that stores address of an instruction
c) A variable that stores address of other variable
d) All of the above
2. Which of the following does not initialize ptr to null (assuming variable declaration of a as
int a=0;)?
a) int *ptr = &a;
b) int *ptr = &a – &a;
c) int *ptr = a – a;
d) All of the mentioned
3. One of the uses for function pointers in C is __________
a) Nothing
b) There are no function pointers in c
c) To invoke a function
d) To call a function defined at run-time
4. What does the following declaration mean?
int (*ptr)[10];
a) ptr is array of pointers to 10 integers
b) ptr is a pointer to an array of 10 integers
c) ptr is an array of 10 integers
d) ptr is an pointer to array
5. What is (void*)0?
a) Representation of NULL pointer
b) Representation of void pointer
87
c) Error
d) None of above
II.Descriptive questions
88
3. Differentiate Array of Pointer and Pointer to an Array.
4. What are the file modes supported in C programming?
5. What is the use of EOF?
6. Write a program to find the sum of an element in an array using pointer to an array.
7. Write a program to read alternate characters from a file.
Summary
The concept of pointer and pointer declaration are discussed in this module. The various
operations in the pointer and the relationship between pointers and an array are explained.
The programming syntax to do various operations in a file and the built-in functions
supporting the file operations are discussed in detail.
Further Reading
Online Links
https://www.programiz.com/c-programming
https://www.geeksforgeeks.org/c-programming-language/
https://www.tutorialspoint.com/cprogramming/index.htm
Glossary Terms
Identifier – The name given to the value or function being referred to in the program. The
naming convention must be followed.
Keywords – The predefined reserved words provided in the programming language to write
syntactic oriented semantic statements.
Variable – Variable is an identifier used to refer to a value in a program, The value of a
89
variable is modifiable anywhere in a programming statement.
Constant – Constant is an identifier used to refer to a value in a program, The value of a
constant is not modifiable anywhere in the program.
Control Statement: The programming statement used to change the sequential flow of
program execution. They are also referred to as selection control statements.
Iterative statement: - The programming statement used to execute a set of statements more
than once based on the condition.
Function – A group of programming statements grouped under a single name for reusability.
The function reduces the size of the program.
Call By Value – Calling the function definition by passing value or identifier as actual
argument is call by value. The actual parameter and formal parameter are treated as two
separate copies.
Call By Reference – Calling the function definition by passing an address of identifier as actual
argument is call by reference. The actual parameter and formal parameter both will refer to
the value in the same location.
Storage Class - The storage class is a concept used to define an identifier in various scope,
lifetime and visibility. Auto, Static, Register and Extern are the four storage classes in C
Programming.
Recursive - The function calling to itself is called as recursive. The self reference has to be
maintained on a recursive conditional basis.
Pointer – Pointer is a concept used to refer to the memory address of a value. It provides
faster execution of programs.
Array – A derived data type stores more than one homogeneous type values.
Multi-Dimensional Array: An array used to store the value in rows and column order to form
a matric.
Structure – Structure is a concept used to define a user defined data type.
Self-Referential Structure – The structure having a data member of its own type is Self-
Referential structure.
Union – The union is a concept used to define a user defined data type. Size of the union will
be equal to the size of the data member with maximum storage space. All the data members
will share the same memory location.
Array of Pointer – The pointer having addresses of more than one value is known as an array
90
of pointer.
Address of Operator – The operator used to refer or access the memory address of a value.
The Address of operator symbol is (&).
Value of Operator – The operator used to refer or access the value through memory address.
The value of operator symbol is (*).
File mode – The file mode is to specify the purpose of opening a file. Their basic file modes
are read, write and append.
File pointer – The pointer identifier of FILE structure type used to point the address of a file
in a memory location.
EOF – The character constant points to the end of file content.
91