Professional Documents
Culture Documents
Storage of data in variables and arrays is temporary- all such data are lost when a program
terminates. Files are used for permanent maintenance of large amounts of data. Computers store
files on secondary storage devices, especially on disks. Usually, a file is a collection of related
records. Each record is a collection of data items (or fields). E.g., a company maintains employee
payroll file, which stores records about the salaries paid to all employees. Each record in that file
may include the fields like empno, name, department, salary … etc. All these records in payroll file
should be organized in such a way that each record should be retrieved very easily.
To facilitate the retrieval of specific records from a file, at least one field in each record is
chosen as a record key. A record key identifies a record as belonging to a particular person or
entity. E.g., empno in payroll file is used to retrieve the specific record easily.
What is a file?
“A file is a collection of data that is stored permanently on disk”.
(or)
“A file is a stream of bytes of arbitrary length, which is used to hold data”.
A file is a sequence of bytes that will be implemented by the operating system to provide
persistent (or permanent) storage. Each file is owned by some user and is protected from
unauthorized use by other users. File provides reliable data storage and it will provide simple,
easy-to-use operations to access data.
1
Types of files
Types of Files
There are two ways to link and access files in a program. These are: by means of library functions
and by means of system-calls of operating system.
1. The files linked and accessed through the library functions are known as stream-oriented
files. These are also called as high-level files, since these involve high-level (programming
language level) functions.
2. It is also possible to link and access files directly by means of an operating system. The
system calls of operating system connect the files with the program. The files linked and
accessed using system calls known as system-oriented files. These are also known as low-
level files because low-level (system level) commands or functions are involved.
Stream-oriented files are supported by C library functions which are common for all operating
systems. But system-oriented files are not at all common to all operating systems because system
calls for each operating system are different.
Stream-oriented files are easier to work with than the system-oriented files because the same
library functions may be used regardless of the device or disk files are involved. Also, the data can
be stored in a manageable form such as one byte at a time.
Stream-oriented files can be subdivided into two categories: text files and binary files. The text
files consist of consecutive characters. These characters can be interpreted as individual data items
or as components of strings or numbers. The manner in which these characters are interpreted is
determined either by the particular library functions used to transfer the information, or by the
format specifiers those start with % with in the library function.
The binary files organize data into blocks containing contiguous bytes of information. These blocks
represent more complex data structures such as arrays and structures. A separate set of library
2
functions is available for processing these binary files. These library functions provide single
instructions that can transfer entire arrays or structures to or from files. These binary files are very
useful to handle file containing machine language contents, e.g., .exe or .com files.
To understand the stream-oriented files, first, it is necessary to understand the concept of stream.
Random-access files are the stream-oriented files in which the data can be accessed
directly. E.g., if a file contains 100 records and we want to access 57 th record in that file, then it is
not necessary to access all the previous 56 records first. We can directly place our file pointer to 57 th
record directly. The random-access files are called as direct-access files.
In order to process the sequential-access file, first we should learn basic operations on files:
3
to read from keyboard and write to monitor (The term console refers to keyboard-monitor pair). But
the file I/O functions read from a file and write to a file (or to the same file).
File I/O is always done in a program in the following sequence:
1. Open the file.
2. Read from or write to the file.
3. Close the file.
A) Opening files:
Before performing any file I/O, the file must be opened. While opening the file, the following are to
be specified:
The name of the file and
The manner (or mode) in which it should be opened (i.e., for reading, writing, reading and
writing, appending at the end of file, or overwriting the file …etc).
The function fopen() is used to open a file. It accepts two strings as arguments with the following
form:
FILE *fopen(filename,mode);
B) Writing to files:
The functions printf(), puts() and putchar() are used to write the content to monitor. To write to
a file, the functions fprintf(), fputs() and fputc() are used. All these functions accept a file pointer
as one of the parameters along with other parameters required by the standard output functions.
1) Writing a character to a file: To write a character to a file, do the following:
Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
Read the character from keyboard using getchar() or scanf().
Input that character as an argument to the function fputc() along with the file pointer
as follows:
int fputc(character,pointer_to_FILE);
Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
Read the string from keyboard using gets() or scanf().
Input that string as an argument to the function fgets() along with the file pointer as
follows:
int fputs(string,pointer_to_FILE);
3) writing formatted data to a file: To write formatted data from a file do the following:
Open the existing file in “w”,“w+”,”a” or “a+” mode using fopen() and handle the file
pointer that is returned.
Read the formatted data from keyboard using scanf().
Input that formatted data to function fscanf() along with the file pointer as follows:
1) Reading a character from a file: To read a character from a file, do the following:
a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer
that is returned.
b. Use the function fgetc() that is used to read a character from file which has the
following prototype:
int fgetc(pointer_to_FILE);
From this prototype it is clear that:
6
o fgetc() takes an argument which is a pointer to the structure FILE and returns
an unsigned integer value that should be converted to a character. We should
place that file pointer which is already returned by using fopen().
o When end-of-file is reached or there is an error, the predefined character EOF
is returned.
Ex: FILE *fp;
char ch;
fp=fopen(“sample.txt”,”r”); //step-a
ch=fgetc(fp); //step-b
while(ch!=EOF) //read character-by-character till the end-of-file is reached
{
printf(“%c”,ch);
ch=fgetc(fp);
}
2) Reading a String from a file: To read a string from the file, do the following:
a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer
that is returned.
b. Use the function fgets() that is used to read a string of specified length from file
which has the following form:
char * fgets(string,size,pointer_to_FILE);
3) Reading formatted data from a file: To read formatted data from a file do the following:
a. Open the existing file in “r” or “r+” mode using fopen() and handle the file pointer
that is returned.
b. Use the function fscanf() that is used to read formatted data (i.e., different forms of
data at a time) from file which has the following prototype:
D) Closing a file: During a write to a file, the data written to it is not put on the disk immediately.
It is stored in a buffer (a temporary storage area in primary memory). When the buffer is full or the
program gets ended, all the content in buffer is actually written back to the disk. The process of
emptying the buffer by writing its content back to disk is called flushing the buffer.
Closing a file flushes the buffer and releases the space taken by FILE structure which is
returned by fopen(). If we want to close a file, pass its file pointer to the function fclose() that has
the following form:
int fclose(pointer_to_FILE);
8
What are pre-defined streams?
stream Meaning
stdin Standard input device (opened for input).
stdout Standard output device (opened for output).
stderr Standard error output device (opened for error output).
The output of a function like printf() goes to the stream stdout. A function like scanf() receives
its input from the stream stdin. We can write to any of the output streams by using functions
like fputc(),fputs()…etc and read from any of input streams by using functions like
fgetc(),fgets()…etc. These streams are considered to be files. Usually, stdin is connected to the
keyboard, stdout and stderr are connected to monitor, stdaux is connected to serial port com1
and stdprn is connected to lpt1.
Write a program to create a file, write some text to it and print that text on monitor.
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
printf(“\n Enter the file name to be created:”);
scanf(“%s”,filename);
fp=fopen(filename,”w”); //first, open file in write mode
if(fp==NULL)
{
printf(“\n unable to open”);
exit(0);
}
printf(“\n Enter some text to file (ctrl+d to end):”);
ch=getchar(); //read a character from key board
while(ch!=EOF) // check that the entered character is not ctrl+d
{
fputc(ch,fp); //write that character to file
ch=getchar(); //again, read a character from key board
}
fclose(fp); // close the file
int feof(pointer_to_FILE);
has the following form:
From this prototype, it is clear that:
o feof() function takes one argument: the file pointer to which we want to search for
EOF character.
o On success, it returns non-zero if an end-of-file character is detected. If end-of-file is
not reached, then it returns 0.
10
Program #3
Write a program to count number of characters, alphabets, digits, white spaces and
special symbols in an existing file.
#include<stdio.h>
main()
{
char filename[15],ch;
FILE *fp;
int ccount,acount,dcount,scount,sscount;
printf(“\n Enter an existing file name to be read:”);
scanf(“%s”,filename);
fp=fopen(filename,”r”); //open an existing file in read mode
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
ccount=acount=dcount=scount=sscount=0; //initially, all counts are 0
ch=fgetc(fp); //read a character from file
while(ch!=EOF)
{
ccount++; //increment character count by 1
if(toupper(ch)>=’A’ &&toupper(ch)<=’Z’) //if it is alphabet
acount++; //increment alphabet count by 1
else if(ch>=’0’ && ch<=’9’) //if it is digit
dcount++; //increment alphabet count by 1
else if(ch==’ ‘ || ch==’\t’ || ch==’\n’) //if it is white space
scount++; //increment space count by 1
else
sscount++; //increment special symbol count by 1
ch=fgetc(fp); //again, read a character from file
}
fclose(fp); //close the file
printf(“\n No.of characters=%d”,ccount);
printf(“\n No.of Alphabets=%d”,acount);
printf(“\n No.of digits=%d”,dcount);
printf(“\n No.of spaces=%d”,scount);
printf(“\n No.of special symbols=%d”,ccount);
}
Output:
Enter an existing filename to be read: master.txt
No.of characters=160
No.of Alphabets=122
No.of digits=2
No.of spaces=30
No.of special symbols=6
11
Program #4
Write a program to write student records to a sequential file and access them
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
float fees;
struct date_of_birth
{
int day,month,year;
}dob;
}s1;
main()
{
FILE *fp;
char ch;
fp=fopen(“sturecords”,”w”); //create a new file
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
scanf(“%d%s%d%f%d%d
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student
record from keyboard
fprintf(fp,”%d\t%s\t%d\t%f\t%d/%d/%d”,s1.rno,s1.name,s1.rank,s1.fees,s1.dob.day,
s1.dob.month,s1.dob.year); //write the student record to file
printf(“\n Do u want to add one more record (y/n):”);
scanf(“\n%c”,&ch);
}while(toupper(ch)!=’N’);
fclose(fp);
12
The above program has one disadvantage: if the members of structure are increased, the functions
fprintf() and fscanf() become difficult to understand. To solve this problem, fwrite() and fread()
functions are introduced.
The function fwrite() is used to write formatted data to the file. It has the following form:
size_t fwrite(ptr,size,n,pointer_to_FILE);
The function fread() is used to read formatted data from the file. It has the following form:
size_t fread(ptr,size,n,pointer_to_FILE);
From this prototype, it is clear that:
o fread() takes four arguments: ptr is a pointer to the block into which data is read.
Size is a value of type size_t, an unsigned integer, used to hold the length of each
item read, in bytes. n is a value of type size_t, an unsigned integer, used to hold
number of data items to read. Pointer_to_FILE is the pointer to the file in which the
data is to be read.
o On success, it returns the number of items (not bytes) actually read. On end-of-file or
error, it returns 0.
Ex: struct student s1;
fread(&s1,sizeof(s1),1,fp);
By using fread() and fwrite() functions, fixed-length records are written or read. By using fprintf()
and fscanf() functions, variable-length records are written or read.
By using fread() and fwrite(), the above program can be modified as follows:
13
Program #5
Write a program to write student records to a sequential file and access them
#include<stdio.h>
struct student
{
int rno,rank;
char name[15];
float fees;
struct date_of_birth
{
int day,month,year;
}dob;
}s1,s2;
main()
{
FILE *fp;
char ch;
fp=fopen(“sturecords”,”w”); //create a new file
if(fp==NULL)
{
printf(“\n Unable to open file”);
exit(0);
}
do
{
printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
scanf(“%d%s%d%f%d%d
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student
record from keyboard
fwrite(&s1,sizeof(s1),1,fp); //write the student record to file
printf(“\n Do u want to add one more record (y/n):”);
scanf(“\n%c”,&ch);
}while(toupper(ch)!=’N’);
fclose(fp);
14
15.3. RANDOM - ACCESS FILES
Random-access files are the stream-oriented files in which the accessing of data is done at any
position. That is the data should be written to or read from any position in the specified file. To
move the position pointer in the file, three functions are very helpful:
1. fseek()- places the position pointer at the specified position.
2. rewind()- places the position pointer to the beginning of the file.
3. ftell()- tells the current position of the position pointer in the file.
fseek() function: The fseek() function is used to place the position pointer at the specified location
in the file. It has the following prototype:
int fseek(pointer_to_FILE,offset,location);
rewind() function: The function rewind() is used to place the position pointer to the beginning of
the file. It has the following prototype:
void rewind(pointer_to_FILE);
ftell() function: The function ftell() is used to get the current file position pointer. It has the
following prototype:
long ftell(pointer_to_FILE);
15
o on success, it returns the current file pointer position. On error, it returns -1 and sets errno
to a positive value.
Program #6
Write a program to demonstrate fseek(), ftell() and rewind() functions
#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp=fopen("stud.txt","w+");
if(fp==NULL)
{
printf("\n Unable to open file:");
exit(0);
}
printf("\n Enter the text into file (end with ctrl+d):");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp);
ch=getchar();
}
ch=fgetc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=fgetc(fp);
}
fseek(fp,5,SEEK_SET); //place the cursor at the position 5
printf("\n The cursor is at %d position",ftell(fp)); //tells the cursor position as 5
printf("\n Enter the character to insert:");
scanf("\n%c",&ch);
fputc(ch,fp); //inserts the character at specified position
ch=fgetc(fp);
while(ch!=EOF) //prints all the characters from specified position
{
printf("%c",ch);
ch=fgetc(fp);
}
rewind(fp); //places the cursor to the beginning of file
printf("\n The cursor is at %d position",ftell(fp));
fclose(fp);
}
Output:
Enter the text into file (end with ctrl+d):
pradeep is a good boy.
16
Program #7
Write a program to reverse the content of file.
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen("sample.txt","w+");
if(fp1==NULL)
{
printf("\n Unable to open file:");
exit(0);
}
printf("\n Enter the text into file (end with ctrl+d):");
ch=getchar();
while(ch!=EOF)
{
fputc(ch,fp1);
ch=getchar();
}
fp2=fopen(“reverse.txt”,”w”);
fseek(fp1,0,2);
while(fseek(fp1,-2,1)= =0)
{
ch=fgetc(fp1);
putchar(ch);
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
}
Output:
Enter the text into file (end with ctrl+d):
Files topic is easy one.
.eno ysae si cipot seliF (content of reverse.txt)
Program #8
Write a program to print the transpose of matrix in a file
#include<stdio.h>
main()
{
FILE *fp;
int i,j;
int matrix[2][3]={{1,2,3},{4,5,6}};
fp=fopen(“mat”,’w”);
fprintf(fp,”\t Transpose matrix\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
fprintf(fp,”%d\t”,matrix[j][i]);
fprintf(fp,”\n”);
}
fclose(fp);
}
Output:
Content of file “mat”
1 4
2 5
3 6
17
Program #9
Write a program to search for particular word in a file
#include<stdio.h>
#include<string.h>
main()
{
WriteFILE *fp;
a program to demonstrate a random-access file
char ch,temp[15],word[15],filename[15];
#include<stdio.h>
int count=0;
main()
{
printf("\n Enter file name:");
struct student
scanf("%s",filename);
{
fp=fopen(filename,"w");
int rno,rank;
printf("\n Enter
charthe text (end with ctrl+d):");
name[15];
ch=getchar(); float fees;
while(ch!=EOF) struct date_of_birth
{ {
fputc(ch,fp); int day,month,year;
ch=getchar();
}dob;
} }s1;
fclose(fp);
FILE *fp;
printf("\n
char ch; Enter the word to be searched:");
scanf("%s",word);
int sz,len,n,i;
fp=fopen(filename,"r");
fp=fopen(“sturecords”,”w”); //create a new file
//fscanf(fp,"%s",temp);
if(fp==NULL)
while(!feof(fp))
{
{ printf(“\n Unable to open file”);
fscanf(fp,"%s",temp);
exit(0);
}if(strcmp(temp,word)==0)
docount++;
} {
fclose(fp); printf(“\nEnter student details (rno,name,rank,fees and date of birth):”);
printf("\n The word %s is occured %d times",word,count);
scanf(“%d%s%d%f%d%d
}
%d”,&s1.rno,s1.name,&s1.rank,&s1.fees,&s1.dob.day,&s1.dob.month,&s1.dob.year); //read the student
Output:
record from keyboard
Enter the file name: sample.txt
fwrite(&s1,sizeof(s1),1,fp); //write the student record to file
Enter the text printf(“\n
into file (end with to
Do u want ctrl+d):
add one more record (y/n):”);
Mater minds are not made.
scanf(“\n%c”,&ch);
Master }while(toupper(ch)!=’N’);
minds are born.
Enter the fclose(fp);
word to be searched: minds
The word minds is occurred 2 times.
sz=sizeof(s1);
len=ftell(fp);
n=len/sz;
fp=fopen(“sturecords”,”r”); //open the file in read mode
if(fp==NULL)
What is { the purpose ferror()?
The ferror() is printf(“\n
a macro Unable to open
that tests thefile”);
given file pointer for a read or write error. It has the
exit(0);
following } prototype:
do
{ int ferror(pointe r_to_FILE);
printf(“\n Enter the record number to read (o to stop):”);
From this prototype,scanf(“%d”,&i);
it is clear that:
if(i>0 && i<=n)
o ferror(){ function takes one argument: the file pointer .
fseek(fp,(i-1)*sz,SEEK_SET);
o On success, it returns non-zero if an error is detected on the named file pointer.
fread(&s1,sz,1,fp);
printf(”\n%d\t%s\t%d\t%f\t%d/%d/%d”,s2.rno,s2.name,s2.rank,s2.fees,s2.dob.day,
s2.dob.month,s2.dob.year);
}
}while(i);
Program fclose(fp);
#10
}
18
Output:
Enter student details (rno,name,rank,fees and date of birth):
1 master 1 27500.00 12 3 1990
Do you want to add one more record (y/n):y
Enter student details (rno,name,rank,fees and date of birth):
2 maya 13 23500.00 11 9 2004
Do you want to add one more record (y/n):y
Enter student details (rno,name,rank,fees and date of birth):
3 maneesha 14 22500.00 23 3 1982
Do you want to add one more record (y/n):n
20
Program #12
Write a program convert the text in file into upper case
#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen(“master.txt”,”r”);
fp2=fopen(“case.txt”,”w”);
ch=fgetc(fp1);
while(ch!=EOF)
{
fputc(toupper(ch),fp2);
ch=fgetc(fp1);
}
fclose(fp1);
fclose(fp2);
fp2=fopen(“case.txt”,”r”);
ch=fgetc(fp2);
while(ch!=EOF)
{
printf(“%c”,ch);
ch=fgetc(fp2);
}
fclose(fp2);
}
output:
content of master.txt
=======
Master minds are not born. They are made.
But master minds are mad.
Master minds’ numbers consist of digits: 0-9
The persons who read this text are master minds
content of case.txt
=========
MASTER MINDS ARE NOT BORN. THEY ARE MADE.
BUT MASTER MINDS ARE MAD.
MASTER MINDS’ NUMBERS CONSIST OF DIGITS: 0-9
THE PERSONS WHO READ THIS TEXT ARE MASTER MINDS
Error-handling
While processing files, we usually assume that:
o The file that is opened exists.
o There is enough space on the disk for the file.
o The functions fseek(), fread(), fwrite()…etc carry out the requested job successfully.
It is important to note that these assumptions are not always true. There is possibility of the
following errors in manipulating files:
21
Error Reason
File not found Wrong file name used (spelling mistake, error in the path specified) or file
actually not present.
Disk full When writing to a disk with no more free sectors.
Disk write The disk has its write protect tag put on or some software has disabled writes
protected to the disk.
Unexpected EOF File length is zero of file length is less than that expected.
Sector not found (i) Reading and writing to two different streams, one as read only and
the other write only, but the file used for these streams is the same.
(ii) The disk head is not aligned on the physical sectors.
The error-handling functions in C are:
perror() function: The perror() function is used to print the nature of the error. It has the
following prototype:
The argument msg points to an optional user-defined message. This message is printed first,
followed by a colon and the implementation-defined message that describes the most recent
error. If you call perror() when no error has occurred, the message displayed is no error.
Program
Write a program to demonstrate perror() function
#include <stdio.h>
#include <stdlib.h>
main()
{
FILE *fp;
char filename[80];
23
Multifile Compilation
Multiple files can be compiled at a time using the command cc. Suppose that there are three files
namely, “first.c”,”second.c” and ”third.c”. These three files can be compiled at a time.This can be
done as follows:
cc first.c second.c third.c
These files will be separately compiled into object files as “first.o”, “second.o” and “third.o” and then
linked to produce an executable program file a.out.
Note:
1) It is also possible to compile each file separately and link them later. E.g., the commands :
cc –c first.c
cc –c second.c
will compile the source files “first.c” and “second.c” into object files “first.o” and “second.o”.
They can be linked together by the command:
cc first.o second.o
2) We may also combine the source files and object files as follows:
cc sample.c second.o
only “sample.c” gets compiled and then linked with the object file “second.o”. This approach
is very useful when one of the multiple source files need to be changed and recompiled or an
already existing object files is to be used along with the program to be compiled.
3) The linker always assigns the same name to the executable object file as a.out. When we
compile another program, this file will be overwritten by the executable object code of the
new program. If we want to prevent from happening, we should rename the file immediately
by using the command: mv a.out name
24
SHORT ANSWER QUESTIONS
25
38. How do variables and symbolic names differ?
39. What are enumeration variables? How are they declared?
40. What would be the value of ‘x’ after execution of the following statement?
int x,y=10;
char z=’a’;
x=y+z;
41. In what ways does a switch statement differ from an if statement?
42. What is a null statement?
43. Compare in terms of their functions, the following pairs of statements.
(i) break and goto
(ii) while and do while
44. Distinguish between (i) Global and (ii) Local variables.
45. How is a pointer initialized?
46. What is the difference between ‘call by reference’ and ‘call by value’?
47. What is the output of the given code?
main()
{
int a,b,x=10;
a=b=x+5;
a=10;
b=20;
printf(”%d %d %d”, a, b, x);
}
26
q=&p;
i=10;
printf(“%d”, **q);
printf(“%d”, *p);
}
52.) Differentiate between getchar() and gets() functions?
52) Define an algorithm.
53) Write the rules for type- conversion.
54) How can you define string constants?
55) Define C token with an example.
56) Differentiate between keywords and identifiers.
57) Define Program loop.
58) Differentiate between Entry-controlled loop and Exit-controlled loop.
59) From the given statement
for(X=(m+n)/2; X>0; X=X/2)
60)justify whether it is valid or not.
61) What is single subscript variable?
62) Give the declaration of two dimensional arrays.
63) Classify functions and define them.
(i)Define longevity.
(ii) Differentiate between malloc and calloc functions.
64) What are logical operators?
65) What is sequential file procession?
66) Write syntax for scanf();
67) Define getchar statement.
68)Define Structure in C programming.
69) What are the values of K and i in the following program:
int K , i =1;
K=i++;
printf(“K= %d, i= %d”,K,i);
80) How can the size of a structure be determined? In what units is the size reported?
81) If a pointer variable points to a structure that contains an array as a member, how can the
element of the embedded array be processed?
82) What are the various file-types that can be specified?
28
UNIT I
4. Write a program to convert the lower case characters to its upper case
characters.
6. Write a program to find the type of triangle formed by the given sides.
10. What are the basic data types and sizes? List out the secondary data types?
12. Write a C-code to find the maximum number among three numbers using conditional
operator.
13. Write a program that reads a character from the keyboard and prints the following
i.) Is the character alphabetic?
ii.) Is the character numeric?
iii.) If alphabetic, is the character uppercase?
iv.) If alphabetic, is the character lowercase?
16. Write about space requirements for variables of different data types.
29
17. Explain about increment and decrement operators, conditional operators in C.
18. Describe four basic data types. How could we extend the range of values they represent?
19. In inventory management, the Economic Order Quantity for single item is given by
EOQ= 2 x demand rate x Set up costs
Holding cost per item per unit time
23. Explain Arithmetic, Rotational, Logical and assignment operators with suitable examples.
24. Write a program to determine whether a number is odd or even and print the message
“Number is odd” or “Number is even” (i) without using else option and
(ii) using else option.
30
UNIT II
1. Write a program to find all prime numbers with in a given set of input numbers.
10. Write syntax of for-loop? Write the while-loop statement equivalent to for-loop.
11. Write a program to count the no.of characters, no.of lines, no. of words, no. of spaces in
given text using switch statement.
15. Write a C program to check whether the given number is perfect or not.
19. Write a program that will read a positive integer and determine and print its binary
equivalent.
31
22. Write a program to reverse a given number of 5 digits.
23. Write a complete C program to compute and print the first m Fibonacci numbers, where m is
the input to the program.
24. Write a program that reads in an integer value for n and then sums the integers from n to
2*n if n is non-negative or from 2*n to n if n is negative. Write the code in two versions one
using only for loop and the other using only while loop.
25. The mathematical operation min(x,y) can be represented by the conditional expression
(x<y)? x: y In similar fashion, using only conditional expression describe the mathematical
operations min(x,y,z) and max(x,y,z,w).
26. The following code is a recursive function that computes the gcd of two positive integers:
int gcd(int p, int g)
{ int r;
if((r=p%q)==0) return q;
else return gcd(q,r);
}
Write and test an equivalent iterative function.
27. Write a program to find the factorial of a given number using recursion.
28.
Differentiate between do-while and while.
What are function prototypes? Explain.
Write a program to read a line of text and write it out backwards using recursion.
32
UNIT III
3. Explain the concept of character arrays and pointers and pointer arrays with
suitable examples.
8. Given are two dimensional arrays A and B which are sorted in ascending order.
i.) Write a program to merge them into a single sorted array ‘C’ that contains
ii.) every item from arrays A and B , in ascending order.
10. Write C function to compare the two given strings without using library functions.
List out all the library functions used to perform operations on strings and its headerfile.
11. Write a program to find transpose of a matrix into same matrix using functions.
14. Explain the command line arguments. What are the syntactic constructs followed in C?
15. Define an array. In what way an array is different from an ordinary variable? What advantage
is there in defining an array size in terms of a symbolic constant rather than a fixed integer
quantity?
.
16. Write a program to sorting of names using pointer arrays.
33
17. Give syntax and declaration of case statement. Compare it with looping constructs.
18. Write a C program to find the product of two matrices A(m x K) and B(K x n).
19. What is a pointer? How are pointers used in call-by-reference type of parameter passing?
Write a C function Swap(a,b) which interchanges the values of variables a and b.
22. Explain the functions calloc(), malloc() and free() with suitable examples.
.
23. Write a program to sort names using pointer arrays.
34
UNIT IV
1. Write a short note on pointers to structures and unions with suitable examples.
2. Write a program to sort a list of library records on name, author using dynamic
allocation.
4. Write a program to sort a list of birth records by date of birth using dynamic
allocation.
6. Write a program to process the student marks in six subjects and sort it on the
student name.
11. Write a program to read a student record in a class of 10 and display it.
12. Write a program using pointers to find the sum of the diagonal elements in a 4 x 4
matrix?
13. Distinguish between an array of structures and array within a structure. Give an example of
each.
14. Define a structure that represent a complex number (contains two floating – point numbers,
called real and imaginary). Write a C program to add, subtract and multiply two complex
numbers.
15. Distinguish between structures and arrays. Explain structure data types with
examples.
17. Distinguish between structures and arrays. Explain structure data type with examples.
35
18. Write a C program to illustrate the use of Unions.
19. Distinguish between structures and arrays. Explain structure data type with example.
21. Write a program to calculate the subject-wise and student-wise totals and store them on a
part of the structure for 100 students and 3 subjects.
22. Write a program using pointers to read in an array of integers and print its elements in
reverse order
23. What is a self-referential structure? For what kinds of applications are self-referential
structures useful?
24. Write a program for library records processing- sort books on author name. Use other
appropriate entries.
36