Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

New C Language

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 56

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )

1/56

Section A [QUESTIONS 1 TO 336]


Q1. Ans.

2 Marks Questions [PAGE 1 TO 67]

Explain the importance of C language. 1. C is portable means program written for one computer may run successfully on other computers. 21. C is fast means i.e the executable program obtained after compiling and linking run very fast. 32. C is compact i.e. the statements in C-language are generally short but are very powerful; several operators can be combined together in just one statement. 34. C language is the middle-level language. Thats why ,The C language has both the simplicity of high-level language and low-level language. What is the structure of c program? i) Any C program is the combination of functions. main() is one such function. ii) The set of statements belonging to a function are enclosed within a pair of braces. iii) Any variable used in the program must be declared before using it. iv) Any c statement always ends with a ; (semicolon) The structure of c program is as follows: # Preprocessor directives .................................... .................................... void main () { body of the main function; ........................; ........................; } What are the relational operators available in C? The various relational operators available in C are: Operator Description > Greater thenthan < Less thenthan >= Greater then than and equal to <= Less then than and equal to == Equal to != Not Equal to What is the purpose of adding comments in a program? Can comments span more then a line. Comments are non-executable statements. With the help of comments we can give description about the program or any particular statement. Comments are enclosed with in /* and */. Any number of comments can be given at any place in the program. Comments can't not be nested. Single line comment is represented as follows: // this is a comment Yes, Aa comment can be split over more than one line, that is known as multi-line comments, as in, /* this is comment */ What is the syntax of PRINTF function of 'C'?

Q2. Ans.

Q3. Ans.

Q4. Ans.

Q5.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


2/56
Ans. printf() is function, which is used to print on the screen the value contained in a variable on the screen.. The general form of printf statement is , printf ("<format string>",<list of variables>);

format string could be , %f for printing real values %d for printing integer values %c for printing character values Q6. What is the syntax of nested if statement? Ans. It is perfectly alright if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called of 'nesting' of if statement. The syntax is as follow: if (condition) { if (condition) do this; else { do this; and this; } } else do this; Q7. What is the syntax of switch statement? Ans. The control statement, which allows us to make a decision from the number of choices, is called switch. Or more correctly switch-case-default, since these three keywords go together to make up the control statement. They most often appear as follows: switch (integer expression) { case constant 1: do this; break; case constant 2: do this; break; case constant 3: do this; break; default: do this; break; } Q8. What is the syntax of FOR statement? Ans. The FOR loop allows us to specify three things about a loop in a single line: a) Setting a loop counter to an initial value. b) Testing the loop counter to determine whether its value has reached the number of repetitions desired. Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


3/56
c) Increasing the value of loop counter each time the program segment within the loop has been executed. The general form of for statement is as under: for (initial counter; test counter; increment counter) { do this; and this; } and this; } Q9. What is format specifier? Ans. Format specifier is used to specify the data type of the variable. The format specifiers for various data types are shown below: %d-------Integer data %c------Character data %f-------Floating point data %ld-----Long Integer %s------String data %e-----Scientific notation for floating point data Q10. Ans. Q11. Ans. What is the scope of local variable? The scope of local variable is that, the variable is accessible within the block where it is declared. Local variable can't be accessed outside of the block, which contains its declaration. Which are the conditional operators available in C? The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is, expression 1 ? expression 2 : expression 3 If expression 1 is true then the value returned will be expression 2 otherwise the value returned will be expression 3. What are the formatted output statements of C? I/O functions can be of two types (i) formatted and (ii) unformatted functions. The basic difference between them is that the formatted functions allow the input read from the keyboard or the output displayed on the VDU to be formatted as per our requirements. For example, if values of average marks and percentage marks are to be displayed on the screen, then details like where this output would appear on the screen, how many spaces would be present between the two values, the number of places after the decimal points etc. can be controlled using formatted functions. printf() and fprintf() are formatted output functions in C. What is pseudo code? Pseudo code is programming code written in general English language, so that no any type of programmers can understand the code properly. Write a short note on type casting? Type casting refers to enforcement of explicitly converting the value of an expression to a particular data type. It is used to convert the data type from lower data type to higher data type and converse for temporary period. So that calculation can be performed with both the data types. e.g. void main() { int a=5;float b; printf(value of a %d,a); b=(float)a; printf(value of b %df,b); }

Q12. Ans.

Q13. Ans. Q14. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


4/56
Q15. Ans. What do you mean by type conversion? In an expression there might be cases when you need to involve different types of variable in a single expression. For example, an expression may contain addition of two integers and the result is required to be multiplied by a float. The expressions that contain variables and constants are evaluated using the following methods, known as Type conversions. The data types are required to be converted for easy calculation of the expression. These conversions are implicitly done by the system. What are the derived data types used in C? The derived data types are : Arrays (array[10]) Functions (function()) Pointers (*pointer) Q17. Ans.

Q16. Ans.

Structures (structure.member)

Enumerated (enumerated_variable) Union (union_name.member)

Q18. Ans.

Q19. Ans.

Q20. Ans.

Q21.

What do you mean by local and global variables? Local variables: Local variables are defined with in the pair of braces or between the body of the function. The scope of the variable is with in the function when function finished they will obsolete. Global variables: These variables defined out side of all the functions. And can be used to any function with in the file because the scope of these variable are global to the file. Explain various programming techniques? Programming techniques are used to make the program simple, efficient, understandable and easy to maintain. The three programming techniques commonly used are:Top down design: - Using this design program is divided into the smaller blocks, which can be linked and called whenever needed. The programmers design the program in different levels and can be called any level at any time. Bottom up design: - It is also designed in the same manner and divide the whole program into the smaller blocks, but when it is called it begins from the smaller block to the bigger till the program end. In this design, program is divided into blocks and the control flows from bottom to top unlike top down design where the control flows from top to bottom. Modular design: - A level consists of one or more modules. The first level is a complete main program and the module of the successive level contains sub modules Execution is controlled by the main program What is sizeof operator? The sizeof operator returns the size, in bytes, of given operand. Syntax is: sizeof (exp) Example: sizeof (float) Result: returns value 4 Differentiate between expression and statement. An expression refers to variables, constants and operators. It represents a single data item, such as a numbers or characters. One or more operators may interconnect these variables or constants. In C, very complex expressions can be solved easily. An algebraic expression in C is represented as follows: Algebraic expression: a x b c x d Its relative C expression will be written as: a * b c* d. What is the use of #define directives statement?

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


5/56
Ans. Q22. Ans. Q23. Ans. Define directives are used to define macros and the constants. This preprocessor starts with #(hash) symbol. What is a macro? How is it different from preprocessor? The macro is a substitution string that is placed in a program. It is replaced by the definition when program is compiled. It is different from preprocessor as preprocessor links the files with the object code. What do you mean by ternary operator? The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is, expression 1 ? expression 2 : expression 3 If expression 1 is true then the value returned will be expression 2 otherwise the value returned will be expression 3.Both if and ? : (Ternary operator) perform the same conditional operation, but ?: process fast as compare to the 'if' statement. The ? (ternary condition) operator is a more efficient form for expressing simple if statements. We can also nested the ternary operator. It has the following form: Condition? True: False Distinguish between unary and binary minus. Unary operators work on one operand and binary operators work on two operands. The unary operators negate the value of the operand For example Int a=5; a=-a; Then the value of a is now 5 In case of binary minus it perform arithmetic subtraction on the given operands For example Int a,b,c; a=90; b=80; c=a+-b Differentiate between comparison and equality operator. A character or symbol indicating a relationship between two or more values or expressions called an operator. These operators include less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), not equal (<>), and equal (==).Thus, equality operator is the subset of comparison operators. Explain various types of errors with examples. Syntax errors: The errors, which occur due the incorrect way to write the code. It may be due to the missing comma, semi colon etc. As the line: printf(hello); will show the error because string is not enclosed in " " . Logical error it is not due to any syntax mistake, but due to incorrect logic. The compiler will not show the error due to this. The programmers himself have to find and correct it. As: for(I=10;I<5;I--) Here the logic is wrong as I is already 10 which is never less then 5. What is the syntax of while statement? initialization of looping variable; While (conditional expression) {

Q24. Ans.

Q25. Ans.

Q26. Ans.

Q27. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


6/56
body of the loop .................... .................... .................... Increment/decrement; } What do you mean by conditional execution? When execution of set of commands is based upon some condition. This is known as conditional execution. Depending upon true or false path we can have different set of instructions to execute. What is difference between if and ? : (Ternary operator)? Both if and ? : (Ternary operator) perform the same conditional operation, but ?: process fast as compare to the 'if' statement. The ? (ternary condition) operator is a more efficient form for expressing simple if statements. We can also nested the ternary operator. It has the following form: Condition? True: FalseBoth if and ?: operator perform the same

Q28. Ans. Q29. Ans.

conditional operation , but ?: process fast as compare to the 'if' statement.


Q30. Explain the function of two keywords: main and void. Ans. main is the function name. It is the first executable function in the program. The program code is written inside the main function. void is the return data type. We use void return type when we dont want to take any return from the function. Syntax is void main(). Q31. Explain what will be the output of the following program code? # include <stdio.h> void main () { int k=10; switch (k%2) { case 0 : k+=2; case 1 : k=0; case 5 : k=1; }; printf (k= %d,k); } The output of this program is K=1 . In the above code, we are not using any break statement, therefore the last case executes in the end, which set the value of k to 1. Explain the unary operators in C The unary operators in C language are ++ (increment operator), -- (decrement operator) and (negation operator). The increment operator ++ adds 1 to the operandincrements the value of an operand by 1, while decrement operator decrements the value of an operand by 1,subtracts 1. Whereas (negation operator), marks that the number is negative numberchanges the sign of the number, i.e, if the value is positive then it makes it negative and vice versa.. They take the following form: ++m; or m++; (pre increment and post increment) --m or m--; (pre decrement and post decrement) -m (negation).

Ans. Q32. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


7/56
Q33. Ans. Explain the bitwise operator with example. C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit level. These operators are used for testing the bits, or shifting them right to left. Bitwise operators may not be applied to float or double. Bitwise operators Operator & | ^ << >> ~ Eg. #include<conio.h> #include<stdio.h> void main() { int a=5,b=6,c,d,e,f; c=a&b; d=a|b; Q34. Ans. Meaning Bitwise AND Bitwise OR Bitwise exclusive OR Shift left Shift right Bitwise NOT (Ones complement)

e=a^b; f=~a; printf("\n c=%d",c); printf("\n d=%d",d); printf("\n e=%d",e); printf("\n f=%d",f); getch(); } How you can determine the memory size occupied by a variable of a particular data type? The value range is calculated from the number of bits occupied by the data type. For eg., int uses 2 bytes , i.e 16 bits; from this 1 bit is taken for sign(- or +). So the range is expressed as 215 to 215 1. Bring out the difference between exit and break control statement. Exit statement is used to come out of from the program. Whereas break statement is used to break loop or switch statement. What are constants? How many types of constants are available in C programming language? A constant is a quantity that doesntwhose value doesnt change throughout the program. This quantity can be stored at a location in the memory of the computer. Types of c conatsntsconstants:C constant can be divided into two major categories. a) Primary constants Integer constants, real constants, character constants. b) Secondary constants Array, pointers, structures, union, enum.

Q35. Ans. Q36. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


8/56

Section A [QUESTIONS 1 TO 37]


Q1. Ans.

5 Marks Questions [PAGE 7 8 TO 1820]

What is the difference between do-while loop and while loop? Give an example to explain. In both the cases the condition is checked. In case of while, condition is checked before the execution of the statements but in case of do-while, statements are executed at least once whether the condition is true or false i.e. condition is checked at the end of the do-while block. A=11; While(a<=10) { printf(%d,a); a++; } Output: [BLANK SCREEN] A=11; Do { printf(%d,a); a++; } While(a<=10); Output: 11

Q2. Ans.

Q3. Ans.

What are the various types of programming languages? Or Why C language called structured language. Unstructured programming: - In unstructured programming the main program directly operates on global data. This programming technique has tremendous disadvantages once the program gets sufficiently large e.g. the programs written in basic language. Structured programming: - This is also known as procedural programming. Using this programming you are able to combine returning sequences of statements into one single place. A procedure call is used to invoke the procedure after the sequence is processed .The main program is responsible to pass data to the individual calls. The data is processed by the procedure and once the procedure has finished the resulting data is present. E.g. C and Pascal language using functions Modular programming: - With modular programming the statements of a common functionality are grouped together into separate modules .A program therefore no longer consist of only one single part. E.g. C language using header files. Object oriented programming:- Object oriented programming is an approach that provides a way of modularizing programs by creating separate/common memory area for both data and functions that can be used as templates for creating copies of such modules on demand. e.g. c++ , java languages using classes and objects. Discuss the structure of a C program. Explain using an example. A C program basically has the following form: 1. Preprocessor Commands 2. Type definitions 3. Function prototypes -- declare function types and variables passed to function. 4. Variables 5. Functions We must have a main () function. A function has the form: type function_name (parameters) {

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


9/56
local variables C Statements } If the type definition is omitted C assumes that function returns an integer type. NOTE: This can be a source of problems in a program. So returning to our first C program: /* Sample program */ main() { printf(I Like C \n'' ); exit ( 0 ); } NOTE: 1. C requires a semicolon at the end of every statement. 2. Printf is a standard C function -- called from main. 3. \n signifies newline. Formatted output exit() is also a standard function that causes the program to terminate. Strictly speaking it is not needed here as it is the last line of main() and the program will terminate anyway. What are the various I/O functions in C? Give Syntax. Or What is meant of I/O. and also discuss I/O types. Input/Output refers to receiving data from any input devices, and sending data to the output devices. I/O function can be classified into two types: 1. Console I/O functions: These are the functions that receive input from keyboard and write output to screen. These functions are classified into 2 parts: a. Unformatting I/O functions(Ex: getch,getchar, gets,puts,putchar etc) b. Formatting I/O functions (Ex: scanf,printf etc) 2. Disk I/O functions: These are the functions that perform I/O operations on secondary storage device like floppy, hard disk etc. The various I/O functions are: 1. scanf(): This function allows you to read data from keyboard that can be formatted accordingly. This input data can be arranged in a particular format. This function generally is written as: scanf(format string, &a1, &a2 .. & an); 2. getch(): This function return the character that has been typed most recently. This character would not be echoed on the screen but is assigned to a variable immediately. For e.g. Char A: A=getch(); 3. getche(): This function echoes or displays the character type on the screen. It is similar to the getch() but the only difference between the two is that this character assigned to a variable is also displayed on the screen. For e.g. Char A: A=getche(); 4. getchar(): This functions is same as getche() but the only difference between the two is that in getche() and getchar() there is a need of a carriage return then only it is assigned to the variable and gets displayed. 5. gets(): scanf() function has a limitation when we enter a multi-word string in a string variable because when space is entered in-between the two words, it is

Q4. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


10/56
assumed that the word is ended so it displays only one word then we use printf() functions. And this function gets(), accept a space when we enter a multi-words. 6. printf(): This function is used to display plain messages to the user. The same function can be used to the display the value of the variables you are using in your program. Syntax is: printf(format string,variable_list); 7. putch() or putchar(): These functions are exactly the same. They transmit a single character to an output device. The length and breadth of rectangle and radius of a circle are input through the keyboard. Write a program to calculate the area and perimeter of the rectangle and the area and circumference of the circle. #include<stdio.h> puts("Enter Radius of circle: "); #include<conio.h> scanf("%d",&radius); int main() printf("\n\nArea and Circumference of { Circle are: %f and %f", (float)(22/7)* int breadth,length,radius; radius*radius, (float) (2*22/7) *radius); clrscr(); getch(); puts("Enter Length and Breadth of rectangle: return 1; "); } scanf("%d %d",&length, &breadth); printf("\n\nArea and Perimeter of Rectangle are:%dand and %d",2*(length+breadth), length * breadth, 2*(length+breadth)); Write a C program to find the real root of a quadratic equation of type ax2+bx+c = 0, where a is not equal 0. #include<stdio.h> #include<conio.h> #include<math.h> int main() {int a,b,c; clrscr(); puts("Enter coefficients a,b and c: "); scanf("%d %d %d",&a, &b,&c); Q7. Ans. If(a!=0) { printf("\n\nRoots are: %f %f",(float)( b+sqrt (b*b-4*a*c)/(2*a)),(float)(-bsqrt(b*b-4*a*c)/(2*a))); getch();} else return 1; }

Q5. Ans.

Q6. Ans.

Write a C program to read characters and print their ASCII codes. #include<stdio.h> #include<conio.h> int main() { char ch; clrscr(); while(1) { clrscr(); puts("\nEnter a character (Enter to quit): "); fflush(stdin); ch=getchar(); printf("%d",ch); puts("\nWant to continue(y/n): "); ch=getche(); if(ch=='n' || ch=='N') break; } getch(); return 1; } What do you mean by data types? Give examples of data types available in C language.

Q8.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


11/56
Ans. The value stored in variable is variable depends upon data type, or we can say Data types is are thea type of data.

, Basic data types available in C are given below. Integer (Int): Int type of constant is a positive or negative number without a decimal point. e.g. -34,506,-11,-9642 .they are whole numbers in the range -32768 to +32767. To print the value of int type of constant we use conversion specifier %d. it It takes two bytes of memory. Float: These are numbers either positive or negative WITH OR WITHOUT DECIMAL E.G. -13.26, 45.890,89,89.0 ETC. They lie in the range 3.4*10-38 to 3.4* 10+38 accurate up to 7 digits and conversion specifier is %f. and it takes four bytes of memory Character (Char): This type constants consists of a character enclosed in a pair of single quotes such as 'a', B', c even a blank space can be used as a character. This variable need only one byte of memory space. tThe conversion specifies is %c. Long: These type of integers have a range -2147484648 2147438648 to + 214774383647 and we use conversion specifies %ld. Double: The keyword double is used to declare variables of the double type and the value assigned is accurate up to sixteen digits it lies in the range 1.7*10-308 to 1.7*10+308 and conversion specifies is %lf. It takes 8 bytes of memory. Q9. Differentiate between operator and operand. Ans. Operator refers to a symbol that represents a particular operation to be performed on data. There are different types of operator in c. Assignment operator: Assignment operators are used to Assign the values of a variable example of these operators are (+=,-=,/=,*= etc). Arithmetic operator: From the arithmetic calculation on the operands these are +,-,*,/ etc.These operators are used in arithmetic calculations like +,-,* etc Modulus operator: Modulus operators are used to find out the remainder by dividing one number with another. ( %) is the symbol for this operator. Relational operator: Use to create relation between operands. E g. >,<,<=,>= etc. Logical operator: These operators are used to create logic relation with in the operands. tThese are &&(AND), ||(OR), !(NOT). Operand: The data used to calculation on which the operation is going to perform is called operand.It refers to the variable upon which operation has to be performed. E.g. In the following expression 12+30, 12 and 30 both are operands and + is an operator. Write down a hierarchy of operators or the order of precedence of the entire operator using in c. Also explain associativity of operators. Precedence order 1 2 3 4 5 Operators ( ), [] , ++, --, -(unary) !, ~, *, &, sizeof *, /, % +, <<, >> Associativity Left to Right Right to left Left to right Left to right Left to right

Q10. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


12/56
6 7 8 9 10 11 12 13 14 15 <, <=, >, >= ==, != &(bitwise AND) ^(bitwise XOR) | (bitwise OR) &&(logical AND) | | (logical OR) ? : (conditional ) =, +=, -=, *=, /=, %= ,(comma operator) Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to Left Right to Left Left to right

Q11. Ans.

Q12. Ans.

Q13. Ans.

Write and compare arithmetic, assignment, logical, bitwise and special operators. Arithmetic assignment is an operator that is used to assign the value of an arithmetic expression to a variable. (=, +=, -=, *=, /=, %=) Logical operator are used to create logic relation with in the operands these are &&(AND), ||(OR), ! (NOT). Bit wise operators allow direct manipulation of individual bits with in a word. They are also used to perform certain numerical computations faster. There are three bit wise operators; 1. Bit wise logical operators a. Bit wise and (&) b. Bit wise or (|) c. Bit wise xor (^) 2. Bit wise shift operators a. Bit wise Left (<<) b. Bit wise right (>>) 3. Ones complement operator (~) Special Operators: C support some Special Operators of interest such as comma (,), sizeof, pointer (*) and member selection (. And ->) operator. What do you mean by control string? What is the purpose of the control string in a scanf function? What type of information does it convey? The control string has placeholders for the variables being used there can also be characters in the control string. For example Scanf (control string, &a1, &a2.&an) Where control string refers to the field format in which data is to be entered and a1, a2 an are the arguments that represent the individual input data items. It tells what type of variable can display there value with the help of conversion specified if we apply this with printf() statement we can also specify the short messages to recognize the values provided by variables. How the memory is allocated? Explain by giving example. The function Malloc is used to allocating allocate memory dynamically. Here is a little function which tries to allocate memory for a string of length n, and which returns zero (false) if it fails and 1 (nonzero, or true) if it succeeds, returning the actual pointer to the allocated memory via a pointer: #include <stdlib.h> int allocstr(int len, char **retptr) { char *p = malloc(len + 1);

/* +1 for \0 */

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


13/56
if(p == NULL) return 0; *retptr = p; return 1; } The caller can then do something like

Q14. Ans.

char *string = "Hello, world!"; char *copystr; if(allocstr(strlen(string), &copystr)) strcpy(copystr, string); else fprintf(stderr, "out of memory\n"); Write a program to find an area of a rectangle. void main( ) { float area,len,bre; printf(enter value for length , breadth ); scanf(%f%f,&len,&bre); area=len*bre; printf(area= %f ,area);

Q15. Ans.

} Write a program to find whether a number is Armstrong or not. Void main() x=x/10; { } int n,x,r,c,s=0; if(cs==n) clrscr(); printf("number is Armstrong"); printf("enter the number:"); else scanf("%d",&x); printf("number is not Armstrong"); n=x; getch(); while(x>0) } { r=x%10; c=r*r*r; s=s+c; Write a program for solving a quadratic equation. #include<processstdio.h> void main() { float a,b,c,d, x1,x2,d2,y1,y2; printf ("enter value of a,b,c in a quadratic equation(a*X*X+b*x+c\n"); scanf("%f%f%f",&a,&b,&c); d=b*b-4*a*c; if(d<0) { d=-d; d2=sqrt(d); y1=(-b)/(2*a); y2=d2/(2*a); printf ("value of x1 is (% of x is (%ff-+i%f)/%f) , y1,y2); printf("value of x2 is (%f-i%f) , y1,y2); and (%f+i%f)/%f",b,d2,(a*2),b,d2,(a*2)); exit(0); } else { d2=sqrt(d) ; x1=(-b+d2)/(2*a);

Q16. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


14/56
x2=(-b-d2)/(2*a); printf("value of x1 is is %f and %f",x1,x2); printf("value of x2 is %f ",x2); } Q17. Ans. Write a program in C to find the value of xn where x and n are positive constants. #include<math.h> void main() { const int a=3;const int b=2;int c; clrscr(); c=pow(a,b); printf("%d",c); getch(); }void main() { int x, n; long int power=1; clrscr(); printf(Enter the values of x and n : \n); scanf(%d %d, &x,&n); for(int i=1;i<=n;i++) { power=power * x; } printf(\n The value of power is %ld, power); } Write a macro in C to swap two data items. #include <stdio.h> clrscr(); #include <conio.h> printf("Before swapping %d %d",a,b); #define swap(x,y) { int t; t=x; x=y; y=t; } swap(a,b); void main() printf("\nAfter swapping %d %d",a,b); { getch(); int a=20,b=30; } Explain the various control statements used in c language. Which is more convenient. Control statements are used to make decisioncontrol the flow of the program. These statements are required to take an action according to the condition. There are two types of control statements: 1. Conditional Decision control statements a. If-else statement b. Switch statement 2. Loop control statements a. For b. While c. Do-While Decision control statements: If statement If else statement Nested ifs

Q18. Ans.

Q19. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


15/56
Switch statement If statement: executes the statements if condition is true syntax :if (condition) { Statements; } If else statement: executes the block of statements if condition is true. Otherwise execute else block. if (condition) { Statements; } else { Statements; } Nested ifs: executes one block out of number of blocks of statements which specify the condition other wise executes else block statements. if (condition) { Statements; } else if(condition) { statements; } else { statements } Switch statement: 1. It can be considered as a generalization of if else statement. 2. In switch we have a multiple choices . and depending on the choice, the value is assigned to a variable, one or more statements from a group of the statements can be executed. 3. The variable used for this purpose is known as switch variable. 4. The variable in the switch statement can be of int or char type only . 5. The switch statement can also contain the default statements in one of the lin.es. iBut it is optional but it should be only one. Switch is better than if-else. The conditional use is in the switch construct: switch (expression) { case const_expression_1: ...block of statements... break; case const_expression_2: ...block of statements... Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


16/56
break; default: ...block of statements.. break; } The appropriate block of statements is executed according to the value of the expression, and is compared with the constant expressions in the case statement. The break statements iensure that the statements in the cases following the chosen one will not be executed. If you would want to execute these statements, then you would leave out the break statements. This construct is particularly useful in handling input variables. Loop control statements:ops A loop is a part of the program through which the control moves several times during the execution of program. The part, which is executed again and again, is known as the body of the loop. In c we have three types of loops. These are known as: The while loop: It executes the statements till the value of an expression is true. while (expression) { statement a; statement b; } There will be no semicolon at the end of the line containing the keyword while. The Do-while loop: It checks the condition at the last. This loop executes the statements atleast once even if the expression is false. do { statement a; statement b; }while(expression); There will be no semicolon at the end of the line containing the keyword do but must be semicolon at the end of keyword while. The for loop: for(Initialization; Condition; Increment/Decrement) { statement 1; statement 2; } Write a program to find leap year. Void main () if (a%4==0 && a%100 != 0 | | a%400= =0) { printf(%d is leap year,a); int a ; else printf(enter year); printf(%d is not a leap year,a); scanf (%d,&a); } Write a C program to formation of pyramid of digits. #include<stdio.h> #include<conio.h> int main() printf(" "); for(j=1;j<=i;j++) printf("%d ",j);

Q20.
Ans.

Q21. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


17/56
{ printf("\n"); int i,j,k; } clrscr(); getch(); for(i=1;i<=5;i++) return 1; { } for(k=5;k>=i;k--) Write a c program to reverse the digits of a long number without using character array.

Q22. Ans.

void main() { { r=num%10; long int num,num1,numrev=0,r; numrev=(numrev*10)+r; clrscr(); num=num/10; printf("Enter a number-->"); } scanf("%d",&num); printf("reverse of %ld is %ld",num1,numrev); num1=num; getch(); while(num>0) } Q23. Write a program to print a Pascal triangle. Ans. #include <stdio.h> # include <conio.h> Void main() { int i,j,k; for (i=1;i<=5;i++) { for (k=20;k>=i;k--)void main() { int i=0,j,a[10][10],s=20,c; clrscr(); for(i=1;i<=5;i++) { for(j=s;j>=i;j--) printf(" "); c=1; a[1] [c]=1; printf(" %d",a[i][c]); if(i>1) { for(c=2;c<i;c++) { Q24. Ans. printf ( ); for (j=1;j<=i;j++) printf (%d,j); for (j=I-1;j>=1;j--) printf (%d,j); printf (\n); } getch(); }a[i] [c]=0; a[i][c]=a[i-1][c-i]+a[i-1][c]; printf(" %d",a[i] [c]); } } if(i>1) { a[i] [c]=1; printf(" %d",a[i] [c]); } s--; printf("\n"); } getch(); } What do you mean by loops? What are different types of loops provided by C language? Loops are used to execute the statements repeatedly according the condition. There are different types of loops in c

While Do while For While loop: This statement is used to execute the loop till the condition is true. Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


18/56
While (expression) { statements } Do while: Statements will ebe executed when the condition is true but in this loop statements are executed at least once whether the condition is true or false. Do { statements }while (expression); For loop: In the for loop the initialization , condition and increment or decrement can be done at one place. for (Initialization; Condition; Increment/Decrement) { statements; } Write a program to reverse the digits of a number. void main() a=n%10; { r=r*10+a; int n,a,r=0; n/=10; printf(enter number); } scanf(%d,&n); printf(reverse of number %d,r); while(n>0) getch(); { } Write a program to find the sum of digits of a number. void main() { int num,sum=0,r; clrscr(); printf("Enter any number : "); scanf("%d",&num); while(num>0) { Q27. Write a program to find the sum of the following series: Sum=1+3+5+7---------------n Ans. void main() { int i,n,sum=0; clrscr(); printf(\nEnter the value of n); scanf(%d, &n); for (i=1;i<=10n;i+=2) { printf("%d\n",i); sum+=i; } printf("Sum of above; %d",sum); getch(); r=num%10; sum+=r; num/=10; } printf("sum of digits is %d",sum); getch(); } Q28. Write a program to print the table of a given number.

Q25. Ans.

Q26. Ans.

Ans. void main() { int n,a=1,b; printf(enter number for table); scanf(%d,& n); while(a<=10) { b=a*n; printf( %d * %d = %d,n,a,b); a++; } getch(); }

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


19/56
} Q29. Write a program to sort n numbers in ascending order. Q30. Write a program in C to generate prime numbers less than 50.

Ans. void main() { int a[5],I,j,temp; for(I=0;I<5;I++) { printf(enter array elements); scanf(%d,&a[I]); } for(I=0;I<4;I++) for(j=I+1;j<5;j++) if(a[I]>a[j]) { temp=a[I]; a[I]=a[j]; a[j]=temp; } printf(sorted list); for(I=0;I<5;I++) printf(%d,a[I]); getch(); } } Q31. Ans.

Ans. void main() { int a=0,b,c; clrscr(); for(b=1;b<50;b++) { for(c=2;c<b;c++) if(b%c==0) break; if(b==1) { printf(" \n%d",b); a++; } } if(c==b) { printf("\n %d",b); }a++; } }} getch(); } } Write a program in C to generate Fibonacci series of 20 terms.

Q32. Ans.

void main() c=a+b; { a=b; int a=0,b=1,c=1,i; b=c; clrscr(); } for(i=1;i<=20;i++) getch(); { } printf(" %d",c); What is the difference between break and continue statements? Explain with the help of an example. Break statement is used to exit from the loop. Whenever break statement is encountered the rest of the statements inside the loop are ignored and the control goes to the next statements after the loop. But the case of using continue is different. Continue statement is used to skip the later on statements and go back to the starting of the loop in order to execute it again. Break Example Continue Example Void main() Void main() { { int I; int I; for (I=1;I<=10;I++) for (I=1;I<=10;I++) { { if (I==5) if (I==5) break; continue; printf(%d,I); printf(%d,I); } }} } }}

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


20/56
OutPut: 1,2,3,4 Q33. Ans. void main()
{ int r,c; clrscr();

OutPut: 1,2,3,4,6,7,8,9,10

Write a program to fill the entire screen with a smiling face. The smiling face has an ASCII value 1. for(c=0;c<=79;c++) printf("%c",21);

for(r=0;r<=24;r++)

getch();}

Q.34 Write a program in C language to produce output as given below 1 121 12321 1234321 123454321 12345654321 Ans. #include <stdio.h> printf ( ); # include <conio.h> for (j=1;j<=iI;j++) Void main() printf (%d,j); { for (j=II-1;j>=1;j--) int Ii,j,k; printf (%d,j); for (iI=1;Ii<=85;Ii++) printf (\n); { } for (k=20;k>=1i;k--) getch(); } Q.35 Ans. # include <stdio.h> # include <conio.h> # include <math.h> void main() { int n,s,i,b=1; float p=0; printf (\n Enter number ); scanf (%d,&n); printf (\n Enter how many number for series ); scanf (%d,&s); for (i=1;i<=s;i+=2) { if (b==1) { p=p+pow(n,i)/(float)i; b=0; } else { p=p-pow(n,i)/(float)i; b=1; }} } printf (\n Value of sin (%d) is %f,n,p); } Write a program in c language to find the value of n using expansion series given below: Sin(x)=x-x3/3+x5/5-x7/7.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


21/56

Q.36

Write a program to sum up the following series: 1 1 + 1 1 + 2 3 4 #include<stdio.h> #include<conio.h> void main() { int n,i; float j=1, sum=0; clrscr(); puts("Enter the upper limit of the series: "); scanf("%d",&n); for(i=1;Ii<=n;Ii++)

., +

1 n

Ans. { if(i%2==0) sum-=(float)(1/ij); else sum+=(float)(1/ji); j++; } printf("\n\nSum of the series is : %.2f",sum); getch(); }

Q37. Ans.

Write a program in C language to find out the sum of first n natural numbers using do.while loop. #include<stdio.h> #include<conio.h> void main() { int no=1,sum=0,final; clrscr() printf ("Enter the value of n final number "); scanf ("%d",&final); do { sum=sum+no; no=no+1; } while (no<=final); printf ("sum is %d ",sum); }

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


22/56

Section B 2 Marks Questions [QUESTIONS 1 TO 23] [PAGE 19 21 TO 2224]


Q1. Ans. What do you mean by arrays? Describe two ways to specify the address of an array element. How is an array name is interpreted when it is passed to a function? An array is a group of similar kind of elements that share a common name and that are differentiated from one another by their positions within the array. a All elements of an array are of same type .in In other words if an array is declared to be of an int type it cannot contain elements that are not of int type. For example: To get the value of the third element of an array list the two ways are b=A[3] Ptr=&A; ptr+3; b=*ptr; When we pass an array as an argument its name is interpreted as the base address of the array. How is memory allocated in an array? Discuss advantages and disadvantages of array. An array can be defined as a group of similar type of variables, which occupy contiguous locations in memory and are referred to by a common name. In case of array multiple values can be stored and accessed easily using single name, as the memory is allocated sequentially so that data can be easily accessed by increment or decrement by single variable. Array can hold similar types of data only. Array may require large amount of contiguous memory, which is not available sometimes. What is a string constant? How do string constants differ from a character constant? A string constant, such as I am a string is an array of characters. It is represented internally in C by the ASCII characters in the string, i.e., I, blank, a, m,. for the above string, and terminated by the special null character \0 so programs can find the end of the string. String constants are often used in making the output of code intelligible using printf ; printf("Hello, world\n"); printf("The value of a is: %f\n", a); String constants can be associated with variables. C provides the char type variable, which can contain one character--1 byte--at a time. A character string is stored in an array of character type, one ASCII character per location. Never forget that, since strings are conventionally terminated by the null character \0, we require one extra storage location in the array. Write a program in C language to convert the given string in uppercase. #include<string.h> void main() { char name[25]; clrscr(); What do you mean by formal arguments relationship between them? Printf("Enter Name"); gets(name); printf("%s",strupr(name)); getch() ; } and the actual arguments and the

Q2. Ans.

Q3. Ans.

Q4. Ans.

Q5.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


23/56
Ans. The formal arguments given while declaring the function Are are required to be checked at the time of passing The the actual arguments. For example: int square(int a,int b) Here a and b are known as formal arguments. In this, the data types for the arguments with the return type Are is specified. When the function is called like square(10,10) Then these are the current actual arguments. What do you mean by functions? What is recursive function? What advantages is there in its use. A function is a self-contained program segment that carries out some specific ,welldefined task and returns a value. A function is also known as sub program that can execute by it in the program. Functions are basically are classified in two categories: Library functions :- These are needed in every program. tThey are stored in the library files known as header file. Commonly useable functions are printf() and scanf(). it is to includedHeader files are to be included at the beginning of the program using pre processors. User-defined functions :- These functions are defined by the users according to their requirements. A recursive function is one which calls itself. This is another complicated idea which you are unlikely to meet frequently. We shall provide some examples to illustrate recursive functions. Recursive functions are useful in evaluating certain types of mathematical function. You may also encounter certain dynamic data structures such as linked lists or binary trees. Recursion is a very useful way of creating and accessing these structures. The major advantages of using functions are as follows: Efficiency of maintenance of code Elimination of redundancy of code Ease of understanding Reusability of code What is meant by a function call? From what parts of a program can a function be called? Function call means calling a function for the purpose of execution. A function can be called by simply using the function name in a statement. Eg. Void mMain() { int p; p=mul(10,5); printf (%d\n,p); } When the compiler encounters a function call, the control is transferred to the function mul (x,y). This function is then executed line by line as described and a value is returned when a return statement is encountered. This value is assigned to p. What is meant by parameter passing? Explain the difference between call by values and reference. The process of passing values to functions is known as parameter passing, with the help of parameters different types of values and number of values can be passed to functions. Parameter passing is of two types. Call by value: In call by value, the original values will be copied into formal values. In this, the value (copy) of the actual arguments are passed to the function. In this way processing is done on the copy of actual variables. So, the changes will not be reflected outside the function. Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

Q6. Ans.

Q.7. Ans.

Q8. Ans.

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


24/56
Call by reference: Here we pass the address of the variable as a parameter instead of value. Here changes will be reflected even outside of the function also. IIn this approach the addresses of the actual arguments are passed to the called function. In this way processing is done on the actual variables. Q9. Ans. Write a program to count number of zeroes, +ve numbers in the given array. void main() { int a[10],i,zero=0,pos=0; clrscr(); printf("Enter ten values\n"); for (i=0;i<10;i++) scanf("%d",&a[i]); for (i=0;i<10;i++) { if (a[i]==0) zero++; if (a[i]>0) pos++; } printf("%d zero's and %d +ve number is in given array",zero,pos); getch(); }

Q.10. Explain the memory management of an integer array. Ans. An array is finite collection of similar elements stored in adjacent memory locations. An array containing n number of elements is referenced using an index that varies from 0 to n-1. In an integer array, each element occupies 2 bytes in memory. For example, consider the following integer array: A[0] a[1] a[2] a[3] a[4] 3268 3270 3272 3274 3276 Here , each element of the array occupies 2 bytes. The starting address is 3268. The next address is 2 bytes ahead of the first. Q.11. How bubble sort method is different from selection sort. Ans. In bubble sort method, the first element is compared with the second one and if it is greater than the second element, they are swapped, this method continues till the list is sorted. Whereas, in selection sort, a minimum function is implemented which finds the minimum element from the list & inserts at the appropriate place. Q12. What condition must be satisfied by all the elements of any given array? Ans. All the elements in any array must belong to same data type. That is if any array is declared as integer array then all the elements in that array must belong to integer type. Q13. Differentiate between sprintf() and sscanf() functions. Ans. The sprintf() function works similar to the printf() function except for small difference . Instead of sending the output to the screen as printf () does, thid this function writes the output to an array of characters. The counterpart of sprintf() is the sscanf() function. It allows us to read characters from a string and to convert and store then them in C variables according to specified formats. The sscanf() function comes in handy for in-memory conversion of characters to values. Q14. What is the difference between x and x? Ans. x represents a string constant and it must be followed by the null character \0, whereas x represents a character constant. Q15. What will be the output of the following program? main() { Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


25/56
char c[2]=A; printf (\n%c,c[0]); printf (\n%s,c); Ans. } The output of the above program is A A. In the above program we have initialized a character array of 2 elements. First we printed the character at 0 position and then we prints the whole string. The output is 2 times A , because here the string contains only one character. What are strings? The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. Character array are also called strings. A string constant is a one dimensional array of characters terminated by a null (\0). For example, car name[]={V,I,R,K,\0}; How can we pass Entire array to a function? Explain with example. main() int I; { for (I=0;I<=n-1;I++) int num[]={1,2,3,4,5,6}; { int I; printf (element = %d,*j); display (&num[0],6); j++; /*increment pointer to point to next } location */ display(int *j, int n) } { } What do you mean by bound checking? In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; probably on top of other data , or on the program itself. This will lead to unpredictable results. There will be no error message to warn you that you are going beyond the array size. It is the responsibility of the programmer to write the code which that will check the upper bound of the array. What do you mean conditional compilation. Conditional compilation means that we can have the compiler to skip over a part of a source code by inserting the preprocessing commands #ifdef and #endif, which have the general form: #ifdef macroname statement 1; statement 2; statement 3; #endif What is the purpose of the return statement? The return statement serves two purposes: 1) On executing the return statement it immediately transfers the control back to the calling program. 2) It returns the value present in the parentheses after return, to the calling program. Why we use functions? 1) Writing functions avoids rewriting the same code over and over.

Q16. Ans.

Q17. Ans.

Q18. Ans.

Q19. Ans.

Q20. Ans.

Q21. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


26/56
2) Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided into separate activities, and each activity placed in a different function, then each could be written and checked, more or less independently. Separating the code into modular functions also makes the program easier to design and understand Explain function prototyping. Function prototype is a non-executable statement. It Provides information to the compiler about the type and Number of arguments for a function. It also tells about the Return type, if any. This check could benefit compiler at Execution time. How two character can be compared? In C language two characters can be compared by simply using ==(equality operator). For eg. If (a==b), where a and b are declared as character variables. Character are compared through their ASCII values.

Q22. Ans. Q23. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


27/56

Section B [QUESTIONS 1 TO 33]


Q1.

5 Marks Questions [PAGE 23 25 TO 3234]

Q3. Ans.

Write a program in C language to Q2. Write a C program to print 5X5 add two matrices. matrix. Ans. Ans. void main() #include<stdio.h> { #include<conio.h> int a[2][2],b[2][2],c[2][2]; int main() for(int i=0;i<2;i++) { for(int j=0;j<2;j++) int matrix[5][5],i,j; scanf("%d",&a[i][j]); clrscr(); for( i=0;i<2;i++) for(i=0;i<5;i++) for( j=0;j<2;j++) for(j=0;j<5;j++) scanf("%d",&b[i][j]); { for( i=0;i<2;i++) printf ("Enter values of matrix[%d][%d]:" ,i for( j=0;j<2;j++) +1, c[i][j]=a[i][j]+b[i][j]; j+1); for( i=0;i<2;i++) scanf("%d",&matrix[i][j]); { } for( j=0;j<2;j++) printf("\n\nYou entered the matrix as..."); printf("%d ",c[i][j]); printf("\n"); printf("\n"); for(i=0;i<5;i++) } { } for(j=0;j<5;j++) { printf(" %d",matrix[i][j]); } printf("\n"); } getch(); return 1; } Write a program to find sum of two matrices. #include<stdio.h> #include<conio.h> int main() { int matrix1[2][2],matrix2[2][2],matrix3[2][2],i,j; clrscr(); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf ("Enter values of matrix1[%d][%d]::", i +1, j+1)); scanf("%d",&matrix1[i][j]); }} for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("Enter values of matrix2[%d][%d]: scanf("%d",&matrix2[i][j]); }} for(i=0;i<2;i++) { for(j=0;j<2;j++) { matrix3[i][j]=matrix1[i][j]+matrix2[i][j]; }} printf("\n\nResultant is...\n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf(" %d",matrix3[i][j]); } printf("\n"); } getch(); return 1;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


28/56
Q4. Ans. ",i+1,j+1); } Write a program to find difference of two matrices. NOTE:- Same as the above program , just in place of "+" we will use "-" in formula. Q5. Write a program to find the transpose of a matrix. Q6. Using functions write a program to find the sum of rows, column of all elements of a matrix.

Ans. #include<stdio.h> #include<conio.h> int main() { int matrix[2][2],i,j; clrscr(); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("Enter values of matrix1[%d][%d]: ",i+1,j+1):); scanf("%d",&matrix[i][j]); } } puts("Transpose of the matrix is..."); for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf(" %d",matrix[j][i]); } printf("\n"); } getch(); return 1; }

Q7.

Write a C program to find minimum and maximum values in a given series of data.

Ans. #include<stdio.h> #include<conio.h> int main() { int arr[10],min,max,i; clrscr();

Ans. #include<stdio.h> #include<conio.h> int main() { int matrix[43][43],i,j; int sum=0; clrscr(); matrix[0][2]=matrix[1][2]=matrix[2][2]=0; matrix[2][0]=matrix[2][1]=matrix[2][2]=0; for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("Enter value of matrix[%d][%d]: ",i+1,j+1); scanf("%d",&matrix[i][j]); }} for(i=0;i<3;i++) { for(j=0;j<3;j++) { matrix[i][3]+=matrix[i][j]; matrix[3][j]+=matrix[i][j]; }} prpriintf("\n\nYou entered the matrix as..."); printf("\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf(" %d",matrix[i][j]); }printf("\n");} for(i=0;i<3;i++) { for(j=0;j<3;j++) { sum=sum+matrix[i][j]; }} printf(The sum of elements are: %d,sum); getch(); return 1; } Q8. Write a C program to sort data in two-dimensional array. Ans. void main() { int a[3][3],b[9],i,j,k=0,temp=0; clrscr(); for(i=0;i<3;i++) for(j=0;j<3;j++) { printf("enter array element-->"); scanf("%d",&a[i][j]);

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


29/56
for(i=0;i<10;i++) { printf("Enter value of arr[%d]:ay: ",i+1)); scanf("%d",&arr[i]); } min=max=arr[0]; for(i=1;i<10;i++) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } printf("\n\nMinimum=%d, Maximum= %d",min,max); getch(); return 1; } b[k]=a[i][j]; k++; } printf("\nentered array\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%d\t",a[i][j]); printf("\n"); } for(i=0;i<8;i++) for(j=i+1;j<9;j++) if(b[i]>b[j]) { temp=b[i]; b[i]=b[j]; b[j]=temp; } k=0; for(i=0;i<3;i++) for(j=0;j<3;j++) { a[i][j]=b[k]; k++; } printf("\nsorted array\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%d\t",a[i][j]); printf("\n"); }getch();} Q10. Write a program to multiply any two matrices. Ans. void main() {int a[10][10],b[10][10],c[10] [10],Ii,j,k,r1,r1,r2,c1, c2; printf( Enter Rows of first matrix ); scanf(%d,&r1); printf( Enter columns of first matrix); scanf(%d,&c1); printf( Enter columns rows of first second matrix); scanf(%d,&r2); printf( Enter columns of first matrix); scanf(%d,&c2); if (c2!=r2) {printf( Multiplication not possible ); exit(0);} printf (Enter first matrix\n); for(I=0;I<r1;I++) for(j=0;j<c2;j++) { printf(Enter array element ); scanf(%d,&a[I][j]); } printf(Enter second matrix \n) for(I=0;I<r2;I++) for(j=0;j<c2;j++) { printf(Enter array element ); scanf(%d,&a[I][j]); } for (I=0;I<r2,I++)

Q9.

Write a program to show the linear search methodology.

Ans. void main() { int a[7],i,f=0,s; printf("enter the numbers:"); for(i=0;i<7;i++) scanf("%d",&a[i]); printf("enter the no. to search:"); scanf("%d",&s); for(i=0;i<7;i++) { if(a[i]==s) { f=1; printf("%d is found at %dth position\n",s,i+1); } } if(f==0) printf("no. not found"); getch(); }

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


30/56
for(j=0;j<c2;j++) { c[I][j]=0; for(k=0;k<r2;k++) c[I][j]+=a[I][k]*b[k][j]; } printf (Result of Multiplication\n); for(I=0;I<r1;I++) { printf(\n); for(j=0;j<c2;j++) printf(\t%d,c[I][j]); }getch(); }

Q11. Ans.

Write a program to transpose a matrix using pointers. void main() /* transposing the matrix */ { for(I=0;I<2;I++) int a[2][2],I,j; { for(I=0;I<2;I++) for(j=0;j<2;j++) { { printf(enter the values for %d row of printf(\t%d,a[j][I]); matrix,I+1); } for(j=0;j<2;j++) printf(\n); { } scanf(%d,&a[I][j]); getch(); } } }

Q12. Ans.

What is the use of following String functions and list the commonly useable function? String library functions are the functions, which are used regularly and stored in library file and whenever these functions are needed , you need to include the required header file in your program. There are different types of functions strlen: This function is used to count the characters in a string. It calculates the length of the string. Syntax: strlen(array variable); strcpy: This function copies the contents of one string into another Syntax strcpy(target,source); strcat: This function is used to concatenate the source string at the end of the target string. Syntax strcat(target,source);

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


31/56
strcmp: This function compares two strings to find out whether they are same of different. The two strings are compared character by character until there is a mismatch or end of the string. These function returns 0 if both the strings are identical. Syntax Strcmp(string1,string2); Q13 Ans. Write a program for comparing two strings. #include<stdio.h> void main() { char str1[20],str2[20]; int res; clrscr(); printf ("\nEnter string one "); gets (str1); printf ("\nEnter string two "); gets (str2); res=strcmp(str1,str2); if (res==0) printf ("\n Both strings are equal"); else if (res>0) printf ("\n String 1 is greater"); else printf ("\n String 2 is greater"); }

Q14. Ans.

How can you apply arithmetic operations on strings? write the role of a atoi( ) function in string. Arithmetic operations can be applied on strings by converting strings to integers using atoi () function. tThis function converts digits in strings to integers. atoi ( ) function is a c library function which is used to convert a string of digits to the integer value. E.g. char st[10]=12345; int n; n= atoi(st); This will assign the integer value 24175 to the integer variable n. Q15. Write a program that accepts a letter and convert it into uppercase to lowercase or lowercase to uppercase? Q16. Write a program to copy a string. Ans. #include<stdio.h> #include<conio.h> #include<string.h> int main() { char str1[20],str2[20]; clrscr(); printf("Enter text: "); gets(str1); strcpy(str2,str1); puts("\nAfter copying to another string...\n"); puts(str2); getch(); return 1; }

Ans. void main() { char n; clrscr(); printf("Enter any character: "); n=getchar(); if (n>='A' && n<='Z') printf("%c",n+32); else if (n>='a' && n<='z') printf("%c",n-32); else printf("Invalid Character"); getch();

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


32/56
} Q17. Write a function that perform a Q18. Write a C program to compare two task similar to a string library strings and concatenate them if they function strlen(). are not equal using pointers. Ans. Ans. #include<stdio.h> void main() #include<conio.h> { char *a,*b,*c; int i,j,compared=0; lenstr(char str[]); clrscr(); int main() printf("Enter first string: "); { gets(a); int len; printf("Enter second string: "); char str[100]; gets(b); clrscr(); for(i=0,j=0;a[i]!=NULL || b[j]!=NULL;i++,j++) puts("Enter a string: "); { if (i!=j) gets(str); { compared=0; len=lenstr(str); break; } printf("\n\nLength of string is %d",len); if (a[i]==b[j]) getch(); compared=1; return 1; else } { compared=0; break; lenstr(char str[]) } { } int i=0; if (compared==1) while(str[i++]!='\0'); printf("Both strings are same"); return i-1; else } { for (i=0;a[i]!=NULL;i++) c[i]=a[i]; j=i; for (i=0;b[i]!=NULL;i++,j++) c[j]=b[i]; c[j]=NULL; printf("%s",c); } getch(); } Q19. Write a program to implement array & for finding largest among n numbers. Q20. Write a C program to check whether given string is palindrome or not.

Ans. int largest(int *a, int n) { int max, I=0 ; max=a[I]; for(I=1;I<n; I++) { if(max<a[I]) max=a[I]; } return max; } void main( )

Ans. #include<string.h> void main() { char a[20]; printf("enter string \n"); scanf("%s",a); int i=strlen(a); int k=--i; for(int j=0;j<k;j++) { if(a[i]!=a[j]) { printf(" not a palindrome");

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


33/56
{ int a[20] , n ,j, max; printf(\nEnter the elements to be entered); scanf(%d,&n); for(j=0;j<n;j++) { printf(\nEnter array element); scanf(%d,&a[j]); } max=largest(a,n); printf(\nThe largest element is %d,max); getch(); } Q21. Create a program to reverse a string without using any string library function. Ans. void main() { char n[20],n1[20]; int c=0,i; printf("enter any string"); gets(n); for(i=0;n[i]!=NULL;i++) c++; for(c=c-1,i=0;c>=0;c--,i++) n1[i]=n[c]; printf("reverse of string is %s",n1); getch(); } exit(0); } i--; } printf(" string is palindrome"); }

Q22.

Create a program to sort the elements of an array?

Ans. void main() { int a[5],I,j,temp; for(I=0;I<5;I++) { printf(enter array elements); scanf(%d,&a[I]); } for(I=0;I<4;I++) for(j=I+1;j<5;j++) if(a[I]>a[j]) { temp=a[I]; a[I]=a[j]; a[j]=temp; } printf(sorted list); for(I=0;I<5;I++) printf( %d,a[I]); getch(); }

Q23.

Write a program in C to Q24. Write a program to count number of concatenate two strings without vowels in a string. using strcat() function. Ans. Ans. void main() void main() { { char a[20]; char s1[10],s2[10],s3[20];int i; int c=0,I; clrscr(); printf(enter any string); printf("Enter first string: "); gets(s1); scanf(%s,&a); printf("Enter second string: "); gets(s2); for(I=0;a[I]!=NULL;I++) for(i=0;i<strlen(s1)+strlen(s2);i++) if(a[I]==a||a[I]==e||a[I]==i||a[I]==o||a[I]==u|| if(i>=strlen(s1)) a[I]==A|| a[I]==E||a[I]==I||a[I]==O||a[I]==U) s3[i]=s2[i-strlen(s1)]; c=c+1; else printf(No of vowels in a string %d,c); s3[i]=s1[i]; getch(); s3[i]=NULL; } printf("After concatenating:\n %s",s3); Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


34/56
getch(); } Q25. Ans. What is recursion? Write a program to find Fibonacci series till a given number using recursion. Recursion is the method to call the function itself inside its body, until some specific condition is true. This process is used for repetitive computation in which each action is stated in terms of the previous result. #include<conio.h> #include<stdio.h> int fib(int n) { if (n==0) return 0; else if (n==1) return 1; else return fib(n-1)+fib(n-2); } void main() { int i=0,num; clrscr(); printf("Enter end number; "); scanf("%d",&num); do { printf("\n%d",fib(i)); i++; }while(fib(i)<=num); getch(); }

Q26. Ans.

Write a c program to calculate number of days between two dates using function. struct date { int year; int day; int mon; }; void main() { struct date d1,d2; void datedif(struct date,struct date); clrscr(); datedif(d1,d2); getch(); } void datedif(struct date d1,struct date d2) { int d,m,y,daydiff; printf("enter first date-->"); printf("\nenter day-->"); Q27. scanf("%d",&d1.day); printf("enter month-->"); scanf("%d",&d1.mon); printf("enter year-->"); scanf("%d",&d1.year); printf("enter second date greater than first-->"); printf("\nenter day-->"); scanf("%d",&d2.day); printf("enter month-->"); scanf("%d",&d2.mon); printf("enter year-->"); scanf("%d",&d2.year); d=d2.day-d1.day; m=d2.mon-d1.mon; y=d2.year-d1.year; daydiff=d+(m*30)+(y*365); printf("difference of days=%d",daydiff); getch(); }

Write recursive function to find the Q28.

Write a program to find factorial of a

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


35/56
greatest common divisor of two numbers. Ans. #include <stdio.h> #include <conio.h> int hcf(int n, int m) { int t; t=m; if (n%m==0) return t; else hcf(m,n%m); } void main() { int a,b,k; clrscr(); a=18;b=16;k=hcf(a,b); printf("\nHCF : %d",k); getch(); } given number. Do recursion function. Ans. int fact(int); void main() { int f,n; printf(Enter any number: ); scanf(%d,&n); f=fact(n); printf("factorial is %d",f); getch(); } int fact(int n) { if(n==1) return 1; else return n*fact(n-1); } it by using

Q29.

Write a function that will calculate and display the roots of a quadratic equation.

Q30.

Write a C function that accepts decimal number and return its equivalent binary number.

Ans. #include<stdio.h> void main() { float a,b,c,d, x1,x2,d2,y1,y2; printf ("enter value of a,b,c in a quadratic equation(a*X*X+b*x+c\n"); scanf("%f%f%f",&a,&b,&c); d=b*b-4*a*c; if(d<0) { d=-d; d2=sqrt(d); y1=(-b)/(2*a); y2=d2/(2*a); printf("value of x1 is (%f+i%f) , y1,y2); printf("value of x2 is (%f-i%f) , y1,y2); exit(0); }

Ans. void main() { int n,a[10],j,i=0; clrscr(); printf("Enter any decimal number: "); scanf("%d",&n); do { a[i]=n%2; n=n/2; i++; } while(n!=0); for(j=i-1;j>=0;j--) printf("%d",a[j]); getch(); }

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


36/56
else { d2=sqrt(d) ; x1=(-b+d2)/(2*a); x2=(-b-d2)/(2*a); printf("value of x1 is %f ",x1); printf("value of x2 is %f ",x2); } #include<stdio.h> #include<math.h> #include<process.h> void main() { float a,b,c,d, x1,x2,d2; printf("enter value of a,b,c in a quadratic equation(a*X*X+b*x+c\n"); scanf("%f%f%f",&a,&b,&c); d=b*b-4*a*c; if(d<0) { d=-d; d2=sqrt(d) ; printf("value of x is (%f-i%f)/%f and (%f+i%f)/ %f",b,d2,(a*2),b,d2,(a*2)); exit(0); } d2=sqrt(d) ; x1=(b+d2)/2*a; x2=(b-d2)/2*a; printf("value of x is %f and %f",x1,x2); } Q31. A 5 digit positive integer is entered through the keyboard. Write a function to calculate sum of digits of the 5 digit number:

A)
Ans.

Without using recursion.

B)

Using recursion.

A) Without recursion void main() { long int num,sum=0,r; clrscr(); printf("Enter a five digit no: "); scanf("%ld",&num); while(num>0) { r=num%10; sum+=r; num/=10; } printf("sum of digits is %ld",sum); getch(); }

B) With recursion int s=0; int sum(int num) { if(num==0) return s; else { s+=(num%10); sum(num/10); } } void main() { clrscr(); printf("sum of digits is %d",sum(565)); getch();

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


37/56
}

Q32. Ans.

Write a program to find the sum of the rows, column, diagonal elements of a matrix. #include<stdio.h> #include<conio.h> int main() { int matrix[3][3],i,j; int sum=0; clrscr(); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("Enter value of matrix[%d][%d]: ",i,j); scanf("%d",&matrix[i][j]); }} #include<stdio.h> #include<conio.h> int main() { int matrix[4][4],i,j; clrscr(); matrix[0][2]=matrix[1][2]=matrix[2][2]=0; matrix[2][0]=matrix[2][1]=matrix[2][2]=0; for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("Enter value of matrix[%d][%d]: ",i+1,j+1); scanf("%d",&matrix[i][j]); } } for(i=0;i<3;i++) {for(j=0;j<3;j++) { priintf("\n\nYou entered the matrix as..."); printf("\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf(" %d",matrix[i][j]); }printf("\n");} for(i=0;i<3;i++) { for(j=0;j<3;j++) { sum=sum+matrix[i][j]; }} printf(The sum of elements are: %d,sum); getch(); return 1; }matrix[i][3]+=matrix[i][j]; matrix[3][j]+=matrix[i][j]; } } printf("\n\nYou entered the matrix as..."); printf("\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf(" %d",matrix[i][j]); } printf("\n"); } getch(); return 1; }

Q.33 Ans.

Write a program in C which finds the sum of elements of an integer array. Use user defined function to pass array to the function. #include<stdio.h> int add(int []); void main() { int a[5],i,sum; clrscr(); for (i=0;i<=4;i++) { printf ("\n Enter no "); sum=add(a); printf ("\n sum is %d",sum); } add(int a[]) { int i,sum=0; for(i=0;i<=4;i++) sum=sum+a[i]; return sum;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


38/56
scanf ("%d",&a[i]); } }

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


39/56

Section C [QUESTIONS 1 TO 22]


Q1.

2 Marks Questions [PAGE 33 35 TO 3639]

Ans.

What is pointer? Why pointers are used and how we initialize pointer variables? OR What kind of information does a pointer variable represent. Pointer is variable that represents the location of a data item. These variables stored in memory location and are assigned a unique number i.e., the address of that location. This address points to whatever is contained within the location in the same way as each array element has its own index. Thus pointers provide a way of accessing a variable without referring to it directly but by using its address. We can initialize pointer by using command (int *p=50;) Q2. Write a program using pointers to copy a string to another string variable. Q3. Write a C program using pointers to multiply two integers. Ans. void main() { int *x,*y,*k; int a,b; clrscr(); *x=20; *y=3;x=&a; y=&b; printf(\nEnter two numbers: ); scanf(%d %d, &a,&b); *k=*x * *y; printf("Multiply: %d",*k); getch(); }

Ans. void main() { char *a="Ajay", *b;char s[]=Jai mata di; char t[25]; char *ss, *tt; ss=s; while(*tt++=*ss++) { *tt=\0; } clrscr(); b=a; printf("%s",b); getch(); } Q4. Ans.

How structure is represented in memory? Whatever be the elements of a structure, they are always stored in contiguous memory locations. Once the new structure data type has been defined one or more variable can be declared to be of that type. The memory consumption of structure is show in the following program; main() { struct book { char name;float price;int pages; }; struct book b1={'A',130.00,550}; printf ("\n address of name = %u",&b1.name); printf ("\n address of price = %u",&b1.price); printf ("\n address of pages = %u",&b1.pages); } Here is the output of the program: Address of name = 1001 Address of price = 1002

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


40/56
Address of pages = 1006 Q5. Ans What are self-referential structures? The self-referential structures are those structures that include an element that is a pointer to another structure of the same type. These structures find their application in building complex data structures such as linked lists, trees and graphs. Explain the user defined data types in "C". Explain with example. or Differentiate between structure and union. Write syntax to declare structure and union. Structure: It is a user defined data type. In a structure we can store various data type variables to make a record. The size of structure is the sum of the memory required by all the variables defined in it. In a structure, initialization is performed through a braces enclosed with list of initializations. Union: It is a user defined data type. Like structure, In a structure we can store various data type variables to make a record in union also. but they need not to be related with each other and Tthe size of the union is the maximum size variable defined in it. All the members of the union share the same memory space. In union, initialization can be done only on its first data member. Struct exp { int rollno; char name[25]; }; Initialization: Struct emp emp1={1000,shikha}; Q7. Ans. Union exp { int rollno; char name[25]; }; Initialization: Union emp emp1 ={1000};

Q6.

Ans.

Write a C program to compute the size of union. union student { int roll_no; char sname[20]; }; void main() { clrscr(); printf ("Size of union is %d bytes",sizeof(union student)); getch(); }

Q8. Ans.

Q9.

Define text & binary files. Text file contain a sequence of characters including carriage returns and linefeeds. In text mode, there is no requirement that individual character remain unaltered as they are written to or read from a file. It is a simple file so we can read easily. Binary file contain a sequence of bytes with a one to one correspondence to the sequence found in the external device (disk, tape) It is a Encrypted file so we cannot read it. What do you mean by data file? What is the primary advantage of using a data file?

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


41/56
Ans. File is place on the disk where a group of related data is stored for later reference. The concept of files came into existence for the safe and organized storage of data. Advantages of data files are; 1. Easy to access and update 2. Provide faster access 3. Transaction need not be sorted

Q10. Ans.

What is purpose of library function feof()? The function is used to check whether the file pointer has reached at the end or not. It returns the non-zero value when theif file pointer points the end of the file has been reached otherwise it return zero. This is generally written as: int feof(FILE *fp)

Q11. Ans.

What are the various types of modes used in file handling? Explain with example. Files Modes Operator Rr wW aA rb RB WBwb abAB

Description Open a text file for reading. Create a text file for writing. If the file exists, it is overwritten. Open a text file in append mode. Text is added to the end of the file. Open a binary file for reading.

Create a binary file for writing. If the file exists, it is overwritten. Open a binary file in append mode. Data is added to the end of the file. r+R+ Open a text file for reading and writing. w+W+ Create a text file for reading and writing. If the file exists, it is overwritten. a+A+ Open a text file for reading and writing at the end. R+B rb+or Open binary file for reading and writing. RB+ wb+W+B Create a binary file for reading and writing. If the file exists, it is or WB+ overwritten. ab+A+B or Open a text file for reading and writing at the end. Q12. Ans. Explain the redirection and command line argument. Redirection means performing input from other than the standard input stream, or output to other than the standard output stream. You can redirect the output of the print and printf statements to a file or a system command, using the `>' , `>>' , and `|' operators. You can redirect input to the getline statement using the `<' and `|' operators.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


42/56
Command Line Argument is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process. For example if we want to execute a program to copy the contents of a file named MYFILE1 to another one named MYFILE2, then we may use a command line like C:\>Program myfile1 myfile2 Here PROGRAM is the filename where the executable code of the program is stored. MYFILE1 is source file and MYFILE2 is target file.

Q13. Ans.

What are the features of structures? 1. The values of a structure variable can be assigned to another structure variable of the same type using the assignment operator. 2. One structure can be nested within another structure. Using this facility complex data types can be created. 3. Like an ordinary variable, a structure variable can also be passed to a function. We may either pass individual structure elements or the entire structure at one go. 4. The way we have a pointer pointing to an int, or a pointer pointing to a char , similarly we can have a pointer pointing to a structure. Such pointers are known as structure pointers.

Q14. Ans.

Q15. Ans.

How structure elements are stored? Whatever be the elements of a structure, they are always stored in contiguous memory locations.Eg. b1.name b1.price b1.pages b 130.00 550 Address of name = 1001 Address of name price = 1002 Address of pagesname = 1006 What do you mean by enumerated data types? How it is useful. The enumerated data type gives you an opportunity to invent your own data type and define what values the variable of this data type can take. This can help in making the program listings more readable, which can be an advantage when a program gets complicated or when more than one programmer would be working on it. Using enumerated data type can also help you reduce programming errors. Its syntax is: enum colour{ red=5,black=2,blue}; then it initializes value 5 to red, 2 to black and 3 to blue If the initialization of elements is not given, it starts from 0 and the next element takes a constant value, one more than the previous element. What is the use of fseek() and rewind() function. The fseek() function lets us move the pointer from one record to another. The rewind() function places the pointer to the beginning of the file, irrespective of where it is present right now. What is the significance of EOF?

Q16. Ans. Q17.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


43/56
Ans. EOF function checks for end of file. EOF determines whether the file associated with handle has reached end of file. Returning values: On success it returns 1 Otherwise returns 0. On error returns -1. What do you mean by Dangling pointer? What type of problems it may cause? Sometimes the variables whose addresses are stored in Pointer pointer variables are deleted after there respective Operationsoperations. But the pointer variables remain pointing Towards towards a the memory locations. Dangling pointer basically Lead leads to wastage of memory space. Why we need to include files? A header file is a library, which stores the inbuilt functions .if we want to use these functions in our program we have to include that particular header file. E.g. printf(), scanf() are stored in stdio.h

Q18. Ans.

Q19. Ans.

Q20. Ans. Q21. Ans.

Q22. Ans.

Pointer is double-edged weapons explain it. A pointer can store address of other variable as well as value also. Where as a variable can store a value only not the address. What is multiple indirection? We can have a pointer point to another pointer that points to the target value. This situation is called multiple indirection, or pointers to pointers. A variable that is a pointer to a pointer must be declared as placing an additional asterisk in front of the variable name. For eg., the following declaration tells the compiler that newbalance is a pointer to pointer of type float: float **newbalance; What do you mean by streams? The C file system is designed to work with a wide variety of devices , including terminals, disk drives, and tape drives. Each Even though each device is very different, the buffered file system transforms each into a logical device called a stream. All streams behave similarly. Because streams are largely device independent, the same function that we can write to a disk file can also be used to write to another type of device, such as the console. There are two types of streams :text and binary.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


44/56

Section C [QUESTIONS 1 TO 232]


Q1. Ans.

5 Marks Questions [PAGE 37 40 TO 495]

Write a C program using pointers to find biggest of given three numbers. void main() printf("X is biggest"); { else int *a,*b,*c,x,y,z; if (*b>*c) x=45; y=78; z=23; printf("Y is biggest"); a=&x; b=&y; c=&z; else clrscr(); printf("Z is biggest"); printf("X:%d, Y:%d, Z:%d\n",x,y,z); getch(); if (*a>*b && *a>*c) } What is the use of pointers? What is a pointer to an array and an array of pointers? A pointer is a variable, which contains the memory address of another variable. We can have a pointer to any variable type. The unary or monadic operator & gives the address of a variable. The indirection or dereference operator * gives the contents of an object pointed to by a pointer. To declare a pointer to a variable do: int *pointer; In C there is a very close connection between pointers and arrays. In fact they are more or less one and the same thing! Suppose Wwhen you declare an array as: int a[10]; you are in fact declaring a pointer a to the first element in the array. That is, a is exactly the same as &a[0]. The only difference between a and a pointer variable is that the array name is a constant pointer - you cannot change the location it points at. When you write an expression such as a[i] this is converted into a pointer expression that gives the value of the appropriate element. To be more precise, a[i] is exactly equivalent to *(a+i) i.e. the value pointed at by a + i . In the same way *(a+ 1) is the same as a[1] and so on. Arrays of Pointers are a data representation that will cope efficiently and conveniently with variable length text lines. This eliminates: complicated storage management. high overheads of moving lines. Q3. Write a program to swap two Q4. Write a C program using pointers Variables by using call by to count the number of characters reference. in a given string. Ans. Ans. void swap(int *a, int *b) void main() {int temp; { temp=*a; char str[20], *ptr; *a= *b; int i,cnt=0; *b = temp; clrscr(); } printf("Enter any string: "); void main( ) gets(str); { int a, b; ptr=&str[0]; printf(\nEnter first numbers); for (i=0;str[i]!=NULL;ii++++,ptr++z) scanf(%d,&a); { printf(\nEnter second numbers); if ((*ptr>='a' && *ptr<='z') || (*ptr>='A' && scanf(%d,&a); *ptr<='Z')) swap(&a,&b); cnt++;} printf(\nAfter swapping values are :%d ptr++;

Q2. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


45/56
%d,a,b); } Q5. Write a C program to sort the numbers by using pointers. printf("%d",cnt); getch(); } Q6. Write a program using pointers to check whether the given string is palindrome.

Ans. void main() { int a[5]={3,1,5,7,8}; int *p,i,j,t; p=a; clrscr(); for(i=0;i<4;i++) for(j=i+1;j<5;j++) if(*(p+i)>*(p+j)) { t=*(p+i); *(p+i)=*(p+j); *(p+j)=t; } for(i=0;i<5;i++) printf("\n %d",a[i]); getch(); }

Ans. void main() { char *a; int i,j,k; printf("enter string \n"); scanf("%s",a); int i=strlen(a); int k=--i; for(int j=0;j<k;j++) { if(a[i]!=a[j]) { printf("Not a Palindrome"); exit(0); } i--; } printf("String is Palindrome"); }

Q7. Ans.

What does function pointer mean? Give an example. The way functions return a data type, similarly, a function can return a pointer. To make this possible you had to declare the function as a pointer called function pointer. int *cube(int n) { { int *k; int r; clrscr(); r=n*n*n; k=cube(3); return &r; printf("Address of cube: %u",k); } printf("\nValue of cube : %d",*k); void main() getch(); } How does pointer arithmetic help a programmer? As you perforqm arithmetic operations using variables, the same can be done with pointers. They increase execution speed. Only two arithmetic operations can be performed on pointer that are increment and decrement. For Example: Void main() { char arr[]=University, *b; b=&arr; printf(B now points to %c,*b); b++; printf(\nNow b is pointing to %c,*b);

Q8. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


46/56
} here b is a pointer variable, which is pointing the first element of char array arr. The output thus is the first character of the array that is U. After b++ expression, Now b points to the next element of the array arr. So the output is now n and so on. Q9. Ans. What is the difference between static and dynamic memory allocation? Discuss the functions in C with which dynamic memory allocation is possible. Dynamic memory enables us to create data types and structures of any size and length to suit our programsthat is needed within the program. The Ffunction malloc() is most commonly used to attempt to grab a continuous portion of memory. It is defined by: void *malloc(size_t, number_of_bytes) malloc() takes the size of memory required to be allocated and allocates that much space from the free memory. If there is not enough memory to be allocated then the fn. returns NULL.That is to say it returns a pointer of type void * that is the start in memory of the reserved portion of size number_of_bytes. If memory cannot be allocated a NULL pointer is returned. There are two additional memory allocation functions, Calloc() and Realloc(). Their prototypes are given below: void *calloc(size_t num_elements, size_t element_size}; void *realloc( void *ptr, size_t new_size); Malloc does not initialize memory (to zero) in any way. If you wish to initialize memory then use calloc.Calloc is slightly more computationally expensive but, occasionally, more convenient than malloc. Create a structure named complex to model a complex number. Using this Structure, write separate functions for adding two complex numbers, subtracting a complex number from another, multiplying two complex number. #include<math.h> #include<stdio.h> #include<conio.h> #include<process.h> void addition(); void subtraction(); void multiplication(); struct complx { int a,b; } c1,c2; void main() { int choice; while(1) { clrscr(); puts("Enter the co-efficients of a+ib: "); scanf("%d %d",&c1.a,&c1.b); Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

Q.10 Ans.

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


47/56
puts("Enter the co-efficients of c+id: "); scanf("%d %d",&c2.a,&c2.b); puts("\n1.\tAddition\n2.\tSubtraction\n3.\tMultiplication\n4.\tExit"); puts("\nEnter your choice by a number(1-4): "); scanf("%d",&choice); switch(choice) { case 1: addition(); break; case 2: subtraction(); break; case 3: multiplication(); break; case 4: exit(0); } getch(); } } void addition() { int real=c1.a+c2.a,imag=c1.b+c2.b; printf("\n\nThe result is:\n(%d)+i(%d)i",real,imag); } void subtraction() { int real=c1.a-c2.a,imag=c1.b-c2.b; printf("\n\nThe result is:\n(%d)+i(%d)i",real,imag); } void multiplication() { int real=c1.a*c2.a + c1.b*c2.b*(-1) , imag=c1.b*c2.a + c1.a*c2.b; printf("\n\nThe result is:\n(%d)+i(%d)i",real,imag); } Q11. Ans. What do you mean by structure? How does a structure differ from an array? A structure is a user defined data type, which represents different types of data within a single group. When you need to store a large data items in one group you made the use of array. The disadvantage of arrays is that it is used to store data items, which are of similar data types. You may have to store different types of data say an int, a char, a float value or may be even an array all together in a group. This situation of string storing different data types in a single group can be done only by structure. Structures are the most common tools used to make these situations possible. Array store all its elements in continuous location but structure is not. Array void main( ) { int rollno[10],j; Structure Struct exp { int rollno;

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


48/56
for(j=0;j<=9;j++) { printf(Enter Roll no); scanf(%d,rollno[j]); } for(j=0;j<=9;j++) printf(Roll no= %d,rollno[j]); getch(); } char name[25]; }; void main() { struct exp obj; obj.rollno=10; obj.name=Ramandeep Singh; }

Q12.

Write a C program to determine a Q13. telephone number of specified customers.

Ans. #include<stdio.h> #include<conio.h> #include<string.h> int main() { struct cust { char name[20],tele[15]; } c[50]; int i=0,counter=0; char ch='y',Name[20]; clrscr(); while(ch=='y' || ch=='Y') { puts("Enter name: ");gets(c[i].name); puts("Enter Phone: ");gets(c[i++].tele); puts("Wanna enter more record(y/n): "); fflush(stdin);ch=getch(); } getch(); ch='y'; while(ch=='y' || ch=='Y') { counter=i-1; i=0; clrscr(); puts("Enter customer name: ");gets(Name); while(i<counter) { if(strcmpi(Name,c[i].name)==0) { printf("\n\n%s %s",c[i].name,c[i].tele); break; } i++;

Write a program to accept the record of 5 employees with their names, age and addresses and also display them. Use structures to implement the program.

Ans. struct personal_info { char name[20], address[20]; int age; }; void main() { struct personal_info pi[5]; int I; for(I=0;I<5;I++) { printf(enter the name:); fflush(stdin); gets(pi[I].name); printf(enter the address:); fflush(stdin); gets(pi[I].address); printf(Enter the age:); scanf(%d,&pi[I].age); } for(I=0;I<5;I++) { printf(\n\nName :) puts(pi[I].name); printf(\n\nAddress :); puts(pi[I].address); printf(\n\nAge:); printf(%d,pi[I].age); } }

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


49/56
} if(i==counter) { printf("\n\nMatch not found..."); } puts("Wanna enter more record(y/n): "); fflush(stdin);ch=getch(); } getch(); return 1; } Q14. Consider the following structure for an employee: Write a program in C that reads name,code and basic pay for 20 employees and calculate the netpay as equal to [ basic pay+HRA (15% of basic pay) + DA (53% of basic pay)]. Then it also prints the data of all the employees. # include <stdio.h> void main() { struct employee { char name [20]; int code,hra,da; int basicpay,netpay; }; struct employee e1[20]; int i; clrscr(); for (i=1;i<=20;i++) { printf ("\n Enter name of employe"); gets (e1[i].name); printf ("\n Enter code of employee"); scanf("%d",&e1[i].code); printf ("\n Enter basic pay of employee"); scanf("%d",&e1[i].basicpay); e1[i].hra=e1[i].basicpay*15/100; e1[i].da=e1[i].basicpay*53/100; e1[i].netpay=e1[i].basicpay+e1[i].hra+e1[i] .da; fflush(stdin); } for (i=1;i<=20;i++) { printf ("\n Name of employe %s",e1[i].name); printf ("\n Code of employee %d",e1[i].code); printf ("\n Basic pay of employe %d",e1[i].basicpay); printf ("\n HRA of employe %d",e1[i].hra); printf ("\n DA of employe %d",e1[i].da); printf ("\n Net pay of employe %d",e1[i].netpay); } }

Ans.

Q15. Ans.

Write a C program to define a structure with data members registeration number, student name and total marks obtained. Declare a structure pointer to read and display the value of the data members using it. #include <stdio.h> #include <conio.h> struct report { int regno,tmarks; char name[20]; }; scanf("%d",&rpt->regno); printf("Enter student name: "); fflush(stdin); gets(rpt->name); printf("Enter total marks: "); scanf("%d",&rpt->tmarks); printf("Output\n"); printf("\nRegistrationNo.:%d",rpt->regno);

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


50/56
void main() { struct report data,*rpt; clrscr(); printf("Enter register number: "); Q16. Write a program in C language to create a data file. printf("\nStudent Name : %s",rpt->name); printf("\nTotal Marks : %d",rpt>tmarks); getch(); } Q17. Write a c program to create a unformatted file.

Ans. void main() { FILE *f1; Char c; printf(data input\n); F1=fopen(input,w); while((c=getchar())!=EOF) putc(c,f1); fclose(f1); printf(\n\ndata output\n\n); F1=fopen(input,r); While((c=getc(f1))!=EOF) printf(%c,c); fclose(f1);

Ans. void main() { char ch; FILE *fp; fp=fopen("myfile.txt","w"); clrscr(); printf("\ntype the text and press x to end.\n\n"); while((ch=getchar())!='x') putc(ch,fp); fclose(fp); }

}
Q18. Ans. Explain with examples the various file handling functions. Files are permanent storage medium of information so that they can be accessed and altered whenever needed. There are some function examples to handle the files. 1. fopen(): To create, process, read or write a file, the first step we require is to open a file. For opening a files a function fopen() is used. For Example: FILE *fp; Fpfp=fopen(filename,mode); 2. fclose(): We have the function fclose() for closing the file. This function closes the existing opened file. For Example: Fclosefclose(fp); 3. getc(): This functions is used to reads character by character from the file. It return an end-of-file (EOF) marker when the end of the file has been reached ior or if there is any error. For Example: Char c; Cc=fgetc(fp); 4. putc(): It is used to write character by character to the file opened. For example: Char c=$; Putcputc(c,fp); 5. fgets(): This function, reads the character from the file pointer into the character array until a newline character is read, or end-of-file is reached. It then appends the terminating null character after the last character reads and returns string if end-of-file occurs before reading any character, and error occurs during input fgets() returns NULL.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


51/56
For Example: Char *fgets(char *s, int n, FILE *fp)

6. fputs(): this function writes to the file pointer except the terminating null character
of string. It returns end-of-file if an error occurs during the output otherwise it returns a non-negative value. For Example: Fputsfputs(const char *s, FILE *fp) 7. fprintf(): this function gives the output on file which the file pointer is pointing to string represents the variable whose values are to be printed. For example: Fprintffprintf(fp, format, variables)

8. fscanf(): This function reads from the file to which the file pointer is pointing. It
returns the values that has been read. For example: Fscanffscanf(fp, format, variables) 9. fread(): This function reads data into an array up to Nitems data items each of size size from the file pointer. If there is an error in reading the file, it return endof-file the number of characters successfully read advances the file position indicator. For example Freadfread(p, size, Nitems, fp) 10. fwrite(): This function appends at the most Nitems item each of the size size in the file of which the file pointer points to, from the array to which the pointer points to. The functions returns the number of items if written successfully, otherwise, returns end-of-file if an error is encountered. For example Fwrite(p, size, Nitems, fp) Q19. Write a C program to create an unformatted master file. Q20. of a Write a program to copy contents

Ans. file to another. #include<stdio.h> Ans. #include<conio.h> #include<stdio.h> #include<process.h> #include<conio.h> int main() #include<process.h> {FILE *fptr; int main() char ch; {FILE *fptr,*fptr1; clrscr(); char ch; fptr=fopen("datafile.txt","w"); clrscr(); if(fptr==NULL) fptr=fopen("datafile.txt","r"); { fptr1=fopen("file.txt","w"); puts ("Error in opening file...\nPress any key if(fptr==NULL) to { break..."); puts ("Error in opening file...\nPress any key getch(); to exit(0); break..."); } getch(); while(ch!='\r') exit(0); Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


52/56
{ fflush(stdin); ch=getche(); fputc(ch,fptr); } fclose(fptr); getch(); return 1; } } while(ch!=NULL) { fflush(stdin); ch=fgetc(fptr); fputc(ch,fptr1); } fclose(fptr);fclose(fptr1); getch(); return 1; }

Q21. Ans.

What are a buffer and error file handler? Buffer: A storage area for data that is used to compensate for a speed difference, when transferring data from one device to another. Usually refers to an area reserved for I/O operations, into which data is read, or from which data is written. It is a storage device, or area on a storage device, which holds data temporarily, until needed for processing or printing. A buffer can also be used to aid communication between two devices with very different processing speeds (such as two modems, or the CPU and the printer). Error File Handler: It is possible that an error may occur during I/O operations on a file. Typical error situations include. 1. 2. 3. 4. Trying to read beyond the end-of-file mark. Device overflow. Trying to use a file that has been opened. Trying to perform an operation on a file, when the file is opened for another type of operation. 5. Opening a file with an invalid filename. 6. Attempting to write to a write-protected file. If we fail to check such read and write errors, a program may behave abnormally when an error occurs. An unchecked error may result in a premature termination of the program or incorrect output. Fortunately, we have two status-inquiry library functions, feof() and ferror() that can help us detect I/O errors in the files. What are command line arguments? Explain them using appropriate example. It is often useful to give program arguments when it is running. This is done with command line arguments, which are arguments of main(). There are two arguments: an integer, argc, which is the number of items in the command line (including the program name), and an array of strings, *argv[], which are the actual items. The first string, argv[0], is the name of the function being executed. If a number is needed, it has to be obtained using sscanf(), which is the same as scanf() except it takes a string as its first argument. This example prints the square root of a number. main(int argc, char *argv[]) /** program to find sqrt(x) **/ { float x; if (argc == 2) { sscanf(argv[1], "%f", &x); printf("the square root of %f is %f\n", x, sqrt(x)); } else

Q22. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


53/56
{ printf("Wrong number of arguments\n"); printf("usage: %s x \n", *argv); Q23. Ans. # include <stdio.h> void main() { FILE *fp; Char ch; int nol=0,not=0,nos=0,noc=0; fp=fopen(pr1.c,r); While (1) { ch=fgetc(fp); if (ch==EOF) break; noc++; if ( ch== ) { nob++; if (ch==\n) nol++; if (ch==\t) not++; }fclose(fp); printf (\n Number of characters = %d,noc); printf (\n Number of blanks = %d,nob); printf (\n Number of tabs = %d,not); printf (\n Number of lines = %d,nol); } } } Write a program to read a file and counts chars, spaces, tabs and new lines in a file.

OTHER IMPORTANT SHORT NOTES QUESTIONS [ PAGE 495-48 51 ]


Q1. Ans. What are the different stages of program development? Creation Compilation Linking Loading Testing Documentation. What is 3GL? All the 3GLs languages are procedure-oriented languages. This language is oriented more towards the problem solution rather then the procedure for solution.It supports structured programming. It includes programming languages designed to be easier for a human to understand. Ex: BASIC, ALGOL, Java What is 4GL? 4GL stands for fourth generation language. These languages are non-procedural, as the user doesnt define the detailed procedure to arrive at the result. It includes the programming languages and environment designed with a specific purpose in mind. This generation languages have the improvement over 3rd generation languages. Some of the 4GLs are dBase, FoxPro etc. Differentiate between ++I and I++. ++I is a pre-increment operator. (It first increments the value and then that value is used in the expression) I++ is a post-increment operator. (It first uses the value and then increments its value) void main() void main()

Q2. Ans.

Q3. Ans.

Q4. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


54/56
{ int a=5; b=a++; printf(a=%d b=%d,a,b) } OutPut: a=6 b=5 Q5. Ans. { int a=5; b=++a; printf(a=%d b=%d,a,b) } OutPut; a=6 b=6

Q6. Ans.

What is the difference between a compiler and an interpreter? Compiler and interpreter both are used to convert the high-level language program into the object source code. But Interpreter:- Interprets the program in line by line Compiler: - Compiles the whole program at a time. What do you mean by keywords? Give some examples. Keywords are the reserved words with some specified function. We cannot use keywords as variable names. In C there are 32 keywords For example if we declare variable like this. C display errors int float; int if; int printf; Error: Too many types of declaration Error: Declaration terminated incorrectly Error: Call of non-function

Q7. Ans.

Explain the difference between if-else and switch. Advantages of switch over if-else: 1. Switch statement reduces the complexity of the problem Dealt dealt with. 2. User can verify various cases depending upon The the nature of the problem. Cases can include check for Specific specific values, in between values etc.
3. The if-else statement could become more complex while dealing with

larger Number number of conditions. Advantages of if-else over switch: 1. In switch, we can check only for equal values not for in-between values. But it is not in case of if-else. 2. In switch, we cant check for floating values, but in if-else we can check for any type of value. Q8. What is the role of goto? Ans. The goto statement is used to alter the normal sequence of program execution by transferring the control to some of the defined level in the program. Or we can say goto statement is used along with a label. when When the it falls to the line containing the goto statement , it jumps automatically to the same corresponding label.

Program Example Vvoid main( ) { int I,f=1; Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


55/56
printf(enter a positive number); scanf(%d,&I); start: { f=f*I ; I--; } if(I>0) goto start; printf( factorial = %d,f); } What is the role of preprocessor directives? To instruct the compiler that we are using a library defined function we specify the header file containing the prototype for the function related to their input or output. These header file are included into your source code using # symbol and known as preprocessors directives. They make the compiler to include the contents of specified file. Using preprocessor we can also specify the macros. They commonly useable preprocessors are #include and #define. In what way an array differ from an ordinary variable. Variable is the memory location where we can store a single value at a time, where as in an array we can store multiple values at the same time. Array needs contiguous memory locations and it can only store same type of data. While declaring array we have to use subscript number with the array declaration for example int a[5] where as ordinary variables are declare without the subscript for example int a. Arrays are useful when we want to store large amount to data on contiguous locations. Different element of an array can be accessed with help of index number. If we want to store 100 numbers then we have to use hundred ordinary variables which becomes tedious for the programmers to declare hundred ordinary variables and to remember their names, with the help of arrays we can store these hundred numbers with in a single variable name and can access then with help of their different index number. What is meant by the address of a memory cell? How are addresses usually numbered? Whenever a variable is declared it is allocated memory and every variable is referred by an address. For example scanf(%d, &a); In this statement we can easily know that a data to be input in the variable named a which would be an integer value. It is necessary to give ampersand sign (&) in scanf() for input, this sign provides the address of the variable in memory. The address is provided in the unsigned integer and highest memory address is allocated to the first declared variable, then the address for another variables is allocated from the remaining memory address. Q12. Ans. Write note on string handling. A string is an array of characters. Any group of characters defined between double quotation marks is a constant string. For Example: My name is Dennis Ritchie

Q9. Ans.

Q10. Ans.

Q11. Ans.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

SUBJECT: C LANGUAGE (PGDCA/MSC/BSC- 1 )


56/56
If we want to include a double quite quote in the string, then we may use it with a backslash as shown below My Name is \Dennis Ritchie\ Character strings are often used to build meaningful and readable programs. The common operating operations performed on character strings are: Reading and writing strings. Combining strings together. Copying one string to another. Comparing strings for equality. Extracting a portion of a string.

Q13. Ans.

Explain the scope of storage classes. Available storage classes for variables are Automatic: declared when entering the block, lost upon leaving the block; the declarations must be the first thing after the opening brace of the block Static: the variable is kept through the execution of the program, but it can only be accessed by that block Extern: available to all functions in the file AFTER the declaration; use extern to make the variable accessible in other files Register: automatic variable which is kept in fast memory; actual rules are machine-dependent, and compilers can often be more efficient in choosing which variables to use as registers. The scope of an object can be local to a function or block, local to a file, or completely global. Local to a function/block: automatic or static variables, which can only be used within that function/block. Function parameters (arguments) are local to that function. Global (local to a file): static variables declared outside all functions, accessible to any functions following the declaration External (accessible in several files): declared as extern, accessible to functions in that file following the declaration, even if the variable is defined in another file.

Prepared By:- Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala. Ph. 0175-2205100, 2215100

You might also like