c programming q & a

31
Department of MCA, BSIT Questions and Answers Brainware Group of Institutions Computer Programing with C - MCA 103 Dear students, Here are the Questions and Answers of Programing in C - MCA 103. Hard copy of it is available in Library. The important Questions and Answers are marked by ** , based on there occurrence in previous WBUT semester exam. [email protected] [email protected] 1

Upload: imranul-mazumder

Post on 30-Mar-2016

257 views

Category:

Documents


0 download

DESCRIPTION

C critical Q and A by faculty of Brainware School of IT

TRANSCRIPT

Page 1: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

Dear students,Here are the Questions and Answers of Programing in C - MCA 103. Hard copy of it is available in Library. The important Questions and Answers are marked by ** , based on there occurrence in previous WBUT semester exam.

[email protected] [email protected] 1

Page 2: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

:: SHORT TYPE :: Q. What are the applications of C programming?Though C is a general-purpose programming language, it has got some special area of work now :· Device Driver / controller development programming· Network / Socket programming· Mobile Application Development· Cryptographic programming

**Q. What is complexity of an Algorithm?An algorithm is a method for solving a class of problems on a computer and the Complexity of an algorithm is the cost, measured in running time, or storage, or whatever units are relevant, of using the algorithm to solve one of those problems. It is a relative term in comparison with other algorithms. Complexity is of two types :· Time Complexity(number of steps that it takes to solve an instance of the problem as a function of the size of the input (usually measured in bits))· Space Complexity(is a related concept, that measures the amount of space, or memory required by the algorithm.)

**Q. With suitable example differentiate between a++ and ++a.a++ is the post-increment operator whereas ++a is the pre-increment operator. They behave differently when they are used in expressions on the right-hand side of an assignment statement as follows:a = 5;b = ++a; // a=6, b=6.Again,a = 5;b = a++; // a=6, b=5.A pre-increment operator first adds 1 to the operand and then the result is assigned to the variable on left. On the other hand, a postfix operator first assigns the value to the variable on the left and then increments theoperand.

Q. What are the naming rules of an identifier?C identifiers enforce the foll owng rules:· They can have alphabets, digits and underscore characters.· They must not begin with a digit.· Uppercase and lowercase letters are distinct.· Keywords cannot be used as identifiers.**Q. What is the difference between ‘a’ and “a”?

[email protected] [email protected] 2

Page 3: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

‘ a’ denotes a character constant whereas “a” denotes a string constant.In C any character enclosed within single inverted commas indicates a character constant. The maximum length of a character constant can be 1 character.Ex. ‘a’, ‘R’, ‘5’, ‘=’.On the other hand, we can enclose any no of characters including blank spaces within double quotes.Ex. “a”, “123”, “C is a programming language”.

Q. What is an unsigned integer constant? What is the significance of declaring a constant unsigned integer?If we declare a variable as unsigned integer constant the range of permissible integer values (for a 16-bit OS) will shift from the range –32768 to +32767 to the range 0 to 65535. Declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise take. So if we know in advance that the value stored in a given integer variable will always be positive we can declare the variable to be unsigned as unsigned int <variable_name>;

**Q. What is implicit and explicit data type conversion in ‘C’?Implicit type conversion : Conversion from lower data type to higher data type is done automatically. This is known as implicit data type conversion, also known as Coercion. It is an automatic type conversion by the compiler. float type data automatically gets converted into double. char and short type data automatically gets converted into int. In a mixed-type expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal C language code:E.g.double d;long l;int i;if(d > i) d = i;if(i > l) l = i;if(d == l) d *= 2;

Explicit type conversion : Here, the RHS data is converted to LHS data by explicit cast operation.E.g.here 2 double variables are first cast into int & then added up.double da = 5.5;double db = 5.5;int result = static_cast<int>(da) + static_cast<int>(db);//Result would be equal 10 and not 11

[email protected] [email protected] 3

Page 4: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

**Q. Explain the difference between L-value and R-value.An Lvalue is an object locator, an expression that designates an object. Historically, ‘L’ stood for “left”, meaning that an lvalue could legally stand on the left (the receiving end) of an assignment statement. Now only modifiable lvalues can legally stand on the left of an assignment statement. On the other hand, R-value goes to the right of the assignment operator.

Q. What do you understand by the term coercion?Conversion from lower data type to higher data type is done automatically. This is known as implicit data type conversion, also known as Coercion. It is an automatic type conversion by the compiler. float type data automatically gets converted into double. char and short type data automatically gets converted into int. In a mixed-type expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal C language code:E.g.double d;long l;int i;if(d > i) d = i;if(i > l) l= i;if(d == l) d*= 2;

Q. What are the three conversion specifications used to read char type data?char ch;1) scanf(“%c”,&ch);2) scanf(“%s”,ch);3) scanf(“%d”,&ch);

**Q. What is the significance of ‘\v’ and ‘\b’ escape sequences? Give example.\v is to print a Vertical Tab : printf(“\v”);\b is to print a backspace : printf(“\b”);

Q. How will you convert the value of a character into ASCII?Here is the code for conversion :void main(){char ch;printf(“\nEnter a character : “);scanf(“%c”,&ch); //read the character valueprintf(“ASCII is : %d”,ch); //print the value as integer

[email protected] [email protected] 4

Page 5: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

**Q. Differentiate between “while” and “do-while” loop

Q. Write briefly the areas of application of for statement.For loop :· can be used as an entry-controlled loop· can be used as an infinite loop(used deliberately with a conditional break)· more structured looking as far as syntax is concerned· can be used to substitute a recursive task

**Q. Write short notes on empty loop.The loop that has no body is called an empty loop. Such as, in case of while loop an empty loop can be constructed as follows:while(condition);Also, in for statement, for(n=1;n<10000;n++);Empty loop can be used as a time delay loop, for example:x=1;while(x++<10000);

Q. How can time delay loop be written in C? Give examples.A time delay loop can be written using empty loop, which is a loop that doesn’t contain even a single statement in the loop body, but with a high value as condition to be false.for(n=1;n<10000;n++);However, it is totally dependent on the machine clock speed hence not a good way to apply delays.Secondly,We can use some library function like delay() or sleep() to make some useful held-up of a program for some seconds/milliseconds passed as argument to the function.

**Q. What are the limitations of an ordinary variable? How are these removed with the use of an array?

[email protected] [email protected] 5

Page 6: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

1) For each variable we can store a single value in it.e.g.int a;If we have to store a larger collection of similar types of values, say of hundred in number, declaring that many number of variables will be too tedious, so here we have to use an array.e.g.int a1, a2, ….. ,a100; //this is too longalternatively,int a[100];2) In case of normal variable, all the variables are not ideally located at contiguous memory locations but on the other hand in case of an array all the data of array will be placed at the contiguously in the memory.3) In normal variables, keeping track of each & individual variable within a long list of variables is a difficult job : programmers has to keep in mind the purpose of each variable. On the other hand in case of an array this need not be cared of since the array index itself is the single point of access to an array(array-name) and an array is formed comprising of several values ideally to serve a common purpose.

Q. Explain the significance of subscript in an array.An array is a collection of similar type of variables under a common name. Now, in order to refer each value of the variables we have to use some kind of index which is known as a subscript of an array. Depending on the value of the subscript we can locate a specific variable of the array & can make use of it.E.g.int arr[10];int i=4;scanf(“%d”, &arr[i]); //read the 5thvariableprintf(“%d”, arr[i]); //print the 5thvariableHere i is the subscript of the array.However, this can be written in another syntax too :scanf(“%d”, (arr+i)); //read the 5th variableprintf(“%d”, *(arr+i)); //print the 5th variable

Q. What are static initialization and dynamic initialization of array?In static initialization of array, the array elements are initialized when they are declared. The general form of initialization of array is:type <array_name>[size] = {list of values};Example: int number[3] = {12, 345, 1};

[email protected] [email protected] 6

Page 7: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

char name[10] = { ‘J’, ’o’, ’h’, ’n’, ’\0’ };On the other hand in dynamic initialization of array, the array elements are explicitly initialized at run time.Example:int x[10];for( j=0; j<10; j++)

scanf(“%d”,&x[j]);

**Q. What are the difference between strlen() and sizeof()?

Q. What is the role played by atoi() in string manipulation? Give examples.It is a macro that converts a string to integer. It’s declared in the header file : “stdlib.h “Declaration:int atoi(const char *s);Remarks:atoi() converts a string pointed to by s to int.Example:#include <stdlib.h>#include <stdio.h>void main(){ int n;char *str = “12345.67”;n = atoi(str);printf(“string = %s integer = %d\n”, str, n);}Output :string = 12345.67 integer = 12345

**Q. What will be the output of the following C segment : main(){

[email protected] [email protected] 7

Page 8: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

char str[] = “CAUTION”char *p;p=str+5;printf(“%c\n”, *p--);printf(“%c”, *p);}The output will be as follows :'O''I'Q. Can we pass function to other functions? If yes, how?Yes, we can pass a function to another function as argument of it. Here’s the example ://Function pointer program...void young(int);void old(int);//prototype of function in which function pointer is passed as an argumentvoid greeting(void (*)(int), int);int main(void){

int age;printf(“How old are you? “);scanf(“%d”, &age);if(age > 30){

greeting(old, age); //call of the outer function}else{

greeting(young, age); //call of the outer function}return 0;

} //definition of the outer functionvoid greeting(void (*fp)(int), int k){

fp(k);}//inner function definitionvoid young(int n){

printf(“Being only %d, you sure are young.\n”, n);}

[email protected] [email protected] 8

Page 9: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

//inner function definitionvoid old(int m){

printf(“Being already %d, you sure are old.\n”, m);}

**Q. What is the role of library function?In writing a program we need library functions such as printf(), scanf() etc. that perform fundamental operations in a computer, such as getting input from the user, printing output to the screen etc. These library functions have been already designed, coded and tested so that we may use them in creating our own functions. To make programming platform independent the compiler designers have included libraries of such primitive functions. We can use these functions in our programs without bothering as to how they are implemented on a particular platform.

**Q. Is prototyping mandatory in C? Justify your answer.Yes. Prototyping is mandatory in C.Either for User-defined or Library functions prototyping is must. It is basically the declaration or signature of the function. For library functions, prototyping is implicitly done when we include the respective header file.E.g.a) User-defined functions :int add(int, int); //Prototype of function add()int add(3, 5); //Callb) Library functions :#include<stdio.h> //Prototype for printf() is implicitly included in the codeprintf(“\nHello”); //Call

**Q. What do you mean by call by value and call by reference?In call by value, only the values of the variables are passed to the called function. So any changes made to the called function does not effect in the calling function. On the other hand, in call by reference the address of the variables are passed. So if we make any change in the called function, that changes also reflect in the calling function.

**Q. What are the conditions to perform recursion?In order to solve a problem recursively, two conditions must be satisfied:

1. The problem must be written in recursive form.2. The problem statement must include a stopping condition.

Q. What are the advantages of user-defined functions?Advantages of user-defined function :

[email protected] [email protected] 9

Page 10: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

· Writing functions prevents rewriting the same code over and over.· By using functions it becomes easier to write programs and keep track of what they are doing· Debugging / Modification / Maintenance becomes easier.· Code abstraction is implemented.· Top Down approach is realized.

**Q. What are the advantages and disadvantages of recursion?The main disadvantage is : often the algorithm may require large amounts of memory if the depth of the recursion is very large. Complexity increases with the usage of system stack, both Time and Space-wise, than a iterative version of the same task.On the other hand as advantage, it has been claimed that recursive algorithms are visibly simple, easier to understand because the code is shorter and is closer to a mathematical definition.

Q. Why the parameters given within a function prototype are called “dummy” parameters?At the time of call & definition of a function, the actual & formal parameters are mentioned respectively. Whereas during the declaration / prototyping of a user-defined function, only the data-types of the arguments are mentioned, not the actual data. Therefore, these parameters are called “dummy” parameters.

Q. Differentiate between a function prototype and function definition.Function prototype: Function prototype is the declaration of the function which consists of the· Function name· Number of arguments & their types· Return typeE.g. int add(int, int);Function definition : Function definition consists of :· Body / code-details of the function followed by :· Function name· Formal parameters to the function· Return typeE.g. int add(int x, int y){ return x+y;}

**Q. What are the different storage classes available in C.1) Automatic: autostorage is automatically allocated on function/block entry and automatically freed when the

[email protected] [email protected] 10

Page 11: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

function/block is exited.2) Optimization Hint: registerregister provides a hint to the compiler that you think a variable will be frequently used.3) Static Storage: staticif used inside a block or function, the compiler will create space for the variable which lasts for the life of the program.4) External References: externIf a variable is declared (with global scope) in one file but referenced in another, the extern keyword is used to inform the compiler of the variable’s existence.

Q. What do you understand by #define?The #define statement is a precompiler directive: it changes the source code before it’s compiled. In a #define directive, the string following the word #define, up to the first blank, is replaced by the model statement that follows, if any. In practice, #defines are used for simple text substitution, as macros, or as input to conditional compiler directives. Each #define will stay in effect until a matching #undef statement or the end of the program. It’s considered good style to use all UPPERCASE for a #define.E.g.#define TRUE 1#define FALSE 0#define TABLESIZE 100

**Q. What are the differences between structure and union?

Q. In what all situations structures are preferred?Ordinary variables can hold one piece of information and arrays can hold a number of pieces of information of same data type. But quite often we deal with entities that are collection of dissimilar data types. For example, if we want to store data about a book which contains its name (a string), its price (a float) and In such situations if we construct individual arrays the program becomes difficult. So the convenient way is to declare a structure variable, which can contain dissimilar data types like,struct book

[email protected] [email protected] 11

Page 12: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

{char name;float price;int pages;

};

Q. What are self-referential structures?Lists contain a reference variable of the type itself as a member. For this reason, these data structures are frequently called ‘self-referential’ or ‘recursive’ data structures. The simplest type of self-referential list structure is a sequence of elements. Each element contains some data, and a reference, often called a pointer, to the next element in the list. We can do it as shown in the following example which will allow us to create an arbitrarily long list of integer values.struct list{

int data;struct list *next; //self-referential

};

Q. What are the restrictions on processing of enumerated data type?· Enumerated data types are used with fixed set of enumerators. Once defined, this number can not be changed.· Enumerators can be overridden by other values if defined so, but can not be used to hold floating point values or string values.

Q. In what sense a structure can be recursive.A structure can be recursive if it is a self-referential structure, that means: a structure having a pointer member referring to a structure of same type.E.g.struct list{

int data;struct list *next; //self-referential

};

Q. What are the difficulties of processing a union?In case of a union, we cannot ideally use all the data members of it at the same time since they share the same memory space in case of a union. In fact, the size of the largest data member of the union forms the size of it.

**Q. How can we pass pointers to a function?

[email protected] [email protected] 12

Page 13: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

Passing pointers to a function means actually passing the address of a variable to the function. The process is called “call by reference”.main(){

int *x = 20;change(x);printf(“%d\n”, x);

}change(int *p){

*p = *p + 10;}Here, the address of ‘x’ has been passed to the called function change() which receives theaddress as pointer variable *p.

**Q. Differentiate between pointer to a variable and pointer to a pointer.A pointer to a variable keeps the address of that variable.Ex. int a, *p;Here p is a pointer to the variable a, that is p keeps the address of a. On the other hand, pointer to a pointer means a pointer, which keeps the address of another pointer type variable.Ex. int a, *p, **p1;Here, p1 is a pointer to the pointer p, that is p1 keeps the address of p which itself is a pointerto the variable a. Q. List the applications of pointers in C.· Call a function where arguments are passed by address· Self-referential structure implementation (Linked list)· Dynamic memory allocation· Used to directly manipulate memory or memory-mapped devices.

Q. Under what condition a pointer variable can point to another pointer variable?A pointer variable can point to another pointer variable when Left Hand Side pointer variable of the assignment is a pointer to pointer of similar data type.E.g.int p1,*p2,**p3;p1 = 100; p2 = &p1;now we can assign the address of p1 which is itself a pointer variable to p3.p3 = &p2;

Q. What are the advantages of data file over other data types?

[email protected] [email protected] 13

Page 14: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

Advantages :1) Data file provides repository of several data items, whereas Data type defines the domain or range forvalues of Data.2) A Data file can hold data of several Data types but the reverse is NOT possible.

**Q. What is the significance of the constant EOF in a C program?EOF is a constant, which indicates that end of file has been reached. This is inserted beyond the last character in the file. The reading should be terminated when EOF is encountered. EOF is very important in testing the end-of-file condition. Any attempt to read past the end of file might either cause the program to terminate with an error or result in an infinite loop.

[email protected] [email protected] 14

Page 15: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

:: LONG TYPE :: **Q. ‘C is a middle level language’, comment on this statement.High Level language:A high-level programming language is a programming language that is more user-friendly, to some extent platform-independent, and abstract from low-level computer processor operations such as memory accesses.Low Level Language:A low-level programming language is a programming language that is more machine specific, and for using any resource of the Computer (such as any computer processor operations such as memory accesses) is directly dependent on the language code.Features of C:It’s a middle level language because it includes some high end tasks like code abstraction and enforcement and checking of data types, and some low level functions like ‘embedded’ use of assembly language and direct output to ports or use of registers. That is why it has become so popular in programming 1) graphics applications or 2) embedded systems. While it does not always require direct knowledge of the hardware you are working on, it helps provide a direct and achievable path for using or even obtaining that knowledge, if wereally need it. C is a high level language because the syntax of loop controls, constructs looks like common language (English-like) we used to communicate. For example if-else, for etc. But no doubt the C-language is mainly used as system programming because of its flexibility viz pointers, case syntax, less confusion. Though it is a high level language, but it is also very near to low level programming. C is high level since it will give us all the features such as portability, documentabity etc.

Q. Differentiate between algorithm and flowchart.An algorithm is a logical and concise list of steps required to solve a problem. An algorithmis composed of a finite set of steps, each of which may require one or more operations. Thefollowing example would explain algorithm more effectively.Example: Calculate and print the sum of two numbers.Step 1: StartStep 2: Read the two number say A & BStep 3: Add A & B and store it in CStep 4: Print CStep 5: Stop.On the other hand, a flowchart is a pictorial representation of step-by-step solution of aprogram. It is a good method of writing down the algorithm.Example: a flowchart to find the sum of two numbers.

[email protected] [email protected] 15

Page 16: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

**Q. Discuss the various operators available in C with the help of example.C operators can be classified into a number of categories. They include:

1. Arithmetic operators2. Relational operators3. Logical operators4. Assignment operators5. Increment and decrement operators6. Conditional operators7. Bitwise operators8. Special operators

1. Arithmetic operators: These operators work on numeric type of operands. There are five arithmetic operators in C. Namely +, -, *, /, %.2. Relational operators: These operators are used to compare two operands to see whether they are equal to each other, unequal, or one is greater or less than the other. While the operands can be variables, constants or expressions, the result is always a numeric value equivalent to either true or false. C language provides six relational operators. Viz. = =, !=, >, <, >=, <=.3. Logical operators: Logical operators are used to combine two or more relational

[email protected] [email protected] 16

Page 17: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

expression. C provides three logical operators. Namely &&, ||, !. 4. Assignment operators: These operators are used to store the result of an expression to a variable. The most commonly used assignment operator is (=).Ex. int a = 5;char ch = ‘x’;5. Increment and decrement operators: The increment operator (++) adds one to the current value of the operand and stores the result back into the operand. The decrement operator (—) subtracts one from the operand and stores the decremented value back into the operand.6. Conditional operators: C provides a ternary operator called conditional operator, represented by :? . The syntax of this operator is: A? B: C. Here A is a conditional expression resulting either true or false. If the value A is true, then expression evaluates to B, otherwise C.7. Bitwise operators : These operators are used for testing the bits, or shifting them right or left. These operators are applicable to integer data types only.8. Special operators : C language provides some special operators. These include comma operator, sizeof operator, pointer operators (& and *) and member selection operators (. and ->) .

Q. What are constants? Discuss their types with examples.Constants are fixed values that remain unchanged during the execution of a program and areused in assignment statements.The declaration for a constant in C language takes the following form:Const <data_type> <variable_name> = <value>Ex. Const float pi = 22/7;C language facilitates five different types of constants.

1. Integer2. Character3. Real4. String5. Logical

1. Integer Constant: An integer constant refers to a sequence of digits and has a numeric value. There are three types of integers in C language, decimal, octal, hexadecimal.Ex: Decimal Integers : 1, 56, 7657, -34 etc.Octal integers : 076, -076, 05 etc.Hexadecimal Integers : 0x56, -0x5D etc.2. Character Constant: A character constant consists of a single character, single digit, or a single special symbol enclosed within a pair of single inverted commas. The maximum length of a character constant is one character.Ex: ‘a’, ‘B’, ‘7’, ‘*’ etc.3. Real or Floating point Constant: A number with a decimal point and an optional preceding sign represents a real constant.

[email protected] [email protected] 17

Page 18: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

Ex: 34.8, -655.33, .2, -56.7, 7. etc.4. String Constant: A string constant is a sequence of one or more characters enclosed within a pair of double quotes (“”).Ex: “a”, “123”, “Welcome to C programming” etc.5. Logical Constant: A logical constant can have either true value or false value. In C, a non-zero value is treated as true while 0 as false.

Q. How comments in C program are given? Explain with an example. What is the purpose of comments?The lines beginning with /* and /* are known as comment lines. Comment lines are not executable statements and therefore anything between /* and /* is ignored by the compiler. In general, a comment can be inserted wherever blank space can occur- at the beginning, middle or end of a line, but never in the middle of a word.Example: main(){ /*……………printing begins…………*/printf(“Hello World”);/*……………printing ends……………*/}Comments cannot be nested. So/*—————/*———————*/——————*/ is not valid and therefore results in an error. A comment can be split over more than one line, as in,/* This isa jazzycomment*/. Such a comment is often called a multi-line comment.Purpose of comments:a) Comments are used in a program to enhance its readability and understanding.b) Comments help the programmers and other users in understanding the various functions and operations of a program and serve as an aid to debugging and testing. **Q. Explain briefly various character input/output functions with examples.The functions that program input/output of one character at a time are known as character I/O functions. Followings are the various character input functions:

1. getchar()2. getch()3. getche()

and the various character output functions are:1. putchar()2. putch()

getchar() & putchar(): getchar() function is used for reading a character from the keyboard.Ex. ch = getchar();This statement reads a character and stores it in variable ch of type char.

[email protected] [email protected] 18

Page 19: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

putchar() is the complementary function of getchar(). It is used to display a character on themonitor. The following statement displays a character value on the monitor whatever is stored inside ch at the current position.putchar(ch);getch() & putch() : getch() is used to accept a character from the keyboard and putch() isused to print a character on the monitor.The advantage of using getch() function is that neither the user is required to press enter keyafter typing a character nor the typed character is echoed to the monitor.getche(): We can also use getche() for receiving a character from the keyboard. The getche()is basically: getch() + e Here, the letter ‘e’ stands for echoes. Accordingly, it doesn’t wait for the enter key to be typed and also echo the typed character to the monitor.

**Q. Explain the difference between break and continue statements with example.The break statement is used to skip the particular part of program code. It can be used in switch case and also in various loops such as while, do, for. In case of loop, break statement is used to terminate the loop.On the other hand, continue statement can be used only in the loops. It causes the loop to be continued with the next iteration after skipping any statements in between.The following fig illustrates the difference of these two statements in while loop:

**Q. Differentiate between various loops available in C language?The C language provides three constructs for performing loop operations. They are:1. The while statement2. The do-while statement3. The for statementComparison of three loops:

[email protected] [email protected] 19

Page 20: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

**Q. What are the different storage classes in C?There are four storage classes in C :

a) Automatic storage classb) Register storage classc) Static storage classd) External storage class

Automatic storage class:Keyword - autoStorage - MemoryDefault initial value - garbage valueScope - Local to the block in which the variable is definedLife - till the control remains within the block in which the variable is defined

Register storage class:Keyword - registerStorage - CPU registersDefault initial value - garbage valueScope - Local to the block in which the variable is definedLife - till the control remains within the block in which the variable is defined.

Static storage class:Keyword - staticStorage – MemoryDefault initial value - zero

[email protected] [email protected] 20

Page 21: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

Scope - Local to the block in which the variable is definedLife - value of the variable persists between different function calls.

External storage class:Keyword - externStorage - MemoryDefault initial value - zeroScope - GlobalLife - As long as the program’s execution doesn’t come to an end

**Q. Explain with the help of example the concept of passing array to functions.Three rules to pass an array to a function

1. The function must be called by passing only the name of the array.2. In the function definition, the formal parameter must be an array type, the size of the array does not need to be specified.3. The function prototype must show that the argument is an array.

To pass a one-dimensional array to a called function, the name of the array without anysubscripts and the size of the array are passed as parameter. For example, largest(a, n)will pass the whole array a of size n to the called function.The prototype declaration of the same function may look like:int largest(int a[], int size)Example: main(){

int largest(int a[], int n); // function prototypeint value[4] = {3,12,22,10};printf(“%d\n”,largest(value,4));

} int largest(int a[], int n){

int j, max;max = 0;for(j=0; j<n; j++)if(max>a[j])max = a[j];return(max);

}In case of a two-dimensional array in the function definition, we must indicate that the arrayhas two dimensions by including two sets of brackets and the size of second dimension mustbe specified as follows:double average(int x[][n], int m, int n){

[email protected] [email protected] 21

Page 22: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

……………………

}

**Q. Write a short note on Recursion v/s Iteration.Recursion: recursion is a process where a function calls itself.Iteration: The iteration constructs are an efficient method of handling a series of statements that must be repeated a variable number of times.Comparison between Iterative and Recursive approaches from performance considerationsFactorial://recursive function calculates n!static int FactorialRecursive(int n){

if (n <= 1) return 1;return n * FactorialRecursive(n - 1);

} //iterative function calculates n!static int FactorialIterative(int n){

int sum = 1;if (n <= 1)return sum;while (n > 1){

sum *= n;n- -;} return sum;

}As we can clearly see the recursive is a lot slower than the iterative (considerably) and limiting (stack overflow). The reason for the poor performance is heavy push-pop of the registers in the ill level of each recursive call. **Q. Explain nesting of structures with example.One structure can be nested within another structure. Using this facility, complex data types can be created. We can nest a structure within another structure, which is in still another structure and so on…The following program shows nested structure:struct address{

char phone[15];

[email protected] [email protected] 22

Page 23: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

char city[25];int pin;

};struct emp{

char name[25];struct address a;

};struct emp e = {“jeru”, “531046”, “Nagpur”, 10};

**Q. Explain array of structures with example.In an array of structure, each element of the array represents a structure variable. Following program illustrates this:void main(){

struct book{

char name;float price;int pages;

};struct book b[100]; // array b of structure book is declared.int j;for(j=0; j<=99; j++){

printf(“\nEnter name, price and pages”) ;scanf(“%c%f%d”, &b[j].name, &b[j].price, &b[j].pages);

} for(j=0; j<=99; j++)

printf(“\n%c%f%d”, &b[j].name, &b[j].price, &b[j].pages);}In an array of structure, all elements of the array are stored in adjacent memory locations. Since each element of this array is a structure and since all structure elements are always stored in adjacent locations, so in the above program b[0]’s name, price and pages in memory would be immediately followed by b[1]’s name, price and pages, and so on.

**Q. Explain with example passing of structures to function.The structure variable can be passed to a function by passing either the individual structureelements or the entire structure variable at one go. But to pass individual elements wouldbecome more tedious as the number of structure elements go increasing, so a better way wouldbe to pass the entire structure variable at a time. This method is illustrated in the following

[email protected] [email protected] 23

Page 24: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

program:#include<stdio.h>struct book{

char name[25];char author[25];int callno;

};void display(struct book);void main(){

struct book b1 = {“Let us C”, “YPK”, 101};display(b1);

}void display(struct book b){

printf(“\n%s%s%d”,b.name,b.author,b.callno);}**Q. What do you mean by ‘Union’? How it can be declared and initialized in a C program?Unions are derived data types. They are used to group a number of different variables together. A union enables us to treat the same space in memory as a number of different variables. A union can be declared using the keyword union as follows:union item{

int m;float x;char c;

} code;This declares a variable code of type union item.

[email protected] [email protected] 24

Page 25: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

Q. Draw a diagram to represent the internal storage of a structure.Whatever be the elements of a structure, they are always stored in contiguous memory locations.Let us consider the following structure:struct book{

char name;float price;int pages;

};struct book b1 = {‘B’, 130.00, 550};The elements of this structure are stored in the memory as shown in the figure.

Q. Give a brief description of various derived data types available in C.There are mainly three derived data-types in C.i. Structure:It represents a record type, ideally. May contain heterogeneous primitive / derived data types. Can be self-referential also.E.g.

struct{char name[50] ;int roll;double marks[3];}student;

ii. Union:Contains heterogeneous primitive / derived data types. Largest sized element or data element forms the size of the union. All the members of union can not be used at the same time to get the best result.E.g.

union{float x;int y;char ch[2];}myunion;

[email protected] [email protected] 25

Page 26: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

iii. enum:Enumeration of the member data are done purposefully. Enumeration value can be changed from default value.

enum dept{accounts,sales,purchase,production};

Q. Explain the method of passing a structure by value as an argument to a function with an example of prototype function declaration and function call.The general syntax of passing a structure by value as an argument to a function is:function_name (structure_variable_name)The called function takes the following form:data_type function_name(struct_type st_name){

………………return(expression);

}Example:struct book{

char name[25];char author[25];int callno;

};void display(struct book) // prototype declarationvoid main(){

struct book b1 = {“Let us C”, “YPK”, 101};display(b1); // function call

}void display(struct book b){

printf(“\n%s %s %d”,b.name,b.author,b.callno);}The output:Let us C YPK 101

[email protected] [email protected] 26

Page 27: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

**Q. Explain with example relationship between single dimension array and pointers.When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations.Suppose, we declare an array x as follows:int x[5] = {1, 2, 3, 4, 5};So if the base address of x is say,1000 then all the elements of the array will be stored as shown in the fig.

Here, the array name x is defined as a constant pointer pointing to the first element, x[0] andtherefore the value of x is 1000, the location where x[0] is stored. That is, x = &x[0]= 1000if we declare p as an integer pointer, then we can make the pointer p to point to the arrayx by the following statement: p = x;Now we can access every value of x using p++ to move from one element to another. Therelationship between p and x is as follows:p = &x[0] (=1000)p +1 = &x[1] (=1002)p +2 = &x[2] (=1004)p +3 = &x[3] (=1006)p +4 = &x[4] (=1008)That is, the address of an element is calculated using its index and the scale factor of the data type. For example:Address of x[3] = base address + (3 X scale factor of int)= 1000 + (3 X 2)= 1006 So, Address of x[n] = base address + (n X scale factor of int)So, when handing arrays, instead of using array indexing, we can use pointers to access array element. For example,*(p + 3) gives the value of x[3].Pointer accessing method is much faster than array indexing.

Q. Explain with the help of examples pointer arithmetic.Like ordinary variables, various arithmetic operations can be performed with the pointers. Such as:a. Pointers can be incremented or decremented.

int a=5, *ptr;

[email protected] [email protected] 27

Page 28: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

ptr=&a; // ptr=65524ptr++; // ptr=65526

This will create a new storage locations, which will be the previous address +2 (for integervariable) in the memory for the variable a.b. Addition of a number to a pointer.

int x=4, *p, *ptr;p = &x;p= p+9;ptr = p+3;

c. Subtraction of a number from a pointer.int x=4, *p, *ptr;p = &x;p= p-6;ptr = p-2;

d. Subtraction of one pointer from anotherOne pointer variable can be subtracted from another provided both variables point to elements of the same array. The resulting value indicates the number of elements separating the corresponding array elements.

void main(){

int arr[] = {10, 20, 30, 40, 45, 78, 56};int *p, *q;p= &arr[1];q= &arr[5];printf(“%d %d”,q-p); // output, 4.

}e. Comparison of two pointer variables.Pointer variables can be compared provided both variables point to objects of the same datatype. So if p1 and p2 are two pointer variable pointing to say,integer variable, then p1>p2,p1 ==p2, p1!=p2 are allowed.Following operations cannot be performed with the pointers:1. Addition of two pointers.2. Multiplication of two pointers.3. Division of two pointers

Q. Explain with example the relationship of two-dimensional arrays with pointers.Pointers can be used to manipulate two-dimensional arrays as well. An element in a two-dimensional array a can be represented by the pointer expression as follows:*(*(a+i) + j) or *(*(p+i) + j) , where p is the pointer variable.Suppose we declare an array a as follows:int a[2][3] = { { 15, 27},

[email protected] [email protected] 28

Page 29: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

{ 22, 31};{ 14, 23}};The elements of a will be stored as :

If we declare p as an int pointer with the initial addess of &a[0][0], then a[i][j] is equivalent to *(p+4 X i+j). If we increment i by 1, the p is incremented by 4, the size of each row. Then the element a[2][3] is given by *(p+2 X 4+3) = *(p+11).

**Q. Describe Dynamic memory allocation and its functions.

C language requires the number of elements in an array at compile time. But our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. So there is a process of allocating memory at run time is known as dynamic memory allocation.Fig shows the conceptual view of storage of a C program in memory. The memory space that is located between stack and permanent storage area is available for dynamic allocation during execution of the program. This free memory region is called the heap. The size of the heap keeps changing when program is executed due to creation and death of variables that are local to functions and blocks.There are four library routines known as “memory management functions” that can be used for allocating and freeing memory during program execution. They are:malloc: allocates request size of bytes and returns a pointer to the first byte of the allocatedspace. Example: ptr = (int *) malloc (100 * sizeof(int)); On successful execution of this statement, a memory space equivalent to 100 times the size of an int bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer ptr of type of int.

[email protected] [email protected] 29

Page 30: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

calloc: allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. Example: ptr = (int *) calloc (10, sizeof(int)); free: free previously allocated space. Example: free(ptr); Here, ptr is a pointer to a memory block which is released by the free function.realloc: modifies the size of previously allocated space. Example: ptr = (int *) realloc(ptr, 20); On successful execution of this statement, a new memory space size 20 is allocated to the pointer variable ptr and returns the pointer to the first byte of the new memory block.

Q. How can you create a data file in C?Creating a data file means opening a file in the writing mode. When the mode is ‘writing’, a file with the specified name is created if the file does not exist.FILE *p;p = fopen(“samplefile”, “w”);the above statements open the file “samplefile” in the writing mode. If any file named “samplefile” already exists, its contens are deleted and the file is opened as a new file. The following program shows how to create a new data file and write data into it.#include <stdio.h>main(){

FILE *f1;char c;printf (“Data input : ”);f1 = fopen(“INPUT”, “w”); // create the file “INPUT”while((c= getchar()) != EOF) // get a character from keyboardputc(c, f1) ; // write a character to INPUTfclose(f1); // close the file INPUTprintf (“Data output : ”);f1 = fopen(“INPUT”, “r”); // reopen the file “INPUT”while((c= getc(f1)) != EOF) // read a character from keyboardprintf(“%c”, c) ; // display a character on screenfclose(f1); // close the file INPUT

}OUTPUTData input : This is a program to test the file handling featuresData output : This is a program to test the file handling features

**Q. Explain Command line argument in C. Actually, the declaration of main function looks like : int main (int argc, char *argv[])This declaration states that

1. main returns an integer value (used to determine if the program terminates successfully)

[email protected] [email protected] 30

Page 31: C Programming Q & A

Department of MCA, BSIT Questions and AnswersBrainware Group of Institutions Computer Programing with C - MCA 103

2. argc is the number of command line arguments including the command itself i.e argc must be at least 13. argv is an array of the command line arguments

The declaration of argv means that it is an array of pointers to strings (the command line arguments). By the normal rules about arguments whose type is array, what actually gets passed to main is the address of the first element of the array. As a result, an equivalent (and widely used) declaration is:

int main (int argc, char **argv)When the program starts, the following conditions hold true:oo argc is greater than 0.oo argv[argc] is a null pointer.oo argv[0], argv[1], ..., argv[argc-1] are pointers to strings

with implementation defined meanings.oo argv[0] is a string which contains the program’s name, or is an

empty string if the name isn’t available. Remaining members ofargv are the program’s arguments.

e.g, print_args echoes its arguments to the standard output – is a form of the Unix echo command./* print_args.c: Echo command line arguments */#include <stdio.h>#include <stdlib.h>int main(int argc, char *argv[]){

int i = 0 ;int num_args ;num_args = argc ;while( num_args > 0){

printf(“%s\n“, argv[i]);i++ ;num_args--;

}}If the name of this program is print_args, an example of its execution is as follows:% print_args hello goodbye solongprint_argshellogoodbyesolong%

[email protected] [email protected] 31