C all types of questions
Transcript of C all types of questions
-
7/31/2019 C all types of questions
1/74
C LanguageQ. Explain Advantages of C language. 1) Every language contains some words whose meaning is fixed and that are called as
Key words C contains (32) minimum key words thus it is compact.
2) Speed of C is one of the fastest
3) C is very flexible language i.e. it give minimum errors.
Q. Which are various levels of computer language? 1) Low Level:- A Low level language is directly understood by machine & so its
speed is fastest but it is very difficult to learn e.g. Machine language.
2) High Low:- A High level language is similar to English & so simple to learn butspeed is slow. e.g. Basic, pas cal etc.
3) Middle level:- A middle level language provides best of low level & high level i.e.speed of low
Q. Explain concept of data type. Job of computer is to take data as an input, to process it & to give an information as an
output
Any data has some nature.
e.g. Roll No. is an integer, fees may be alphanumeric,Name is alphabetic
A data type indicates nature of data
* data type in C *
Section- I
1) Name: int
Size: 2 bytes (in RAM)Range: -32768 to 32767
Purpose: Storing whole no. i.e. integer / storing +ve & -ve whole no.s
Q. Explain any tricks for data type int. i) In C when you divide one integer by another int, result is also integer
e.g. consider x= 5/2*2Here, x will be 4
ii) Consider, following statementsx = 32767
1
-
7/31/2019 C all types of questions
2/74
x = x + 1
Here, x will be -32768 this is because range in C circular i.e. after 32767
Comes -32768
2)Name: Unsigned int
Size: 2 bytes (in RAM)Range: 0 to 65535
Purpose: Storing positive integers.
3) Name: Long int
Size: 4 bytes ( in RAM)
Range: -214 cores to 214 cores (approx)
Purpose: Storing +ve & -ve integers in bigger range.
4) Name: Unsigned long int
Size: 4 bytes (in RAM)
Range: 0 to 428 crore (approx)Purpose: storing +ve integers in biggest range.
Q. Concept of precision Precision means no of digits that can be stored accurately after decimal point.
It is of 2 types-I) single ii) double
I) single- It Means accuracy of 6 digits after decimal pt.
ii) double- It Means accuracy of 12 digits after decimal point
Section- II
Fractional data types1.Name: float
Size: 4 bytes
Precision: Single
Range: Parochially Unlimited (unto 1038)Purpose: Day to day fractional calculation
2.Name: double
Size: 8 bytesPrecision: Double
Purpose: Scientific calculationsRange: Practically unlimited (10308)
Q. A float var can also store integers, Explain why not to use float
always
2
-
7/31/2019 C all types of questions
3/74
instead of long.
i) Float does not provide 100% accuracy. e.g. It you store 10 in float, it has to bestored as 10.000001 or 9.999999
ii) Calculations with float are lower than cal with long.
Q. Explain Concept of ASCII Code.
ASCII stands for American standard Code for Information Interchange. A computertreats characters as numbers. Every character has some code. i.e. A no which is store
in memory when you press a character.
There are total 256 character in ASCII code ranging from 0 to 255
concept of ASCII code was developed for standardization. i.e. All computers shouldhave some code for given character.
Unicode :- (Universal Code)
It is the latest code, ASCII code supports only English character where asUnicode supports English as well as non-eng 65536 characters.
Section -III
character data types-
Name: Char
Code used: ASCII
Size: 1 byte
Capacity: 1 character.
Programs in C language.# Objective-
Q. Write a C programmed which displays message Hello Wordmain ( )
{printf(Hello World);
}
Q. What is Function?
Just like a book is sub-divided into chapters, a C program is subdivided into
sections called as Function.
Working of above program-
1) C provides 2 type of functions namely Library function & User defined
function.
2) A library function is a ready-made function doing a particular job C provides
3
-
7/31/2019 C all types of questions
4/74
100 of such function
3) Suppose, you want to do a particular job but no ready-made function is availablethen you have to define your own function
4) [ ]- parenthesis indicates a function.{ - (Opening curly brasses) indicates a function started.
}- ( Closing curly bracket) indicates a function ended.
5) printf is a library function used for printing i.e. displaying on the screen.
6) C uses (;) semicolon as statement terminator out of all C function, one function
is most imp called as main.
Q.Explain significance of function main.
main [ ], is one of the most important function.
* Write a C-program which display following outputwelcome to C
welcome to C + +
main ( ) {
printf (welcome to C);
printf( \n welcome to C + +);
}
Note:- By dealt a printf start displaying output, where, last, printf, ends but you
may take it to next line by using \n.
# Concept of Escape sequence-
An Escape sequence is \ (Backslash) followed by a character. It changes original
meaning of such escape & sequences
e.g. \t, \q, \n, etc.\t - means give a tab.
tab = 4 spaces.
Q.Write a program which displays message HELLO
main ( ){printf(\ Hello \);
}Note:- means message started us ended but you want to change the meaning so useescape sequence \
Consider following printf
4
-
7/31/2019 C all types of questions
5/74
printf (abs\b\bd) ;
It will display add, because back slash b means back space
# objective-When you run any of the previous program, you get output of current program along with
output of previous program provides solution.
Consider following program
main ( ){
clrscr ( );
printf(Hello World);}
clrscr() is a library function which clears the output screen.
# Objective:-When you run any of the previous program, you cant see the output but you see a program
it self provides solution.
Consider,
main ( ){
clrscr ( );
printf (Hello World);printf(\n press any key to continue);
getch( );
}
Q. Explain why to use getch ( ) at the end of main
C provide two screens namely program screen & user screen (output screen)When you run the program, C switches from program screen to user
screen; but C waits there only as long as program is running i.e. for fraction of
second. So C immediately comes back to program screen.
Library function getch waits until user presses any key; so problem is solved.
# Objective:-All previous program show black & white out put. Modify program to display
message Hello Word in blue color with yellow background.
# include
main( )
{clrscr ( );
textcolor (BLUE);
textbackground (YELLOW);
5
-
7/31/2019 C all types of questions
6/74
cprintf(Hello Word);
getch( );
}
Note:-1) text color is a library function which sets foreground (text) color; where as text
background is a function which sets background color.
2) A set of colors is already available. All color names are in upper case.e.g. BLUE, YELLOW, CYAN, RED, etc.
3) All the colors are defined in the file namely , so #include line is used.
4) printf dose not understand color, you must use C printf to use color.
Q. Write a program which displays message Hello at the centre of screen.
main ( )
{
clrscr( );gotoxy(40,12);
printf(Hello);
getch();}
Note:-
By default printf displays message wherever the cursor is; but you may move cursor
wherever you want with library function gotoxy.x stands for column &
y stands for Rows
Q. Write a C program, which defines initializes two variables &
displays their value on the screen.
main ( )
Hello
6
-
7/31/2019 C all types of questions
7/74
{
int x,y;
clrscr( );x=10;
y=20;
printf(x is%d, y is%d,x,y);getch( );
}
Output: z is 10, y is 20
Q. Concept of conversion specification:-printf is used to display the value of a variable of any data type so, it demands that youspecial format for the data type i.e. conversion specification.
Format Table-Data type Format
i) int % d (decimal)% o (Octal)
% x (hexadecimal)
ii) Unsigned int % u (unsigned)
iii) long int % ld (long decimal)
iv)unsigned long int % lu (long unsigned)
v) float % f (float)
vi) double % lf (long float)
vii) char % c (character)
viii) string % s (string)
ix) Pointer % u or % p
Q. Explain types of errors in C
There are following types & errors:
i) compile time errors:-
There are errors in syntax:
e.g. Nat gluing semicolon (;) after a statement ,gluing (;) after main,
7
-
7/31/2019 C all types of questions
8/74
typing key-work in upper case,
You can net run a program in this case, so there is no damage.
ii) Run time errors:
There are the errors which are not report eel. Here, program runs but may give wrong
answer & may crash.e.g. giving wrong format in printf
such errors are the want because your client fauns then.
Q. Write a program which inputs an integer from key-board & displays
it on the screen.
void main ( )
{int x;
clrscr( );
printf (Enter x:);
scant (%d,&x);printf(Inx is%d,x);
getch( );}
Output-
Enter x: 10x is 10
Q. Write a program which inputs 2 integer from key-board & display
their sum.#include
#include
void main()
{int no1,no2;
int sum;
clrscr();printf("Enter no.1:");
scanf("%d",&no1);
printf("Enter no.2:");scanf("%d",&no2);
sum=no1+no2;
printf("\n sum of %d and %d is %d",no1,no2,sum);printf("\n Press any key to continue");
getch();
}
Q. Write a program which inputs makes obtained by a student in 3
subjects & display average for that student.//pro to display average of 3 subject
8
-
7/31/2019 C all types of questions
9/74
#include
#include
void main(){
int sub1,sub2,sub3;
int total;float avg;
clrscr();
printf("Enter marks of the three subject:\n");scanf("%d %d %d",&sub1,sub2,sub3);
total=sub1+sub2+sub3;
avg=total/3.0;
printf("\n Average is %.2f",avg);printf("\n Press any key to continue");
getch();
}
Note:-You can input multiple variables in one scanf; in that case give values space. Separated or
enter separatede.g. Enter marks in 3 subjects: 70
80
90
Q. Write the program which inputs distance in miles & display same
distance in km (1 mile = 1.8 km).//pro to convert miles into km
#include#include
void main()
{float miles,km;
clrscr();
printf("Enter distance in miles:" );scanf("%f",&miles);
km=1.8*miles;
printf("\n %.2fmiles= %.2fkm",miles,km);
printf("\n press any key to continue");getch();
}
Q. Write a program which inputs 2 integers from key-board & display
the largest.//pro to find largest intgers from 2 no.s
#include
9
-
7/31/2019 C all types of questions
10/74
#include
void main()
{int x,y;
clrscr();
printf("\n Enter two integers:");scanf("%d %d",&x,&y);
if(x>y)
{printf("\n %d is largest",x);
}
else
{printf("\n %d is largest",y);
}
getch();
}Q. Explain types of statements.
there are 3 types of statementsi) Sequence:- It is a set of statements which will run only once unconditionally
e.g. x=1;
y=2;
ii) Selection:- Here, a condition is done; otherwise another job is done.
e.g. as shown in previous program.
iii) Loops:- Here, a set of statements is repeated as long as condition is true.
e.g. i=1;while (i=b&&a>=c)
10
-
7/31/2019 C all types of questions
11/74
{
printf("\n % is largest",a);
}else if(b>=a&&b>=c)
{
printf("\n %d is largest",b);}
else
{printf("\n %d is largest",c);
}
getch();
}
Q. Explain logical (Boolean) operator in C.
Logical operators are used to combine multiple conditions. C provides following
logical operator-1. && (AND):- Here , Result is true only when, all the condition are true.
2. : : (OR):- Here, Result is true when at least one of the condition is true3. ! (NOT):- Here, if condition is true then result is false.
Q. sales & chicks wreathe they from a treasure; it so display type of
triangle.
//pro to display type of triangle
#include#include
void main(){
int a,b,c;
clrscr();printf("\n Enter 3 sides :");
scanf("%d %d %d",&a,&b,&c);
if(a+b
-
7/31/2019 C all types of questions
12/74
}
else
{printf("\n ");
}
getch();}
1] Input cost price & selling Price of an item & display whether there is
profit or loss or no profit, no loss.void main()
{
int a,b,c;
clrscr();printf("enter purchasing price");
scanf("%d is purchasing price",a);printf("enter selling price");scanf("%d is selling price",b);
if(a>b)
{
c=a-b;printf("%d is loss",c);
}
else if(b>a){
c=b-a;
printf("%d is profit",c);}
else
{
printf("no loss no profit");}
getch();
}
2] Input marks obtained by a student in 3 sub; check whether student
has passed; if so display grade of the student.
//pro to display whether student is passed & display grade
#include
#include
void main()
12
-
7/31/2019 C all types of questions
13/74
{
int x,y,z;
float avg;clrscr();
printf("\n Enter marks of 3 subject:");
scanf("%d%d%d",&x,&y,&z);avg=(x+y+z)/3;
if(avg>=75)
{printf("\n Distinction");
}
else if(avg>=60&&avg=35&&avg
-
7/31/2019 C all types of questions
14/74
{
printf("\n Point is on y-axis");
}else
{
printf("Point is not on x or y axis");}
getch();
}
Q. Input an year from key-board & check whether it is leap year. An
year when one of the following is true.
1) Year is divisible by 4 but not divisible by 100
2) Year is divisible by 400
//pro for checking leap year
#include
#include
void main(){
int year;
clrscr();printf("\n enter Year:");
scanf("%d",&year);
if((year%4==0&&year%100!=0)||(year%400==0)){
printf("\n %d is leap year",year);}else
{
printf("\n %d is not leap year",year);
}getch();
}
Q. Input a character from key-board & check whether it is lower case
or upper case or a digit or special character.
#include
void main(){
char ch;
clrscr();textcolor(RED);
textbackground(GREEN);
cprintf("Enter a charcter from keyboard");
scanf("%c",ch);
14
-
7/31/2019 C all types of questions
15/74
if(ch>='a'&&ch='A'&&ch='0'&&ch
-
7/31/2019 C all types of questions
16/74
Note:-
void main()
{Int i ;
clrscr();
i=1;while(i
-
7/31/2019 C all types of questions
17/74
sum=sum+no;
i=i+1;
}printf("\n sumis %ld",sum);
getch();
}
Point:-
*Concept of Index variable:- An Index variable is a variable which control no. oftimes the loop will run.
e.g. i in above program.
* Concept of accumulator:- An accumulator is a temporary variable which stores
intermediate resultse.g. sum in above programGenerally, it is initialized with zero for repeated additions and with one for repeat
multiplication
Q. What will happen in the above program if statement sum= 0 is
absent?
You will get a wrong answer. This is because, you are trying to use uninitialisedvariable sum. In that case, C dose not show error but uses non-sense values stored in thevariable i.e. Garbage values.
So, before you use a variable, make sure that you have
initialized variable using one of the following:-i) direct assignment
e.g. sum = 0
ii) Key board input with scanf:e.g. scanf(%d,,&no);
Q. Modify the program before, for multiplying 3 no. s.
Make following change change variable name from sum to product
Initials product with 1. i.e. product = 1
Inside loop replace line of sum with product = product * no; Below loop shrew product;
i = i + 1
i.e. = +1
Q. Draw a table which explains execution of sum program. (no. e.g. 10,
20, 30, or whatever are given by us).i i< = 3 sum no sum = sum + no
17
-
7/31/2019 C all types of questions
18/74
1 1< = 3 0 10 0+10= 10
(T)
2 2< = 3 10 20 10 +20 = 30(T)
3 3< =3 30 40 30 +40 = 70
(T)4 4< = 3 70
(F)
Note:-
Above table indicates a computer science technique called as dry running, using this
technique, you can verify; whether a program is correct or not without running program.
Q. Write a program which inputs a no. from key-board & displays sum
of its digits for e.g. If you enter 1,2,3, output should be 6 *
#include
#includevoid main()
{Into no,digit,sum;
Clrscr ();
sum=0;printf(\n Enter no:);
scanf(%d,&no);
while(no>0)
{//get last digit
digit=no%10;sum=sum+digit;//reduce no
no=no/10;
i=i+1;}
printf("\n sum is %d",sum);
getch();}
Note:-Logic of above program Whenever you divide a no by 10, Remainder is the last
digit.
e.g. 123%10 give 3Similarly when you divide a no. by 10 last digit is lost
e.g.123/10 = 12
Q. Explain concept of comment.
18
-
7/31/2019 C all types of questions
19/74
Suppose, you are developing a program with complicated logic, then after few daysyou may not understand the program also, other will find it difficult.
So, It is recommended that you write a comment C ignores the comment It is just fordevelopers understanding.
C provides 2 types of comments-
1]Multilane Comment:-e.g.
/*
A loop to find
Sum of digits*/
2]Single line comment-
e.g.// find digit
Q. Write an algorithm for finding largest of two Integers.
1. START2. Define x & y as integer
3. Display Enter two nos4. Input x and y
5. IF x > y
then
Display x is largestelse
Display y is largest.
6. STOP.
Q. Write an algorithm for finding sum of digits of a number.
1. START
2. Define no, digits, sum as Integer
3. Display Enter no
4. Input a no.
5. sum 0
6. while no > 0
loop
digit no Mod. 10
sum sum + digit
no no/10end loop
7. Display sum
8. STOP
Q. Write a program demonstration for loop.
void main ( )
{
19
-
7/31/2019 C all types of questions
20/74
int i;
clrscr ( );
for ( i =1; i< =4; i = i + 1{
printf(in i is %d,i);
}//end forgetch ( );
} //endmain
Note:-
Working of for loop-
It contains 3 section; namely - Initialization, condition & modification
Sections are separated with semicolon (;).First initialization is learn, then inanition is check eel; if it is true statements are executed
& then modification is line. Then, again condition is checked and so on.
Note:-Variation in the loop-
1] You require multiple initializations, conditions, modifications
e.g.
for (i = 1,j = 1; i< = 5 && j< =5; i = i + 1, j = j + 1){
printf (\n%d,%d,i,j);
}//end for
2] Thus, you lave the separate multiple initializations or moderations by comma (,)3] Not giving initialization section;
i = 1;
for (;i< = 4; i = i + 1){
printf(\n d;);
}//end for4] Not giving modification section-
i = 1;
for (; i< = 4;)
{printf(n%d,i);
i = i + 1;
} //end for5] Not giving any section to ovate infelt loop
For (; ;)
{// code
}
20
-
7/31/2019 C all types of questions
21/74
Q. Write a program which inputs no. from key-board & performs their
sum. It should stop when user enters -ve no.
//pro to display addition of no.s upto -ve no. is entered
#include
#includevoid main()
{
int no;long int sum;
clrscr();
sum=0;while(1) //infinite loop
{
printf("\nEnter no,negative to stop:");
scanf("%d",&no);
if(no
-
7/31/2019 C all types of questions
22/74
clrscr ( );
while (i< = 3)
printf(\n%d,i);
i = i +1;
getch( );
}
output- Infinite loop will occur forever display 1. Press control + break to stop it.
Q. Write a program demonstrating pre-increment & post-increment
operators.
//pro for demonstrating pre-increament & post-increament
#include
#include
void main(){
int x=4,y;
clrscr();y=++x; //pre-increament
printf("\n y is %d, x is %d",y,x);
x=4;y=x++; //post-increament
printf("\n y is %d, x is %d",y,x);
getch();
}
Output:-
y is 5, x is 5
y is 4, x is 5
Q. Explain advantages of pre increment & post increment over operator
plus.
1] their speed is faster as compared to plus.2] They are compact.
Q what is the difference between pre-increment &post-increment.
1] Pre & post are some if used an their own i.e. + +x; is same as x + +;
2] But they are different if used in assignment
e.g. consider y = + + x;
It means the following,
x = x + 1;y = x; i.e. pre increment means first increment & then assign.
On the other hand, consider y = x + +;
22
-
7/31/2019 C all types of questions
23/74
It means as following:-
y = x;
x = x + 1; i.e. post increment means first assign then increment.
Q. Write a program which performs input validation using do while
loop.//pro for checking leap year
#include#include
void main()
{int rno;
int sub1,sub2;
float avg;
clrscr();do
{
printf("\n enter positive rollno:");scanf("%d",&rno);
}while(rno
-
7/31/2019 C all types of questions
24/74
#include
void main()
{int no1,no2,result;
int choice;
clrscr();do
{
printf("\n 1.add, 2.subtraction, 3.multiplication, 0.exit. Enter your choice:");scanf("%d",&choice);
if(choice>=1&&choice = 1 && choice < = 3)
{printf(\n Result A calculation is %d, result);
}
Q. Write a program which finds sum of squares of that n numbers.
//pro to find sum of square of n no.
#include
#include
void main(){
24
-
7/31/2019 C all types of questions
25/74
int n,i;
long int sum;
sum=0;clrscr();
i=1;
printf("\n Enter n:");scanf("%d",&n);
while(i=0);
Scanf(%d:,&no);}while(no
-
7/31/2019 C all types of questions
26/74
Q. Rewrite above program using for loop.
for (i=1, fact=1; i
-
7/31/2019 C all types of questions
27/74
fib1=0;
fib2=1;
printf("\n %d \n %d",fib1,fib2);sum=fib1+fib2;
//display number in series,less than 50
while(sum
-
7/31/2019 C all types of questions
28/74
1 2 3
1 2 3 4
void main ( ){
int i,j ;
clrscr( );for (i=1;i
-
7/31/2019 C all types of questions
29/74
Here, you cant display i or j. So, you need 3 rd variable k
1] Add following line before clrscr ( );
int k = 12] Replace statements in inner for loop with following statements
{
printf(%5d,k);k + +;
}//end;
Q. Display following pyramid
a
a b
a b c
a b c dvoid main ( ){int i, j;
char ch;
for (i=1; i
-
7/31/2019 C all types of questions
30/74
Q. Write a program which displays pyramid of as many levels as you
want & for the character you specify.
void main()
{
int I,j,level;char ch;
clrscr();
printf(Enter character:);scanf(%c,&ch);
printf(\n Enter no of levels:);
scanf(%d,&level);for(i=1;i
-
7/31/2019 C all types of questions
31/74
}
getch();
}
Note:-
Above program is similar to the program which displayed following pyramid1
2 3
4 5 6Here, basic problem is how to adjust pyramid shape. Solution is, display space before
drawing in current level. Number of level e.g. by 3 to adjust triangle shape.
30 127 2 3
24 4 5 6
Q. Write a program which interchanges values of two variables.
void main()
{int a,b,c;
clrscr();
printf(\n before interchanging no1=%d ,no2=%d,a,b);//store 1st no into 3rd variable
c=a;
//copy second no into 1st no
a=b;//copy 3rd variable into 2nd no
b=c;printf(\n After interchanging no1=%d, no2=%d,a,b);getch();
}
ARRAYS
Q. What is an array?An array is ordered collection of elements, all same type.
Q. Explain need for array.
Suppose, you need to processmarks of 100 students then there are 2 approaches
1] Without array i.e. Define 100 separate variables. This will be complicated.2] Just define 1 variable which can star 100 values i.e. An Arrays.
31
-
7/31/2019 C all types of questions
32/74
This is manageable because you use just 1 name and simply change the subscript (index)
to access different values.
Q. It following line valid?
int a [ ];
No. this is because arrays in C are static i.e. their size must the defined while creating.This is limitation to arrays in C.
Giving array at the line of definition
e.g. int a[ ] = {10,20,30,};
Q. What will happen in the above program it for loop condition is i
-
7/31/2019 C all types of questions
33/74
y = y* x;
Q. Write a program which finds largest of 5 nos. using array.
Q. Define a string.
A string is set of characters terminated with a special characters called Null.
Q. Explain how to work with a string
1] Define a char array because one char variable can store only 1 character. So, instead
of defining separate variable for each char; Define just 1 array.Give size of array 1 more than maximum required.
e.g. It name of student can be upto 30 characters,
char name [31];
2] Input the string from key-board either using scan f with %s or get s library function.e.g. scanf(%s, name);
e.g. gets (name);
It is recommended to use gets always because it can input a string with or withoutspace. On the other hand, scanf stop when space is found.
Q. Explain significance of Null character.
Null is a character with ASCII code 0. It is not visible on the screen & also not
available on key-board.
It is represented as \0 i.e. A character whose ASCII code is zero. You dont have
to type Null, library functions, like scanf; gets internally put Null
Q. What is the difference between a and a
a is a character constant. It can hold only 1 character. On the then hand a is a stringi.e. set of the character terminated with null value.i.e.\c
e.g. a a + \0
Note:-
Position on 1st character and j on last characters If they are same, increment i &
decrement j
Q. Explain concept of multidimensional arrays.
Suppose, a college contains 4 divisions of 30 students each, then it may be logically
wrong to represent it as int a [120]; instead you use 2-D array i.e. int a [4][30];Similarly, if a college has branches in 5 cities, each city with 4 divisions of 30 students,
then use 3-D array.
e.g. int a [5][4][30];C language allows array with any dimension but generally arrays above 3-D are
rarely used.
33
-
7/31/2019 C all types of questions
34/74
Q. Explain general guidelines for developing a good quality program.
1] Never try to develop a program directly create an algorithm or flowchart & then
translate it in to program2] Make sure that variable names are descriptive & meaningful.
3] Divide the program into multiple sections start each section with a comment describing
purpose and logic of the section. Leave a blank line after each section.4] Indentation is a must along with ending comments for control structures.
Shorting:-Suppose a set of numbers are stored in an array then soling means arranging the no.s
numerically in increasing ruler or decreasing order (In case of character data, alphabetical
ruler).Consider following no.s
70 3 80 -4 20
These no. s can he sorted using a sorting algorithm called as section sort, as
follows.1] Find the smallest in the runs 1st no. to last no; & interchange it with 1st no. So, smallest
comes at 1st position.
2] Now, find the smallest in the range 2nd no. to last no. & interchange it with 2nd no. so, 2nd
smallest comes at 2nd position
Similarly, carry but further steps.
70 3 80 -4 20-4 3 -80 70 20
-4 3 20 70 80
-4 3 20 70 80
FUNCATION
Q. Write a program which sum of two integers using a separate
Function.
1] Above program define 2 functions namely main & sum.2] As per C rulers, you can not define one function inside another function i.e. everyfunction must be defined separately
Section of C function3] Section 2:- It represents name of the function. It is as per following ruler-
i) Function name must start with an alphabetic but can also contain digits later on.ii) Function name can not contain special character like space, dash but can
contain underscore.
iii) Function name should be up to 31 character and should be meaningful.
34
-
7/31/2019 C all types of questions
35/74
iv) Name of a function can be same as that of library function; but in that case the
library function is not available. So, dont give name same as library function
i.e. press control + f after taking cursor on function name. If you get help, itmeans it is library function
4] Section3:- It represents Input to a function Technically, inputs are called as argumentsare as per following rules:-
i) A function can take multiple arguments, al may be off same type or different.ii) Each argument must be defined separately and argument list must be comma(,)
separated.
iii) A function may not take argument in that case, leave section 3 blank or
preferably write void
5] Section 1:- It represents data type of written value i.e. data type of output; it is as per
following rules-
i) A function can take many inputs but can have only one output.ii) Type of output may or may not be same as that of input.
iv) A function may not have out put; in that case write void in section 1. If youleave it blank, C assumes int
Section 1:-It represent data type of the written value i.e. data type of output. It is as per the
following rules.
1. A function can take many inputs but can have only one output.
2. Type of output may or may not be same as that of input.3. A function may not have output in that case write void in section 1. If you leave it
blank C assumes int
Section 4:-
It is the largest & the most imp section of function. It dose the actual job.
Section 5:-
It is optional It is present only If section 1 is not valid. Its job is to written i.e. to send
back output
e.g. return(;
Note:-
Working of above program1) When you run the program main is called internally.
2) Main calls sum, then main stops & controlled transfers to sum; C language copies
value of X into a & y into b
35
-
7/31/2019 C all types of questions
36/74
Compare function definition with function call.
Function Definition Function call1) A function definition contain many lines 1) A function call contains only
one lines
2) You mustnt give semicolon after first 2) You must give semicolon after call
line of definition.
3) You have to give data type of argument 3) You mustnt give data type of
Argument
4) Inside one function your cant define 4) Inside are function can call any
Another function
Q. Explain concept of actual arguments &formal arguments?
Formal arguments are the arguments given in function definitione.g. a, b in above program.
On the other hand actual arguments are the arguments given in function call.e.g. x & y in above program
Whenever you call a function copies each actual into corresponding formal.
e.g. x to a & y to b
Q. Is it possible to give some names from actual & formal
yes, but not recommended multiple function can have variables with same names. Butstill these variables are different.
But this may he confusing so give definition names for actual parameter.
Q. In the above program will following line work inside function sum.z = x + y
No, this is because variable x, y, z are defined inside main. i.e. they are local variableof main as per C rules, local variable of one function are available only do that function.
Q. Write a function which finds factorial of an integer.
//pro to find factorial of given no#include
#includedouble findfact(int n);void main(void)
{
int x;double y;
clrscr();
printf("\n Enter no >= o:");
36
-
7/31/2019 C all types of questions
37/74
scanf("%d",&x);
y=findfact(x);
printf("\n Factorial of %d is %lf",x,y);getch();
}
double findfact(int n){
double result;
int i;result=1;
for(i=1;i0)
{
digit=no%10;result=result+digit;
no=no/10;
}//end while
return result;
37
-
7/31/2019 C all types of questions
38/74
}//end sum digits
Q. Write a function which draws a pyramid using character given by
user & with as many levels as user wants
e.g. if user wants char * & level 3 pyramid will be *
* *
* * *
* * * *
* * * * *
#include#include
void drawpyramid(int level);
void main(void){
int level;
clrscr();
printf("enter no of levels");scanf("%d",&level);
drawpyramid(level);getch();
}
void drawpyramid(int level){
int i,j;
for(i=1;i
-
7/31/2019 C all types of questions
39/74
clrscr();
printf("enter no");
scanf("%d",& x);y=checkeven(x);
if(y==1)//true
{ printf("\n %d is even",x);
}
else{
printf("\n %d is odd",x);
}
getch();}
int checkeven(int no)
{ int result;
if(no%2==0){
result=1;//true
}else
{
result=0;//false
}return result;
}
Q. Write a program which receives an array in a function & finds the
smallest.
//pro which receives an array in a function & finds smallest#include
#include
int checkpalino(int a[],int n);void main(void)
{
int x[6];
int i,smallest;clrscr();
for(i=0;i
-
7/31/2019 C all types of questions
40/74
printf("\n Smallest no is %d",smallest);
getch();
}
int findsmall(int a[],int n)
{ int smallest;
int i;
smallest=a[0];for(i=0;i
-
7/31/2019 C all types of questions
41/74
int result;
int i,j;
i=0;j=strlen(a)-1; //index of last character
while(i
-
7/31/2019 C all types of questions
42/74
getch();
}
int CheckPrime(int no)
{
int result;int i;
if(no==1||no==2)
{result=1;
return result;
//check for prime
i=2;while(i
-
7/31/2019 C all types of questions
43/74
if(i==no)
{
result=1;}
else
{result=0;
}
return result;}// end CheckPrime
Q. Write a function which finds sum of series 1+3+5+7+.+n
//write a function which finds sum of series 1+3+5+....+n#include
#include
long sumseries(int n);
void main(void){
int n;long res;
clrscr();
printf("Enter an odd no representing n:");scanf("%d",&n);
res=sumseries(n);
printf("\nSum of no.s upto %d is %ld",n,res);
getch();}
long sumseries(int n){
long res;
int i=1;res=0;
while(i
-
7/31/2019 C all types of questions
44/74
3. How for will it be available
(provides following storage classes.)
1. Auto ( Automatic)-
Where is it stored RAM
What is the default value Garbage
How far available only in the function in which it is defined storage class oflocal variable is by default auto. e.g. statement int x; actually means, auto int x;
2.Extern (External):-
It is storage class for global variables,
Where is it stored RAM
What is the default value Zero
How far available to al the functions defined below ite.g.
void show(void)
extern int x ;void main(void)
{clrscr();
printf(\n x=%d,x);getch();
}
int x=10;void show(void)
{
printf(\n x=%d,x);}
Note:-In the above program global variable x is defined after main & before show function. So,
show can use x but main can not
But it you give statement extern int x; above main then it
means variable x is defined some where else in the program. So, now main can use x.
3. Register-
Where is it stored CPU register
Default value Garbage
How far available only in the function in which it is defined.
e.g. register int x;
Concept of register-CPU contain certain internal memory locations called as register their size
depends upon CPU.e.g. size of register for 16 bit CPU is 16 bits i.e. 2 bytes
CPU can directly process contents of register, so if a variable is frequently used; e.g. index
variable of for loop, you may like to store it register for faster speed.There may be following limitations-
44
-
7/31/2019 C all types of questions
45/74
1] no. of register is limited, so you may only request C to use register C may or may not
accept it. In that case, C marks it auto.
2] Which variable can be stored, depends on register size; for e.g. considering 2 bytesregister only int or char variable can be stored in register.
4] Static:- Where is it stored RAM
Default value Zero
How far available only in the function in which it is defined but in case ofauto, value of a variable is lost when function is over where as for static, value of
variable is maintained even after function is over.
Note:-
Suppose, first line if increment is int x = 5; then it means auto int x = 5;
In that case output will bex = 6
x = 6x = 6
This is because value auto variable is lost every time function is overBut it 1st line static int x = 5; then output will be
x = 6
x = 7x = 8
This is because static variable is logically when function is called for the 1 st time.
Later on, it value is maintained even after function is over.
Q. Draw a flowchart & write a program using recursive function to findfactorial of given no.
1) Recursion is a process of a function calling itself.
2) When to use recursion?- Use recursion only when solution to a problem can be expressed in terms of
solutions to subsets of the problem.
For e.g. 1] n! = n*n -1 !2] sum (n) = n + sum (n - 1)
3] a b = a*a b - 1
3) How to leveler a properly working recursion function?
- A recursion then must be developed very carefully, otherwise program maycrash. So, ensure following things crash. So, answer following things -
i) There must he a terminating pt i.e. the point at which fun will not call itself.ii) Every time fun calls itself, it should move nearer to the termination pt. So,
ultimately termination pt will be reached.
4) Advantages & disadvantage of rears ion
45
-
7/31/2019 C all types of questions
46/74
Advantages:-
Certain problem in computer science are extremely difficult. Such problem may
become manageable with recursion e.g. Data structure problems.
Disadvantage:-
1) Recursive function must be written carefully, otherwise problem will crash.2) Recursive function may require more execution time & may take more memory as
compared to non-recursive function.
Programdouble power(int a,int b);
void main(){
int a,b;
double result;
clrscr();
printf("enter two numbers:");scanf("%d%d",&a,&b);
result=power(a,b);printf("\n result is %lf",result);
getch();
}//end maindouble power(int a,int b)
{
if(b==0)//terminiting point
{return 1;
}else{
return a*power(a,b-1);//recursion
}// end if}//end power
Flowchart
46
-
7/31/2019 C all types of questions
47/74
Q. write a function which finds ab using recursion
double power(int a,int,b);void main()
{
int a,b;
double result;
clrscr();printf(Enter two nos:);
scanf(%d%d,&a,&b);result=power(a,b);
printf(\n result is %lf,result);
getch();}
double power(int a,int b)
{if(b==0)
{return 1;
}
else
{return a*power(a,b-1); //recursion
}
}
start
Display enter no
Input no
Call fact(no)
stop
Display result
Isno=?
Return
No*fact(no-1)
Return 1
47
-
7/31/2019 C all types of questions
48/74
Q write a fucnction which finds sum of 1st n no.s
#include
#include
long sum(int n);void main(void)
{
int n;long result;
clrscr();
printf(\n Enter no:):
scanf(%d,&n);result=sum(n);
printf(\n sum of %d no is %ld ,n,result);
getch();
}long sum(int n)
{If(n==0)
{
return 0;}
Else
{
return n+sum(n-1);}
}
Q. flowchart of while do-while, for statement
While
48
-
7/31/2019 C all types of questions
49/74
For
start
initialise
Is
conditio
n true
statement
stop
49
start
initialise
Isconditio
n true
statement
stop
modification
start
initialise
-
7/31/2019 C all types of questions
50/74
Note:-
For loop & while loop run minimum zero times, because condition may be initially
false; on the other hand, do-while loop runs minimum once run because 1st statement areexecuted & then condition is checked
For loop is compact, as compared to while loop because it provide initialization,
condition, modification on single line.Generally, rather for loop or while is used. Do-while loop is used only for menu
driven programs & input validation program.
Q. Differentiate between break and continue statements.
Break is a C key-word used to terminate a loop. On the other hand, continue is used to
by pass remaining statements & to go to beginning of loop.e.g. Write a program which inputs salary for five employees & displays bonus as perfollowing rules-
1] Employee gets bonus only if salary is less than 10,000
2] Processing should stop if salary is negative
//calculate bonus if salary
-
7/31/2019 C all types of questions
51/74
{
break;
}if(basic
-
7/31/2019 C all types of questions
52/74
3] Unary Operators:-Operation Operators
1) Unary minus (negation) -
2) Pre-increment/post increment + +3) Pre-decrement/post decrement - -
4) Precedence high priority -
Low priority + +, - -
* Associatively- Right to Left
4] Relational Operators:-Operation Operator
1) Greater than >
2) Less than =4) Less than or equal to < =
5) Equal to = =6) Not equal to ! =
7) Precedence high priory , > =
Low priory = =, 1 =
* Associatively - Left to Right
5] Ternary Operators:- [question mark(?), colon(;)
C Provides only one ternary operator (operator with 3 operands) i.e. ?, :its format is as follows
condition ? expression 1 : expression 2 :
TRUE FALSE
e.g. consider following if
if (x>y)
{
z = x;}
else
{z = y;
}
It may be represented any compact format using? And : (conditional operators)z = x>y? x: y;
52
-
7/31/2019 C all types of questions
53/74
* Associatively - Right to Left
6] Logical Operators:-
These are the operators used for interconnecting condition. They are also called asbad lion operators
Operation Operator1. Logical and & &
2. Logical or : :
3. Logical not !
4. Precedence !
& &: :
Q. Explain Bitwise operators in C.
All the operators except bitwise operators work at variable level, on the other handbitwise operators work at bit level i.e. lowest unit of measurement in computers.
C provides following bitwise operators
1] TILDE ~ (ones complement):-This operator toggles a bit i.e. 1 to 0 and 0 to 1.
e.g. Suppose A in binary format isq = 10100010 then
~ q = 01011101
1] Application of ones compliment-
Suppose, computer wants to find a-b then, it uses following steps.
i) Find ones compliment of b.ii) Add 1 to it to find twos compliment
iii) Add it with a
2] : (Bitwise or) -This operator ors each bit in 1st no. with related bit in 2nd no. Result will be 1
when at least one of the bits is 1
e.g. a = 10100010b = 00111000
a: b = 10111010
Application of bitwise or -It is used for turning on a specific bit without disturbing other bits
e.g. a = 10100010
no. for turning = 00001000on bit 3
53
-
7/31/2019 C all types of questions
54/74
result = 10101010
3] &(Bitwise and)-It ands each bit in no. 1 with cores pending bit in no. 2 Result will be 1 only when
both the bits are 1
e.g. a = 10100010b = 01101010
a & b = 00100010
*Application of bitwise & -It is used to turn off a specific bit without disturbing other bits
e.g. a = 10101010
no. to turn of bit 3 = 11110111
result 10100010
4] ^ CARET (Bitwise XOR)-It XOR (exclusive or) rach bit in no. 1 with corresponding bit in no. 2 Result
is 1 only if both the bits are different
e.g. a = 10100011b = 11010011
a ^ b = 01110000
* Application of bitwise XOR-It XOR any bit with zero, result is same bit; but if you XOR any bit with 1, you get
toggled bit. So, if you want to toggle a particular bit without disturbing other bits, use a no.with all zero and 1 only at particular position:e.g. a = 10100011
no. to toggle bit 3 = 00001000
a ^ b = 10101011
5]
-
7/31/2019 C all types of questions
55/74
Here, all bits are shifted towards right. In that process, right most bit is over written
& 0 is introduced at left most position.
e.g. a = 1000a>>1 = 0100
Application of Bitwise Right Shift-
Right shifting a no. once is like dividing by 2, right shifting n times is like dividing by 2 n.
e.g. a=1000=8a>>=0100=4
a>>2=0010=2
Precedence of bitwise operator-
High Priority: ~
>
&^
Low priority: |
Associativity is left to right for all operators except once compliment- It is right to left.
Complete chart for operators:
Operator Operation Associativity
- Unary Minus++ Increment Right to left
-- Decrement (Unary operator)
! Logical negations
~ Once compliment
* Multiplication Left to right
/ division
% Modulus
+ Addition Left to right
- Subtraction> Bitwise right shift
< Less than
Greater than
>= Greater than equal to
= = Equal to Left to right
55
-
7/31/2019 C all types of questions
56/74
! = Not equal to
& Bitwise Left to right
^ (caret) Bitwise or Left to right
&& Logical and Left to right
|| Logical or Left to right
?: Conditional (ternary) Left to right= Assignment Left to right
Q.Explain concept of pre-processor.
Pre-processor is an altogether separate language which can be mixed with c.
A C program when compiled is first send to pre-processor compiler and then output of pre-
processor goes to c compiler.
Rules for pre-processor statements:-1) A pre-processor statement must start with #
2) It need not terminate with ;Pre-processor provides following facilitiesi)Defining constant with # define
ii) Getting contents of header files
i.e. h file; with #include
#define
Suppose, you require a constant many times in the program then instead of hardcoding i.e.directly giving const each time or storing it in a variable ,which is logically
wrong; use #define to define constant
#define may be also used to change the look of a C program as per your liking.e.g.
#define BEGIN{#define END }
void main()
BEGINprintf(Hello);
END
#include
Header files are with extensions .h. There are two types of header files1) System defined:
e.g. stdio.h,conio.h etc.These files contains prototype i.e. first line of library function, commonly
used constants and structures etc. These files are present in subdirectory include of turbo c
directorye.g.c:\tc\INCLUDE
Such files are included using angle brackets.(< >)
56
-
7/31/2019 C all types of questions
57/74
e.g. #include
2) User defined:Suppose you require 30 constant in 50 program then instead of giving 30
#define statement in each program create your own header file e.g. mymath.h. With these
statements is, store it in a current directory.Use to include then
e.g. #includemymath.h
stands for current directory where as < > stands for directory include.
POINTERS
Q. Explain concept of an address
Memory is set of bytes, when you define a variable, compiler stores it at a specific
bytes .
An address is index no of the bytes at which compiler stores the variable.
Q. What is the pointer?
A pointer is a special type of variable which can store address of any variable of its
base type.
Consider following codeint x=10;
int *p;
p=&x;
Statement int *p; indicates that p is an int pointer, operator & stands for address of
operators e.g. p=&x; ,means store address of x into p.
Q.Explain importance of pointer
In computer, an address is more important than a value. Variable of an ordinary datatype can not process address only pointers can process address. So knowledge of pointers isa must to get full advantage of power of C.
Q. Write a program demonstrating operations of a pointer
void main(){
int x=10;
int *p;
57
-
7/31/2019 C all types of questions
58/74
clrscr();
p=&x;
printf("\n x is %d,address of x is %u",x,&x);printf("\n p is %u and address of p is %u",p,&p);
printf("\n value pointed by p is %d",*p);
*p=40;printf("\n value pointed by p is %d,x is %d",*p,x);
getch();
}
Q. Explain various operation possible with a pointer with a suitable. e.g.
Following operation are possible with a pointer
1) Defining a pointere.g. int *p;
Here , p contains garbage by default.
2) Initializing a pointer :Use operator &(address of) for this process
e.g. p=&x;here , p is initialised with address of x
3) Reading value pointed by pointer i.e. reading *p:e.g. printf(\n %d,*p);
Here , *p is 10 as per given diagram.
4) Changing value pointed by pointer:e.g. *p=40;
it means , at address 1000 store value 40.
5) Displaying address stored in a pointer . An address is an index no. of bytes,in the
range 0 to 65535 i.g. unsigned intger . So , %u is used display address stored in
the pointer
Q. Suppose P contains address of x, then what is the relation between *P
and x.
P contains address of x, *P is the pointed value i.e. x. so, whenever you use *P, itssame as using x.
Q. What will be output of following program
//pro to demonstrate array-pointer relationship
#include#include
void increment(int *x,int *y);
void main (void)
58
-
7/31/2019 C all types of questions
59/74
{
int a=10,b=20;
clrscr();printf("\n Before increment a=%d,b=%d",a,b);
increment(&a,&b);
printf("\n After increment a=%d,b=%d",a,b);getch();
}
void increment(int x){
x=x+1
}
Output-
Before increment a=10
After increment a=10
Memory Map
1000 a
2000 x
After call
Memory Map
1000 a
2000 x
Q. Explain call by value.
It is one of the ways to pass parameters (arguments). Here, value of actual parameter
comes the formal change later on, actual will not change.e.g. in the above program value of actual parameter a comes into formal parameter x, but if
x change later on, a will not change.
Q. Explain what will happen in following cases?Case-I return x ;
return y;
Case -II return x, y, z;
Case -I whenever 1st return statement is found, function is over. So, x will be returned.
Case-II Whenever you give a list of values, only the last value in the list will be returned.
So, z will be returned. Thus, in any case; only one value returns.
59
10
1
10
11
-
7/31/2019 C all types of questions
60/74
Q. What will be output of following program void increment (int*x,
int*y);
//pro to demonstrate array-pointer relationship
#include#include
void increment(int *x,int *y);
void main (void){
int a=10,b=20;
clrscr();printf("\n Before increment a=%d,b=%d",a,b);
increment(&a,&b);
printf("\n After increment a=%d,b=%d",a,b);
getch();}
void increment(int *x,int *y)
{*x=*x+1;
*y=*y+1;
}
Q. Explain concept of call by address.
Or
Explain call by reference.
It is one of the ways topass parameter. Here, address of actual parameter is copied intoformal parameter then if you make any change through the formal, actual parameter willchange. e.g. in the above program; address of actual parameter a comes to formal parameter
x. then if you change through x i.e. you change * x, actual parameter a will change.
You return only one value using keyword return. But, in real life most of the
times, you need to return multiple values. Call by address can be used for returningindirectly multiple values, using pointers.
Q. Write a program using array, pointer relationship.
#include#include
void main (void)
{
int a[5]={10,20,30,40,50};int *p;
int i;
clrscr();
60
-
7/31/2019 C all types of questions
61/74
p=a; //p points to array start
for(i=0;i
-
7/31/2019 C all types of questions
62/74
void show(int *p,int n)
{
int i;for(i=0;i
-
7/31/2019 C all types of questions
63/74
}
2] Once template is defined, you can create as many variable as you want using that
template.3] To accesses element of a structure variable use membership operators
i.e. operator. (dot)
e.g. printf(%d,a.x);
Note:- input and output of a structure variable is just an extension of regular input output
e.g. to input int a; you use scanf(%d,&a); where as to input point a; formal isscanf(%d,&a.x);
Thus, you use regular formal & then follow it with membership operator
Q. Is it possible to use structure inside structure?
Yes, as per C rules an element in a structure can be of ready made type or user definetype.
Q. Write a program which uses structure inside structure
//structure inside structure
#include#include
struct point
{int x;
int y;
};
struct circle
{float radius;
struct point centrepoint;
};void main()
{
struct circle c;
clrscr();printf("\n Enter circle radius:");
scanf("%f",&c.radius);
printf("\n Enter x and y for circle:");scanf("%d %d",c.centrepoint.x,c.centrepoint.y);
printf("\n Circle radius is:%f ",c.radius);
printf("and centre of the circle is at x=%d y=%d",c.centrepoint.x,c.centrepoint.y);getch();
}
63
-
7/31/2019 C all types of questions
64/74
e.g. suppose, you have created a data type named as struct engine & then you are creating a
data type named as struct car, then one of the element in struct car will be of type struct
engine
Q. Write a program to process details for set of students like roll no.,
name, marks in 2 subjects calculate average & display tabular mark listFor all the students
#inclide
#define n 5
#include
#define n 2struct student
{
int rno;
char name[30];int sub1,sub2;
float avg;
};
void main()
{struct student a[n];
int i;
clrscr();//input student details
for(i=0;i
-
7/31/2019 C all types of questions
65/74
-
7/31/2019 C all types of questions
66/74
2] Call by address- Her you send only the address of structure variable. In address always
takes 2 byte irrespective of size of structure So, it is economical.
Q. Write a program which inputs & outputs a structure using separate
function.
Q. What is union? Compare it with structure
Just like structure, Union is also a user defined data type, but there are following
differences.
Structure Union1.Memory is allocated for each element of 1. Memory is allocated only for largest
structure variable separately elements of union.
e.g. A structure with int and float members e.g. Union with int & float members takes
takes 6 bytes. only 4 bytes.
2. You are allowed to use as many element 2. You can use only 1 element at a time of
of a structure variable as you want at a time Union variable.
3. you can initialize a structure variable 3. You can not initialize a union variable
while defining. while defining.
e.g. srtuct point a = {10, 20}
4. Takes more memory but is still 4. Takes less memory but still is used
Commonly used; because it is flexible. rarely; because it has limitations.
5. e.g. struct point {int x; 5. e.g. Union demo
inty; { int x;
}; floaty;
};Struct point a Union demo a
Q. Explain error too many types in declaration
You must give ; after structure template is over. If you dont give it you get aboveerror.
FILE HANDLINGQ. Explain significance of file handling.
variable are stored in RAM but content of RAM are temporary i.e. contents are lostwhen power is disrupted. So, you need File Handling for permanent storage of data.
Q. Write a program which display contents of the disk file, whose name
is specified by user.
//pro to display content of the file
66
-
7/31/2019 C all types of questions
67/74
#include
#includevoid main()
{
FILE *p;char ch;
char filename[31];
clrscr();printf("\n Enter name of the file");
gets(filename);
//open the filep=fopen(filename,"r");
//check for opening failure
if(p==0) //if(p==NULL){
printf("\n Can not open file:");getch();
return ;
}
//Display content of file
while(1)
{//Read character from file
ch=fgetc(p);
//Is It End Of File
if(ch==EOF)
{break;
}
else
{printf("%c",ch);
}
}fclose(p);
getch();
}
Note:-
1] Significance of stdio.h-
67
-
7/31/2019 C all types of questions
68/74
It is a heder file which cantains important definitions required for file handling
so, every file handling program must include it.
2] steps in file handling-i) Open the file i.e. bring the file from disk to RAM.
ii) It opening fails, stop the program. Otherwise, read from the file or write to the file or
both as per need.iii) finally, close the file. This is because from the moment you open the file & upto
moment you close it, all operations happen in RAM only. Any change will be saved back
to disk only when you close the file. Also, at a time you can open only files & dont closethem, limit will be reached.
Q. Modify above program to count no. of characters, words, lines,
vowels.
#include#include
void main()
{FILE *p;
char ch;int charcount=0,wordcount=0,linecount=0,vowelcount=0;
char filename[30];
clrscr();printf("\n Enter name of the file");
gets(filename);
//open the filep=fopen("E:\sonu\count.c","r");
//check for opening failureif(p==0) //if(p==NULL)
{
printf("\n Can not open file:");getch();
return ;
}
//Display content of file
while(1)
{//Read character from file
ch=fgetc(p);
charcount++;if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
{
vowelcount++;}
68
-
7/31/2019 C all types of questions
69/74
if(ch||' '||ch=='\t'||ch=='\n')
{
wordcount++;}
if(ch=='\n')
{ linecount++;
}
//Is It End Of File
if(ch==EOF)
{break;
}
}
printf("File contains %d characters,%d vowels %d lines",charcount,vowelcount,wordcount,linecount);
fclose(p);getch();
}
Q. Write a program to copy 1 file to another as per user demand.
//pro to copy one file to another file as per user demand
#include#include
void main(){FILE *d;
FILE *b;
char ch;char source[31],target[31];
clrscr();
printf("\n Enter name of the source file");scanf("%s",source);
printf("\n Enter name of the target file:");
scanf("%s",target);
//open the file
d=fopen(source,"r");
//check for opening failure
if(d==0) //if(d==NULL)
{printf("\n Can not open file:");
69
-
7/31/2019 C all types of questions
70/74
getch();
return ;
}
//open target file for writing
b=fopen(target,"w");if(d==0)
{
printf("\n Can not open file:");getch();
return ;
}
while(1)
{
//Read character from file
ch=fgetc(d);//Is It End Of File
if(ch==EOF){
break;
}else
{
fputc(ch,b);
}//close files to save back changes
fcloseall();
printf("\n File %s has been copied to file %s",source,target);getch();
}
}
Note:-Writing a character into a file-use library function fputc to write given character into givenfile. E.g. fputc (ch, b);
Reading a character from a file-use library function fgetc it returns (EOF) i.e. end of file
when file endse.g. ch=fgetc(a)
Opening a file-use library function fopen. If takes 2 parameters of type string firstparameter gives path of the file to be opened where as 2nd parameter indicates file opening
mode.
e.g. a=fopen(demo.txt,r);
70
-
7/31/2019 C all types of questions
71/74
e.g. by default it is assumed that file is present in current directory, but if it is present in any
other directory, you must give full path. Suppose path is c:\x\demo.txt then fopen will be
c:\\x\\demo.txt Here \\ is used because single \ means escape character in C.fopen allocates memory for the file & returns its starting memory address.
Q. Write a program which create a data file representing student detailslike roll no. name, marks in 2 subjects, average.
#include#include
struct student
{
int rollno;
char name[31];
int sub1,sub2;
float avg;};
void main(){
FILE *p;
struct student a;char choice='y';
clrscr();
//open data file for writingp=fopen("student.txt","w");
//check for opening failureif(p==0){
printf("ERRORE");
getch();return ;
}
//Input student deatils and read them to file
while(choice=='y')
{
printf("\n Enter rollno,name,marks of 2 subject:");scanf("%d%s%d%d",&a.rollno,&a.name,&a.sub1,&a.sub2);
a.avg=(a.sub1+a.sub2)/2.0;
//write to file
fprintf(p,"%d%s%d%d%.2f\n",a.rollno,a.name,a.sub1,a.sub2,a.avg);printf("\n Do u want to continue?y/n");
71
-
7/31/2019 C all types of questions
72/74
fflush(stdin);
scanf("%c",&choice);
}fclose(p);
printf("Saved");
getch();}
Q. Assume that file student txt contains details of student. Write a
program which display tabular marklist for students by reading data
from that file.
//pro to display content of the file
#include
#includevoid main()
{
FILE *p;
char ch;char filename[31];
clrscr();
printf("\n Enter name of the file");gets(filename);
//open the filep=fopen(filename,"r");
//check for opening failure
if(p==0) //if(p==NULL){
printf("\n Can not open file:");
getch();return ;
}
//Display content of file
while(1)
{//Read character from file
ch=fgetc(p);
//Is It End Of Fileif(ch==EOF)
{
break;}
72
-
7/31/2019 C all types of questions
73/74
else
{
printf("%c",ch);}
}
fclose(p);getch();
}
Note:-Writing variable of any data type into file- fputc can write only a character into file where
as fprintf can write variable of any data type into fileIts format is same as printf except its first parameter, which indicates pointer
to the file into which to write.
Reading variable of any data type from the file- fgetc can read only a character from a file
but fscanf can be used to read variable of any data type; from the file. Its format is same asscanf except the 1st parameter which indicates pointer to the file from which to read.
Q. Explain various file handling modes in C.
Mode Operation possibler Only reading from existing text file
rb Only reading from existing binary.
w File it is a very risky mode because
[wb] its contents are lost and if it doesnt exit it iscreated.
r+ It is the best mode. It allows both reading q.
writing for existing file without destroying it.
w+ same as w+, but in addition
[wb+] you can also read from the file
a It means append i.e. writing
[ab] at the end of the file.
a+ It is same as a but in
[ab+] addition you can also read from the file.
73
-
7/31/2019 C all types of questions
74/74
***
74