NOTES FOR C LANGUAGE PART 4
How to declare and input/output array of structure?
Let us see an example
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct emp
{
char name[20];
int age;
float salary;
};
void main()
{
struct emp e[3];
int i;
float temp;
for(i=0;i<3;i++)
{
printf(“\n enter name,age and salary”);
scanf(“%s %d %f”,e[i].name,&e[i].age,&temp);
e[i].salary=temp;
}
printf(“\n details of 3 employees”);
for(i=0;i<3;i++)
{
printf(“\n name=%s,age=%d and salary=%f”,e[i].name,e[i].age,e[i].salary);
}
getch();
}
for given input:
ram 22 2200
shyam 23 2300
ajay 24 2400
output will be
name=ram,age=22,salary=2200.000000
name=shyam,age=23,salary=2300.000000
name=ajay,age=24,salary=2400.000000
How to declare and initialize and output array of structure?
let us see an example
#include <stdio.h>
#include <conio.h>
struct emp
{
char name[20];
int age;
float salary;
};
void main()
{
struct emp e[3]={“ram”,22,2200,”shyam”,23,2300,”ajay”,24,2400};
int i;
printf(“\n details of 3 employees”);
for(i=0;i<3;i++)
{
printf(“\n name=%s,age=%d and salary=%f”,e[i].name,e[i].age,e[i].salary);
}
getch();
}
output will be
name=ram,age=22,salary=2200.000000
name=shyam,age=23,salary=2300.000000
name=ajay,age=24,salary=2400.000000
How to pass a structure variable to function?
let us see an example
#include <stdio.h>
#include <conio.h>
struct emp
{
char name[20];
int age;
float salary;
};
void main()
{
struct emp e={“ram”,22,2200};
void display(struct emp);
display(e)
getch();
}
void display(struct emp e)
{
printf(“\n name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
}
output will be
name=ram,age=22,salary=2200.000000
Demonstrate call by value and structure variable passed to function.
#include <stdio.h>
#include <conio.h>
struct emp
{
char name[20];
int age;
float salary;
};
void main()
{
struct emp e={“ram”,22,2200};
void alter(struct emp);
printf(“\nbefore call of function inside main name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
alter(e);
printf(“\n after call of function inside main name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
getch();
}
void alter(struct emp e)
{
printf(“\n inside called function before change name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
strcpy(e.name,”raman”);
e.age=25;
e.salary=2500;
printf(“\n inside called function after change name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
}
output will be
before call of function inside main name=ram,age=22,salary=2200.000000
inside called function before change name=ram,age=22,salary=2200.000000
inside called function after change name=raman,age=25,salary=2500.000000
after call of function inside main name=ram,age=22,salary=2200.000000
How to pass array of structure to function?
let us see an example remembering array is always passed by reference.
We can note that passing to single dimension numeric array to function and passing single dimension array of structure are analogous.
#include <stdio.h>
#include <conio.h>
#define size 3
struct emp
{
char name[20];
int age;
float salary;
};
void main()
{
struct emp e[size];
void input(struct emp []);
void output(struct emp []);
input(e);
output(e);
getch();
}
void input(struct emp e[])
{
int i;
float temp;
for(i=0;i<size;i++)
{
scanf(“%s %d %f”,e[i].name,&e[i].age,&temp);
e[i].salary=temp;
}
}
void output(struct emp e[])
{
int i;
for(i=0;i<size;i++)
{
printf(“\n name=%s,age=%d and salary=%f”,e[i].name,e[i].age,e[i].salary);
}
}
for given input:
ram 22 2200
shyam 23 2300
ajay 24 2400
output will be:
name=ram,age=22,salary=2200.000000
name=shyam,age=23,salary=2300.000000
name=ajay,age=24,salary=2400.000000
What do you mean by pointer to structure?
We know about pointer to integer,pointer to float and so on. Similary we can have pointer to structure.
Let us see an example:
#include <stdio.h>
#include <conio.h>
struct emp
{
char name[20];
int age;
float salary;
};
void main()
{
struct emp e={“ram”,22,2200};
struct emp *f;
f=&e;
printf(“\n name=%s,age=%d,salary=%f”,f->name,f->age,f->salary);
getch();
}
explanation:we can access data members of structure variable e in following ways:
during ouput
e.name, e.age, e.salary
f->name,f->age,f->salary;
(*f).name,(*f).age,(*f).salary; /* *f.name is invalid */
during input
e.name, &e.age, &e.salary
f->name,&f->age,&f->salary;
(*f).name,&(*f).age,&(*f).salary;
How can we pass structure variable as reference.
#include <stdio.h>
#include <conio.h>
#include<string.h>
struct emp
{
char name[20];
int age;
float salary;
};
void main()
{
struct emp e={“ram”,22,2200};
void alter(struct emp*);
printf(“\nbefore call of function inside main name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
alter(&e);
printf(“\n after call of function inside main name=%s,age=%d,salary=%f”,e.name,e.age,e.salary);
getch();
}
void alter(struct emp *f)
{
printf(“\n inside called function before change name=%s,age=%d,salary=%f”,f->name,f->age,f->salary);
strcpy(f->name,”raman”);
f->age=25;
f->salary=2500;
printf(“\n inside called function after change name=%s,age=%d,salary=%f”,f->name,f->age,f->salary);
}
output will be
before call of function inside main name=ram,age=22,salary=2200.000000
inside called function before change name=ram,age=22,salary=2200.000000
inside called function after change name=raman,age=25,salary=2500.000000
after call of function inside main name=raman,age=25,salary=2500.000000
Write a program to demonstrate function taking structure as argument and returning structure.
let us see an example
#include<stdio.h>
#include<conio.h>
struct complex
{
float real,imag;
};
void main()
{
struct complex c1={1,1},c2={2,2},c3;
struct complex add(struct complex,struct complex);
c3=add(c1,c2);
printf(“\n result of addition: real=%f,imaginary=%f”,c3.real,c3.imag);
getch();
}
struct complex add(struct complex c1,struct complex c2)
{
struct complex temp;
temp.real=c1.real+c2.real;
temp.imag=c1.imag+c2.imag;
return temp;
}
What do you mean by union?
A union is a user defined data type in c which allows the overlay of more than one variable in the same memory location.
Why we need union?
Normally every variable is stored in a separate location and as a result, each of these variables have their own addresses, often, if it is found that some variables used in the program are used only in a small portion of the source code. For example, if a string of 200 bytes called filename is required by the first 500 lines of code oly, and another string called output of 400 bytes is required by the rest of the code(i.e. both strings are not needed simultaneously), it would be a waste of memory to declare separate arrays of 200 and 400 bytes. The union construct provides a means by which the memory space can be shared and only 400 bytes of memory are used.
How to declare union?
Declaration of union is similar to structure but uses union keyword instead of struct keyword. E.g.
union emp
{
char name[20];
int age;
};
declaration of union variable.
union emp e;
or
union emp
{
char name[20];
int age;
}e;
now e has two data members name and age. Variable e will take no. of bytes required by largest data member which is 20 bytes.
Explain scope of a union/struct variable.
Scope of union is similar to scope of struct. If declaration of struct/union is not inside any curly brace then any function can declare and use struct/union variable known as global declaration. If declaration of struct/union is inside curly brace of function definition then the function which contains structure declaration can declare and use struct/union variable and declaration of structure is known as local scope.
#include<stdio.h>
#include<conio.h>
void main()
{
union emp
{
char name[20];
int age;
}e;
strcpy(e.name,”ram”);
printf(“\nname= %s”,e.name);
printf(“\nage= %d”,e.age); /* age has meaningless value */
e.age=20;
printf(“\nname= %s”,e.name); /* now name has meaningless value */
printf(“\nage= %d”,e.age);
getch();
}
explanation: in above program only main function can declare and use union variable.
Differentiate structure and union.
Structure
|
Union
|
Structure uses struct keyword.
|
Union uses union keyword.
|
The amount of memory taken by a structure variable is sum of sizes of all the data members.
|
The amount of memory taken by a structure variable is size of largest data member in terms of no. of bytes.
|
We can store values in all data members without any loss of value.
|
Only one union data member can be assigned value which we can access. The data member which stores value most recently has valid value and others have invalid values.
|
We don’t need additional variable to identify active(most recently used) member.
|
We need additional variable to identify active(most recently used) member.
|
Structure consumes more memory when compared to union when not all the members are required to access simultaneously.
|
union consumes less memory when compared to structure when not all the members are required to access simultaneously.
|
Write a program to demonstrate memory difference between structure and union
#include<stdio.h>
#include<conio.h>
void main()
{
union emp1
{
char name[20];
int age;
}e1;
union emp2
{
char name[20];
int age;
}e2;
printf(“\n no. of bytes taken by structure %d”,sizeof(e1));
printf(“\n no. of bytes taken by union %d”,sizeof(e2));
getch();
}
Write short notes on enumerated data type.
enum is a keyword which can be used to create user defined data type. using enum we can assign symbolic name to small list of integers.
#include<stdio.h>
#include<conio.h>
enum Boolean {false,true};
void main()
{
enum Boolean e; /* declaration of enum variable which can take value either false or true */
e=true;
printf(“\n value of true=%d”,e);
getch();
}
explanation: since first item in list is false therefore it will take value 0, second item in list is true therefore it will take value 1 and so on if any more.
Dynamic memory allocation
What do you mean by dynamic memory location/write short notes on dynamic memory allocation/write short notes on malloc, calloc, realloc, free/ how dynamic memory allocation helps to solve complex problems?
dynamic memory allocation refers to the allocation of memory during progam run time for variables which are pointer. Dynamic memory is allotted from heap memory. Dynamic memory allocation helps to solve complex problems of data structure like linked list, stacks, queues where run time memory allocation is prime need.. Dynamic memory is also important when size of array is not known during program run time.
There are some function which are useful in dynamic memory allocation:-
1.malloc-declaration - void * malloc(size_t size);
The function malloc allocates a block of memory in bytes as specified by parameter size from the free data area (heap). it allows a program to allocate an exact amount of memory explicitly, as and when required. the parameter passed to malloc is of the type size_t. this type is declared in the header file stddef.h. ‘size_t’ is equivalent to unsigned int data type.
return value of malloc: malloc returns address of first byte of memory chunk allotted if memory allocation is successful otherwise returns NULL.
int *p;
p=(int *)malloc(sizeof(int)*1000);
Above statement will allocate 2000 bytes of memory from heap.
If it is required to check whether memory allocation was successful or not we can use following statement:
if (p==NULL)
printf(“\n memory allocation failed”);
2.free-declaration- void free(void *block);
free is a library function that dis-allocates memory block allotted to pointer by function calloc,malloc or realloc.
example
free((int*)p);
3.calloc-declaration- void * calloc(size_t nitems, size_t size);
calloc is a library function to allocate memory. if memory allocation is successful it return address of first byte of memory chunk allotted otherwise returns NULL.
e.g.
two allocate memory of 2000 bytes as in the previous example of malloc we can use
int *p;
p=(int *)calloc(1000,sizeof(int));
4.realloc-declaration- void *realloc(void *block,size_t size)
realloc adjusts the amount of memory allocated to the block to size, copying the contents to a new location if necessary.
int *p;
p=(int *)malloc(sizeof(int)*5); /* allocated 10 bytes */
suppose after some time we need 20 bytes and we do not want to destroy values stored in 10 bytes then we can use realloc as follows
p=(int *)realloc(p,sizeof(int)*10);
Differentiate malloc,calloc.
malloc
|
calloc
|
malloc takes one argument which is type unsigned int which stands for total no. of bytes to allocate
|
calloc takes two arguments which are no. of items to allocate memory for, and size of each item in bytes
|
The memory location allotted by malloc contains garbage value at memory location.
|
The memory location allotted by calloc contains default value zero or null string( for pointer to character).
|
Syntax is: void * malloc(size_t size)
|
Syntax is :void * calloc(size_t nitems, size_t size)
|
Write short notes on null pointer.
null pointer is special pointer value defined in stdlib.h,,malloc.h,stdio.h etc. when library function malloc,calloc, fopen fails operating successfully; they assign null pointer value to pointer. Sometimes usually in data stature we initialize pointer to value NULL.
using NULL:
(i) int *p=NULL; /* pointer initialized to NULL pointer value */
(ii)int *p;
p=(int *)malloc(2000);
if(p==NULL)
{
we can give statements to execute when memory allocation fails.
}
(iii)FILE *fp;
fp=fopen(“c:\\ram.txt”,”r”);
if(fp==NULL)
{
we can give statements to execute when file open operation fails.
}
How to avoid declaration of ordinary variable if using pointer?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *p;
p= (int *) malloc (sizeof(int)); /* allocate 2 bytes only */
*p=30;
printf(“\n value =%d”,*p);
getch();
}
How to create single dimension (numeric) dynamic array?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *p;
int n,i;
printf(“\n enter no. of elements”);
scanf(“%d”,&n);
p= (int *) malloc (sizeof(int)*n); /* allocate 2*n bytes to generate an array p[n] */
printf(“\n enter %d values”,n);
for(i=0;i<n;i++)
scanf(“%d”,&p[i]); /* or (p+i) */
printf(“\n values are\n”);
for(i=0;i<n;i++)
printf(“%d”,p[i]); /* or *(p+i) */
getch();
}
How to create single dimension (character) dynamic array?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char *p;
int n,i;
printf(“\n enter maximum no. of characters”);
scanf(“%d”,&n);
p= (char *) malloc (sizeof(char)*(n+1)); /* allocate 1*(n+1) bytes to generate an array p[n+1] */
printf(“\n enter string”);
scanf(“%s”,p);
printf(“\n the string is %s”,p);
getch();
}
How to create double dimension (numeric) dynamic array?/using array of pointers?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *p[3]; /* pointers are p[0],p[1],p[2] */
int n,i,j;
printf(“\n enter no. of columns”);
scanf(“%d”,&n);
for(i=0;i<3;i++)
p[i]= (int *) malloc (sizeof(int)*n);
/* now p[3][n]; exists */
printf(“\n enter %d values are\n”,n*3);
for(i=0;i<3;i++)
for(j=0;j<n;j++)
scanf(“%d”,&p[i][j]); /* or (*(p+i)+j) */
printf(“\n the array is \n”);
for (i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf(“\t %d”,p[i][j]); /* or *(*(p+i)+j) */
printf(“\n”);
}
getch();
}
How to create double dimension (numeric) dynamic array/using pointer to array ?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int (*p)[3];
int n,i,j;
printf(“\n enter no. of rows”);
scanf(“%d”,&n);
p= (int *[]) malloc (sizeof(int)*n*3);
/* now p[n][3]; exists */
printf(“\n enter %d values are\n”,n*3);
for(i=0;i<n;i++)
for(j=0;j<3;j++)
scanf(“%d”,&p[i][j]); /* or (*(p+i)+j) */
printf(“\n the array is \n”);
for (i=0;i<n;i++)
{
for(j=0;j<3;j++)
printf(“\t %d”,p[i][j]); /* or *(*(p+i)+j) */
printf(“\n”);
}
getch();
}
How to create double dimension (numeric) dynamic array/using pointer to pointer?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int **p;
int m,n,i,j;
printf(“\n enter no. of rows and columns”);
scanf(“%d %d”,&m,&n);
p= (int **) malloc (sizeof(int)*m);
for(i=0;i<m;i++)
p[i]=(int *)malloc(sizeof(int)*n);
/* now p[m][n]; exists */
printf(“\n enter %d values are\n”,m*n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&p[i][j]); /* or (*(p+i)+j) */
printf(“\n the array is \n”);
for (i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(“\t %d”,p[i][j]); /* or *(*(p+i)+j) */
printf(“\n”);
}
getch();
}
How to declare and use pointer to structure without using ordinary variable?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct emp
{
char name[20];
int age;
};
void main()
{
struct emp *e;
e=(struct emp *)malloc(sizeof(struct emp));
printf(“\n enter details of employee name and age:\n”);
scanf(“%s %d”,e->name,&e->age);
printf(“\ndetails of employee : name and age:\n”);
printf(“%s %d”,e->name,e->age);
getch();
}
How to declare dynamic array of structure using pointer to structure?
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct emp
{
char name[20];
int age;
};
void main()
{
struct emp *e;
int n;
printf(“\n enter no. of elements”);
scanf(“%d”,&n);
e=(struct emp *)malloc(sizeof(struct emp)*n);
/* now we have struct emp e[n]; */
printf(“\n enter details of %d employees : name and age:\n”,n);
for(i=0;i<n;i++)
{
scanf(“%s %d”,e[i].name,&e[i].age);
}
printf(“\ndetails of %d employees : name and age:\n”,n);
for(i=0;i<n;i++)
{
printf(“%s %d”,e[i].name,e[i].age);
}
getch();
}
File Handling
How pointer is useful in file handling?
file handling requires declaration of pointer to structure FILE. FILE is a predefined structure in stdio.h. when we open file for file handling purposes(reading, writing, modifying) using fopen library function file is opened in computer’s memory location address of which is stored in pointer to structure FILE.
Write short notes on file handling in c/ write short notes on input-output operation on file.
File i/o operation is always done in a program in the following sequences
1.open the file
before performing i/o in any file, file must be opened.
fopen is the library function used to open the file.
declare the pointer to predefined structure FILE (all in uppercase)
FILE *fp;
open the file using fopen library function.
fp=fopen(“filename”,”mode”);
filename should be any valid dos filename , mode can be any one out of the modes r,w,a,r+,w+,a+. Be careful mode must be given in lowercase only. ‘rt’ indicates read-text mode ‘rb’ read-binary.
2. read or write to the file
read/ write data from/to the opened file.
3. close the file
during a write to a file, the data written is not put on the disk immediately but it is stored in the buffer. When the buffer is full, all its contents are actually written to the disk. The process of emptying of buffer by writing its contents to disk is called flushing the buffer.
closing the file flushes the buffer and releases the memory space taken by the pointer to structure.
closing of file is done using fclose library function
fclose(filepointer);
Write notes on different modes of opening file.
(i)r : stands for read only mode. file must be existing otherwise fopen function will return NULL.
(ii) w: stands for write mode. if file exists file is replaced by new contents. If file doesn’t exist new file is created.
(iii) a: stands for append. if file exists new contents can be added at last. If file doesn’t exist file is created.
(iv) r+: opens an existing file for reading, adding and modifying. If file doesn’t exist fopen will give NULL.
(v)w+: opens a file for reading, adding and modifying. If file exists it will be overwritten.
(vi)a+: opens a file for reading and adding only. If file does not exist new file is created. we can modify existing contents.
What are the different ways of organizing files in c/ differentiate text and binary mode of file handling.
How does append mode differs from write mode?
Dos creates files in two different ways viz. as binary file or text file therefore there are two different ways of organizing the file.
Text mode
|
Binary mode
|
if the file is specified as the text type, the file i/o functions interpret the contents of the file when reading or writing the file.
|
if a file is specified as the binary type, the file i/o functions do not interpret the contents of the file when reading or writing the file.
|
When reading file in text mode, end of file character(^z with ascii value 26 ) must be there to tell that end of file has reached.
|
No end of file character is required.
|
A new line character is stored in file as carriage return and linefeed.
|
A new line character is stored as linefeed character
|
Additional disk memory is consumed to store same data when compared to binary mode( for each new line character it takes two bytes)
|
Consumes no additional disk memory (for each new line it takes just one byte).
|
When numbers oriented data need to save it is disk space consuming when compared to binary mode of file handling for example:
When storing value of integer , int a=1244; it will take 4 bytes in text mode.
|
When numbers oriented data need to save it is less disk space consuming when compared to text mode of file handling for example:
When storing value of integer , int a=1244; it will take 2 bytes because ‘a’ is integer
|
Text mode of file handling is slow because there is interpretation/conversion from text to binary and binary to text when reading and writing.
|
It is fast because there is no interpretation/conversion from text to binary and binary to text.
|
Write program to create sequential data file.
example of character by character reading and writing sequentially(unformatted).
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
FILE *fp;
fp=fopen(“c:\\ram.txt”,”w”);
if(fp==NULL)
{
printf(“\n file open operation failed “);
getch();
exit (1);
}
printf(“\n enter contents of file control+z to end the file\n”);
while((ch=fgetc(stdin))!=EOF)
fputc(ch,fp);
fclose(fp);
fp=fopen(“c:\\ram.txt”,”r”);
printf(“\n contents of file is as follows\n”);
while((ch=fgetc(fp))!=EOF)
fputc(ch,stdout);
getch();
}
Write contents of one file to other file.
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main(int argc,char *argv[])
{
FILE *fp,*ft;
if (argc!=3)
{
printf(“\n usage: programfilename sorucefilename targetfilename”);
getch();
exit (1);
}
fp=fopen(argv[1],”r”); /* open source file in read mode */
ft=fopen(argv[2],”w”);/* open target file in write mode */
/* let us check either of the file open operations failed, if failed then terminate program */
if (fp==NULL || ft == NULL)
{
printf(“\n file open operation failed”);
getch();
exit (1);
}
while((ch=fgetc(fp))!=EOF)
fputc(ch,ft);
fclose(fp);
fclose(ft);
getch();
}
save the file with name cp.c. compile the file (executable file will generate)
go to dos prompt and give command:
cp teena.text meena.txt press enter
Note:source file teena.txt must be existing and target file name must not be existing with read only attribute set or a directory with same name must not be in use.
Write short notes on error handling(during file i/o operation) in c.
There may be many sources of error when doing file input/output operation
(i)When opening the file for reading one can assume the file already exists but it is not existing.
(ii)When opening the file for reading file exists in bad sector where problem of reading is generating.
(iii)When opening the file for write mode, file already exists with read-only attribute set therefore file can not be replaced
(iv)When opening the file for write mode, disk is write protected or a directory with same name is already in use.
when error in opening file occurs fopen returns NULL therefore further operation on files must be done after checking value of file pointer is not NULL.
a global variable ‘errno’ is set to a specific value meant to designate the type of error, whenever an error occurs in a file i/o function. Value of ‘errno’ can be used to perform the required exception processing. The function ‘perror’ can be used to print the nature of the error. the function ‘strerror’ can be used to obtain a char pointer to the error string . the function ‘clearer’ can be used to reset the error indicator of a stream.
Write short notes on fprintf and ,fscanf.
(i)fscanf: fscanf is a library function which can be used to read data from stream(file).
syntax is fscanf(filepointer,”format string”,&var1,&var2…);
(ii)fprintf:fprintf is a library function which can be used to write data to stream(sequence of bytes or file).
syntax is fprintf(filepointer,”format string”,var1,var2…);
fscanf and fprintf is used for formatted data read/write to stream sequentially,
Write short notes on Random access file.
random access file allows to read/ write data from any location. random access file uses function fread,fwrite for the purpose of reading and writing. when reading/writing data in random access file length of record must be fixed. structure declaration and its variable declaration allows user to read and write data in terms of fixed no. of bytes. Noramlly random access file uses binary mode of file handling.
Write a program using fscanf, fprintf to read/write sequential formatted input/output file operation.
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
FILE *fp;
fp=fopen(“c:\\ram.txt”,”w”);
if (fp==NULL)
{
printf(“\n file open operation failed”);
getch();
exit (1);
}
printf(“\n enter name,age and salary control+z to end”);
while(fscanf(stdin,”%s %d %f”,name,&age,&salary)!=0)
fprintf(fp,”%s %d %f”,name,age,salary);
fclose(fp);
fp=fopen(“c:\\ram.txt”,”r”);
while(fscanf(fp,”%s %d %f”,name,&age,&salary)!=0)
fprintf(stdout,”%s %d %f”,name,age,salary);
fclose(fp);
getch();
}
Write short notes on buffered and unbuffered files.
the character written to a stream are immediately output to the file or device in unbuffered file. the character written to a stream are accumulated and then written as a block to the file or device in buffered files. buffering speeds file input/output operation. stdin and stdout are unbuffered if they are not redirected otherwise they are fully buffered.
Write short notes on low-level file handling.
when the functions fread, fwrite, etc. , are used data transfer occurs first to the buffers and then to the disk. in low level file functions, the data is not buffered but directly written to the file. the low leve file function use file handles. open, read, write etc. are used as unbuffered file handling.
#include<stdio.h>
#include<io.h>
void main()
{
FILE *fp;
fp=fopen(“text”,”wt”);
fwrite(“1. this is fwrite\n”,1 strlen(“1. this is fwrite\n”),fp);
write(fileno(fp),”2. this is write \n”);
fclose(fp);
}
data of file “text” is as follows
2. this is write
1. this is fwrite
Write short notes on following functions:-
fseek, ferror, ftell, fflush, fread/fwrite, feof, rewind, perror, error/Write the format of fseek function
(i)fseek:
int fseek(FILE *stream,long offset,int position-with-respect-to);
the function fseek set the file pointer associated with a stream to a new position.
parameters are as follows:
stream:stream whose file pointer fseek will set.
offset:difference in bytes between position-with-respect-to and the new position for the stream.
position-with-respect-to can be any one out of three settings:
SEEK_SET (seek from beginning),SEEK_CUR (seek from current position), SEEK_END (seeks from end of file).
return value: returns value 0 on success.
on failure it returns a non zero value. fseek returns an error code only on an unopened file or when a non-existing device is accessed.
(ii)ferror: ferror is a macro that tests the given stream for a read or write error. If the stream error indicator has been set, it remains so until clearer or rewind is used or stream is closed.
syntax: int ferror(FILE * stream)
return value: returns a non-zero if an error is detected on the specified stream.
(iii)ftell: fetll returns the current file pointer position for the specified stream.
syntax: long ftell(FILE *stream)
return value: on success returns the current file pointer position.
on error returns -1 and sets errno to a positive value.
(iv)fflush: if the given steam has a buffered output then fflush writes the output of the stream to the associated stream.
syntax: int fflush(FILE *stream)
return value: on success it returns 0
on failure it returns EOF.
Appendix:
Write a c program that read the afternoon day temperature for each day of the month and then report the month average temperature as well as the hottest ad coolest day.
this program requires single dimension array to store day temperature of each day. it requires addition of elements of single dimension array finding average and coolest and hottest day.
#include<stdio.h>
#include<conio.h>
void main()
{
float a[31];
float sum=0,avg,hot,cool;
int n,i,hotday,coolday;
printf("\n enter no. of days in current month");
scanf("%d",&n);
printf("\n enter each day temperature");
for(i=0;i<n;i++)
scanf("%f",&a[i]);
/* find sum now */
for(i=0;i<n;i++)
sum=sum+a[i];
/* find average */
avg=sum/n;
hot=a[0];
cool=a[0];
hotday=1;
coolday=1;
for(i=1;i<n;i++)
{
if(hot<a[i])
{
hot=a[i];
hotday=i;
}
if(cool>a[i])
{
cool=a[i];
coolday=i;
}
}
printf("\n average temperature=%f",avg);
printf("\n hottest temperature %f on day %d",hot,hotday);
printf("\n coolest temperature %f on day %d",cool,coolday);
getch();
}
Write program to print all combination of 1 2 3.
this requires nested loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k;
clrscr();
for(i=1;i<=3;i++)
for(j=1;j<=3;j++)
for(k=1;k<=3;k++)
if(i!=j && j!=k && i!=k)
printf("\n %d %d %d",i,j,k);
getch();
}
Write program using the function power(a,b) to calculate the value of a raised to b.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c;
float power(float,float);
printf(“\n enter value of a and b”);
scanf(“%f %f”,&a,&b);
c=power(a,b);
printf(“\n value =%f”,a);
getch();
}
float power (float a,float b)
{
return pow(a,b);
}
Write program to count no. of tabs, new lines, character and space of a file.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int i,ch=0,sp=0,tb=0,ln=0;
char rd[80];
fp=fopen("c:\\ram.txt","r");
while(fgets(rd,80,fp)!=0)
{
ln++;
for(i=0;rd[i]!='\0';i++)
{
if(rd[i]=='\t')
tb++;
else if(rd[i]==' ')
sp++;
else
ch++;
}
}
fclose(fp);
printf("\n space=%d,tab=%d,newline=%d",sp,tb,ln);
}
Write program to create a file ‘data’ containing a series of integers and count all even numbers present in the file ‘data’.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int i,even=0,odd=0,n;
fp=fopen("c:\\ram.txt","w");
printf("\n enter integers , control+z to end\n");
while(fscanf(stdin,"%d",&n)!=EOF)
{
fprintf(fp,"\t%d",n);
}
fclose(fp);
fp=fopen("c:\\ram.txt","r");
while(fscanf(fp,"%d",&n)!=EOF)
{
printf("\t%d",n);
if(n%2==0)
even++;
else
odd++;
}
printf("\n no. of even=%d,no. of odd =%d",even,odd);
getch();
}
What will be output statement to print ‘welcome to programming world’ in c and c++
ans:
in c:
#include<stdio.h>
#include<conio.h>
void main()
{
printf(“welcome to programming world”);
getch();
}
in c++:
#include<iostream.h>
#include<conio.h>
void main()
{
count<<“welcome to programming world”;
getch();
}
Write statement to double the value of v and halve the value of x
ans:
v=v*2;
x=x/2;
if a program consists the statement scanf (“%3d”,&n) and input is 1234567:
(a)what value is assigned to n ( assuming n is integer):
ans 123
(b)what value will be assigned to n if control string reads scanf(“%7d”,&n);
ans since 1234567 is out of range of signed integer therefore it will store negative value.
Write program to accept two numbers and operator (+,-,*,/) and display the result using if-else.
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b;
char ch;
printf("\n enter +, -, * ,/ as one of the operator ");
printf("\n enter expression as follows: operand1 operator operand2\n");
scanf("%f %c %f",&a,&ch,&b);
if(ch=='+')
printf("\n addition=%f",a+b);
else if(ch=='-')
printf("\n subtraction=%f",a-b);
else if(ch=='*')
printf("\n multiplication=%f",a*b);
else if(ch=='/')
printf("division=%f",a/b);
else
printf("\n invalid operator");
getch();
}
Write a c program to read following matrix (row wise) and print the same column wise:
2 3 6
-7 0 8
ans:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3];
int i,j;
printf("\n enter values in row measure order\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\n the matrix in printed in column measure order\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf("\t%d",a[j][i]);
printf("\n");
}
getch();
}
What function is enables a user to input information while program is in execution?
ans : scanf, getch, getchar, getche ,gets ,fgets ,fscanf etc.
Write a program to read item number, rate and quantity from an inventory file and print the followings:
1. items having quantity > 5.
2. total cost of inventory.
#include<stdio.h>
#include<conio.h>
#include<process.h>
struct item
{
int itemnumber;
int quantity;
float rate;
};
void main()
{
FILE *fp;
struct item e;
float cost=0;
int n;
fp=fopen("inv","wb");
if(fp==NULL)
{
printf("\n file open operation failed");
exit (1);
}
while(1)
{
printf("\n enter itemnumber,quantity and rate:\n");
scanf("%d %d %f",&e.itemnumber,&e.quantity,&e.rate);
fwrite(&e,1,sizeof(e),fp);
printf("\n enter more item if yes then enter 1,if no enter 0:");
scanf("%d",&n);
if(n==0)
break;
}
fclose(fp);
fp=fopen("inv","rb");
while(fread(&e,1,sizeof(e),fp)!=0)
{
cost=cost+e.rate*e.quantity;
if(e.quantity>5)
printf("\n item number=%d,item quantity=%d,item rate=%f",e.itemnumber,e.quantity,e.rate);
}
printf("\n total cost of inventory=%f",cost);
getch();
}
Write program of binary search .
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],st=0,en=4,mi=(st+en)/2,val,i;
printf(“\n enter five values in ascending order”);
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
printf(“\n enter value to search”);
scanf(“%d”,&val);
for ( ;st<=en;mi=(st+en)/2)
{
if (val>a[mi])
st=mi+1;
else if (val<a[mi])
en=mi-1;
else
break;
}
if(st<=en)
printf(“\n value found at index %d”,mi);
else
printf(“\n value not found”);
getch();
}
write program to count no. of vowels,consonant and space.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[80];
int i,v=0,s=0,c=0;
printf("\n enter sentence:");
gets(a);
for(i=0;a[i]!='\0';i++)
{
switch(a[i])
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
break;
case ' ':
s++;
break;
default :
c++;
}
}
printf("\n vowel=%d,space=%d,consonant=%d",v,s,c);
getch();
}
Write program to count no. of words,character,spaces,vowels.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[80],b[40][40];
int i,v=0,s=0,c=0,j=0,k=0,w=0;
printf("\n enter sentence:");
gets(a);
for(i=0;a[i]!='\0';i++)
{
switch(a[i])
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
break;
case ' ':
s++;
break;
default :
c++;
}
if(a[i]!=' ')
{
b[k][j]=a[i];
j++;
}
else
{
b[k][j]='\0';
j=0;
k++;
}
}
b[k][j]='\0';
for(i=0;i<=k;i++)
if(strcmp(b[i],"")!=0)
{
w++;
}
printf("\n vowel=%d,space=%d,consonant=%d, no. of words=%d ",v,s,c,w);
getch();
}
Write program to find whether a given year is leap or not.
#include<stdio.h>
#include<conio.h>
#include<conio.h>
void main()
{
int n;
printf(“\n enter an year “);
scanf(“%d”,&n);
(n%400==0||(n%4== 0 &&n%100!=0))?printf(“\n leap”):printf(“\n not leap”);
getch();
}
No comments:
Post a Comment