C Material

  • July 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View C Material as PDF for free.

More details

  • Words: 8,957
  • Pages: 41
C Language Material

G.S.PRAVEENA

Page2

-By

Index 1. Basics of programming fundamentals

03

2. Functions and Pointers

09

3. Pre-processor

11 12

5. String Functions

14

6. Structures

15

7. I/O Function

17

8. Files

19

9. Dynamic Memory Allocation

21

10. Sorting Techniques

23

11. Sample programs

27

Page2

4. Arrays

C Language Material: BASICS OF PROGRAMMING FUNDAMENTALS: 1. What are the important aspects (properties) of programming language? Four important aspects of any language are the way it stores data, the way it operates upon this data, how it accomplishes input and output and how it lets you control the sequence of execution of instructions in a program. 2. What is problem solving? Problem solving is a creative process. It is an act of defining a problem, determining the cause of the problem, identifying, prioritizing, and selecting alternatives for a solution and implementing a solution. 3. What are the steps involved in program development? The various steps involved in Program Development are: a. Defining or Analyzing the problem

e. Compiling and Running the Program

b. Design (Algorithm)

f. Testing and Debugging

c. Coding

g. Maintenance

d. Documenting program

the

4. How do you analyse the problem? Tasks in defining a problem: Specifying the input requirements. Specifying the output requirements and Specifying the processing requirements. 5. What is design and how to design a program?

6. What is algorithm?

Page2

A design is the path from the problem to a solution in code. Program Design is both a product and a process. The process results in a theoretical framework for describing the effects and consequences of a program as they are related to its development and implementation.

An algorithm is a step-by-step description of the solution to a problem. It is defined as an ordered sequence of well-defined and effective operations which, when carried out for a given set of initial conditions, produce output, and terminate in a finite time. The term “ordered sequence” specifies, after the completion of each step in the algorithm, the next step must be unambiguously defined. An algorithm must be: Definite, Finite, Precise and Effective and Implementation independent ( only for problem not for programming languages). 7. What is pseudo code? Pseudo code is an informal high-level description of an algorithm that uses the structural conventions of programming languages, but omits language-specific syntax. It is an outline of a program written in English or the user's natural language. 8. What is flow chart? Explain the symbols used? Flowchart is a diagrammatic representation of an algorithm. It uses different symbols to represent the sequence of operations, required to solve a problem. It serves as a blueprint or a logical diagram of the solution to a problem. 9. What is coding? An algorithm expressed in programming languages is called Program. Writing a program is called Coding. The logic that has been developed in the algorithm is used to write the program. 10. What is documentation? What is the need of documenting the program?

11. What is need of compiling the program?

Page2

Documentation explains how the program works and how to use the program. Documentation can be of great value, not only to those involved in maintaining or modifying a program, but also to the programmers themselves. Details of particular programs, or particular pieces of programs, are easily forgotten or confused without suitable documentation. Documentation comes in two forms: * External documentation, which includes things such as reference manuals, algorithm descriptions, flowcharts, and project workbooks * Internal documentation, which is part of the source code itself (essentially, the declarations, statements, and comments)

Compilation is a process of translating a source program into machine understandable form. The compiler is system software, which does the translation after examining each instruction for its correctness. The translation results in the creation of object code. After compilation, Linking is done if necessary. Linking is the process of putting together all the external references (other program files and functions) that are required by the program. The program is now ready for execution. During execution, the executable object code is loaded into the computer’s memory and the program instructions are executed. 12. What is testing? Testing is the process of executing a program with the deliberate intent of finding errors. Testing is needed to check whether the expected output matches the actual output. Program should be tested with all possible input data and control conditions. Testing is done during every phase of program development. Initially, requirements can be tested for its correctness. Then, the design (algorithm, flow charts) can be tested for its exactness and efficiency. Structured walk through is made to verify the design. 13. What is debugging? Debugging is a process of correcting the errors. Programs may have logical errors which cannot be caught during compilation. Debugging is the process of identifying their root causes. One of the ways to ensure the correctness of the program is by printing out the intermediate results at strategic points of computation. Debugging is the hardest part of programming because of improper documentation. 14. What is the difference between debugging and testing? Testing means detecting errors. Debugging means diagnosing and correcting the root causes. 15. What is a Programming Language? Computer Programming is an art of making a computer to do the required operations, by means of issuing sequence of commands to it. 16. What are the types of programming languages?

Low Level Languages and High Level Languages. 17. What is C?

Page2

There are two major types of programming languages:

C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. It is often know as middle level language as it inherits both the features of high level and low level language. 18. What are the characteristics of c languages? Characteristics of C Language The increasing popularity of C is due to its various desirable qualities: *C language is well suited for structured modular programming. * C is a robust language with rich set of built-in functions and operators. * C is smaller which has minimal instruction set and programs written in C are efficient and fast. * C is highly portable (code written in one machine can be moved to other). * C is highly flexible. * C allows access to the machine at bit level (Low level (Bitwise) programming). * C supports pointer implementation - extensive use of pointers for memory, array, structures and functions. 19. What are called escape sequence? Escape sequences are non printable characters, which begin with backward slash and followed by one or more special characters. The frequently used escape sequences are given below: Horizontal tab (\t) Form feed (\f) Vertical tab (\v) Back Space (\b) Carriage return (\r) Back Slash (\\) New line (\n) Null (\0) 20. Define a constant? A constant is an entity that doesn’t change. A constant in C refers to the fixed values that do not change during the execution of a program. There are two types of constants: Symbolic constants and Constant variables, also called readonly variables. 21. How many types of constants are there? What are they?

a. Primary (integer, float, char) b. Secondary (array, pointer, structure, union)

Page2

There are mainly two types of constants

22. Define the term Variable. Variable is a named memory location. It can store one value at a time. Every time new value is assigned, the old value is overwritten 23. Define datatype. Data types are used to indicate the type of value represented or stored in a variable, the number of bytes to be reserved in memory, the range of values that can be represented in memory, and the type of operation that can be performed on a particular data item. 24. Define the term “key word”. Why can’t we use key word as variable’s name? Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. 25. What is an identifier? Identifiers are names given to various programming elements such as variables, constants, and functions. It should start with an alphabet, followed by the combinations of alphabets and digits. No special character is allowed except underscore (_). An Identifier can be of arbitrarily long. Some implementation of C recognizes only the first eight characters and some other recognize first 32 characters. 26. How many no. of keywords are there in C language? What are the different control structures available in C? There are 32 keywords available in C language. The decision control statements are: if statement, if-else statement and the conditional operator. 27. What are the different operators available in c?

28. What is the “Order of Precedence”?

Page2

The following are the different operators available in C: Arithmetic operators Assignment operators Relational operators Unary operators Logical operators Bitwise operators

_______________________________________________________________ _________ Operator Name Association _______________________________________________________________ _________ ( ) [ ] -> .

Parentheses, Index, member access operators Left to Right

! – sizeof() (Typecast) * & Logical NOT, unary minus, indirection, address Right to Left ++ --

Increment and decrement operators. Right to Left

*/% to Right +-

Multiplicative operators.

Left

Additive operators. Left to Right

< > <= >= Inequality comparators. Left to Right == != &&

Equality comparators Left to Right Logical AND. Left tot Right

|| to Right

Logical OR.

?:

Conditional. Right to Left

= op=

Assignment. Right to Left

, to Right

Comma

Left

Left

29. What is typecasting?

Page2

_______________________________________________________________ __________

C provides a mechanism for allowing the programmer to change the default data type of a given expression. This is called Typecasting. Typecasting allows a variable to behave like a variable of another type. C provides two types of type conversions: Implicit and Explicit type conversions. 30. Name different IF statements. The if statement has three basic forms: Simple if-else, Nested if and if-else if ladder. 31. What is Short circuit evaluation? Whenever the expression with the operators && and || are evaluated, the evaluation process stops as soon as the outcome, true or false is known. 32. What is the hierarchy of operators? Operators ! */% +< > <= >= == != && || =

Type Logical NOT Arithmetic and modulus Arithmetic Relational Relational Logical AND Logical OR Assignment

33. What is a conditional operator (ternary operator)? What is its syntax? It is shortened form of if-statement and its syntax: Expression 1? Expression 2 : expression 3 34. What are the different types of loop control instructions available in C? There are 3 loop control instructions. Those are 1. For 2. While 3. Do...while

The loop (loop control instruction) involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied.

Page2

35. How does a loop work?

36. What is the use of BREAK statement? When break is encountered inside any loop, control automatically passes to the first statement after the loop. A break is usually associated with an if. 37. What is the use of continue statement? If we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The keyword continue allows us to do this. When continue is encountered inside any loop, control automatically passes to the beginning of the loop. A continue is usually associated with an if. 38. What is the difference between an entry controlled loop and an exit controlled loop? If the condition of the loop is tested before the control enters into the loop then it is called entry control loop (While)and if the condition is tested at exit then it is exit controlled loop(dowhile). 39. What is switch statement? The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default 40. What is the need of break statement in switch? If the break is not used in a case statement the control will not come out of the switch and it goes executing the following cases till it encounters a break otherwise it all the statements in the switch. 41. What is goto statement? Takes the control where ever you want, is done by using goto statement. Better don’t use it. 42. Why is programming?

goto

statement

not

preferred

in

The big problem with goto’s is that when we do use them we can never be sure how we got to a certain point in our code. They obscure the flow of control.

The exit ( ) function is a standard library function which terminates the execution of the program.

Page2

43. What does a exit () function do?

FUNCTIONS AND POINTERS 44. What is a function? A function is a self-contained block of statements that perform a coherent task of some kind. 45. Why do we use functions? We use functions because 1. Writing functions avoids rewriting the same code over and over. 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. 46. What is the mechanism used to convey message to the function? The mechanism used to convey information to the function is the ‘argument’. 47. What are the different mechanisms available?

parameter

passing

There are two parameter passing mechanism available. Those are: Call by value and Call by address 48. What is the use of 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. In the above program the value of sum of three numbers is being returned 49. What is the default return type any function? The default return type of any function is int.

Whenever we called a function and passed something to it we have always passed the ‘values’ of variables to the called function. Such function calls are called ‘calls by value’. By this we mean, on calling a function we are passing values of variables to it. 51. What is a pointer?

Page2

50. What is call by value mechanism?

Pointer is a variable which holds the address of another variable. 52. What is recursion? A function is called ‘recursive’ if a statement within the body of a function calls the same function. 53. Explain the terms associated with a function. Take a function as below Void main() { Int n,p; Int reverse (int);/* function prototype*/ Set of statements; n=reverse (p); /* function is called parameters*/ Set of statements; }

with

actual

Int reverse(int n)/* function heading with parameters*/ { Set of statements; Return(x); /* control goes back to function*/ }

formal

calling

1. In the above code snippet main () is calling function because the function reverse is called and reverse is called function 2. If a function (here reverse ()) is written below main () its prototype must be included in the calling function otherwise it should be declared globally so that the function call does not raise any error. It informs the compiler about the function. 3. The parameters present in the function call are called actual parameters and the parameters which are there in function heading are formal parameters 4. Return statement in function is the last executable statement. If we write any statements after if those are not going to be executed 5. Return type of a function is the type of value that is returned by the function in the present example int is the return type because reverse function returns int.

The difference between call by value and call by address is 1. The changes made to formal parameters are not reflected in the calling function in the call by value. Where as in the call by address changes will be reflected

Page2

54. What is the main difference between call by value and call by reference (address)?

2. By using call by value at most we can change a single value by return statement from called function where as by the use of call by address we can change many values in the calling function 55. What is the difference among int, short and long data types? Short is at least 2 bytes big, long is at least 4 bytes big, short is never bigger than int’s and int’s are never bigger than longs. 56. What is the difference between int and unsigned int? Declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise take. 57. What does a storage class tell us? A storage class tells us: 1. Where the variable would be stored. 2. What will be the initial value of the variable, if initial value is not specifically assigned? (i.e. the default initial value). 3. What is the scope of the variable; i.e. in which functions the value of the variable would be available. 4. What is the life of the variable; i.e. how long would the variable exist. 58. What are the different classes available in C? There are 4 storage classes available in c. Those are Automatic storage class (local) (default value is garbage) Register storage class (default value is garbage) Static storage class (default value is zero) External storage class (global) (default value is zero) 59. When do we use a static variable? Use static storage class only if you want the value of a variable to persist between different function calls.

Use register storage class for only those variables that are being used very often in a program. A typical application of register storage class is loop counters, which get used a number of times in a program.

Page2

60. When do we register variables? Give an example.

PRE PROCESSOR 61. What is a pre processor? It is a program that processes our source program before it is passed to the compiler. 62. What is the function of pre-processor? Pre-processor expands Macro expansion and File inclusion. 63. What is pre processor directive? # is called pre processor directive. Its job is to expand macros and files (headers) 64. What is a macro? Macro is a named constant. It is defined using #define Ex. # define A 5 Where ever A is found in the program 5 is substituted there We can have macro with arguments Ex. #define AREA(x) (3.14 * x * x) Macro call leads to substitution 65. What is the difference between “goto.c” and ? #include "goto.c"

This command would look for the file goto.c in the current directory as well as the specified list of directories as mentioned in the include search path that might have been set up.

#include

This command would look for the file goto.c in the specified list of directories only.

66. What is a search path? They include search path is nothing but a list of directories that would be searched for the file being included. Different C compilers let you set the search path in different manners. If you are using Turbo C/C++ compiler then the search path can be set up by selecting ‘Directories’ from the ‘Options’ menu. On doing this a dialog box appears. In this dialog box against ‘Include Directories’ we can specify the search path.

Yes we can. By using #pragma directive we can do it Ex. Void fun1 ( ); Void fun2 ( );

Page2

67. Is there any provision in c language to start execution from other than main ()?

#pragma startup fun1 #pragma exit fun2 main ( ) { printf (“\nInside maim”); } void fun1 ( ) { printf (“\nInside fun1”); } void fun2 ( ) { printf (“\nInside fun2”); } Output : Inside fun1 Inside main Inside fun2

ARRAYS 68. What is the need for going an array? If there are situations in which we would want to store more than one value at a time in a single variable. Ex. For example, suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such a case we have two options to store these marks in memory: 1. Construct 100 variables to store percentage marks obtained by 100 different students, i.e. each variable containing one student’s marks. 2. Construct one variable (called array or subscripted variable) capable of storing or holding all the hundred values. Obviously, the second alternative is better. A simple reason for this is, it would be much easier to handle one variable than handling 100 different variables. 69. What is an array? An array is a collection of similar elements. The first element in the array is numbered 0, so the last element is 1 less than the size of the array. An array is also known as a subscripted variable. Before using an array its type and dimension must be declared.

No, there is no boundary checking for arrays in c.

Page2

70. Is there any boundary check available for arrays in c?

71. Discuss the call by value and call by reference with arrays. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function. 72. How a pointer is associated to an array? Ex.

Int a [10]; Int *p; p=a; p [1] is same as a [1] Here in the above snippet p is pointer and it is pointing to an array called a; we can access the whole array with the help of the pointer 73. How do we pass an entire array to a function? Just passing the address of the zeroth element of the array to a function is as good as passing the entire array to the function. It is also necessary to pass the total number of elements in the array 74. What is a two dimensional array? The two-dimensional array is also called a matrix. Ex. Int a [4] [5]; It is two dimensional arrays of 4 rows and 5 columns Indirectly two dimensional arrays is nothing but collection of 1D arrays 75. What is an array of pointers? Since a pointer variable always contains an address, an array of pointers would be nothing but a collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables or addresses of array elements or any other addresses. All rules that apply to an ordinary array apply to the array of pointers as well. 76. What is a 3D array? A three-dimensional array can be thought of as an array of arrays of arrays. The outer array has three elements. 77. What are the things that can be done on pointers?

78. Different sorting techniques in C.

Page2

Addition of two pointers, Multiplication of a pointer with a constant and Division of a pointer with a constant.

Bubble sort, selection sort, insertion sort, quick sort, merge sort and heap sort.

STRING FUCTIONS 79. What is a string? A string constant is a one-dimensional array of characters terminated by a null (‘\0’). For example, char name [ ] = {‘H’, 'A', 'E', 'S', 'L', 'E', 'R', '\0’} ; or char name [] =”UGY” /* \0 is appended by c*/ The terminating null (‘\0’) is important, because it is the only way the functions that work with a string can know where the string ends. 80. What is the format specifier on to the screen?

used to print strings

The %s used in printf ( ) is a format specification for printing out a string. The same specification can be used to receive a string from the keyboard. 81. What are the different pre defined string functions available in C?

strcpy strncpy strcmp strncmp strcmpi stricmp strnicmp strdup strchr strrchr strstr strset strnset strrev

Use Finds length of a string Converts a string to lowercase Converts a string to uppercase Appends one string at the end of another Appends first n characters of a string at the end of another Copies a string into another Copies first n characters of one string into another Compares two strings Compares first n characters of two strings Compares two strings without regard to case ("i" denotes that this function ignores case) Compares two strings without regard to case (identical to strcmpi) Compares first n characters of two strings without regard to case Duplicates a string Finds first occurrence of a given character in a string Finds last occurrence of a given character in a string Finds first occurrence of a given string in another string Sets all characters of string to a given character Sets first n characters of a string to a given character Reverses string

Page2

Function strlen strlwr strupr strcat strncat

STUCTURES 82. Why do we use structure? A structure contains a number of data types grouped together. These data types may or may not be of the same type. 83. Define structure. Structure is collection of variables of different data type name under single entity. 84. What are the terms associated with structure? Example 1: Struct emp { Int empno; Char ename [20]; Float sal; }; This is called structure definition. Memory is not allocated to the members when the structure is defined. Struct emp a; a is structure variable of tag emp; Memory is allocated to the members when the structure is instantiated. In the above structure the total memory allocated to it is 2+20+4 i.e. 26 Example 2: We can instantiate a structure at the time of definition it self Struct emp { Int empno; Char ename [20];

} a, b, c; a, b, c are structure variables

Page2

Float sal;

Example 3: See these examples to have a better idea about declarations struct book { char name; float price; int pages; }; struct book b1, b2, b3; Is same as... struct book { char name; float price; int pages; } b1, b2, b3; Or even... struct { char name; float price; int pages; } b1, b2, b3; 85. Why are the structures defined globally? Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. In very large programs they are usually put in a separate header file, and the file is included (using the pre-processor directive #include) in whichever program we want to use this structure type. 86. How do we access structure members? Let us take the structure struct book { char name [20]; float price; int pages; } b1, b2, b3; B1 is the name of the structure We use dot operator to access structure members Ex. B1.name=”yugander”;

87. What is an array of structure?

Page2

Syntax is Structure name. field name;

struct book { char name [20]; float price; int pages; } b [100]; B is array of structures where each element is nothing it is structure. Some times like this a lot of variables (b1 to b100 for storing data about hundred books) needed to be handled. Therefore he allowed us to create an array of structures; an array of similar data types which themselves are a collection of dissimilar data types. 88. Can we structure?

assign

value

of

structure

to

other

Yes we can assign for example a, b are two structures we can do a=b provided both structures belong to the same tag 89. Can we have structure within a structure? We can use structure within a structure. But inner structure definition must be written in above outer structure. 90. If a structure is associate with a pointer, how do we operate members? By using -> operator we have to operate member fields of structure. 91. Can you send a structure to a function using call by value and call by address? We can send a structure to a function by both the mechanisms. 92. What is a self referential structure? If structure has one of its members type as its own type then it is called self referential structure.

INPUT/OUTPUT FUNCTION: 93. What are the different I/O functions available? There are numerous library functions available for I/O. These can be classified into three broad categories: Functions to receive input from keyboard and write output to VDU.

Page2

Console I/O functions

File I/O functions

Functions to perform I/O operations on floppy disk or hard disk.

94. What is console? The screen and keyboard together are called a console. 95. How does sprint() work? The sprintf( ) function works similar to the printf( ) function except for one small difference. Instead of sending the output to the screen as printf( ) does, this function writes the output to an array of characters. 96. How does a sscanf() work? It allows us to read characters from a string and to convert and store them in C variables according to specified formats. The sscanf( ) function comes in handy for in-memory conversion of characters to values. You may find it convenient to read in strings from a file and then extract values from a string by using sscanf( ). The usage of sscanf( ) is same as scanf( ), except that the first argument is the string from which reading is to take place. 97. What getche()?

is

the

difference

between

getch()

and

These functions return the character that has been most recently typed. The ‘e’ in getche( ) function means it echoes (displays) the character that you typed to the screen. As against this getch( ) just returns the character that you typed without echoing it on the screen. 98. What is the difference between getchar() and fgetchar()? getchar( ) works similarly and echo’s the character that you typed on the screen, but unfortunately requires Enter key to be typed following the character that you typed. The difference between getchar( ) and fgetchar( ) is that the former is a macro whereas the latter is a function. Here is a sample program that illustrates the use of these functions. 99. What is union?

A variable with union type stores one of the values defined by that type. The same rules govern structure and union declarations. Unions can also have bit fields.

Page2

A "union declaration" specifies a set of variable values and, optionally, a tag naming the union. The variable values are called "members" of the union and can have different types. Unions are similar to "variant records" in other languages.

Members of unions cannot have an incomplete type, type void, or function type. Therefore members cannot be an instance of the union but can be pointers to the union type being declared. A union type declaration is a template only. Memory is not reserved until the variable is declared. If a union of two types is declared and one value is stored, but the union is accessed with the other type, the results are unreliable. For example, a union of float and int is declared. A float value is stored, but the program later accesses the value as an int. In such a situation, the value would depend on the internal storage of float values. The integer value would not be reliable. 100. What are the similarities between union and structure? Structures and unions share the following characteristics: •





Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field. The only operators valid for use with entire structures and unions are the simple assignment (=) and sizeof operators. In particular, structures and unions cannot appear as operands of the equality ( == ), inequality (! =), or cast operators. The two structures or unions in the assignment must have the same members and member types. A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable; that is, the entire structure or union is copied into the corresponding parameter.

101. What is the difference between structure and a union? The union is a structure. The main difference between structure and union is, the size of the union is equal to the size of the largest member of the union where as size of the structure is the sum of the size of all members of the structure. And one more thing is that, at a time we can use one member of the union.

102. How do you open a file?

Page2

FILES

Before we can read (or write) information from (to) a file on a disk we must open the file. To open the file we have called the function fopen( ). 103. How do you read file content? To read the file’s contents from memory there exists a function called fgetc( ). ch = fgetc ( fp ) ; fgetc( ) reads the character from the current pointer position, advances the pointer position so that it now points to the next character, and returns the character that is read, which we collected in the variable ch. 104. What does a fputc() do? The fputc( ) function is similar to the putch( ) function, in the sense that both output characters. However, putch( ) function always writes to the VDU, whereas, fputc( ) writes to the file. 105. What are the different file opening modes? Read(r), write(w), append(a) modes And r+, w+, a+ we can do read, write, append with these three. 106. How do you close a file? By using fclose() we can close a opened file. 107. What is binary file? A binary file is merely a collection of bytes. This collection might be a compiled version of a C program (say PR1.EXE), or music data stored in a wave file or a picture stored in a graphic file. A very easy way to find out whether a file is a text file or a binary file is to open that file in Turbo C/C++. If on opening the file you can make out what is displayed then it is a text file, otherwise it is a binary file. 108. Why do use fprintf()? The only function that is available for storing numbers in a disk file is the fprintf( ) function.

109. Why do we go for a binary file?

Page2

Text and characters are stored one character per byte, as we would expect. Numbers are stored as strings of characters.

If large amount of numerical data is to be stored in a disk file, using text mode may turn out to be inefficient. The solution is to open the file in binary mode and use those functions (fread( ) and fwrite( ) which are discussed later) which store the numbers in binary format. It means each number would occupy same number of bytes on disk as it occupies in memory. 110. Why fread and fwrite are more important? Any database management application in C must make use of fread( ) and fwrite( ) functions, since they store numbers more efficiently, and make writing/reading of structures quite easy. Note that even if the number of elements belonging to the structure increases, the format of fread( ) and fwrite( ) remains same. 111. Explain rewind(),ftell(),fseek(). The rewind( ) function places the pointer to the beginning of the file, irrespective of where it is present right now. The fseek( ) function lets us move the pointer from one record to another. fseek ( fp, -recsize, SEEK_CUR ) ; If we wish to know where the pointer is positioned right now, we can use the function ftell( ). It returns this position as a long int which is an offset from the beginning of the file. The value returned by ftell( ) can be used in subsequent calls to fseek( ) 112. What are command line parameters? The arguments that we pass on to main( ) at the command prompt are called command line arguments. The function main( ) can have two arguments, traditionally named as argc and argv. Out of these, argv is an array of pointers to strings and argc is an int whose value is equal to the number of strings to which argv points. When the program is executed, the strings on the command line are passed to main.

Operator ~ >> << & | ^

Meaning One’s complement Right shift Left shift Bitwise AND Bitwise OR Bitwise XOR(Exclusive

Page2

113. What are the bitwise operators?

OR)

114. What are enumerators? An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name of the (optional) enumeration tag and defines the set of named integer identifiers (called the "enumeration set," "enumerator constants," "enumerators," or "members"). A variable with enumeration type stores one of the values of the enumeration set defined by that type. Variables of enum type can be used in indexing expressions and as operands of all arithmetic and relational operators. Enumerations provide an alternative to the #define preprocessor directive with the advantages that the values can be generated for you and obey normal scoping rules. In ANSI C, the expressions that define the value of an enumerator constant always have int type; thus, the storage associated with an enumeration variable is the storage required for a single int value. An enumeration constant or a value of enumerated type can be used anywhere the C language permits an integer expression. Example: enum DAY /* Defines an enumeration type */ { saturday, /* Names day and declares a */ sunday = 0, /* variable named workday with */ monday, /* that type */ tuesday, wednesday, /* wednesday is associated with 3 */ thursday, friday } workday; The value 0 is associated with saturday by default. The identifier sunday is explicitly set to 0. The remaining identifiers are given the values 1 through 5 by default.

DYNAMIC MEMORY ALLOCATION 115. What is dynamic storage allocation?

116. What is Dynamic memory allocation?

Page2

A storage allocation technique in which the storage assigned to a computer program varies during program execution, based on the current needs of the program and of other executing programs.

The process of allocating memory at run time is known as dynamic memory allocation. 117. What functions?

are

the

dynamic

memory

allocation

Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management. Function Task Malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space Calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the memory Free Frees previously allocated space Realloc Modifies the size of previously allocated space. 118. Explain memory allocation process.

According to the conceptual view the program instructions and global and static variable in a permanent storage area and local area variables are stored in stacks. The memory space that is located between these two regions in available for dynamic allocation during the execution of the program. The free memory region is called the heap. The size of heap keeps changing when program is executed due to creation and death of variables that are local for functions and blocks. Therefore it is possible to encounter memory overflow during dynamic allocation process. In such situations, the memory allocation functions mentioned above will return a null pointer. 119. How to allocate a block of memory? A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form: ptr=(cast-type*)malloc(byte-size);

Example: x=(int*)malloc(100*sizeof(int));

Page2

ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size.

120. How to allocate multiple blocks of memory? Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast-type*) calloc(n,elem-size); The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned. 121. How to release the used space? Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function. free(ptr); ptr is a pointer that has been created by using malloc or calloc. 122. How to alter the size of allocated memory? The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize); This function allocates new memory space of size newsize to the pointer variable ptr ans returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.

123. What is sorting algorithm?

Page2

SORTING TECHNIQUES:

A sorting algorithm is an algorithm that puts elements of a list in a certain order. 124. Name different types of sorting algorithms. In this table, n is the number of records to be sorted. The columns "Average" and "Worst" give the time complexity in each case, under the assumption that the length of each key is constant, and that therefore all comparisons, swaps, and other needed operations can proceed in constant time. "Memory" denotes the amount of auxiliary storage needed beyond that used by the list itself, under the same assumption. These are all comparison sorts. Name Bubble sort Selection sort Inserting sort Merge sort Quick sort Heap sort

Average O(n2) O(n2) O(n2) O(n logn) O(n logn) O(n logn)

Worst O(n2) O(n2) O(n2) O(n logn) O(n2), O(log n) O(n logn)

Memory O(1) O(1) O(1) O(n) O(1)

125. Explain Bubble sort. Bubble sort is a straightforward and simplistic method of sorting data that is used in computer science education. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. While simple, this algorithm is highly inefficient and is rarely used except in education. A slightly better variant, cocktail sort, works by inverting the ordering criteria and the pass direction on alternating passes. Its average case and worst case are both O(n²). Step-by-step example:

First Pass: ( 5 1 4 2 8 ) ( 1 5 4 2 8 ) Here, algorithm compares the first two elements, and swaps them. (15428) (14528) (14528) (14258) ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) Now, since these elements are already in order, algorithm does not swap them. Second Pass:

Page2

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared.

(14258) (14258) (14258) (12458) (12458) (12458) (12458) (12458) Now, the array is already sorted, but our algorithm does not know if it is completed. Algorithm needs one whole pass without any swap to know it is sorted. Third Pass: (12458) (12458) (12458) (12458) (12458) (12458) (12458) (12458) Finally, the array is sorted, and the algorithm can terminate. Algorithm for bubble sort: procedure bubbleSort( A : list of sortable items ) defined as: for each i in 1 to length(A) do: for each j in length(A) downto i + 1 do: if A[ j -1 ] > A[ j ] then swap( A[ j - 1], A[ j ] ) end if end for end for end procedure 126. Explain Selection sort. Selection sort is a simple sorting algorithm that improves on the performance of bubble sort. It works by first finding the smallest element using a linear scan and swapping it into the first position in the list, then finding the second smallest element by scanning the remaining elements, and so on. Selection sort is unique compared to almost any other algorithm in that its running time is not affected by the prior ordering of the list: it performs the same number of operations because of its simple structure. Selection sort requires (n - 1) swaps and hence Θ(n) memory writes. However, Selection sort requires (n - 1) + (n - 2) + ... + 2 + 1 = n(n - 1) / 2 = Θ(n2) comparisons. Thus it can be very attractive if writes are the most expensive operation, but otherwise selection sort will usually be outperformed by insertion sort or the more complicated algorithms.

64 25 12 22 11 11 25 12 22 64 11 12 25 22 64

Page2

Here is an example of this sort algorithm sorting five elements:

11 12 22 25 64 Pseudo code for selection sort: for i ← 0 to n-2 do min ← i for j ← (i + 1) to n-1 do if A[j] < A[min] min ← j swap A[i] and A[min] 127. Explain Insertion sort. Insertion sort is a simple sorting algorithm that is relatively efficient for small lists and mostly-sorted lists, and often is used as part of more sophisticated algorithms. It works by taking elements from the list one by one and inserting them in their correct position into a new sorted list. In arrays, the new list and the remaining elements can share the array's space, but insertion is expensive, requiring shifting all following elements over by one. The insertion sort works just like its name suggests - it inserts each item into its proper place in the final list. The simplest implementation of this requires two list structures - the source list and the list into which sorted items are inserted. To save memory, most implementations use an in-place sort that works by moving the current item past the already sorted items and repeatedly swapping it with the preceding item until it is in place. Shell sort is a variant of insertion sort that is more efficient for larger lists. This method is much more efficient than the bubble sort, though it has more constraints. Pseudo code of insertion sort: insertionSort(array A) for i = 1 to length[A]-1 do begin value = A[i] j = i-1 while j >= 0 and A[j] > value do begin A[j + 1] = A[j] j = j-1 end A[j+1] = value end

Merge sort takes advantage of the ease of merging already sorted lists into a new sorted list. It starts by comparing every two elements (i.e., 1 with 2, then 3 with 4...) and swapping them if the first should come after the second. It then merges

Page2

128. Explain Merge sort.

each of the resulting lists of two into lists of four, then merges those lists of four, and so on; until at last two lists are merged into the final sorted list. Of the algorithms described here, this is the first that scales well to very large lists, because its worst-case running time is O(n log n). Example:

Pseudo code for merge sort: function mergesort(m) var list left, right, result if length(m) ≤ 1 return m var middle = length(m) / 2 for each x in m up to middle add x to left for each x in m after middle add x to right left = mergesort(left) right = mergesort(right) result = merge(left, right) return result

Heap sort is a much more efficient version of selection sort. It also works by determining the largest (or smallest) element of the list, placing that at the end (or beginning) of the list, then continuing with the rest of the list, but accomplishes this task efficiently by using a data structure called a heap, a special type of binary tree. Once the data list has been made into a heap, the root node is guaranteed to be the largest element. When it is

Page2

129. Explain Heap sort.

removed and placed at the end of the list, the heap is rearranged so the largest element remaining moves to the root. Using the heap, finding the next largest element takes O(log n) time, instead of O(n) for a linear scan as in simple selection sort. This allows Heap sort to run in O(n log n) time. 130. Explain Quick sort.

Quick sort is a divide and conquer algorithm which relies on a partition operation: to partition an array, we choose an element, called a pivot, move all smaller elements before the pivot, and move all greater elements after it. This can be done efficiently in linear time and in-place. We then recursively sort the lesser and greater sub lists. Efficient implementations of quick sort (with in-place partitioning) are typically unstable sorts and somewhat complex, but are among the fastest sorting algorithms in practice. Together with its modest O(log n) space usage, this makes quick sort one of the most popular sorting algorithms, available in many standard libraries. The most complex issue in quick sort is choosing a good pivot element; consistently poor choices of pivots can result in drastically slower (O(n²)) performance, but if at each step we choose the median as the pivot then it works in O(n log n). Pseudo code for quick sort: function partition(array, left, right, pivotIndex) pivotValue := array[pivotIndex] swap array[pivotIndex] and array[right] // Move pivot to end storeIndex := left for i from left to right − 1 if array[i] ≤ pivotValue swap array[i] and array[storeIndex] storeIndex := storeIndex + 1 swap array[storeIndex] and array[right] // Move pivot to its final place return storeIndex

SAMPLE PROGRAMS: 1. Factorial using recursive function.

#include

Page2

#include<stdio.h>

long double facto(int n) { if(n>0) return(n*facto(n-1)); else return(1); } void main() { int n; clrscr(); printf("enter number\n"); scanf("%d",&n); if(n==0||n==1) printf("%d!=%d",n,1); else printf("%d!=%Lf",n,facto(n)); getch(); } 2. Reverse of a number. #include<stdio.h> #include void main() { int sum=0,x,n;

printf("enter a value of n: "); scanf("%d",&n);

Page2

clrscr();

while(n>0) { x=n%10; sum=sum*10 + x; n=n/10; } printf("%d",sum); getch(); } 3. Armstrong number #include<stdio.h> #include void main() { int s,sum=0,n,a; clrscr(); printf("\nEnter the no."); scanf("%d",&n); a=n; while(n!=0) { s=n%10; sum=sum+s*s*s; n=n/10;

if(sum==a) printf("\nThe no.is an armstrong no.",a);

Page2

}

else printf("\nNot an armstrong no"); getch(); } 4. Reverse of a string. #include<stdio.h> #include void main() { char a[10]; int i,j,count=0; clrscr(); printf("Enter the first string:"); gets(a);//scanf("%s",&a); for(i=0;a[i]!=0;i++) count++; for(j=count;j>=0;j--) printf("%c",a[j]); getch(); } 5. Logic for the multiplication of the 2D matrix mat3[i][j]=mat3[i][j]+(mat1[i][k]*mat2[k][j]); 6. Fibonacci series #include<stdio.h>

void main()

Page2

#include

{ int f1=0,f2=1,f3,n,i=3; clrscr(); printf("Enter the number greater than 2: "); scanf("%d",&n); printf("%d\t%d",f1,f2); while(i<=n) { f3=f1+f2; printf("\t%d",f3); f1=f2; f2=f3; i++; } getch(); } 7. Whether the given number is a prime or not. #include<stdio.h> #include void main() { int n,i=1,count=0; clrscr(); printf("enter a number greater than two");

while(n<=1)

Page2

scanf("%d",&n);

{ printf("\nre-enter a value i.e greater than 1\n"); scanf("%d",&n); } for(i=1;i<=n;i++) { if(n%i==0) c=c+1; }

if(c==2) printf("the number is a prime number"); else printf("the number is not a prime number"); getch(); } 8. Printing prime number up to n. #include<stdio.h> #include void main() { int n,i=1,c=0,x,count=0; clrscr(); printf("enter any number");

for(n=1;n<=x;n++)

Page2

scanf("%d",&x);

{ for(i=1;i<=n;i++) { if(n%i==0) c=c+1; } if(c==2) { count=count+1; printf("\t%d",n); } c=0; } printf("\n Number of prime numbers is %d", count); getch(); } 9. How to read and print a 3x3 matrix. #include<stdio.h> #include void main() { int i,j,a[3][3]; clrscr(); printf("Enter the values in the matrix:\n");

{

Page2

for(i=0;i<=2;i++)

for(j=0;j<=2;j++) { scanf("%d",&a[i][j]); } } printf("\nThe following is the values entered in the matrix:\n"); for(i=0;i<=2;i++) { for(j=0;j<=2;j++) { printf("\t%d",a[i][j]); } printf("\n"); } getch(); } 10. Check whether palindrome or not.

the

word

or

a

number

is

a

#include<stdio.h> #include void pal(int i, int j,char s[]) { if (s[i]==s[j]) {

printf("\n Palindrome");

Page2

if(i>=j)

else pal(i+1,j-1,s); } else { printf("\n not a palindrome"); return; } } void main() { char a[20]; int i,l=0; clrscr(); printf("enter string"); scanf("%s",a); for(i=0;a[i]!=0;i++) l++; pal(0,l-1,a); getch(); } 11. Swap two numbers without using the third variable. #include<stdio.h> #include

{

Page2

void main()

int a,b; clrscr(); printf(“\n Enter the two numbers a and b:”); scanf(“%d%d”, &a, &b); a=a+b; b=a-b; a=a-b; printf(“\n The swapped numbers are a=%d and b= %d”,a,b); getch();

Page2

}

Related Documents

C Material
July 2020 2
C++ Material
October 2019 4
C -material
July 2020 1
Material
May 2020 52
Material
November 2019 67
Material.
May 2020 51