0% found this document useful (0 votes)
19 views94 pages

Lab Week3&4 Abdullah Emam

The document is a lab manual for Programming with C at Fayoum International Technological University, detailing the curriculum for first-year students in the Information Technology program. It covers control statements, including if, switch, and their variants, with examples and exercises to illustrate their usage. The manual is prepared by Abdullah Emam and includes evaluation criteria for lab performance and submission.

Uploaded by

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

Lab Week3&4 Abdullah Emam

The document is a lab manual for Programming with C at Fayoum International Technological University, detailing the curriculum for first-year students in the Information Technology program. It covers control statements, including if, switch, and their variants, with examples and exercises to illustrate their usage. The manual is prepared by Abdullah Emam and includes evaluation criteria for lab performance and submission.

Uploaded by

Abdullah Emam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Fayoum International Technological University

Student Name: ……………………………………………………………….…………


Student Group: …………………………………………………………………………

Lab Instructor : Abdullah Emam

Lab Performed In: School Lab

Programming with C - Lab


Semester - II

Fayoum International Technological University


Faculty of Technology
Information Technology Program
First Year – Essentials in C programming
Academic Year (2024/2025)

______________________
Course Instructor / Lab Engineer

Prepared by Abdullah Emam

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 1
LAB POINTS SCORE
Lab Performance [10] 0 1 2 3 4 5
Lab Participation
Lab Activity Completion on the Same Day

Lab Submission [10] 0 1 2 3 4 5


Completeness & Correctness
Required Conclusion & Results

No of Checks
SUB TOTAL
TOTAL SCORE

LAB POINTS SCORE


Lab Performance [10] 0 1 2 3 4 5
Lab Participation
Lab Activity Completion on the Same Day

Lab Submission [10] 0 1 2 3 4 5


Completeness & Correctness
Required Conclusion & Results

No of Checks
SUB TOTAL
TOTAL SCORE

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 2
WEEK – 4
1 Control Statements (Conditional): If and its Variants
2 Switch (Break)
3 Sample C Programs
------------------
Control Statements (Conditional – Decision Making)
We have a number of situations where we may have to change the order of execution of
statements based on certain conditions, or repeat a group of statements until certain
specified conditions are met. This involves a kind of decision making to see whether a
particular condition has occurred or not and then direct the computer to execute certain
statements accordingly.
C language possesses such decision-making capabilities and supports the following
statements known as control or decision-making statements.
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement

Decision making with ‘if’ statement


The if statement is a powerful decision-making statement and is used to control the flow
of execution of statements. It is basically a two-way decision statement and is used in
conjunction with an expression. It takes the following form:
𝑖𝑓(𝑡𝑒𝑠𝑡 𝑒𝑥𝑝𝑟𝑒𝑠𝑠𝑖𝑜𝑛)
It allows the computer to evaluate the expression first and then depending on whether
the value of expression (or condition) is true (1) or false (0), it transfers the control to a
particular statement. This point of program has two paths to follow, one for the true
condition and the other for the false condition.
Entry

test
expression?

True

Two-way Branching

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 3
Programming with C - Lab

Examples of decision making, using if statement are


1. if (bank balance is zero) borrow money
2. if(age is more than 60) person retires

The if statement may be implemented in different forms depending on the complexity of


conditions to be tested.
1. Simple if statement
2. if…else statement
3. Nested if…else statement
4. else if ladder
Simple ‘if’ statement
The general form of a ‘simple if’ statement is
Syntax:
if(test_expression)
{
statement_block;
}
statement_x;
‘statement_block’ may be a single statement or a group of statements. If the test
expression is true the ‘statement_block’ will be executed, otherwise the ‘statement_block’
will be skipped and the execution will jump to ‘statement_x’.

Flowchart for Simple If

Example: To check whether student is passed or failed.


/*Program to check whether student is passed or failed*/
#include<stdio.h>
main()
{
int marks;

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 4
Programming with C - Lab

printf("Enter student marks: ");


scanf("%d",&marks);
if(marks>50)
printf("Student Passed");
if(marks<50)
printf("Student Failed");
}

Output:
(1) Enter student marks: 55
Student Passed

(2) Enter student marks: 40


Student Failed

If-Else Statement
The if-else statement is an extension of the ‘simple if’ statement. The general form is
Syntax:
if(test_expression)
{
true-block-statements;
}
else
{
false-block-statements;
}
statement_x;

If the test_expression is true, then the true-block-statement(s), immediately following the


if statement are executed; otherwise the false-block-statement(s) are executed. In either
case, either true-block-statements or false-block-statements will be executed, not both.

Flowchart for If Else

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 5
Programming with C - Lab

Example: Program to check whether given number is even or odd


/*Program to check whether given number is even or odd*/
#include<stdio.h>
#include<conio.h>
main()
{
int num; =
printf("Enter number: ");
scanf("%d",&num);
if(num%2 == 0)
printf("%d is even number",num);
else
printf("%d is odd number",num);
}

Output:
(1) Enter number: 53
53 is odd number
(2) Enter student marks: 42
42 is even number

Nested If… Else Statement


When a series of decisions are involved, we may have to use more than one if…else
statement in nested form as follows:
Syntax:
if(test_condition1)
{
if(test_condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 6
Programming with C - Lab

If the test_condition1 is false, the statement-3 will be executed; otherwise it continues to


perform the second test. If the test_condition2 is true, the statement-1 will be executed
otherwise statement-2 will be evaluated and then the control is transferred to the
statement-x;
Flowchart for Nested If…Else

Example: Program to find the largest of three numbers


/*Program to find the largest of three numbers*/
#include<stdio.h>
main()
{
int a,b,c;
printf("Enter the three values: ");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
printf("%d is largest",a);
else
if(b>a && b>c)
printf("%d is largest",b);
else
printf("%d is largest",c);

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 7
Programming with C - Lab

Output:
Enter number: 5 6 7
7 is largest

Else If Ladder
There is another way of putting if’s together when multipath decisions are involved. A
multipath decision is a chain of if’s in which the statement associated with each else is an
if. It takes the following general form:

Syntax:
if(condition1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-3)
statement-3;
...
...
...
else if(condition-n)
statement-n;
else
default-statement;
statement-x;

This construct is known as else if


ladder. The conditions are evaluated
from the top downwards. As soon as
a true condition is found, the
statement associated with it is
executed and the control is
transferred to statement-x. When all
the n conditions become false, then
the final else containing the default-
statement will be executed.

The logic of execution for ‘else if


ladder statements’ is shown in the
flowchart below.

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 8
Programming with C - Lab

Example: Program to illustrate concept of else-if ladder to select color


/*Program to select color*/
#include<stdio.h> main()
{
int n;
printf("Enter any number between 1 & 4 to select color: \n");
scanf("%d",&n);
if(n==1)
{
printf("You selected Red color");
}
else if(n==2)
{
printf("You selected Green color");
}
else if(n==3)
{
printf("You selected yellow color");
}
else if(n==4)
{
printf("You selected Blue color");
}
else
{
printf("No color selected");
}

}
Output:
(1) Enter any value between 1 & 4 to select color: 4
You selected Blue Color
(2) Enter any value between 1 & 4 to select color: 1
You selected Red Color
(3) Enter any value between 1 & 4 to select color: 5
No color selected

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 9
Programming with C - Lab

SWITCH-CASE STATEMENT
When one of many alternatives is to be selected we can design a program using 'if'
statement, to control the selection. However, the complexity of such programs in C
number of alternatives increases. The program becomes difficult to read and follow.

The switch test or checks the values of given variable (or expression) against a list of case
values and when a match is found a block of statements associated with that case is
executed. The switch makes one selection when there are several choices to be made.

The general form of switch statement is

Syntax:
switch(expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break;
:
:
default: default-block;
break;
}
statement-x;

The expression is an integer expression or characters. Value-1, value-2, ... are constants or
constant expressions and are known as case labels. Each of these values should be unique
within a switch statement.

Block-1, block-2, ... are statements lists and may contain 0 or more statements. There is
no need to put braces ({ }) around these blocks. Case labels end with a colon(:).

When a switch is executed the value of the expression is compared against the value
(value-1, value-2, ...). If a case is found whose value of expression then block of
statements that follows the case are executed.

The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement, transferring the control to the statement-x
following the switch statement.

The default is an optional case, when present, it will be executed if the value of the
expression does not match with any of the case values.

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 10
Programming with C - Lab

If not present, no action takes place and if all matches fail; the control goes to the
statement-x.

The selection process of switch statement is illustrated in flow chart:

Example 1: Program to print words corresponding numbers below 9


/*Print words corresponding numbers below 9*/
#include<stdio.h>
main()
{
int n;
printf("Enter a number(0-9): ");
scanf("%d",&n);
switch(n)
{
case 0: printf("Zero");
break;
case 1: printf("One");
break;
case 2: printf("Two");
break;
case 3: printf("Three");
break;
case 4: printf("Four");
break;
case 5: printf("Five");
break;

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 11
Programming with C - Lab
case 6: printf("Six");
break;
case 7: printf("Seven");
break;
case 8: printf("Eight");
break;
case 9: printf("Nine");
break;
default: printf("More than 9");
}
}
Output:
Enter a number (0-9): 3
Three
Enter a number (0-9): 10
More than 9

Algorithms for Conditional and Case Control

Example: Write an algorithm to find the largest of three numbers.


Step 1. Read the numbers a, b, c
Step 2. If a>b AND a>c then
Step 3. Print ''a is the largest number"
Step 4. Else If b>a AND b>c then
Step 5. Print ''b is the largest number"
Step 6. Else Print ''c is the largest number"
Step 7. End of program.

Example: Write an algorithm to calculate pay salary with overtime.


[Salary depends on the pay rate and the number of hours worked per week. However, if you work more
than 40 hours, you get paid time-and-a-half for all hours worked over 40.]
Step 1. Read hours and rate
Step 2. If hours ≤ 40 then
Step 3. Set salary as hours * rate
Step 4. Else
Step 5. Set salary as [40 * rate + (hours – 40) * rate * 1.5]
[salary = pay rate times 40 plus 1.5 times pay rate times (hours worked - 40)]
Step 6. Print salary
Step 7. End of program.

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 12
Programming with C - Lab

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 13
Programming with C - Lab

Sample C Programs
1. To check whether number is +ve, -ve or zero
/*Program to check number is positive, negative or zero*/
#include<stdio.h>
main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n>0)
printf("Number is Positive");
if(n<0)

printf("Number is Negative"); if(n==0)


printf("Number is Zero");
}
Output:
Enter a number: -2
Number is Negative
Enter a number: 0
Number is Zero
Enter a number: 6
Number is Positive

2. To check two numbers are equal


/*Program to check whether the given numbers are equal*/
#include<stdio.h>
#include<conio.h>
main()
{
int num1,num2;
printf("Enter 2 numbers: ");
scanf("%d %d",&num1,&num2);
if(num1==num2)
printf("Both the numbers are equal");
}
Output:
Enter 2 numbers: 6 6
Both the numbers are equal
Enter 2 numbers: 3 2

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 14
Programming with C - Lab
3. Check whether given character is vowel or consonant.
/*Program to check whether the given character is vowel or consonant */
#include<stdio.h>
main()
{
char x;
printf("Enter letter: ");
x=getchar();
if(x=='a'||x=='A'||x=='e'||x=='E'||x=='i'||x=='I'||x=='o'||x=='O'
||x=='u'||x=='U')
printf("The character %c is a vowel",x);

else
printf("The character %c is a consonant",x);
}
Output:
Enter letter: p
The character p is a consonant
Enter letter: a
The character a is a vowel
4. Program to calculate square of numbers whose least significant digit is 5.
/*Program to calculate square of numbers whose LSD is 5 */
#include<stdio.h>
main()
{
int s,d;
printf("Enter a Number: ");
scanf("%d",&s);
d=s%10;
if(d==5)
{
s=s/10;
printf("Square = %d %d",s*s++,d*d);
}
else
printf("\nInvalid Number");
}

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 15
Programming with C - Lab
Output:
Enter a Number: 25
Square = 625

Enter a Number: 32
Invalid Number

5. To obtain the electric bill as per the charges below


No of Units Consumed Rates (In Rs.)
500 and above 5.50
200-500 3.50
100-200 2.50
Less than 100 1.50

/*Program to obtain electric bill as per meter reading*/


#include<stdio.h>

main()
{
int initial,final,consumed;
float total;
printf("Initial & Final Readings: ");
scanf("%d %d",&initial,&final);
consumed = final-initial;
if(consumed>500)
total=consumed*5.50;
else if(consumed>=200 && consumed<=500)
total=consumed*3.50;
else if(consumed>=100 && consumed<=199)
total=consumed*2.50;
else if(consumed<100)
total=consumed*1.50;
printf("Total bill for %d units is %f",consumed,total);
}
Output:
Initial & Final Readings: 1200 1500
Total bill for 300 units is 1050.000000

Initial & Final Readings: 800 900


Total bill for 100 units is 250.000000

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 16
Programming with C - Lab
6. To check whether letter is small, capital, digit or special symbol.
/*Program to check small,capital,digit or special*/
#include<stdio.h>
#include<conio.h>
main()
{
char x;
printf("Enter character: ");
scanf("%c",&x);
if(x>='a' && x<='z')
printf("Small letter");
else if(x>='A' && x<='Z')
printf("Capital letter");
else if(x>='0' && x<='9')
printf("Digit");
else
printf("Special Symbol");
}
Output:
Enter character: *
Special Symbol
Enter character: T
Capital letter

Enter character: a
small letter
Enter character: 6
Digit

7: Program to check whether a letter is vowel or consonant


/*Program to check whether given letter is vowel or consonant*/
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf("Enter Character: ");
ch = getch();
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 17
Programming with C - Lab
case 'o':
case 'O':
case 'u':
case 'U': printf("Character %c is Vowel",ch);
break;
default: printf("Character %c is Consonant",ch);
}
}

Output:
Enter Character: a
Character a is Vowel

Enter Character: B
Character B is Consonant
8: Program to calculate Arithmetic Operations depending on operator.
/*Print words corresponding numbers below 9*/
#include<stdio.h>
main()
{
int a,b; ;
printf("Enter any arithmetic operator: ");
scanf("%c",&ch);
printf("Enter two numbers: ");
scanf("%d %d",&a,&b);
switch(ch)
{
case '+': printf("\nThe sum is %d",a+b);
break;
case '-': printf("\nThe difference is %d",a-b);
break;
case '*': printf("\nThe product is %d",a*b);
break;
case '/': printf("\nThe quotient is %d",a/b);
break;
case '%': printf("\nThe remainder is %d",a%b);
break;
default: printf("Not Valid Operator");
}
}
Output:
Enter any arithmetic operator: *
Enter two numbers: 8 4
The product is 32

Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 18
Programming with C - Lab
1-Write a program to check whether number is negative or positive
using if….else.

Logic : if number >=0 then positive else negative


#include<stdio.h>
void main()
{
int x;
printf (“Enter any number :- “);
scanf (“%d”,&x); //input value of x
if (x>=0)
//check for positive number
printf (“%d is a positive number”,x);
else
printf (“%d is negative number”,x);
}

2-Write a program to enter a number and display whether the number is positive or
negative using ternary operator.
Ternary operator is a control statement similar to if…else statement: Syntax of
ternary operator is: (Condition)?true statement :false statement ; Where condition is
formed using variable and operator (relational operator), true statement is the
statement to be executed when the condition is true and false statement will be
executed when the condition is false (just like else statement). It is used when logic
is very simple in conditional statement.

Program:
Page 19
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab
#include<stdio.h>
void main()
{
int x;

printf (“Enter any number :- “);


scanf (“%d”,&x); //input value of x
(x>=0) ? printf (“Number is positive”):printf(“Number is negative”);
}

3- Write a program to display greatest number out of two numbers using ternary
operator.

4- Write a program to enter your age, and display the message whether “eligible to
vote” or “not eligible to vote”.

5- Write a program to check whether number is even or odd.

6-Write a program to enter a number and display whether number is divisible by 5


or not.

7- Write a program to enter a number and check number is divisible by


2 and 4 both.

8- Write a program to enter a number and check whether number is divisible by 3


and 7.

9- Write a program to check character is vowel or consonant .(Example


Page 20
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab
of nested if…else)

10- Write a program to enter two numbers and find the greatest number.

11- Write a program to enter three numbers and find the smallest number.

12-Write a program to enter number and check whether divisible by 4, 12 or both.

13-Write a program to enter a number between (1 to 7) and display accordingly


Sunday to Saturday using switch case. Use goto statement to continue program till
user’s press Y(Yes)

12- Write the output of the following program :

#include<stdio.h>
void main()
{
int n;
printf(“Enter no. between 1 and 3 “);
scanf(“%d”,&n);
switch(n)
{
case 1: printf(“\n1”);
break;
case 2: printf(“\n2”);
break;
case 3: printf(“\n3”);
break;
default: printf(“\nWrong choice”);
break;
}
}

13- Write a program to enter two numbers x and y and also enter an operator (+,-
Page 21
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab
,*,/,%). Find out the result using switch case.Continue your program till the user
press ‘Y’ to continue.

14- Write a program to display numbers from 1 to 10 using goto statement.


Note: goto can be used to repeat statement for number of times. Goto is controlled
by if…else statement. Remember when we use goto statement in program the speed
of a program is getting slow. It’s better to use loop instead of goto statement. Goto
is not considered as good programming practice.

#include<stdio.h>

int main()
{
int x=1;

labelx:
printf(“\n%d”,x);
x=x+1;
if(x<=10)
goto labelx;
}

14-Predict the output of the following program.


#include<stdio.h>
void main()
{
int x=1;
A:
/*to clear screen*/
printf("\n%d",x);
x=x+1;
B:
printf("\n%d",x+1);
x=x+2;
if(x<=10)
goto A;
Page 22
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab
else if(x<=20)
goto B;
else
return 0;
}

15- Predict the output of the following program:


#include<stdio.h>
void main()
{
int a=10;
Label1:
printf(“\n%d”,a);
a=a+10;
Label2:
printf(“\n%d”,a);
a=a+20;
if(a<=100)
goto Label1;
else if(a>=100 && a<=300)
goto Label2;
return 0;
}

Page 23
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab
LAB EXERCISE #3

Objective(s):
To understand the programming knowledge using Decision Statements (if, if-else,
if-else-if ladder, switch and GOTO)

Program: Write a program to print whether a given number is even or odd.

#include<stdio.h>
Int main()
{
int num;
printf("Enter the number: ");
scanf(“%d”,&num);
if(num%2==0)
printf(“\n %d is even”, num);
else
printf(“\n %d is odd”, num);
return 0;
}

Output:
Enter the number: 6
6 is even

Page 24
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab
Programs List :
1. Write a Program to Check Whether a Number is Prime or not.
2. Write a program to find the largest and smallest among three entered numbers
and also display whether the identified largest/smallest number is even or odd.
3. Write a program to compute grade of students using if else adder. The grades are
assigned as followed:
Marks Grade
b. marks<50 F
c. 50≤marks< 60 C
d. 60≤marks<70 B
e. 70≤marks<80 B+
f. 80≤marks<90 A
g. 90≤mars≤ 100 A+

4.Write a program to find whether a character is consonant or vowel using


switch statement.

#include <stdio.h>
int main()
{
char ch;
printf(“Enter any alphabet:”); //input alphabet from user
scanf(“%c”, &ch);
switch(ch)
{
case „a‟:
case „A‟:
printf(“Vowel”);
break;
case „e‟:
case „E‟:
printf(“Vowel”);
break;
case „i‟:
case „I‟:
Page 25
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab
printf(“Vowel”);
break;
case „o‟:
case „O‟:
printf(“Vowel”);
break;
case „u‟:
case „U‟:
printf(“Vowel”);
break;
default:
}
}

5.Write a program to print day name using switch case.


6.Write a program to determine whether the input character is capital or small
letter, digits or special symbol.
7.Write a program to check whether a date is valid or not.
8. Write a program to check whether a number is positive, negative or zero
using switch case.

Page 26
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
Programming with C - Lab

Prepared by IT & CSE Page 27


Programming with C - Lab

Prepared by IT & CSE Page 28


Programming with C - Lab

increment a pointer, its value is increased by the length of the data type that it points to.
This length is called the scale factor.
The number of bytes used to store various data types depends on the system and can
be found by making use of the sizeof operator.

POINTERS AND ARRAYS

When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations. The base
address is the location of the first element (index 0) of the array. The compiler also defines
the array name as a constant pointer to the first element. Suppose we declare an array x
as follows:
int x[5] = {1,2,3,4,5};
Suppose the base address of x is 1000 and assuming that each integer requires 2 bytes, the
five elements will be stored as follows:

The name x is defined as a constant pointer pointing to the first element x[0] and
therefore the value of x is 1000 i.e., x = &x[0] = 1000.
Similarities between pointer and array
A pointer and an array are similar in some respects. Array name x contains address of the
first element of array. &x[0] == x
As x contains address of first element, it can be used as pointer to access the value of first
element as shown below.
a = *x;
The above statement stores the value of first element of array x into variable x. This is
same as a = x[0];
So an array name can be used as a pointer and the reverse is also true. The following
code will use an array as a pointer and a pointer to access an array.

int *p;
int a[5],x;
p = a; /*p now points to first element of a*/
*p = 20; /*stores value 20 in first element of array a[0]*/
x = *a; /*will store value of first element of the array into x*/

Prepared by IT & CSE Page 29


Programming with C - Lab

An array in memory Pointer pointing to an array

All the following will store value 20 into 0th element of the array.
*p = 20; p[0] = 20; *a = 20; a[0] = 20;
Pointer Arithmetic:
All that an array name contains is the starting address of array. For the program to access
the complete array just by using starting address, we need to understand pointer
arithmetic.
Adding an integer to pointer
When you add an integer to pointer then the value (address) of pointer is incremented by
the size of data type to which pointer points. See the following example:
int *p;
int a[5];
p=a; /*p points to first element of the array*/
p++; /*p now points to second element a[1]*/
p is a pointer to int. So when you increment p by one it is incremented by number of bytes
occupied by int, which is 2 bytes. If the value of p is 1000 then when you increment p, it
becomes 1002. If a float pointer (float *fp) is increment by one, then it is incremented by
4 bytes, as float occupies 4 bytes.
Subtracting an integer from pointer
Subtracting a pointer makes pointer pointing to previous element. That means the pointer
is decremented by the size of the data type to which the pointer is pointing.

Example: Program to access an array using pointer


#include<stdio.h>
main()
{
int *p,i;
int a[5];
clrscr();
p=&a;
printf("Enter 5 elements: ");
for(i=0;i<5;i++) {
scanf("%d",p);
p++;

Prepared by IT & CSE Page 30


Programming with C - Lab
}
p=a;
printf("The entered 5 elements: ");
for(i=0;i<5;i++) {
printf("%d ",*p);
p++;
}
printf("\nDisplay array in reverse order: ");
for(--p;p>=a;p--)
printf("%d ",*p);
getch();
}
Output:
Enter 5 elements: 4 5 2 6 3
The entered 5 elements: 4 5 2 6 3
Display array in reverse order: 3 6 2 5 4

Pointers to two-dimensional arrays


Pointers can be used to manipulate two dimensional arrays as well. In one-dimensional
array x, the expression
*(x+i) or *(p+i)
represents the element x[i]. Similarly, an element in a two-dimensional array can be
represented by the pointer expression as follows:
*(*(a+i)+j) or *(*(p+i)+j)

The figure illustrates how this expression represents the element a[i][j]. The base address
of the array a is &a[0][0] and starting at this address, the compiler allocates contiguous
space for all the elements, row-wise. That is, the first element of the second row is placed

Prepared by IT & CSE Page 31


Programming with C - Lab

immediately after the last element of the first row and so on. Suppose we declare an
array a as follows:
int a[3][4] = {{15,27,11,35},{22,19,31,17},{31,23,14,36}};
The elements of a will be stored as shown below:

If we declare p as an int pointer with the initial address of &a[0][0], then


a[i][j] is equivalent to *(p+column_size x i+j) => *(p+4*i+j)

You may notice that, if we increment i by 1, the p is incremented by 4, the size of each
row, making p element a[2][3] is given by *(p+2*4+3) = *(p+11).
That is the reason why, when a two-dimensional array is declared, we must specify the
size of each row.
Example: Program to illustrate pointer to two-dimensional array
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,*p;
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr();
printf("Elements of An Array with their addresses\n\n");
p=&a[0][0];
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
printf("[%5u]-%d ",(p+3*i+j),*(p+3*i+j));
printf("\n");
}
printf("\nElements of array:\n\n");
for(i=0;i<3;i++) {
for(j=0;j<3;j++)
printf("%d ",*(*(a+i)+j));
printf("\n");
}
getch();
}
Output:
Elements of An Array with their addresses
[65482]-1 [65484]-2 [65486]-3
[65488]-4 [65490]-5 [65492]-6

Prepared by IT & CSE Page 32


Programming with C - Lab
[65494]-7 [65496]-8 [65498]-9

Elements of array:

1 2 3
4 5 6
7 8 9

Dissimilarities between pointer and array name


We used till now a pointer and array name interchangeably. But they are not identical in
all respects. The following are the differences between array name and a pointer:
❑ First array name is constant and a pointer is a variable. You can change the value of
pointer by storing an address into it. But you cannot change the address stored in array
name. Because, if the address of the first element is lost then the total array will be
inaccessible.
❑ A pointer is not initialized, whereas an array name is initialized to the address of the first
element of the array.

POINTERS AND CHARACTER STRINGS


A String is an array of characters, terminated with a null character. Like in 1-D arrays, we
can use pointer to access the individual characters in a string.

Example: Program to read string from keyboard and display it using character pointer.
#include<stdio.h>
#include<conio.h>
main()
{
char name[15],*ch;
printf ("Enter Your Name:");
gets(name);
ch=name; /* store base address of string name */
while (*ch!='\0') {
printf ("%c",*ch);
ch++;
}
getch();
}

Output:
Enter Your Name: KUMAR
KUMAR

Example: Program to find length of a given string including and excluding spaces using
pointers.
#include<stdio.h>
#include<conio.h>

Prepared by IT & CSE Page 33


Programming with C - Lab
main()
{
char str[20],*s;
int p=0,q=0;
clrscr();
printf ("Enter String:");
gets(str);
s=str;
while (*s!='\0') {
printf ("%c",*s);
p++; s++;
if (*s==32) /* ASCII equivalnet of ' ' (space)is 32*/
q++;
}
printf ("\nLength of String including spaces: %d",p);
printf ("\nLength of String excluding spaces: %d",p-q);
}

OUTPUT:
Enter String: POINTERS ARE EASY

POINTERSAREEASY
Length of String including spaces: 17
Length of String excluding spaces: 15

POINTER to POINTER
It is possible to make a pointer pointing to another pointer. Then it becomes a pointer
pointing to another pointer, which in turn points to a value. The following example, will
use a pointer to a pointer to an integer.
int **pp; /*pointer to pointer to integer*/
int *p; /*pointer to integer*/
int v=30; /*integer*/
p=&v; /*make p pointing to v*/
pp=&p; /*make pp pointing to p*/

/*now all the below will display 30*/


printf(“Value: %d”,v);
printf(“Value: %d”,*p);
printf(“Value: %d”,**pp);

When you use **pp the following step will be taken


➢ First the value of pp is taken. According to figure it is 200.
➢ Then the value from memory location 200 is taken, which is 300 in the example.
➢ Then from that location, the value is taken which is 30.

Prepared by IT & CSE Page 34


Programming with C - Lab

Array of Pointers
It is possible to have an array of pointers. In this case each element of the array will be a
pointer.
The following code will create an array of 5 integer pointers and then make the first
element pointing to an integer variable.
int *p[5]; int v=30;
p[0]=&v;
printf("%d",v);
printf(" %d",*p[0]);
Each element of the array is a pointer that can point to an integer. But remember, unless
initialized all elements of the array will be uninitialized pointer. So make sure you use
elements only after making them point to a valid location.
The following figure shows how an array of pointer looks like in memory.

Example: Program to display strings using array of pointers.


#include<stdio.h>
main()
{
char st[10][20],*p[10];
int i;
clrscr();
printf("Enter 10 strings: ");
for(i=0;i<10;i++)
gets(st[i]);
printf("\nDisplay 10 strings: ");
for(i=0;i<10;i++) {
p[i]=&st[i];
puts(p[i]);
}
getch();
}

Prepared by IT & CSE Page 35


UNIT - 5

WEEK - 10
1 Structures: Definition, Syntax, Nested Structures
2 Pointers to Structures
3 Unions: Definition, Syntax
------------------
Structures
We often have to store a collection of values. When the collection is of the same type
then array is used to store values. When the collection of values is not of the same type
then a structure is used to store the collection.
An Array is a group of related data items or collection of homogeneous data that share a
common name i.e. it contains elements of same datatype. If we want to represent a
collection of data items of different types using a single name, then we cannot use an
array.
C supports a constructed data type known as structure which is a method of packing data
of different types. A structure is a convenient tool for handling a group of logically related
data items. It is a collection of heterogeneous data that share a common name.
A structure is a collection of items which may be of different types referenced commonly
using one name. Each item in the structure is called as a member.
Declaration of Structure
A structure is also called user-defined data type. When a structure is declared a new data
type is created. You declare a structure using keyword struct. The following is the syntax
to declare a structure:
struct [structure-name]
{
members declaration
}[variables];

If we want to store details of an employee we have to create a structure:


struct employee
{
int eno;
char ename[20];
char eadd[100];
float bs;
};

Prepared by IT & CSE Page 36


Programming with C - Lab

Memory Image for structure employee

The above is a structure declaration for employee structure. Employee structure contains
members eno, ename, eadd, and bs. Each member may belong to a different type of
data. When you declare a structure you just create a new data type - struct employee.
Structure name is otherwise known as tag. The tag name may be used subsequently to
declare variables that have the tag’s structure.
Note that the above declaration has not declared any variables. It simply describes a format called
template to represent information as shown below:

eno Integer
ename 20 Characters
eadd 100 Characters
bs Float

While declaring a structure you can also declare variables by giving list of variables after
right brace. Members of a structure may be of standard data type or may be of another
structure type.
struct point
{
int x,y;
}fp,sp; /*sp and fp are two structure variables*/

Declaring Structure variable


You can declare structure variables using struct structname. You can use a variable of any
structure anywhere in the program where the structure is visible. Normally structures are
declared at the beginning of the program and outside all functions, so that they are global
and available to the entire program.
Following is the declaration of structure variable e1:
struct employee e1;

When the variables are created to the template then the memory is allocated. The
number of bytes occupied by structure variable is equal to the total number of bytes
required for all members of the structure. For example, a variable of struct employee will
occupy 126 bytes (2+20+100+4). So, 126 bytes are allocated for the employee structure
variable e1.

Prepared by IT & CSE Page 37


Programming with C - Lab

Accessing a member
A structure is a collection of members. All members are to be accessed using a single
structure variable. So to access each member of the structure you have to use member
operator (.).
We can assign values to members of a structure in a number of ways. The members
themselves are not variables. They should be linked to structure variables in order to
make them meaningful members.
structure-variable.member
The following is an example for accessing member of a structure variable.
struct employee x;
x.eno=10; /*place 10 into eno number*/
scanf("%f",&x.bs);
strcpy(x.ename,"Santosh");
printf("%d %s %f",x.eno,x.ename,x.bs);
Once you use member operator to access a member of a structure, it is equivalent to a
variable of the member type. That means x.eno in the above example is equal to any
integer variable as eno is of integer type.
Structure Initialization
We can initialize a structure variable by listing out values to be stored in members of the
structure within braces after structure variable, while declaring the variable.
main()
{
struct st_record
{
int rno;
char name[20];
int weight;
float height;
};
struct st_record st1={1, "Ashok",60,180.75};
struct st_record st2={2, "Balu",50,185.72};


}
C language does not permit the initialization of individual structure members within the
template. The initialization must be done only in the declaration of the actual variables.
Example: Program to demonstrate how to use structure
main()
{

Prepared by IT & CSE Page 38


Programming with C - Lab
struct employee
{
int eno;
char ename[20];
char eadd[100];
float bs;
};
struct employee x;
int hra;
printf("Enter employee details: ");
scanf("%d",&x.eno);
gets(x.ename);
gets(x.eadd);
scanf("%f",&x.bs);

if(x.bs>15000)
hra = 1500;
else
hra = 1000;

printf("Details of employee\n");
printf("Employee Number: %d\n",x.eno);
printf("Employee Name: %s\n",x.ename);
printf("Employee Address: %s\n",x.eadd);
printf("Employee Basic Salary: %f\n",x.bs);
printf("Employee Salary: %f\n",x.bs+hra);
}

Array of structures
Just like how we create an array of standard data types like int, float etc, you can create
an array of structures also. An array of structures is an array where each element is a
structure. You can declare an array of structures as follows:
struct employee edet[10];

Now edet is an array of 10 elements where each element can store data related to an
employee. To access eno of 5th element you would enter:
edet[5].eno=105;

Example: Program to take marks details of 10 students and display the name of the
student with highest marks.
main()
{
struct smarks
{

Prepared by IT & CSE Page 39


Programming with C - Lab
char sname[20];
int marks;
};
struct smarks marks[10];
int i,pos;
for(i-0;i<10;i++)
{
printf("Enter student [%d] name: ",i);
gets(marks[i].sname);
printf("Enter student [%d] marks: ",i);
scanf("%d",&marks[i].marks);
}
pos=0;
for(i=1;i<10;i++)
{
if(marks[i].marks > marks[pos].marks)
pos=i;
}
printf("Student %s has got highest marks %d\n",
marks[pos].sname,marks[pos].marks);
}

An array of smarks structure

Structures and assignment


We can copy the value of one structure variable to another when both the structure
variables belong to same structure type. For instance if you have two variables called x
and y of structure employee then you can copy value of y to x using simple assignment
operator.
x=y;
Copying one structure variable to another is equivalent to copying all members of one to
another. Interesting fact about structure assignment is even members that are of string
type are copied. Remember copying a string to another is not possible without using

Prepared by IT & CSE Page 40


Programming with C - Lab

strcpy function. But when you copy one structure variable to another of the same type,
the data (including strings) will be automatically copied.
Assume that x and y are variables of employee structure, copying y to x would copy even
ename and eadd though they are strings. Because copying a structure variable to another
structure variable is equivalent to copying the entire block (allocated to y) to another (block
allocated to x) in memory.

Pointer to Structure
A pointer can also point to structure just like how it can point to a standard data type.
The process is similar to what we have already seen with standard data types.
struct employee *p; /*a pointer pointing to struct employee*/
Now p can be made to point to e1 (a variable of struct employee) as follows:
struct employee *p;
struct employee e1 = {1, "Srikanth","Vizag",65000};
p=&e1; /* make p point to e1 */
To access a member of a structure variable using a pointer to structure, use arrow
operators. Arrow operator is combination of hyphen and greater than symbol (->).
pointer-to-struct -> member
In order to use p, which is a pointer to struct, to access the data of e1, which is a struct
employee variable, use arrow operator as follows:
printf("%d %f", p->eno, p->bs);
In fact you can also use * operator to access a member through pointer. The following is
the expression to access member x using pointer p.
x = (*p).x;
Remember parantheses around *p are required as without that C would take member
operator (.) first and then indirection operator (*), as . has higher precedence than *. That
means *p.x would be taken as *(p.x) by C and not as (*p).x.
Example: Program to illustrate pointer to structure variables concept.
#include<stdio.h>
main()
{
struct employee
{
int eno;
char ename[20];
float bs;
};

Prepared by IT & CSE Page 41


Programming with C - Lab
struct employee e,*emp;
clrscr();
printf("Enter employee name: ");
gets(e.ename);
printf("Enter employee number: ");
scanf("%d",&e.eno);
printf("Enter employee salary: ");
scanf("%f",&e.bs);
emp = &e;
printf("\nEmployee Details:\n");
printf("%d\t%s\t%0.2f",emp->eno,emp->ename,emp->bs);
getch();
}
Output:
Enter employee name: BalaGuru
Enter employee number: 201
Enter employee salary: 27000
Employee Details:
201 BalaGuru 27000.00

Nested Structure
A structure may contain a member that is of another structure type. When a structure is
used in another structure, it is called as nested structure.
Let us add a new member – date of joining (dj) to employee structure. DJ is consisting of
members’ day, month and year. So it is another structure. Here is the complete declaration
of both the structures.
struct date
{
int d;
char m[15];
int year;
};
struct employee
{
int eno;
char ename[20];
float bs;
struct date dj;
};
The figure above depicts the memory image of struct employee. It contains four
members where member DJ again contains another three members.

Prepared by IT & CSE Page 42


Programming with C - Lab

Accessing nested structure


To access members of nested structure, first we need to access the member in the outer
structure and then the member of nested structure. For example, the following example
shows how to initialize and access nested members.

struct employee e1 = {1,"Ken",10000,{10,"October",2012}};

printf("Date : %d-%s-%d",e1.dj.d,e1.dj.m,e1.dj.y);

Example: Program to illustrate structure within structure concept.


#include<stdio.h>
main()
{
struct student
{
int rno;
char name[20];
int marks;
struct dob
{
int d;
char mon[20];
int y;
}db;
}s[2];
int i;
clrscr();

for(i=0;i<2;i++)
{
printf("Enter Student [%d] Roll Number: ",i+1);
scanf("%d",&s[i].rno);
fflush(stdin);
printf("Enter Student [%d] Name: ",i+1);
gets(s[i].name);
printf("Enter Student [%d] Marks: ",i+1);
scanf("%d",&s[i].marks);
printf("Enter Student [%d] Date of Birth: ",i+1);
scanf("%d %s %d",&s[i].db.d,s[i].db.mon,&s[i].db.y);
}
printf("\nStudents Details:\n");
for(i=0;i<2;i++)
{
printf("\n%d\t%s\t%d\t%d-%s-%d\n",s[i].rno,s[i].name,
s[i].marks,s[i].db.d,s[i].db.mon,s[i].db.y);
Prepared by IT & CSE Page 43
Programming with C - Lab
}
getch();
}

Unions
Unions are the concept borrowed from structures and follow the same syntax as
structures. However there is a distinction between them in terms of storage. In structures
each member has its own storage location, where as all the members of union use the
same location i.e. all through a union may contain many members of different types; it
can handle only one member at a time. In a union, memory is allocated to only the largest
member of the union. All the members of the union will share the same area. That is why
only one member can be active at a time.
Like structure, a union can be declared using keyword union as follows:
union item
{
int m;
char c;
float x;
}code;
This declares a variable code of type union item. The union contains 3 members, each
with different data type. However we can use one of them at a time. This is due to the fact
that only one location is allocated for a union variable, irrespective of its size.
1000 1001 1002 1003
c→
 m →
 x →
The compiler allocated a piece of storage that is large enough to hold largest variable
type in the union. In the declaration above, the member x requires 4 bytes which is largest
among the members.
For example, if we use x in the above example, then we should not use m and c. If you
try to use both at the same time, though C doesn’t stop; you overwrite one data with
another. If you access m after x and c, then the value available in union will be the value
of m. If you display all the members the value of m will be the same and rest all will be
garbage values.
A union is used for 2 purposes:
1) To conserve memory by using the same area for two or more different variables.
2) To represent the same area of the memory in different ways.

Prepared by IT & CSE Page 44


Programming with C - Lab

Example: Program to illustrate concept of unions.


#include<stdio.h>
#include<conio.h>
main()
{
union number
{
int n1;
float n2;
char name[20];
};
union number x;
clrscr();
printf("\nEnter Name: ");
gets(x.name);
printf("Enter the value of n2: ");
scanf("%f", &x.n2);
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("\n\nValue of n1 = %d",x.n1);
printf("\nValue of n2 = %f",x.n2);
printf("\nName = %s",x.name);
getch();
}

Output:
Enter Name: Zaheer
Enter the value of n2: 3.23
Enter the value of n1: 6
Value of n1 = 6
Value of n2 = 3.218751
Name = ♠

Prepared by IT & CSE Page 45


UNIT - 4

WEEK - 11
1 Functions: Definition, Syntax, Terminology
2 Function Declaration, Classification (Arguments and Return Type)
3 Storage Classes, Sample C Programs
------------------
Functions
Functions are building blocks of a C program. Understanding functions is one of the most
important steps in C language.
Definition
A function is a self-contained program segment that carries out a specific, well-defined
task. A function is a collection of instructions that performs a specific task. Every function
is given a name. The name of the function is used to invoke (call) the function. A function
may also take parameters (arguments). If a function takes parameters, parameters are to be
passed within parentheses at the time of invoking function.
A function theoretically also returns a value, but you can ignore the return value of the
function in C language. Function name must follow the same rules of formation as other
variables in C. The argument list contains valid variable names separated by commas.
C is a function-oriented language. Many operations in C language are done through
functions. For example, we have used printf() function to display values, scanf() function
to read values from keyboard, strlen() function to get the length of the string etc.
Classification of Functions
C functions can be classified into two categories namely
➢ Library functions
➢ User defined functions.
The main difference between these 2 categories is that
❑ library functions are not required to be written by the user, printf, scanf, strlen, sqrt
and pow, etc belong to the category of library functions.
❑ user defined function has to be developed by the user at the time of writing a
program. main() function is an example of user-defined function. Every program
must have a main function to indicate where the program has to begin its execution.
Standard/Library functions
A function which is made available to programmer by compiler is called as standard
or pre-defined function. Every C compiler provides good number of

Prepared by IT & CSE Page 46


Programming with C - Lab

functions. All that a programmer has to do is use them straight away. For example,
if you have to find length of a string , use strlen() without having to write the
required code.
The code for all standard functions is available in library files, like cs.lib, and
graphics.lib. These library files are supplied by the vendor of compiler. Where
these libraries are stored in the system depends on the compiler. For example, if
you are using Turbo C, you find libraries in LIB directory under directory where
Turbo C is installed.
Declarations about standard functions are available in header files such as stdio.h,
and string.h. Turbo C provides around 400 functions covering various areas like
Screen IO, graphics, disk IO etc.

User-defined functions
User-defined function is a function that is defined by user. That means, the code
for the function is written by user (programmer). User-defined functions are similar
to standard functions in the way you call. The only difference is instead of C
language providing the function, programmer creates the function.
If a program is divided into functional parts than each part may be independently coded
and later combined into single unit.
Advantages of Functions:
❑ The length of the source program can be reduced by using functions at
appropriate places.
❑ It becomes easier to locate a faculty functions.
❑ Many other programs may use a function.

User-defined functions are used mainly for two purposes:


(1) To avoid repetition of code
In programming you often come across the need to execute the same code in
different places in the program. For example, if you have to print an array at the
beginning of the program and at the end of the program. Then you need to write
the code to display the array twice.
If you create a function to display the array, then you have to call the function once
at the beginning of the program. That means, the source code need not be written
for multiple times. It is written only for once and called for multiple times.

(2) To break large program into smaller units


It is never a good idea to have a single large code block. If you write entire C
program as one block, the entire blocks ends up in main() function. It becomes
very difficult to understand and manage.

Prepared by IT & CSE Page 47


Programming with C - Lab

If you can break a large code block into multiple smaller blocks, called functions,
then it is much easier to manage the program. In the following example, instead of
taking input, processing and displaying output in main() function, if you can divide
it into three separate functions, it will be much easier to understand and manage.
main()
{

/* take input here */


...

/* process the input here */


...

/* display output here */


...

}
Single large main() function

main()
{
takeinput();
process();
displayoutput();
}

takeinput()
{
}
process ()
{
}
displayoutput()
{
}
Main() function calling other functions
Creating user-defined function
A user-defined function is identical to main() function in creation. However, there are
two differences between main function and a user-defined function.
❑ Name of main() function is standard, whereas a user-defined function can have
any name.
❑ main() function is automatically called when you run the program, whereas a
user-defined function is to be explicitly called.
Terminology of Functions

Function Declaration:
A function may contain declaration and definition. Function declaration specifies function
name, return type, and type of parameters. This is normally given at the beginning of the
program. Though it is not mandatory in all cases, it is better to declare each function. In
fact header files (*.h) contain declarations of all standard functions.

Prepared by IT & CSE Page 48


Programming with C - Lab

The following is the syntax for function declaration.


return-type functionname ( parameters );
Function declaration is called as Prototype declaration. Though it is not necessary in
majority of cases, it is needed in cases where the following conditions apply:
▪ Call to function comes before definition of the function
▪ Function returns non-integer value.
Function Definition:
Function definition is where the statements to be executed are given. When the function
is called the statements given here are executed.
return-type functionname ( parameters )
{
statements;
return value;
}
Return type specifies the type of value function returns. If function doesn’t return any
value then it must be void.
Parameters are formal parameters of the function.
Statements are the statements to be executed when function is called.
Return statement is used to return a value from function.

Caller and Callee


The function which calls another function is called caller. The function which is called by
the caller is called callee.
Passing Parameters:
A parameter or argument is a value passed to function so that function can use that value
while performing task. A function may take none, one or more parameters depending
upon the need.
Example: line(); /*function that pass no parameters*/
line(20); /*function that pass one parameter*/
getaverage(10,20); /*function that pass more than one parameter*/
Actual Parameter: It is the value that is passed to function while calling the function. For
example; 10 and 20 values that we passed to line() and getaverage() function in the above
are actual parameters.
Formal Parameter: Variable that is used to receive actual parameter is called formal
parameter.
Example: getaverage(int a, int b); Here a and b are formal parameters.

Returning Value:
Normally after performing the task functions return a value. The return value may be of
any type. But a function can return only one value. To return a value from the function,
we have to first specify what type of value the function returns and then we have to use
return statement in the code of the function to return the value.

Prepared by IT & CSE Page 49


Programming with C - Lab

When return type is not explicitly mentioned it defaults to int. If a function doesn't
return any value then specify return type as void.
A function returns the value to the location from where it has been called.

Storage Classes
Properties of a variable:
A variable in C language is associated with the following properties:
Property Meaning
Name is used to refer to variable. This is a symbol using which the
Name
value of the variable is accessed or modified.
Data type Specifies what type of value the variable can store
The value that is stored in the variable. The value is not known
Value
unless the variable is explicitly initialized.
The address of the memory location where the variable is allocated
Address
space
Specifies the region of the program from where variable can be
Scope
accessed.
Visibility Specifies the area of the program where variable is visible.
Extent Specifies how long variable is allocated space in memory.

Blocks:
C is a block structured language. Blocks are delimited by { and }. Every block can have its
own local variables. Blocks can be defined wherever a C statement could be used. No
semi-colon is required after the closing brace of a block.
Scope
The area of the program from where a variable can be accessed is called as scope of the
variable. The scope of a variable determines over what parts of the program a variable is
actually available for use (active). Scope of the variable depends on where the variable is
declared. The following code illustrate the scope of a variable:
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
. . . .
}
The scope of a variable may be either global or local.

Prepared by IT & CSE Page 50


Programming with C - Lab

Global Scope: It means the variable is available throughout the program. It is available to
all functions that are defined after the declaration of the variable. This is the scope of the
variables, which are declared outside of all functions. Variables that have global scope are
called as Global Variables.
In the above example, variable g has global scope; that means the variable is accessible to
all the functions of the program (main, sum) that are defined after the variable is defined.
Local Scope: Variables declared at the beginning of the block are available only to that
block in which they are declared. When the scope of the variable is confined to block it is
called as Local Scope. Variables with local scope are called as Local Variables.
In the above example, variables x and y have local scope; that means the variables are
accessible only to the functions at which they are declared.
C allows you to create variables not only at the beginning of a function, you can also
declare variables at the beginning of the block.
main()
{
int x; /* scope of x is throughout main function */
. . . .
if( ...) {
int p; /* scope of p is accessible only within if block */
. . . .
}
else {
int q; /*scope of q is accessible only within else block*/
. . . .
}
}

You cannot change the scope of a variable, it is completely dependent on the place of
declaration in the program.
Visibility:
Normally visibility and scope of variables are same. In other words, a variable is visible
throughout its scope.
Visibility means the region of the program in which a variable is visible. A variable can
never be visible outside the scope. But it may be invisible inside the scope.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}

Prepared by IT & CSE Page 51


Programming with C - Lab
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
}
In the above code, variable g has global scope. But it becomes invisible throughout the
function sum as a variable with the same name is declared in that function.
When a global variable is re-declared in a function then the local variable takes
precedence i.e., g in function sum will reference g in function but not g declared as global
variable. So, in this case though g has scope throughout program, it is not visible
throughout function sum.

For global variable to get its visibility in a function, when a local variable with same variable
name is declared and use we use scope resolution operator(::). This helps in accessing
global variable even though another variable with same name is existing.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
::g=g+10; /*global variable g is used now with the operator*/
/*'::' called scope resolution operator*/
}
Extent/Lifetime
Also called as Longevity. This refers to the period of time during which a variable resides
in the memory and retains a given value during the execution of a program. Longevity has
a direct effect on the utility of a given variable.
A variable declared inside a block has local extent. Because it exists in the memory as
long as the block is in execution. It is created when block is invoked and removed when
the execution of the block is completed.
On the other hand, variable declared outside all functions has static extent as they remain
in memory throughout the execution of program.

Prepared by IT & CSE Page 52


Programming with C - Lab

Though variable is available in memory, we can access it only from the region of the
program to which the variable is visible. That means, just because the variable is there in
the memory we cannot access it.

STORAGE CLASS SPECIFIERS


'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a variable can be used. Storage
class defines the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a
computer where variable is stored. There are two memory locations in a computer system
where variables are stored as: Memory and CPU Registers.
Functions of storage class:
❑ To determine the location of a variable where it is stored?
❑ Set initial value of a variable or if not specified then setting it to default value.
❑ Defining scope of a variable.
❑ To determine the life of a variable.
Syntax:
[storage-class] data type variable [= value] ;
Types of Storage Classes
▪ auto
▪ register
▪ static
▪ extern

auto or Automatic Storage class


This is normally not used as it is always implicitly associated with all local variables. The
keyword used for this storage class is auto. An auto variable is automatically created and
initialized when control enters into a block and removed when control comes out of block.
auto int i=30; /*an auto variable with local scope and extent*/

Storage Location: Main Memory


Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.
Example: Program to illustrate how auto variables work.
main() {
auto int i=10;
clrscr();

Prepared by IT & CSE Page 53


Programming with C - Lab
{
auto int i=20; Output:
20 10
printf("%d",i);
}
printf("\t%d",i);
}
register or Register Storage class
We can tell the compiler that a variable should be kept in registers (which are memory
locations on microprocessors used for internal operations), instead of keeping in the
memory (where normal variables are stored).
Since a register access is much faster than a memory access, keeping the frequently
accessed variables (e.g. loop control variables) in the registers will lead to faster
execution of program. Most of the compilers allow only int or char variables to be placed
in the register.
register int i;
The above is a request to the compiler to allocate a register to variable i instead of
allocating memory. If the register is available then i is placed in register, otherwise it is as
usual given memory location.
The programmer doesn't know whether register is allocated or memory is allocated to a
variable that is used with register storage class. So, it is not possible to use address
operator (&) with variables that contain register storage specifier. This is of the fact that
registers do not contain address.
It is not applicable for arrays, structures or pointers. It cannot not used with static or
external storage class.
Storage Location: CPU registers
Default Value: Garbage
Scope: Local to the block in which variable is declared
Lifetime: till the control remains within the block.
Since, there are limited number of register in processor and if it couldn't store the variable
in register, it will automatically store it in memory.
Example:
main()
{
register int i;
for(i=0;i<10000;i++)
. . . .
}

Prepared by IT & CSE Page 54


Programming with C - Lab

static or Static Storage Class


static is the default storage class for global variables. This is used to promote local extent
of a local variable to static extent.
The value of static variables persists until the end of the program. A variable can be
declared static using the keyword static like
static int x;
static float y;
When you use static storage class while declaring local variable, instead of creating the
variable and initializing it whenever control enters the block, the variable is created and
initialized only for once - when variable's declaration is encountered for first time. So a
variable with static extent will remain in the memory across function calls.
Storage Location: Main Memory
Default Value: Zero
Scope: Local to the block in which variable is declared
Lifetime: till the value of the variable persists between different function calls.
Example: Program to illustrate the properties of a static variable.
main() {
int i;
for (i=0; i<3; i++)
incre();
}
incre() {
int avar=1;
static int svar=1;
avar++; svar++;
printf("\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
Output:
Automatic variable value: 2 Static variable value: 2
Automatic variable value: 2 Static variable value: 3
Automatic variable value: 2 Static variable value: 4

extern or External Storage class:


extern is used to give a reference of a global variable that is visible to ALL the program
files. When you use 'extern' the variable cannot be initialized as all it does is point the
variable name at a storage location that has been previously defined.
External variable can be accessed by any function. They are also known as global
variables. Variables declared outside every function are external variables.

Prepared by IT & CSE Page 55


Programming with C - Lab

When you have multiple files and you define a global variable or function which will be
used in other files also, then extern will be used in another file to give reference of defined
variable or function.
In case of large program, containing more than one file, if the global variable is declared
in file 1 and that variable is used in file 2 then, compiler will show error. To solve this
problem, keyword extern is used in file 2 to indicate that, the variable specified is global
variable and declared in another file.
/* File1.c */
extern int count; /* refers to an external variable count */
inccount() {
count++;
}

/* File2.c */
#include"File1.c"
int count; /* creates variable count with static extent */
main() {
. . .
}
In this case program File1.c has to access the variable defined in program File2.c.
Storage Location: Main Memory
Default Value: Zero
Scope: Global/File Scope
Lifetime: as long as the program execution doesn't come to an end.
Example: Program to illustrate extern storage class
write.c
void write_extern();
extern int count;
void write_extern()
{
count = count + 2;
printf("Count is %d\n",count);
Output:
}
Count is 7
mmain.c Count is 9
#include"write.c"
int count=5;
main() {
write_extern();
write_extern();
}

Prepared by IT & CSE Page 56


Programming with C - Lab

Category of Functions:
A function depending on whether arguments are present or not and whether a value is
returned or not may belong to one of the following categories:
1. Functions with no arguments and no return value.
2. Functions with arguments and no return value.
3. Functions with arguments and return value.
4. Functions with no arguments and return value.
Functions with no arguments and no return value
When a function has no argument, it does not receive any data from calling function.
When it does not return a value, the calling function does not receive any data from called
function. In effect, there is no data transfer between calling function & called function.
Program 1:
#include<stdio.h>
main()
{
printf("Text in main Function\n");
print();
}
print()
{
printf("\nText in print function");
}
Program 2:
#include<stdio.h>
main()
{
printf("Addition of 2 numbers:\n");
sum();
}
sum()
{
int a,b;
printf("Enter 2 numbers: ");
scanf("%d %d",&a,&b);
printf("\nSum of %d and %d is %d",a,b,a+b);
}

Functions with no arguments and return value


When a function has no argument, it does not receive any data from calling function.
When it does return a value, the calling function receives data from called function. In
effect, there is data transfer between called function & calling function.
Program:
#include<stdio.h>
float average();
main()
{
float avg;

Prepared by IT & CSE Page 57


Programming with C - Lab
printf("Average of 3 numbers:\n");
avg = average();
printf("Average: %f",avg);
}
float average()
{
int a,b,c,s;
printf("Enter 3 numbers: ");
scanf("%d %d %d",&a,&b,&c);
s=a+b+c;
return s/3.0;
}
Functions with arguments and no return value
When a function has argument(s), it does receive data from calling function. When it does
not return a value, the calling function receives does not data from called function. In
effect, there is data transfer between calling function & called function.
Program 1:
#include<stdio.h>
main()
{
dline(15);
printf("\nFunctions...");
dline(15);
getch();
}
dline(int n)
{
int l;
for(l=0;l<n;l++)
putch('-');
}
Program 2:
#include<stdio.h>
void interest(float,int,float);
main()
{
int t;
float p,r;
printf("Enter principal amount: ");
scanf("%f",&p);
printf("Enter time period: ");
scanf("%d",&t);
printf("Enter rate: ");
scanf("%d",&r);
interest(p,t,r);
}
void interest(float pr,int tp,float rate)
{
float si;

Prepared by IT & CSE Page 58


Programming with C - Lab
si = (pr*tp*rate)/100;
printf("Simple Interest for Rs %0.2f is %0.2f",pr,si);
}
Functions with arguments and return value
When a function has an argument, it receives back any data from calling function. When
it returns a value, the calling function receives any data from called function. In effect,
there is a data transfer between the calling function & called function.
Program:
int getsum(int n);
main()
{
int v,sum;
printf("Enter n value: ");
scanf("%d",&v);
sum = getsum(v);
printf("Sum=%d",sum);
}
int getsum(int n)
{
int s=0;
for(;n>0;n--)
s+=n;
return s;
}

Prepared by IT & CSE Page 59


Programming with C - Lab

WEEK - 12
1 Parameter Passing Techniques
2 Passing Parameters Types
3 Recursion
------------------
Parameter Passing Techniques: Call by Value & Call by Reference
Call by Value:
If data is passed by value, the data is copied from the variable used in main() to a variable
used by the function. So if the data passed (that is stored in the function variable) is
modified inside the function, the value is only changed in the variable used inside the
function.
When we call a function then we will just pass the variables or the arguments and we
doesn’t pass the address of variables , so that the function will never effects on the values
or on the variables.
So Call by value is that the values those are passed to the functions will never effect the
actual values those are Stored into the variables.
Example: Program to illustrate the concept of call by value
#include <stdio.h>
swap (int, int);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(a, b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}
swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Output:
Enter value of a & b: 2 3
Before swapping: 2 3
After swapping: 2 3

Prepared by IT & CSE Page 60


Programming with C - Lab

Call by Reference:
If data is passed by reference, a pointer to the data is copied instead of the actual variable
as it is done in a call by value. Because a pointer is copied, if the value at that pointers
address is changed in the function, the value is also changed in main().
In the call by reference we pass the address of the variables whose arguments are also
send. So that when we use the reference then, we pass the address the variables.
When we pass the address of variables to the arguments then a function may effect on
the variables. So, when a function will change the values then the values of variables gets
automatically changed and when a function performs some operation on the passed
values, then this will also effect on the actual values.
Example: Program to illustrate the concept of call by reference
#include <stdio.h>
swap (int *, int *);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Enter value of a & b: 2 3
Before swapping: 2 3
After swapping: 3 2

Passing an array as argument to function:


An array is actually held as an address to an area of memory. This means that when you
come to pass it into a function, it can only be passed in as a reference.

Also, when you define the parameter to read in the data in the function prototype, you
declare it as though you were reading in a single-item variable instead of an array. When
an array is passed as parameter, only the name of the array is given at the time of calling
function the formal parameter is to be declared as an array.

Prepared by IT & CSE Page 61


Programming with C - Lab

It is then up to the function to read the first item from the array, move the pointer along
to the next item, and then carry on until it finds the end of the array - thus, it has to
somehow know how long the array is.
function_name(int x[5])
function_name(int x[])
The parameter x in the above declarations are also internally taken as an integer pointer
by C to access the elements of the array from the first element.
Passing a 1-dimensional array as argument to function:
Example 1: Program to print the given array
printarray(int []);
main()
{
int a[5],i;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printarray(a);
}
printarray(int ar[5])
{
int i;
for(i=0;i<5;i++)
printf("%d\n",i[ar]);
}

Example 2: Program to find largest from the given array


#define SIZE 50
int big(int [], int);
main()
{
int a[SIZE], n, i, b;
printf("\nEnter size of array: ");
scanf("%d", &n);
printf("\nEnter elements:\n");
for (i=0; i<n; i++)
scanf("%d", &a[i]);
b = big(a, n);
printf("\nLargest number: %d", b);
}
int big(int a[], int n)
{
int b, i;
b = a[0];
for(i=0; i<n; i++)
if (a[i] > b) b = a[i];
return b;
}

Prepared by IT & CSE Page 62


Programming with C - Lab

Passing a 2-dimensional array as argument to function:


Example: Program to find Diagonal elements of given matrix
#define ROW 10
#define COL 10
int trace(int [][], int, int);
main()
{
int a[ROW][COL], row, col, i, j, sum;
printf("\nEnter no. of rows and columns of a matrix: ");
scanf("%d %d", &row, &col);
printf("\nEnter elements:\n");
for (i=0; i<row; i++)
for (j=0; j<col; j++)
scanf("%d", &a[i][j]);
printf("\nMatrix is:\n\n");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
printf("\t%d", a[i][j]);
printf("\n");
}
sum = trace(a, row, col);
printf("\nSum: %d", sum);
}
int trace(int x[ROW][COL], int r, int c)
{
int i, j, s=0;
for (i=0; i<r; i++)
for (j=0; j<c; j++)
if (i == j) s = s + x[i][j];
return s;
}
Passing String as Parameter to function
This is similar to the concept of passing an array to a function as argument. With strings
(i.e. character arrays) - we have one advantage: we know that the end of the array is
marked by a zero character, so as long as we know where the beginning of the array is,
we can find the end of the string of characters by moving from the beginning of the array
to the end one-character at a time.
Example: Program to modify a string and display.
main()
{
char st[20];
printf("Enter Name: ");
gets(st);
modifystring(st);
printf("\n%s",st);
}
modifystring(char st[20]) {
strcat(st," Welcome");

Prepared by IT & CSE Page 63


Programming with C - Lab
}

Passing structure as argument to function


A structure can be passed to a function. To pass a structure to a function you have to
pass it just like how you would pass standard data types like int and float.
Example: Program to illustrate the concept of passing structure to function.
struct point
{
int x,y;
};
void display(struct point t);
main()
{
struct point p;
printf("Read Coordinates of a point: ");
scanf("%d %d",&p.x,&p.y);
display(p);
}
void display(struct point t)
{
printf("Coordinates of a point: x=%d, y=%d",t.x,t.y);
}
When you are sending a structure to a function, make sure that both calling function and
called function have access to structure. This can be done if you declare the structure at
the beginning of the program.
Just like how we send a structure variable to a function you can also send an array of
structures to a function.
Return a Structure
A function can also return a structure as return type. All that you have to do is specify
return type as structure and return a structure variable.
Example: Program to call a function that returns a variable of structure.
struct point {
int x,y;
};
struct point getpoint();
main()
{
struct point p;
p = getpoint();
printf("Coordinates of a point: x=%d, y=%d",p.x,p.y);
}
struct point getpoint()
{
struct point t;
printf("Enter point coordinates: ");
scanf("%d %d",&t.x,&t.y);
return t;
}

Prepared by IT & CSE Page 64


Programming with C - Lab

Passing array to function and accessing array with pointer


Whenever you send an array to function as parameter, you send the address of the array
and not the complete array. That means, whenever an array is passed it is passed by
reference. The formal parameter in called function is nothing but a pointer pointing to first
element of array.
function_name(int *x): This declaration declares x as an integer pointer. All that C needs
here is a pointer to integer.
Example: Program to display the given array of elements.
main()
{
int arr[10],i;
printf("Enter 10 elements: ");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
displayarray(arr);
}
displayarray(int *a)
{
int i;
printf("Elements in reverse order: ");
for(i=10-1;i>=0;i--)
printf("%d ",*(a+i));
}
Passing string to function and accessing string with pointer
Strings which are made up of characters, we'll be using pointers to characters. However,
pointers only hold an address; they cannot hold all the characters in a character array.
This means that when we use a char * to keep track of a string, the character array
containing the string must already exist.
Example: Program to accept string and display vowels
vowels(char *p);
main()
{
char str[10];
printf("\nEnter the string: ");
gets(str);
vowels(str);
}
vowels(char *p)
{
int i,l;
l=strlen(p);
printf("\n\nThe vowels in the string are: ");
for(i=0;i<l;i++)
{
if(p[i]=='a' || p[i]== 'e' || p[i]=='i' || p[i]=='o' ||
p[i]=='u'|| p[i]=='A' || p[i]=='E' || p[i]=='I' ||
p[i]=='O' || p[i]=='U')
{

Prepared by IT & CSE Page 65


Programming with C - Lab
printf("%c",p[i]);
}
else
continue;
}
}

Calling Function within Function


One of the main reasons of using various functions in your program is to isolate
assignments; this allows you to divide the jobs among different entities so that if
something is going wrong, you might easily know where the problem is.
Functions trust each other, so much that one function does not have to know HOW the
other function performs its assignment. One function simply needs to know what the other
function does, and what that other function needs.
Once a function has been defined, other functions can use the result of its assignment.
Imagine you define two functions A and B.

If Function A needs to use the result of Function B, function A has to use the name of
function B. This means that Function A has to “call” Function B:

When calling one function from another function, provide neither the return value nor
the body, simply type the name of the function and its list of arguments, if any.
Example: Program to call function inside a function.
main()
{
processinput();
getch();
}
processinput()
{
int a,b,sum;
printf("Enter 2 numbers: ");
scanf("%d %d",&a,&b);
sum = process(a,b);
displayresult(a,b,sum);
}
process(int a,int b)
{
return a+b;
Prepared by IT & CSE Page 66
Programming with C - Lab
}
displayresult(int x,int y,int s)

Prepared by IT & CSE Page 67


Programming with C - Lab
{
printf("Sum of 2 numbers %d and %d is %d",x,y,s);
}
Pointer to Function
It is also possible to have a pointer pointing to a function. A pointer to a function contains
the address of the location to which control is transferred when you use the pointer.
The following example shows how to declare a pointer to a function and use it to
invoke the function.
/*pointer pointing to function that returns void*/
void (*fp)();
void print();
main()
{
/*make fp pointing to print function*/
fp = print;
/*call print function through pointer to function*/
(*fp)();
}
void print()
{
printf("Hello! From Function Print...");
}

Recursion
Recursion is a process of defining something in terms of itself and is sometimes called
circular definition. When a function calls itself it is called as recursion. Recursion is natural
way of writing certain functions.
Recursive Function: A function is said to be recursive if a statement in the body of the
function calls itself. Each recursive function must specify an exit condition for it to
terminate, otherwise it will go on indefinitely.
A simple example of recursion is presented below:
main()
{
printf("\nThis is an example of recursion");
main();
}

When executed, this program will produce an output like:


This is an example of recursion
This is an example of recursion



This is an example of recursion

Prepared by IT & CSE Page 68


Programming with C - Lab

Execution must be terminated abruptly (suddenly or unexpected) or forcibly, otherwise


the execution will continue infinitely.
Recursive functions can be effectively used to solve problems where the solution is
expressed in terms of successively applying the same solution of the subset of the
problem.
When we write recursive functions we must have an if statement somewhere to force the
function to return without recursive calls being executed. Otherwise function will never
return back and will be terminated with an error saying “out of stack space”.
Example: Program to find sum of n below numbers using recursion.
#include <stdio.h>
main()
{
int n,sum;
printf("\nEnter n value: ");
scanf("%d", &n);
sum = sum_num(n);
printf("\nSum of %d below numbers is %d",n,sum);
getch();
}
sum_num(int n)
{
if (n == 1)
return n;
else
return n+sum_num(n-1);
}
sum_num(5) returns (5 + sum_num(4),

which returns (4 + sum_num(3),

which returns (3 + sum_num(2),

which returns (2 + sum_num(1),

which returns (1)))))


Example: Program to find factorial of given number using recursion.
#include <stdio.h>
long fact(int);
main()
{
int n;
long f;
printf("\nEnter number to find factorial: ");
scanf("%d", &n);
f = fact(n);
printf("\nFactorial: %ld", f);
getch();
}

Prepared by IT & CSE Page 69


Programming with C - Lab
long fact(int n)
{
int m;
if (n == 1)
return n;
else
return n * fact(n-1);
}

Example: Program to find the GCD of two given integers using Recursion
#include<stdio.h>
#include<conio.h>
int gcd (int, int); //func. declaration.
void main( )
{
int a, b, res;
clrscr( );
printf("Enter the two integer values:");
scanf("%d%d", &a, &b);
res= gcd(a, b); // calling function.
printf("\nGCD of %d and %d is: %d", a, b, res);
getch( );
}
int gcd( int x, int y) //called function.
{
int z;
z=x%y;
if(z==0)
return y;
gcd(y,z); //recursive function
}
Example: Program to generate the Fibonocci series using Recursion.
#include<stdio.h>
#include<conio.h>
int fibno(int); // function declaration.
void main()
{
int ct, n, disp;
clrscr( );
printf("Enter the no. of terms:");
scanf("%d", &n);
printf("\n The Fibonocci series:\n");
for( ct=0; ct<=n-1; ct++)
{
disp= fibno(ct); //calling function.
printf("%5d", disp);
}
getch( );
}

int fibno( int n)


Prepared by IT & CSE Page 70
Programming with C - Lab
{
int x, y;
if(n==0)
return 0;
else if(n==1)
return 1;
else
{
x= fibno( n-1);
y= fibno( n-2);
return (x+y);
}
}

Prepared by IT & CSE Page 71


UNIT-5

WEEK - 13
1 Files: Definition, Opening, Closing of Files
2 Reading and Writing of Files
3 Sample C Programs
------------------
File Handling
If the program requires the input data either 1 or 2, the user could supply the data at any
time. But if the details of the student in a very large institution are required to prepare
marks statement for all, we have to enter the whole details every time to our program.
This requires large man power, more time & computational resources; which is a
disadvantage with the traditional way of giving inputs to a program for execution with the
basic I/O functions.
When the data of the students are stored permanently, the data can be referred later and
makes the work easier for the user to generate the marks statement. When you have to
store data permanently, we have to use FILES. The files are stored in disks.
DEFINITION:
A file can be defined as a collection of bytes stored on the disk under a name. A file may
contain anything, in the sense the contents of files may be interpreted as a collection of
records or a collection of lines or a collection of instructions etc.
A file is a collection of records. Each record provides information to the user. These files
are arranged on the disk.
Basic operations on files include:
➢ Open a file
➢ Read data from file/Write data to file
➢ Close a file
To access the data in a file using C we use a predefined structure FILE present in stdio.h
header file, that maintains all the information about files we create (such as pointer to char
in a file, end of file, mode of file etc).
FILE is a data type which is a means to identify and specify which file you want to operate
on because you may open several files simultaneously.
When a request is made for a file to be opened, what is returned is a pointer to the
structure FILE. To store that pointer, a pointer variable is declared as follows:

FILE *file_pointer;
where file_pointer points to first character of the opened file.

Prepared by IT & CSE Page 72


Programming with C - Lab

Opening of a file:
A file needs to be opened when it is to be used for read/write operation. A file is opened
by the fopen() function with two parameters in that function. These two parameters are
file name and file open mode.
Syntax: fopen(filename, file_open_mode);
The fopen function is defined in the “stdio.h” header file. The filename parameter refers
to any name of the file with an extension such as “data.txt” or “program.c” or "student.dat"
and so on.
File open mode refers to the mode of opening the file. It can be opened in ‘read mode’
or ‘write mode’ or ‘append mode’.
The function fopen() returns the starting address of file when the file we are trying to open
is existing (i.e. success) else it returns NULL which states the file is not existing or
filename given is incorrect.
E.g.: FILE *fp;
fp=fopen("data.txt","r");
/*If file exists fp points to the starting address in memory
Otherwise fp becomes NULL*/
if(fp==NULL) printf("No File exists in Directory");
NULL is a symbolic constant declared in stdio.h as 0.
Modes of Operation:
1. "r" (read) mode: open file for reading only.
2. "w" (write) mode: open file for writing only.
3. "a" (append) mode: open file for adding data to it.
4. "r+" open for reading and writing, start at beginning
5. "w+" open for reading and writing (overwrite file)
6. "a+" open for reading and writing (append if file exists)
When trying to open a file, one of the following things may happen:
➢ When the mode is ‘writing’ a file with the specified name is created if the file does
not exist. The contents are deleted, if the file is already exists.
➢ When the purpose is ‘appending’, the file is opened with the current contents safe.
A file with the specified name is created if the file does not exist.
➢ When the purpose is ‘reading’, and if it exists, then the file is opened with the
current contents safe; otherwise an error occurs.
With these additional modes of operation (mode+), we can open and use a number of
files at a time. This number however depends on the system we use.
Closing a file:
A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from the buffers and
all the links to the file are broken. It also prevents any accidental misuse of file.

Prepared by IT & CSE Page 73


Programming with C - Lab

Closing of unwanted files might help open the required files. The I/O library supports a
function to do this for us.
Syntax: fclose(file_pointer);
/*This would close the file associated with the FILE pointer file_pointer*/
fcloseall();
/*This would close all the opened files. It returns the number of files it closed. */
Example: Program to check whether given file is existing or not.
#include<stdio.h>
main()
{
FILE *fp;
fp=fopen("data.txt","r");
if(fp==NULL) {
printf("No File exists in Directory");
exit(0);
}
else
printf("File Opened");
fclose(fp);
getch();
}
Reading and Writing Character on Files
To write a character to a file, the input function used is putc or fputc. Assume that a file is
opened with mode 'w' with file pointer fp. Then the statement,

putc(character_variable,file_pointer);
fputc(character_variable,file_pointer);
writes the character contained in the 'character_variable' to the file associated with FILE
pointer 'file_pointer'.
E.g.: putc(c,fp);
fputc(c,fp1);
To read a character from a file, the output function used is getc or fgetc. Assume that a
file is opened with mode 'r' with file pointer fp. Then the statement,

character_variable = getc(file_pointer);
character_variable = fgetc(file_pointer);
read the character contained in file whose FILE pointer 'file_pointer' and stores in
'character_variable'.
E.g.: getc(fp);

Prepared by IT & CSE Page 74


Programming with C - Lab

fgetc(fp);
The file pointer moves by one character position for every operation of getc and putc. The
getc will return an end-of-file marker EOF, when end of the file has been reached.
Therefore, the reading should be terminated when EOF is encountered.
Example: Program for Writing to and reading from a file
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Write data to file: \n");
f1 = fopen("test.txt","w");
while((c=getchar())!='@')
putc(c,f1);
/*characters are stored into file until '@' is encountered*/
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("test.txt","r"); /*reads characters from file*/
while((c=getc(f1))!=EOF)
printf("%c",c);
fclose(f1);
getch();
}
Example: Program to write characters A to Z into a file and read the file and print the
characters in lowercase.
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Writing characters to file... \n");
f1 = fopen("alpha.txt","w");
for(ch=65;ch<=90;ch++)
fputc(ch,f1);
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("alpha.txt","r");
/*reads character by character in a file*/
while((c=getc(f1))!=EOF)
printf("%c",c+32); /*prints characters in lower case*/
fclose(f1);

Prepared by IT & CSE Page 75


Programming with C - Lab
getch();
}
Example: Program to illustrate the append mode of operation for given file.
#include<stdio.h>
main()
{
FILE *f1;
char c,fname[20];
clrscr();
printf("Enter filename to be appended: ");
gets(fname);
printf("Read data from file: \n");
f1 = fopen(fname,"r");
if(f1==NULL)
{
printf("File not found!");
exit(1);
}
else
{
while((c=getc(f1))!=EOF)
printf("%c",c);
}

fclose(f1);
f1 = fopen(fname,"a");
while((c=getchar())!='@')
putc(c,f1);
/*characters are appended into file with existing data until
'@' is encountered*/
fclose(f1);
getch();
}

Reading and Writing Integers getw and putw functions:


These are integer-oriented functions. They are similar to getc and putc functions and are
used to read and write integer values. These functions would be useful when we deal with
only integer data.
The general forms of getw and putw are:
putw: Writes an integer to a file.
putw(integer,fp);
getw: Reads an integer from a file.
getw(fp);

Prepared by IT & CSE Page 76


Programming with C - Lab

Example: Program to illustrate getw and putw functions.


#include<stdio.h>
main()
{
int n,num,i,sum=0;
FILE *fp;
clrscr();
printf("Enter the number of integers to be written to file: ");
scanf("%d",&n);
fp = fopen("numbers.txt","w");
for(i=0;i<n;i++)
{
scanf("%d",&num);
putw(num,fp);
}
fclose(f1);
fp = fopen("numbers.txt","r");
while((num=getw(fp))!=EOF)
{
sum=sum+num;
}
fclose(fp);
printf("Sum of %d numbers is %d\n\n",n,sum);
printf("Average of %d numbers is %d",sum/n);
getch();
}
End of File: feof()
The feof() function can be used to test for the end of the file condition. It takes a FILE
pointer as its only argument and returns a non-zero integer value if all the data from
specified file has been read and returns zero otherwise.
This function returns true if you reached end of file in given file, otherwise returns false.
while(!feof(fp))
{
....
....
....
}
/*executes set of statements in the loop until EOF is encountered*/

fgets and fputs functions:


fputs writes string followed by new line into file associated with FILE pointer fp.
fputs(char *st, FILE *fp);
E.g.: fputs(str,fp);

Prepared by IT & CSE Page 77


Programming with C - Lab

fgets reads characters from current position until new line character is encountered or
len-1 bytes are read from file associated with FILE pointer fp. Places the characters read
from the file in the form of a string into str.
fgets(char *st,int len,FILE *fp);
E.g.: fgets(str,50,fp);
Example: Program to illustrate fgets and fputs function.
#include<stdio.h>
main()
{
FILE *fp;
char s[80];
clrscr();
fp=fopen("strfile.txt","w");
printf("\nEnter a few lines of text:\n");
while(strlen(gets(s))>0)
{
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
printf("Content in file:\n");
fp=fopen("strfile.txt","r");
while(!feof(fp))
{
puts(s);
fgets(s,80,fp);
}
fclose(fp);
getch();
}
fprintf and fscanf functions
The functions fprintf and fscanf perform I/O operations that are identical to the familiar
printf and scanf functions, except of course that they work on files. The first argument of
these functions is a file pointer, where specifies the file to be used.
fprintf(): Writes given values into file according to the given format. This is similar to printf
but writes the output to a file instead of console.
fscanf(): Reads values from file and places values into list of arguments. Like scanf it
returns the number of items that are successfully read. When the end of file is reached, it
returns the value EOF.
The general form of fprintf and fscanf is

Prepared by IT & CSE Page 78


Programming with C - Lab

fprintf(file_pointer/stream, “control string”, list);


fscanf(file_pointer/stream, “control string”, list);
where file_pointer is a pointer associated with a file that has been opened for writing.
The stream refers to a stream or sequence of bytes that can be associated with a device or
a file. The following are the available standard file pointers/streams:
➢ stdin refers to standard input device, which is by default keyboard.
➢ stdout refers to standard output device, which is by default screen.
➢ stdprn refers to printer device.
➢ stderr refers to standard error device, which is by default screen.
The control string (format specifier) contains output specifications for the items in the list.
The list may include variables, constants and strings.
E.g.:
fprintf(fp, “%s %d %f”, name, age, 7.5); /*writes to file*/
fprintf(stdout, “%s %d %f”, name, age, 7.5); /*prints data on console*/
fscanf(fp, “%s %d %f”, name, &age, &per); /*reads from file*/
fscanf(stdin, “%s %d %f”, name, &age, &per); /*reads data from console*/
Example: Program to illustrate fprintf and fscanf function.
#include<stdio.h>
main()
{
FILE *fp;
int number,quantity,i;
float price,value;
char item[20],filename[10];
clrscr();
printf("Enter filename: ");
gets(filename);
fp=fopen(filename,"w");
printf("Enter Inventory data: \n");
printf("Enter Item Name, Number, Price and Quantity
(3 records):\n");
for(i=1;i<=3;i++) {
fscanf(stdin,"%s %d %f %d",item,&number,&price,&quantity);
fprintf(fp,"%s %d %0.2f %d",item,number,price,quantity);
}
fclose(fp);
fprintf(stdout,"\n\n");
fp=fopen(filename,"r");
printf("Item Name\tNumber\tPrice\tQuantity\tValue\n");
for(i=1;i<=3;i++)

Prepared by IT & CSE Page 79


Programming with C - Lab
{
fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
value=price*quantity;

fprintf(stdout,"%s\t%10d\t%8.2f\t%d\t%11.2f\n",item,number,price,
quantity,value);
}
fclose(fp);
getch();
}

Prepared by IT & CSE Page 80


Programming with C - Lab

WEEK - 14
1 Binary Files, Random Accessing of Files
2 Enum, Typedef
3 Preprocessor Commands, Sample C Programs
------------------
BINARY FILES
Binary file is a file that is used to store any type of data. Binary files are typically used to
store data records.
Text file is a file which contains readable characters and a few control characters like tab,
new line etc. Example for text file is .txt, .c and etc. If the contents in a file are readable
then it is a text file. Text file is terminated with a special character ^Z or any other
character depending on programmer’s choice.
A Binary file is a file in which anything goes. Example for binary file is .exe, .obj, .dat and
.com file. In these files, the contents are unreadable and show meaningless characters.
Binary files are not terminated with any special character.
As Binary files don’t have termination character, we have to specify whether you are
dealing with text file or binary file. This is done using b (binary) qualifier in the modes of
operation as (wb, rb, ab, wb+, rb+, ab+). The modes perform the same operation as like for
text files.
Data file (.dat) is example of binary file. Data file is a collection of records. Each record is
a structure. Whatever you have in a structure variable in memory that is copied to file as
it is. So, if an integer is occupying two bytes the same number of bytes even on the file
and the exact memory image is copied to file.
Writing to binary file using fwrite()
The function fwrite can be used to write a block of memory into file. Whatever you have
in that block of memory that is written into file as it is.
int fwrite(void *address, int size, int noblocks, FILE *fp);
void *address is starting address of the block that is to be written. fopen
takes bytes from this address in memory.
int size Size of each block in bytes. Use of sizeof operator to get exact
number of bytes to be written while you are dealing with
structures.
int noblocks How many blocks are to be written? The size of each block is
specified by int size. So, total number of bytes written will be
size*noblocks

Prepared by IT & CSE Page 81


Programming with C - Lab

FILE *fp Identifies the file into which the data is to be written.
fwrite returns the number of blocks written and NOT number of bytes written.
E.g.: fwrite(&s, sizeof(s), 1, fp);
In this, one structure is written to file. The starting address of the structure variable
is taken using address operator &s. Size is taken using sizeof operator.
Reading binary files with fread()
fread() is same as fwrite() in syntax but does the opposite. It reads a block from file and
places that block into memory (a structure variable).
int fread(void *address, int size, int noblocks, FILE *fp);
fread returns the number of blocks read. If fread() couldn’t read record successfully it
returns 0.
E.g.: fread(&s, sizeof(s), 1, fp);
This place’s the data read from file into structure.
Example: Program to illustrate fread() and fwrite() functions.
#include<stdio.h>
struct student
{
int sno;
char sname[20];
char gender;
int tfee;
int fpaid;
};
main()
{
FILE *fp;
struct student s;
char c='y';
clrscr();
fp = fopen("student.dat","wb");
while(c=='y')
{
printf("Enter student details:\n");
scanf("%d",&s.sno);
fflush(stdin);
gets(s.sname);
fflush(stdin);
s.gender=getchar();
scanf("%d %d",&s.tfee,&s.fpaid);
fwrite(&s,sizeof(s),1,fp);
printf("Add student details...Press y or n: ");

Prepared by IT & CSE Page 82


Programming with C - Lab
fflush(stdin);
scanf("%c",&c);
}
fclose(fp);
printf("\nStudent Details\n");
fp=fopen("student.dat","rb");
printf("SNO \t Name \t Gender \t TotalFees \t FeesPaid \t
BalanceFee\n");
while((fread(&s,sizeof(s),1,fp))!=0)
{
printf("%d \t %s \t %4c \t\t %6d \t %5d \t\t %5d\n",
s.sno,s.sname,s.gender,s.tfee,s.fpaid,(s.tfee-s.fpaid));
}
fclose(fp);
getch();
}
Hence if large amount of numerical data is to be stored in a disk file, using text mode may
turn out to be inefficient. The solution is to open the file in binary mode and use those
functions (fread() and fwrite()) which store the numbers in binary format. It means each
number would occupy same number of bytes on disk as it occupies in memory.

RANDOM ACCESS TO FILES


So far we accessed the file sequentially, accessing from first byte to last byte. But it is also
possible to access the file from a particular location.
When we are interested in accessing only a particular part of a file and not in reading
other parts, it can be done with the concept of Random access. Random access allows
you to move to a particular position in the file and perform input and output from that
position.
When you access the file from beginning to end it is called Sequential Access. When you
read/write file from a specific position, it is called Random Access. Random Access means
moving the pointer of the file to the required location and read/write content at the location.
It can be achieved with the help of functions fseek(), ftell() and rewind() available in the
I/O library.
ftell(): ftell takes file pointer and returns a number type long that corresponds to the current
position. This function is useful in saving the current position of a file, which can be used
later in the program. It takes the following form:
variable = ftell(file_pointer);
E.g.: n = ftell(fp);

Prepared by IT & CSE Page 83


Programming with C - Lab

n would give the relative effect (in bytes) of current position. This means that n
bytes have already been read or written.

fseek(): It is used to move the file pointer position to a desired location within the file. It
takes the following form: fseek(file_pointer, offset, position);
file_pointer is a pointer to the file concerned, in which the pointer is to be moved.
The offset is a number or variable of type long. It is the number of bytes by which pointer
should move from the position. Positive value moves forward and negative value moves
backward.
The position indicates from where the movement should take place. It can take one of the
following:
0 – Beginning of file
1 – Current position
2 – End of the file
Instead of numbers the symbolic constants – SEEK_SET, SEET_CUR, SEEK_END, which are
declared in stdio.h can also be used.
When the operation is successful, fseek returns a zero. If we attempt to move the file
pointer beyond file boundary an error occurs and fseek returns -1.
E.g.:
• fseek(fp, 100, 0) – Moves pointer fp forward to 100th byte from the beginning of the
file. The first byte is at index 0. fseek() skips first 100 bytes (0-99) and places
pointer at byte with index 100.
• fseek(fp, -25L, 1) - Moves pointer fp backward by 25 byte from current position of
the file.
• fseek(fp, -10L, 2) - Moves pointer fp backward by 100 bytes from end of the file.
/*Following snippet reads fifth record from student.dat*/
struct student s;
FILE *fp;
/*open file in read binary mode*/
fp = fopen("student.dat","rb");
/*skip 4 record and move to 5th record*/
fseek(fp, sizeof(struct student)*4,0);
/*read a record*/
fread(&s,sizeof(struct student),1,fp);

EXAMPLES OF FSEEK & FTELL


FI.TXT contains the following content
H e l l o h i h o w a r e y o u
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
d e a r s t u d e n t s EOF
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

Prepared by IT & CSE Page 84


Programming with C - Lab

Example: Program to print every 5th character from beginning in a given file.
#include<stdio.h>
main()
{
int n=0;
char c;
FILE *fp;
clrscr();
fp = fopen("f1.txt","r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
n=n+5;
fseek(fp,n,0);
}
getch();
}
Output: h oe e
Example: Program to print every 5th character from current position in a given file.
#include<stdio.h>
main()
{
int n=0;
char c;
FILE *fp;
fp = fopen("f1.txt","r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
fseek(fp,5,1);
}
getch();
}
Output: hh ore
Example: Program to print contents of a given file in reverse
#include<stdio.h>
main()
{
int n=1,i;
char c;
FILE *fp;
clrscr();
fp = fopen("f1.txt","r");
while((c=getc(fp))!=EOF);

Prepared by IT & CSE Page 85


Programming with C - Lab
i=ftell(fp);
fseek(fp,-n,2);
while(i>=0)
{
c=getc(fp);
printf("%c",c);
n++;
i--;
fseek(fp,-n,2);
}
getch();
}
Output: stneduts raed uoy era woh ih olleh
Example: Program to print contents of file from end
#include<stdio.h>
main()
{
int n=1,i;
char c;
FILE *fp;
clrscr();
fp = fopen("f1.txt","r");
while((c=getc(fp))!=EOF);
i=ftell(fp);
n=i;
fseek(fp,-(n),2);
while(n!=0)
{
c=getc(fp);
printf("%c",c);
n--;
fseek(fp,-n,2);
}
getch();
}
Output: hello hi how are you dear students
Example: Program to print every 5th character from end
#include<stdio.h>
main()
{
int n,i;
char c;
FILE *fp;
clrscr();

Prepared by IT & CSE Page 86


Programming with C - Lab
fp = fopen("f1.txt","r");
while((c=getc(fp))!=EOF);
i=ftell(fp);
n=1;
fseek(fp,-n,2);
while(n<i)
{
c=getc(fp);
printf("%c",c);
n=n+5;
fseek(fp,-n,2);
}
getch();
}
Output: suaoa l

rewind(): It takes a file pointer and resets the position to the start of the file.
Syntax: rewind(file_pointer);
For example, the statement
rewind(fp);
n=ftell(fp);
would assign 0 to n because the file position has been set to the start of the file by
rewind. The first byte in the file is numbered as 0, second as 1 and so on.
This function helps us in reading a file more than once, without having to close and open
the file. Whenever a file is opened for reading or writing a rewind is alone implicitly.
This function can be used for the modes of operation with + as postfix to the modes (w,
a, r, wb, rb, and ab).
Example: Program to illustrate rewind() function.
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Write data to file: \n”);
printf("Specify @ to end the file reading \n\n");
f1 = fopen("sample.txt","w+");
while((c=getchar())!='@')
putc(c,f1);
rewind(f1);
printf("\nRead data from file: \n");
while((c=getc(f1))!=EOF)
printf("%c",c);

Prepared by IT & CSE Page 87


Programming with C - Lab
fclose(f1);
getch();
}

Enumeration
An enumeration is a user-defined data type consists of integral constants and each
integral constant is given a name. Keyword enum is used to defined enumerated
data type.

enum type_name{ value1, value2,...,valueN };


Here, type_name is the name of enumerated data type or tag.
And value1, value2,....,valueN are values of type type_name.

By default, value1 will be equal to 0, value2 will be 1 and so on but, the


programmer can change the default value.
// Changing the default value of enum elements
enum suit{
club=0;
diamonds=10;
hearts=20;
spades=3;
};

Declaration of enumerated variable


Above code defines the type of the data but, no any variable is created. Variable
of type enum can be created as:
enum boolean{
false;
true;
};
enum boolean check;
Here, a variable check is declared which is of type enum boolean.
Example of enumerated type
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday,
saturday};
int main(){
enum week today;
today=wednesday;
printf("%d day",today+1);

Prepared by IT & CSE Page 88


Programming with C - Lab
return 0;
}
Output
4 day

typedef
typedef is a keyword used in C language to assign alternative names to existing types. Its
mostly used with user defined data types, when names of data types get slightly
complicated. Following is the general syntax for using typedef,
typedef existing_name alias_name
Lets take an example and see how typedef actually works.
typedef unsigned long ulong;
The above statement define a term ulong for an unsigned long type. Now
this ulong identifier can be used to define unsigned long type variables.
ulong i, j ;

Application of typedef
typedef can be used to give a name to user defined data type as well. Lets see its use with
structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name ;
Here type_name represents the stucture definition associated with it. Now
this type_name can be used to declare a variable of this stucture type.
type_name t1, t2 ;

Example of structure definition using typedef


#include< stdio.h>
#include< conio.h>
#include< string.h>
typedef struct employee
{
char name[50];
int salary;
} emp ;
void main( )
{
emp e1;

Prepared by IT & CSE Page 89


Programming with C - Lab
printf("\nEnter Employee record\n");
printf("\nEmployee name\t");
scanf("%s",e1.name);
printf("\nEnter Employee salary \t");
scanf("%d",&e1.salary);
printf("\nstudent name is %s",e1.name);
printf("\nroll is %d",e1.salary);
getch();
}

typedef and Pointers


typedef can be used to give an alias name to pointers also. Here we have a case in which
use of typedef is beneficial during pointer declaration.

In Pointers * binds to the right and not the left.


int* x, y ;

By this declaration statement, we are actually declaring x as a pointer of type int,


whereas y will be declared as a plain integer.
typedef int* IntPtr ;
IntPtr x, y, z;
But if we use typedef like in above example, we can declare any number of pointers in a
single statement.

C Preprocessor directives:
• Before a C program is compiled in a compiler, source code is processed by a
program called preprocessor. This process is called preprocessing.
• Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
• Below is the list of preprocessor directives that C language offers.

S.no Preprocessor Syntax Description


1 Macro #define This macro defines constant value and can be
any of the basic data types.
2 Header file #include The source code of the file “file_name” is
inclusion <file_name> included in the main program at the specified
place
3 Conditional #ifdef, #endif, #if, Set of commands are included or excluded in
compilation #else, #ifndef source program before compilation with
respect to the condition

Prepared by IT & CSE Page 90


Programming with C - Lab

4 Other #undef, #pragma #undef is used to undefine a defined macro


directives variable. #Pragma is used to call a function
before and after main function in a C program

A program in C language involves into different processes. Below diagram will help you
to understand all the processes that a C program comes across.

Example program for #define, #include preprocessors in C:


• #define - This macro defines constant value and can be any of the basic data
types.
• #include <file_name> - The source code of the file “file_name” is included in
the main C program where “#include <file_name>” is mentioned.
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
void main()
{

Prepared by IT & CSE Page 91


Programming with C - Lab
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

}
Output:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?

Example program for conditional compilation directives:


a) Example program for #ifdef, #else and #endif in C:
• “#ifdef” directive checks whether particular macro is defined or not. If it is
defined, “If” clause statements are included in source file.
• Otherwise, “else” clause statements are included in source file for compilation and
execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
Output:
RAJU is defined. So, this line will be added in this C file

b) Example program for #ifndef and #endif in C:


• #ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined,
“If” clause statements are included in source file.
• Otherwise, else clause statements are included in source file for compilation and
execution.
#include <stdio.h>

Prepared by IT & CSE Page 92


Programming with C - Lab
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);

#endif
return 0;
}
Output:
SELVA is not defined. So, now we are going to define here

c) Example program for #if, #else and #endif in C:


• “If” clause statement is included in source file if given condition is true.
• Otherwise, else clause statement is included in source file for compilation and
execution.
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}
Output:
This line will be added in this C file since a = 100

Example program for undef in C:


This directive undefines existing macro in the program.
#include <stdio.h>
#define height 100
void main()

Prepared by IT & CSE Page 93


Programming with C - Lab
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}
Output:
First defined value for height : 100
value of height after undef & redefine : 600

Prepared by IT & CSE Page 94

You might also like