Lab Week3&4 Abdullah Emam
Lab Week3&4 Abdullah Emam
______________________
Course Instructor / Lab Engineer
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
No of Checks
SUB TOTAL
TOTAL SCORE
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
test
expression?
True
Two-way Branching
Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 3
Programming with C - Lab
Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 4
Programming with C - Lab
Output:
(1) Enter student marks: 55
Student Passed
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;
Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 5
Programming with C - Lab
Output:
(1) Enter number: 53
53 is odd number
(2) Enter student marks: 42
42 is even number
Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 6
Programming with C - Lab
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;
Lab Manual for Programming in C Lab by. Abdullah Emam IT program Page 8
Programming with C - Lab
}
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.
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.
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
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)
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
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
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
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.
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;
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”.
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.
#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.
#include<stdio.h>
int main()
{
int x=1;
labelx:
printf(“\n%d”,x);
x=x+1;
if(x<=10)
goto labelx;
}
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)
#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+
#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:
}
}
Page 26
Lab Manual for Programming in C Lab by. Abdullah Emam IT program
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.
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*/
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.
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
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:
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
Elements of array:
1 2 3
4 5 6
7 8 9
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>
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*/
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.
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];
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*/
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.
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()
{
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
{
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;
};
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.
printf("Date : %d-%s-%d",e1.dj.d,e1.dj.m,e1.dj.y);
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.
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 = ♠
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
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.
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()
{
}
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.
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.
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.
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 */
. . . .
}
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.
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.
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();
}
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);
}
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
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
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.
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]);
}
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)
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();
}
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( );
}
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.
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.
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);
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);
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();
}
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
fprintf(stdout,"%s\t%10d\t%8.2f\t%d\t%11.2f\n",item,number,price,
quantity,value);
}
fclose(fp);
getch();
}
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
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: ");
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);
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);
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);
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.
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 ;
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.
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.
}
Output:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
#endif
return 0;
}
Output:
SELVA is not defined. So, now we are going to define here