Sunteți pe pagina 1din 74

1

C Language
Q. 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 but speed 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*2 Here, x will be 4 ii) Consider, following statements x = 32767

2 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 typesI) 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 types 1.Name: float Size: 4 bytes Precision: Single Range: Parochially Unlimited (unto 1038) Purpose: Day to day fractional calculation 2.Name: double Size: 8 bytes Precision: Double Purpose: Scientific calculations Range: Practically unlimited (10308)

Q. A float var can also store integers, Explain why not to use float always

instead of long. i) Float does not provide 100% accuracy. e.g. It you store 10 in float, it has to be
stored 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 computer
treats 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 should have some code for given character. Unicode :- (Universal Code) It is the latest code, ASCII code supports only English character where as Unicode supports English as well as non-eng 65536 characters.

Section -III
character data typesName: Char Code used: ASCII Size: 1 byte Capacity: 1 character.

Programs in C language. # ObjectiveQ. Write a C programmed which displays message Hello Word
main ( ) { 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 program1) 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

4 100 of such function 3) Suppose, you want to do a particular job but no ready-made function is available then 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 output
welcome 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 use escape sequence \ Consider following printf

5 printf (abs\b\bd) ; It will display add, because back slash b means back space

# objectiveWhen 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<conio.h> main( ) { clrscr ( ); textcolor (BLUE); textbackground (YELLOW);

6 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 <conio.h>, 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.

Hello

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 ( )

7 { 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 you special format for the data type i.e. conversion specification.

Format TableData type


i) int

Format
% d (decimal) % o (Octal) % x (hexadecimal) % u (unsigned) % ld (long decimal) % lu (long unsigned) % f (float) % lf (long float) % c (character) % s (string) % u or % p

ii) Unsigned int iii) long int iv)unsigned long int v) float vi) double vii) char viii) string ix) Pointer

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,

8 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( ); } OutputEnter x: 10 x is 10

Q. Write a program which inputs 2 integer from key-board & display their sum.
#include<stdio.h> #include<conio.h> 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

9 #include<stdio.h> #include<conio.h> 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 separated e.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<stdio.h> #include<conio.h> 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<stdio.h>

10 #include<conio.h> 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 statements


i) 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<5) { printf (%d,i); i = i +l; }

Write a program which inputs 3 no. and display the largest. //pro to find largest from 3 no.s
#include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("\n Enter 3 no.s : "); scanf("%d%d%d",&a,&b,&c); if(a>=b&&a>=c)

11 { 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 operator1. && (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 true 3. ! (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<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); printf("\n Enter 3 sides :"); scanf("%d %d %d",&a,&b,&c); if(a+b<c||b+c<a||a+c<b) { printf("\n Not a triangle"); } else if(a==b&&b==c) { printf("\nEquilateral"); } else if(a==b||b==c||c==a) { printf("\n Isosceleus");

12 } 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<stdio.h> #include<conio.h> void main()

13 { 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<70) { printf("\n first class"); } else if(avg>=35&&avg<60) { printf("\n Second class"); } else { printf9"\n Fail"); } getch(); }

3] Input a point from key-board & check whether it is at origin or x axis or y-axis or not on both.
//pro to dispaly location of point #include<stdio.h> #include<conio.h> void main() { int x,y; clrscr(); printf9("\n Enter two intgers from keyboards as points:"); scanf("%d%d",&x,&y); if(x==0&&y==0) { printf("\n Point at origin"); } else if(x!=0&&y==0) { printf("\n Point is on x-axis"); } else if(x==0&&y!=0)

14 { 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<stdio.h> #include<conio.h> 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<conio.h>
void main() { char ch; clrscr(); textcolor(RED); textbackground(GREEN); cprintf("Enter a charcter from keyboard"); scanf("%c",ch);

15 if(ch>='a'&&ch<='z') { printf(" \n Entered character %c is lower case alphabet",ch); } else if(ch>='A'&&ch<='Z') { printf("\n Enetered character %c is UPPER case alphabet",ch); } else if(ch>='0'&&ch<='9') { printf("\n Enetered character %c is a digit",ch); } else { printf("\n Entered character %c is a special symbol",ch); } printf("\n Press any key to continue"); getch(); }

Q. Explain deferens between 0& 0 0 represents no. zero but 0 zero represents character zero (ASCII code of 0 is not
zero)

Q. Explain whether following statement are valid or not char ch; ch = a; ch = ch+1; printf(%c, ch); It is valid; This is because a character is internally stored as a number i.e. ASCII code.
e.g. a means a7, so variable ch now contain b

Q. Is following code valid char ch; ch= a; printf (\n%d,%c,ch,ch); It is valid, it will display following output.
97, a A character is internally a number i.e. ASCII code so, if you displayed as %c, you get the character itself but as %d, you get the ASCII code.

Q. Write a program using while loop to display numbers from 1to5.

16 Note:void main() { Int i ; clrscr(); i=1; while(i<=5) { printf(\n I is %d,i); I=i+1; } getch(); } A loop is a set of statement which runs multiple times as long as condition is true

Q. Explain no. of times while loop runs at a minimum & at a maximum. i) Suppose, condition is initially false then while loop will not run:
e.g. In the program before, i = 11; while (i< = 5) thus, loop runs zero times at a minimum ii) If condition never becomes false, while loop will never stop i.e. will run infinitely. e.g. In the program before , if statement i = i + 1 is absent in while loop. To stop, infinitely running loop-hold down control key & press break key.

Q. Write a program which inputs 3 no. from key-board & display their sum. Use a loop. //pro to display addition of 3 no.s using while
#include<stdio.h> #include<conio.h> void main() { int i,no; long int sum; clrscr(); i=1; sum=0; while(i<=3) { printf("\nEnter no:"); scanf("%d",&no);

17 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. of


times the loop will run. e.g. i in above program.

* Concept of accumulator:- An accumulator is a temporary variable which stores


intermediate results e.g. sum in above program Generally, 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 uninitialised
variable sum. In that case, C dose not show error but uses non-sense values stored in the variable 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

18 1 2 3 4 1< = 3 (T) 2< = 3 (T) 3< =3 (T) 4< = 3 (F) 0 10 30 70 10 20 40 0+10= 10 10 +20 = 30 30 +40 = 70

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<studios> #include<conio.h> void 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 3 Similarly when you divide a no. by 10 last digit is lost e.g.123/10 = 12

Q. Explain concept of comment.

19

Suppose, you are developing a program with complicated logic, then after few days
you 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 for developers understanding. C provides 2 types of comments1] Multilane Comment:e.g. /* A loop to find Sum of digits */ 2] Single line commente.g. // find digit

Q. Write an algorithm for finding largest of two Integers. 1. START


2. Define x & y as integer 3. Display Enter two nos 4. Input x and y 5. IF x > y then Display x is largest else 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/10 end loop 7. Display sum 8. STOP

Q. Write a program demonstration for loop. void main ( )


{

20 int i; clrscr ( ); for ( i =1; i< =4; i = i + 1 { printf(in i is %d,i); }//end for getch ( ); } //endmain Note:Working of for loopIt 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 loop1] 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 for 4] Not giving modification sectioni = 1; for (; i< = 4;) { printf(n%d,i); i = i + 1; } //end for 5] Not giving any section to ovate infelt loop For (; ;) { // code }

21

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<stdio.h> #include<conio.h> void main() { int no; long int sum; clrscr(); sum=0; while(1) //infinite loop { printf("\nEnter no,negative to stop:"); scanf("%d",&no); if(no<0) { break; } else { sum=sum+no; }//end if }//end while printf("\n sum is %ld",sum); getch(); } * In C zero means false & any non-zero i.e. +ve or -ve no means true. So, while (1) means infinite loop because 1 will be always A finite loop may slip and its own but infinite loop must be stopped force fully with key-word break. Use of break is allowed only inside a loop

Q. Rewrite above program using for loop. change first line of loop from while (!) to for ( ; ;) Q. What will be output of following program? void main ( ) { int i; i = 1;

22

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<stdio.h> #include<conio.h> 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 + +;

23 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<stdio.h> #include<conio.h> void main() { int rno; int sub1,sub2; float avg; clrscr(); do { printf("\n enter positive rollno:"); scanf("%d",&rno); }while(rno<=0);//end while do { printf("\n enter subject1 marks in range 0 to 100:"); scanf("%d",&sub1); }while(sub1<0||sub1>100);//end while do { printf("\n enter subject2 marks in range 0 to 100:"); scanf("%d",&sub2); }while(sub2<0||sub2>100);//end while avg=(sub1+sub2)/2.0; printf("\n for rollno % average is %.2f",rno,avg); getch(); }

Q. Great a menu driver program using do while loop; to preterm auditor subtraction, multiplication as per user choice. //menu driven pro using while
#include<stdio.h>

24 #include<conio.h> 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<=3) { printf("\n Enter 2 no.s"); scanf("%d%d",&no1,&no2); if(choice==1) { result=no1+no2; } else if(choice==2) { result=no1-no2; } else if(choice==3) { result=no1*no2; } }//end if printf("\n Result is %",result); }while(choice!=0); getch(); } Note:Above program will show correct answer only if choice is 1 to3 otherwise it will show garbage answer. So, equality last printf if (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<stdio.h> #include<conio.h> void main() {

25 int n,i; long int sum; sum=0; clrscr(); i=1; printf("\n Enter n:"); scanf("%d",&n); while(i<n) { sum=sum+i*i; i++; }//end while printf("\n Sum of first %d no.s is %ld",n,sum); getch(); }

Q. Rewrite above while loop using for loop.


for (i = 1, sum = 0; 1< = n; i + +) { sum = sum + i*i; }//end for

Q. Write a program input an integer from key-board & find its factorial provides input validation.
void main() { int i,j; long int fact; clrscr(); do { Printf(Enter no:>=0); Scanf(%d:,&no); }while(no<0); I=1; Fact=1; While (i<=no) { Fact=fact*I; I++: }// end while printf(\n factorial of %d is %ld,n,fact); getch(); }

26

Q. Rewrite above program using for loop. for (i=1, fact=1; i<=no;1++)
{ fact=fact*| }

Q. Write a program to check whether a given no. is prime or not void main()
{ int no,i; clrscr(); printf("\n Enter no:"); scanf("%d",&no); if(no==1||no==2) { printf("\n%d is prime",no); } else { i=2; while(i<no) { if(no%i==0) { printf("%d is notprime",no); getch(); return; } else { i++; } } } getch(); } Note:Key-board return is used to terminate a program

Q. Write a program to display fibonaccl series. void main()


{ int fib1,fib2,sum; clrscr();

27 fib1=0; fib2=1; printf("\n %d \n %d",fib1,fib2); sum=fib1+fib2; //display number in series,less than 50 while(sum<50) { printf("\n %d",sum); //whatever is currently fib2 should become fib1 fib1=fib2; //whatever is sum currently should become fib2 fib2=sum; //recalculate sum sum=fib1+fib2; }//end while getch(); }//end main

Q. Using nested for loop i.e. for loop inside for loop.
void main() { int i,j; clrscr(); for(i=1;i<=3;i++) { for(j=1;j<=2;j++) { printf(\n j=%d,i=%d,j,i); } printf(\n); } getch(); }

Note:In the above program every time crate the loop runs epe, irons for loop runs 2 times. So, Inner for loop runs total 6 times. Thus, it outer for loop runs in times & inner for loop runs in times, then effectively inner for loop runs m*n times.

Q. Write a program to display following pyramid 1 1 2

28

1 2 3 1 2 3 4 void main ( )
{ int i,j ; clrscr( ); for (i=1;i<=4;i++) { For (j=1;j<=i;j++) { printf(%5d,j); } printf(\n); }//end for i getch( ); }//end main Outer for loop controls the current level you want 4 levels, So I change from 1 to 4. Inner for loop displays elements for the current level contains 1 element, second level contains I elements. So, inner for loop must run I no. of times i.e. j< = i % 5d means display integer right justified in the width of 5. e.g. 4 spaces & then 1 -------1 This is, its adjust pyramid shape. When inner for loop is over, one level is over, next level must start an next line. So, printf (\n) is used.

Q. Modify above program the display following perused 1 2 2 3 3 3 4 4 4 4 Simply change printf of inner for loop as follows.
printf(%5d,i);

Q. Modify above program to display following program 1 2 3 4 5 6 7 8 9 10

29

Here, you cant display i or j. So, you need 3rd variable k


1] Add following line before clrscr ( ); int k = 1 2] 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 d void main ( )


{ int i, j; char ch; for (i=1; i<4;i++) { ch= a; for(j=1;j<=i;j++) { printf (%5c,ch); } ch++; printf(\n); }//end for i getch( ); }//end main

Q. Modify provides program to display pyramid of stars. * * * * * * * * * * 1] Modify line of char ch; as follows;
char ch = *; 2] Comment out line ch + + inside for loop

30

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<=level;i++) { for(j=1;j<=i;j++) { printf(%6c,ch); } printf(\n); } getch(); }

Q. Write a program which displays triangular pyramid as follows:


void main() { int i,j,k,m,space; clrscr(); k=1; spaces=30; for(i=1;i<=3;i++) { for(m=1;m<=i;m++) { printf( ); } for(j=1;j<=I;j++) { printf(%6d,k); k++; } //reduce spaces spaces=spaces-3; printf(\n);

31 } getch(); } Note:Above program is similar to the program which displayed following pyramid 1 2 3 4 5 6 Here, 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 1 27 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 process marks 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.

32 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<10. No syntax error will he display but C will display 5 valid & 5 garbage values.
Thus there is no brunets checking in C It is developers job to check that index used within the limb of array.

Q. It may he confusing to week with O based indexing. Is their any alternative? In that case use one loused indexing e.g. If you want in star 5 values, after define array
of size 6 and use elements only term index 1 and rewires e.g. void main ( ) { int a[6]; for(i = 1; i< 6; i + +) { //process array } getch ( ); }

Q. What is Type Casting? Type Casting is a process of concertina one data type into another
e.g. average = (float)sum /5; Here, sum is converted from int to Float

Q. What will be displayed by following code: int x = 300 ; long y; y = x*x; printf(%d,y); You will also he int but it is more than 32767 & so will be -ve.
To solve this problem replace line y = x*x with following 2 linesy = x;

33 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 without space. 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 string
i.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.

34

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 program 2] 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. every function must be defined separately Section of C function 3] Section 2:- It represents name of the function. It is as per following ruleri) ii) iii) Function name must start with an alphabetic but can also contain digits later on. Function name can not contain special character like space, dash but can contain underscore. Function name should be up to 31 character and should be meaningful.

35 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, it means it is library function

4] Section3:- It represents Input to a function Technically, inputs are called as arguments are as per following rules:i) ii) iii) A function can take multiple arguments, al may be off same type or different. Each argument must be defined separately and argument list must be comma(,) separated. 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 rulesi) 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 you leave 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 program 1) 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

36

Compare function definition with function call.

Function Definition
1) A function definition contain many lines

Function call
1) A function call contains only one lines 2) You must give semicolon after call 3) You mustnt give data type of Argument 4) Inside are function can call any function

2) You mustnt give semicolon after first line of definition. 3) You have to give data type of argument 4) Inside one function your cant define Another

Q. Explain concept of actual arguments &formal arguments? Formal arguments are the arguments given in function definition
e.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. But
still 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 variable of 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<stdio.h> #include<conio.h> double findfact(int n); void main(void) { int x; double y; clrscr(); printf("\n Enter no >= o:");

37 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;i<=n;i++) { result=result*i; } return result; }

Q. Write a function to input 5 digit integer & calculation sum of digits. //pro to input 5 digit integer & calculate sum of digit
#include<stdio.h> #include<conio.h> int sumdigit(int no) void main(void) { int x; int y; clrscr(); printf("\n Enter no with 5 digit"); scanf("%5d",&x); y=sumdigit(x); printf("n sum of digit %d is %d",x,y); getch(); }//end main int sumdigit(int no) { int result; int digit; result=0; while(no>0) { digit=no%10; result=result+digit; no=no/10; }//end while return result;

38 }//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<stdio.h>
#include<conio.h> 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<=level;i++) { for(j=1;j<=i;j++) { printf("%6d",j); } printf("\n"); } }

Q. Write a function which checks whether given integer is even or odd. #include<stdio.h>
#include<conio.h> int checkeven(int no); void main(void) { int x; int y;

39 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<stdio.h> #include<conio.h> int checkpalino(int a[],int n); void main(void) { int x[6]; int i,smallest; clrscr(); for(i=0;i<6;i++) { printf("\n Enter a element %d:",i+1); scanf("%d",&x[i]); } smallest=findsmall(x,6);

40 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<n;i++) { if(a[i]<smallest) { smallest=a[i]; } } return smallest; }

Q. Write a function which checks whether the given string a palindrome or not? //pro to check given no is palinodrome or not
#include<stdio.h> #include<conio.h> int checkpalino(char []); void main(void) { char s[51]; int result; clrscr(); printf("\n Enter a string:"); gets(s); result=checkpalino(s); if(result==1) { printf("\n string %s is a palinodrome",s); } else { printf("\n string is not palinodrome",s); } getch(); } int checkpalino(char a[]) {

41 int result; int i,j; i=0; j=strlen(a)-1; //index of last character while(i<j) { if(a[i]==a[j]) { i++; j--; } else { break; } }//end while if(i<j) { result=0; } else { result=1; } return result; }

Q. Write a function which checks whether given no. is prime no. or not //program to check given no is prime or not
int checkPrime(int no); void main(void) { int x; int y; clrscr(); printf("Enter no:"); scanf(" %d ",&x); y=checkPrime(x); if(y==1) { printf("/n no%d is prime",x); } else { printf("/n no %d is not prime",x); }

42 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<no) { if(no%i==0) { break; } else { i++; } } if(i==no) { result=1; } else { result=0; } return result; // check for prime i=2; while (i<no) { if(no%i==0) { break; } else { i++; } }

43 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<stdio.h> #include<conio.h> 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<=n) { res=res+i; i=i+2; } return res; }

Q. What is storage class? Explain various storage classes with e.g. Storage class of a variable influences following things.
1. Where the variable is storage. 2. What will be its default value

44 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 of local 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 it e.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 registerCPU 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-

45 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 bytes register 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 of auto, 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 be x=6 x=6 x=6 This is because value auto variable is lost every time function is over But it 1st line static int x = 5; then output will be x=6 x=7 x=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 find factorial 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 may crash. 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

46

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.

Program
double 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 main double 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

47

start Display enter no Input no Is no=?

Return 1

Call fact(no)
Return No*fact(no-1)

Display result

stop

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 } }

48

Q write a fucnction which finds sum of 1st n no.s


#include<stdio.h> #include<conio.h> 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

49

start

initialise

Is conditio n true

statement stop

For
start

initialise

Is conditio n true

statement start modification initialise stop

50

statement

Is conditio n true

stop 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 are executed & 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 per following rules1] Employee gets bonus only if salary is less than 10,000 2] Processing should stop if salary is negative //calculate bonus if salary<100000 #include<stdio.h> void main() { float basic,bonus; int i; clrscr(); i=1; while(i<=5) { printf("\n Enter basic salary:"); scanf("%f",&basic); if(basic<0)

51 { break; } if(basic<10000) { bonus=basic*0.50; printf("\n Bonus is Rs.%.2f",bonus); i++; } else { i++; continue; } } getch(); }

Q. Explain types of operators in C along with their precedence & associatively. C provides following types of operators1) Arithmetic 2) Assignment 3) Unary 4) Relational 5) Ternary 6) Logical 7) Bitwise

1] Arithmetic Operator:Arithmetic Operation


1. 2. 3. 4. 5. 6. Addition Subtraction Multiplication Division Modulus Precedence

Arithmetic Operator
+ * / % high priory. * / % low priory.

* Associatively (order of evaluation)If you come across multiple operators with same priority. It is from left to right.

2] Assignment Operator:Assignment is from right to left.

52

3] Unary Operators:Operation
1) Unary minus (negation) 2) Pre-increment/post increment 3) Pre-decrement/post decrement 4) Precedence

Operators
++ -high priority Low priority + +, - -

* Associatively- Right to Left 4] Relational Operators:Operation


1) Greater than 2) Less than 3) Greater than or equal to 4) Less than or equal to 5) Equal to 6) Not equal to 7) Precedence

Operator
> < >= <= == != 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;

53

* Associatively - Right to Left 6] Logical Operators:These are the operators used for interconnecting condition. They are also called as bad lion operators

Operation
1. Logical and 2. Logical or 3. Logical not 4. Precedence

Operator
&& : : ! ! && : :

Q. Explain Bitwise operators in C. All the operators except bitwise operators work at variable level, on the other hand
bitwise 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 is q = 10100010 then ~ q = 01011101 1] Application of ones complimentSuppose, 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 = 10100010 b = 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 = 00001000 on bit 3

54 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 = 10100010 b = 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 = 10100011 b = 11010011 a ^ b = 01110000

* Application of bitwise XORIt 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] << (Bitwise left shift)In left shift, all the bits are shifted towards left. In that process, left most is lost & 0 is introduced at right most position

* Application of left shift bit Left shifting once is same as multiplying by 2, left shifting n times is same as multiplying by 2nd e.g. a = 0010 = 2 a<<1 = 0100 = 4 a<<2 = 1000 = 8

6]>>(Bitwise Right shift)-

55 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 = 1000 a>>1 = 0100

Application of Bitwise Right ShiftRight shifting a no. once is like dividing by 2, right shifting n times is like dividing by 2n. e.g. a=1000=8 a>>=0100=4 a>>2=0010=2 Precedence of bitwise operatorHigh 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 Unary Minus Increment Decrement Logical negations Once compliment Multiplication division Modulus Addition Subtraction Bitwise left shift Bitwise right shift Less than Less than equal to Greater than Greater than equal to Equal to Associativity Right to left (Unary operator)

Left to right

Left to right Left to right Left to right

Left to right

56 != & ^ && || ?: = Not equal to Bitwise (caret) Bitwise or Logical and Logical or Conditional (ternary) Assignment

Left to right Left to right Left to right Left to right Left to right 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 preprocessor 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 facilities i)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 hard coding 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() BEGIN printf(Hello); END #include Header files are with extensions .h. There are two types of header files 1) 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 directory e.g.c:\tc\INCLUDE Such files are included using angle brackets.(< >)

57 e.g. #include<stdio.h> 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 code int 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 data
type can not process address only pointers can process address. So knowledge of pointers is a 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;

58 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 pointer e.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, its
same as using x.

Q. What will be output of following program //pro to demonstrate array-pointer relationship


#include<stdio.h> #include<conio.h> void increment(int *x,int *y); void main (void)

59 { 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 } OutputBefore increment a=10 After increment a=10 Memory Map 1000 2000 10 10 a x

After call Memory Map 1000 2000 10 11 a 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.

60

Q. What will be output of following program void increment (int*x, int*y); //pro to demonstrate array-pointer relationship
#include<stdio.h> #include<conio.h> 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 to pass parameter. Here, address of actual parameter is copied into
formal parameter then if you make any change through the formal, actual parameter will change. 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 returning indirectly multiple values, using pointers.

Q. Write a program using array, pointer relationship. #include<stdio.h>


#include<conio.h> void main (void) { int a[5]={10,20,30,40,50}; int *p; int i; clrscr();

61 p=a; //p points to array start for(i=0;i<5;i++) { printf("\n %d",*p); p=p+1; } getch(); }

Q. Is arithmetic possible with pointers? If so, is it same as regular arithmetic? Yes, arithmetic is possible with pointers. But, it is not same as regular arithmetic in
following ways1) In regular arithmetic, all operations are legal but in pointer e.g. P=P+1 b) Subtraction an integer from pointer ; c) Subtraction 2 pointers 2) Suppose, P is an int pointer & P contains address 1000. Now consider P=P+1; Here, P will not be 1001 but 1002, this is because p+1 means move forward by size of 1 integer i.e. by 2 bytes. p+np+m*n p-np-m*n Here, m stands for size of base data type. e.g. If p contains one thousand, p+3 is equivalent to p+m*n i.e. p+2*3 i.e. 1006

Q. Explain why pointer arithmetic is different from regular arithmetic. Suppose, pointer p contains start address of int array a i.e. 1000. Now consider p=p+1
with regular arithmetic p=1001. which is useless. But pointer arithmetic p becomes 1002 i.e. p points to next element. Thus, basic idea behind pointer arithmetic is to position the pointer at specific element of array and incrementing should position it on previous element.

Q. Write a program which sends an array to a function & processes that array. #include<stdio.h>
#include<conio.h> void show(int*p,int n); void main () { int a[5]={10,20,30,40,50}; clrscr(); int *p; show(a,5); getch(); }

62 void show(int *p,int n) { int i; for(i=0;i<n;i++) { printf("\n %d",*p); p=p+1; } } Output10 20 30 40 50

Is it possible to send an array to function? If so, explain how to do it. Yes, it is possible to send an array to a function. There are 2 ways to send an array1) send each element of array as separate parameter but this is not economical & not continent. 2) Send only starting address of an array along with count f no. of element of array e.g. show (a, 5); This is economical & hence commonly done.

STRUCTURE
Q. What is a structure? A structure is user define data type. C provides -2 types of data types1) ready made i.e. built in data types 2) User defined data types Suppose, you need to work with points but there is no ready made data type representing a point. So, you need to create your own data type presenting a point e.g. struct point { int x; int y; }; All element in an array must be of same data type where as element in a structure may or may not be of same data type.

Q. Explain steps while working with a structure 1] A structure is user defined data-type so, you must inform C-language about it by
giving structure template. e.g. struct point { intx; inty;

63 } 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 is scanf(%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 define
type.

Q. Write a program which uses structure inside structure //structure inside structure
#include<stdio.h> #include<conio.h> 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(); }

64 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 list For all the students #inclide<stdio.h> #define n 5
#include<stdio.h> #define n 2 struct 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<n;i++) { printf("\n Enter student roll no:"); scanf("%d",a[i].rno); fflush(stdin); printf("\n Enter full name:"); gets(a[i].name); printf("\n Enter marks of 2 subject:"); scanf("%d %d",&a[i].sub1,&a[i].sub2); a[i].avg=(a[i].sub1+a[i].sub2)/2.0; } //display result in tabular form printf("\n%10d %30s %10d %10d name","Sub1","Sub2","Average"); for(i=0;i<n;i++) { printf("\n %10d %30s %15.2f",a[i].rno,a[i].name,a[i].sub1,a[i].sub2,a[i].avg); }

%15.2f","Roll

no.","Full

%10d

%10d

65 getch(); }

Q. Write a program which demonstrate use of structure pointer. struct point


{ int x; int y; }; void main ( ) { struct point a ={10, 20}; struct point *p; p=&a; printf(\nPoint is x=%d,y=%d,px,py); printf(\n point is x=%d,(*p).x,(*p).y); getch( ); }

Q. Explain various ways to access structure element through structure pointer 1] Using operator * consider *p.x Here
Unary operators*and. Are used but their associatively i.e. order of evaluation for operator with same priority (is right to left) i.e. . first & then * but you want * first & then . So, you must use (*P).* 2] Using operator- > (minus greater than) e.g p- >x Generally, this way is preffered

Q. It is possible to send a structure to a function? If so, explain various ways for it. Yes, just like you can pass a variable of readymade data type like int to a fun; you can
also pass variable of user define type i.e. structure variable. Three are 2 ways to pass a structure variable 1] Call by value i.e. you send the value of structure variable; but it is not economical e.g. It size of structure is 5000 bytes then you have to send 5000 bytes

66 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
1.Memory is allocated for each element of structure variable separately e.g. A structure with int and float members takes 6 bytes. 2. You are allowed to use as many element of a structure variable as you want at a time 3. you can initialize a structure variable while defining. e.g. srtuct point a = {10, 20} 4. Takes more memory but is still Commonly used; because it is flexible. 5. e.g. struct point {int x; inty; }; Struct point a

Union
1. Memory is allocated only for largest elements of union. e.g. Union with int & float members takes only 4 bytes. 2. You can use only 1 element at a time of Union variable. 3. You can not initialize a union variable while defining. 4. Takes less memory but still is used rarely; because it has limitations. 5. e.g. Union demo { int x; floaty; }; 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 above
error.

FILE HANDLING
Q. Explain significance of file handling. variable are stored in RAM but content of RAM are temporary i.e. contents are lost
when 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

67

#include<stdio.h> #include<conio.h> void main() { FILE *p; char ch; char filename[31]; clrscr(); printf("\n Enter name of the file"); gets(filename); //open the file p=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-

68 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 handlingi) 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 close them, limit will be reached.

Q. Modify above program to count no. of characters, words, lines, vowels. #include<stdio.h>
#include<conio.h> 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 file p=fopen("E:\sonu\count.c","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); charcount++; if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') { vowelcount++; }

69 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 ",charcount,vowelcount,wordcount,linecount); fclose(p); getch(); } vowels %d lines

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<stdio.h> #include<conio.h> 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:");

70 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 given file. 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 ends e.g. ch=fgetc(a) Opening a file-use library function fopen. If takes 2 parameters of type string first parameter gives path of the file to be opened where as 2nd parameter indicates file opening mode. e.g. a=fopen(demo.txt,r);

71 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 details like roll no. name, marks in 2 subjects, average. #include<stdio.h>
#include<conio.h> 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 writing p=fopen("student.txt","w"); //check for opening failure if(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");

72 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<stdio.h> #include<conio.h> void main() { FILE *p; char ch; char filename[31]; clrscr(); printf("\n Enter name of the file"); gets(filename); //open the file p=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; }

73 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 file Its 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 as scanf except the 1st parameter which indicates pointer to the file from which to read.

Q. Explain various file handling modes in C. Mode Operation possible


r rb w [wb] r+ w+ [wb+] a [ab] a+ [ab+] Only reading from existing text file Only reading from existing binary. File it is a very risky mode because its contents are lost and if it doesnt exit it is created. It is the best mode. It allows both reading q. writing for existing file without destroying it. same as w+, but in addition you can also read from the file It means append i.e. writing at the end of the file. It is same as a but in addition you can also read from the file.

74

***

S-ar putea să vă placă și