Saturday, March 19, 2016

UNIT-III
Structures

53. A structure is a collection of one or more variables, possibly of different data types, grouped together under a single name for convenient handling. A structure is a convenient way of grouping several pieces of related information together.
Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as 'members of structure'.

54.
Syntax of structure definition:
struct tag_name
{
data_type member_1;
data_type member_2;
data_type member_n;
};

55.
Defining a Structure(using typedef)
typedef defines and names a new type, allowing its use throughout the program. typedefs usually occur just after the #define and #include statements in a file.
Example structure definition.
typedef struct
{
char name[64];
char course[128];
int age;
int year;
} student;
This defines a new type student variables of type student

56.
Declaring Stucture Variables:
The first way is to declare a structure followed by structure definition like this :
struct structure_name
{
structure _member;
.....
}instance_1,instance_2,..instance_n;
In the second way, we can declare the structure instance at a different location in our source code after structure definition(in the main function).
Here is structure declaration syntax :
struct struct_name instance_1,instance_2 instance_n;
Example: struct student s;


57.
Accessing Members of a Structure
Each member of a structure can be used just like a normal variable, but its name will be a bit longer. In the above, member name of structure „s will behave just like a normal array of char, however we refer to it by the name
s.name
Here the dot is an operator which selects a member from a structure(member operator). Where we have a pointer to a structure we could dereference the pointer and then use dot as a member selector. This method is a little clumsy to type. Since selecting a member from a structure pointer happens frequently, it has its own operator -> which acts as follows. Assume that st_ptr is a pointer to a structure of type student, We would refer to the name member as
st_ptr -> name

58.
Structures and functions
A structure can be passed as a function argument just like any other variable. This raises a few practical issues.
A structure can be passed to a function in 3 ways.
(i) Passing individual members of the structure to a function.
(ii) Passing a copy of the structure variable( Call by value).
(iii) Passing a structure by passing its pointer to the structure.

59.
Nested structures(Structures within Structures) :
Structures can be used as structures within structures. It is also called as 'nesting of structures'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
- - - - - - - - - - -
- - - - - - - - - - -
<data-type> element n;
}inner_struct_var;
}outer_struct_var;

60.
Arrays within Structures:
Sometimes, it is necessary to use structure members with array.
Program :
#include <stdio.h>
#include <conio.h>
struct result
{
int rno, mrks[5];
char nm;
}res;

61.
Arrays of structures:
An array of structures for the example is declared in the usual way: 100 books
struct book
{
char name[20];
char author[20];
int pages;
float price;
} struct student[100];

62.Self referential Structures

A structure can contain a pointer to another structure of its own type, or even to itself. This is because a pointer to a structure is not itself a structure, but merely a variable that holds the address of a structure. Pointers to structures are quite invaluable, in fact, for building data structures such as linked lists and trees.
A pointer to a structure type variable is declared by a statement such as the following:
struct student *st_ptr;

63.
Applications of Structures

1.      Complex numbers in mathematics

2.      structures could be used to hold the locations of points in multi-dimensional space

3.      Apart from holding data, structures can be used as members of other structures. Arrays of structures are possible, and are a good way of storing lists of data with regular fields, such as databases.

4.      Another possibility is a structure whose fields include pointers to its own type. These can be used to build chains (programmers call these linked lists), trees or other connected structures.







UNIONS

64.
Union is user defined data type used to stored data under unique variable name at single memory location. Union is similar to that of structure. Syntax of union is similar to structure.

To declare union data type, 'union' keyword is used.
Union holds value for one data type which requires larger storage among their members.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;

65.
major difference between structure and union is 'storage.' In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time.

66.








67.

68.
Enumerations
An enumeration is a data type consisting of a set of named values that represent integral constants, known as enumeration constants.
An enumeration also referred to as an enumerated type because we must list (enumerate) each of the values in creating a name for each of them. In addition to providing a way of defining and grouping sets of integral constants, enumerations are useful for variables that have a small number of possible values.
ENUM is closely related to the #define preprocessor.
It allows you to define a list of aliases which represent integer numbers. For example if you find yourself coding something like:
#define MON 1
#define TUE 2
#define WED 3
You could use enum as below.
enum week { Mon=1, Tue, Wed, Thu, Fri Sat, Sun} days;
or
enum escapes { BELL = '\a', BACKSPACE = '\b', HTAB = '\t',
RETURN = '\r', NEWLINE = '\n', VTAB = '\v' };
or
enum boolean { FALSE = 0, TRUE };
An advantage of enum over #define is that it has scope This means that the variable (just like any other) is only visable within the block it was declared within.
We can declare an enumeration type separately from the definition of variables of that type.We can define an enumeration data type and all variables that have that type in one statement

69.
Bit Fields
In addition to declarators for members of a structure or union, a structure declarator can also be a specified number of bits, called a "bit field." Its length is set off from the declarator for the field name by a colon. A bit field is interpreted as an integral type.
Bit Fields allow the packing of data in a structure


FILE MANAGEMENT IN C  

70.
A file is nothing but a place on the disk where a group of related data is stored. Until here we read and write data through console I/o functions scanf and printf, which always use the keyboard /screen as the target place.

71

The basic file operation in ‘C’
Ø Naming a file
Ø Opening a file
Ø Reading data from a file
Ø Writing data to a file
Ø Closing file

72

File handling functions in ‘C’ library
fopen( ) → creates a new life for use/open existing file
fclose( ) → closes file
getc( ) → read a char from file
putc( ) →writes a char to file
fprintf →writes a set of data values to a file
fscanf → reads a se of data values from a file
getw( ) → reads an integer from a file
putw( ) → writes an integer to a file
fseek( ) → sets the position to a designed point in file
ftell( ) → sets the position to the beginning of file

73
Text files
Text files store character data. A text file can be thought of as a stream of characters that can be processed sequentially

74
Binary files
As far as the operating system is concerned, a binary file is no different to a text file. It is a collection of bytes.

75.
Mode for opening a file
r →opens file for reading only
w → opens file for writing only
a → opens file for appending (adding)data.
r+ → for both reading and writing at the beginning only
w+ → after writing we may read the file without closing and reopening
a+ → open a file in read and append mode
ð When the mode is writing new file is created (or) the contents are deleted, if the file is already existed.
ð When the mode is appending, the file is opened and add the contents of new (or) new file also created, if file does not exist.
ð When the mode is reading, if the file existed then the file is opened with the current contents safe otherwise an error occurs.

76.
Input/output operations on Files:
getc and putc functions: the simplest file I/o functions are getc and putc.
ð „getc is used to read a char from a file

Example: c=getc(fp1);
ð „putc is used to write a char to a file

Example: putc(c1,fp1);
EOF – End of file (when EOF encountered the reading / writing should be terminated)

77.
The getw and putw functions:
These are integer oriented functions. These are similar to above functions and are used to read and write integer values. These are useful when we deal with only integer data. The general format is
putw (integer , fp);
getw(fp);
The fprintf and fscanf functions:
Until now, we handle one char/integer at a time. But these functions handle a group of mixed data simultaneously.
Syntax of fprintf is
fprintf (fp, “control string”, list);

78.

ð fscanf is used to read list of items from a file
ð fprintf is used to write a list of items to a file.

79.
Error handling during I/o operations:
→ During I/o operations on a file an error may occur. The error may be,
→ Trying to read beyond the end-of-file
→ Device overflow
→ Trying to use a file that has not been opened.
→ If the modes are not mentioned properly
→ Open a file with invalid name
→ Try to write contents to a write protected file

feof and ferror functions help us to detect I/o errors in the file
ð feof is used to test an end of file condition . It takes a FILE pointer as its only argument and returns a non zero integer value if all the data has been read, and returns zero otherwise.

Example: if (feof(fp))
printf(“end of data”);
ð ferror reports the status of the file indicated . It also takes a FILE pointer as its argument and returns a non zero integer if an error has been detected up to that point, during processing , otherwise returns o.

if (ferror(fp)!=0)
printf(“an error has ocured”);
This prints an error message, if reading is not successful.

80.
Random Access to files:
Until now we read and write data to a file sequentially. In some situations we need only a particular part of file and not other parts. This can be done with the help of fseek, ftell, rewind functions.

81.
ftell: It takes a file pointer and returns number of type long , that corresponds to the current position. This is useful in saving the current position of file.
Example: n=ftell(fp);
n’ would give the relative offset (in bytes) of current position. i.e., n bytes have all ready been read/ write.
rewind: It takes file pointer and resets the position to the start of the file.
Example: rewind(fp);
fseek: This function is used to move file position to a desired location within file.
Syntax: fseek (file pointer, offset, position)
Example: fseek (Fp1, 0L,); → go to the beginning
Fseek(fp1,m,1) → go forward by m bytes
Position 0 ─ beginning
1─ current position
2─ end of file
Offset Positive ─ move forward
Negative ─move backward
OL ─ no more (stay)
If the fseek file operation is successful, it returns 0 else returns -1 (error occur)
82.

Command line arguments:
As we know „main function is marked the beginning of the program. This „main can take two arguments argc and argv and information contained in the command line is passed on to the program through these arguments.
→ Argc – is an argument counter (counts the No. of arguments on the command line)
→ Argv – is am argument rector (array of char, pointers which points command line)

83.
Dynamic Memory Allocation
Dynamic allocation is a pretty unique feature to C (amongst high level languages). It enables us to create data types and structures of any size and length to suit our programs need within the program.

84.
Malloc, Sizeof, and Free
The Function malloc is most commonly used to attempt to ``grab'' a continuous portion of memory. It is defined by:
void *malloc(size_t number_of_bytes)

85.

Calloc and Realloc
There are two additional memory allocation functions, Calloc() and Realloc(). Their prototypes are given below:
void *calloc(size_t num_elements, size_t element_size};
void *realloc( void *ptr, size_t new_size);

Realloc is a function which attempts to change the size of a previous allocated block of memory

malloc does not initialize memory (to zero) in any way. If you wish to initialize memory then use calloc. Calloc there is slightly more computationally expensive but, occasionally, more convenient than malloc


UNIT-1

1.      Define a Computer?
ANS:  A computer is an electronic device capable of manipulating numbers and symbols under the control of a set of instructions known as computer program.
2.       List out the various components of the computer?
ANS:
1. Arithmetic and Logical unit
2. Memory unit
3. Control unit
4. Input unit
5. Output unit

3.      List out the various componrnts of CPU?
The CPU (Central Processing Unit) Consists of.
a. ALU (Arithmetic Logic Unit)
b. CU (Control Unit)
c. MU (Memory Unit)

a. The Control Unit Controls all the activities of the Computer. It sends commands and control signals and finds the sequence of instruction to be executed.
b. Memory Unit is the place where all input data and results are stored. Computer memory is also available in the form of Random Access Memory (RAM)
c. ALU Consists of CKTs for arithmetic operations(+,-,*,/) and logical operations (<,>,>=,<=,==,!=)

4.      RAM : It is a temporary storage medium in a computer. The data to be processed by the computer are transferred from a storage devices or a keyboard to RAM results from a executed program are also stored in RAM. The data stored will be erased when the computer is off.
5.      ROM (Read only Memory) : This is a non-volatile or data storage medium which stores start up programs (operating systems). This essentially stores the BIOS (Basic Input Operating System)

6.      Write notes on programming languages?
Languages of different Generation Computer.
1. First – Generation Language : All the instructions are in the binary form and are referred to as machine level or low level language (LLL). It is very difficult to read the instructions written in binary  Eg : 00110101011101110001, 101100001010101


2. Second – Generation Language: all the instruction are in the forms of mnemonics. The symbolic instruction language called as Assembly Language. All the symbolic instructions are converted into binaries with the help of translator called Assembles. Source Program Eg : ADD A, B, R,

             3. Third – Generation Language : These are written in English with symbols and digits. Then 
                  are known as High level language (HLL). common high level languages are c,c++, 
                  COBOL, BASIC, FORTRAN, PASCAL, etc.

7.       ASCII (American Standard Code For Information Interchange) is commonly used for translation of source Program into object program
8.      Features of “C” Language :
1. It is robust language because of rich set of binary in – function
2. It is efficient and fast because of its variant data-types and powerful operation.
3. It is highly Portable i.e., programs written in one computer can be run on another
4. It is well suited for structure program, thus allows the user to think about the problem in the terms of functional blocks.
5. Debugging, testing and maintenance is easy
6. ability to extend itself, we can continuously add our own functions to the program.

9.      Complier : This reads the entire source program and converts it to the object code. It provides error not of one line, but errors of the entire program. It executes as a whole and it is fast

10.  Interpreter : It reads only one line of a source program at a time and converts it into an object code. In case of errors/same will be indicated instantly. It executes line by line and it is slow

11.  Linker is a function which links up the files that an present in the operating system, it also links the files for the hardware and makes the system ready for executing.

12.  Preprocessor : This is a program, that processes the source program before it is passed on to the compiler. The program typed in the editor is the source code to the preprocessor, then it passed the source code to the compiler. It is not necessary to write program with preprocessor & activity Preprocessor directories are always initialized at the beginning of the program. it begins with the symbol (#) hash. It place before the main() function

Eg: # include <station>  # define PI 3.14

13.  Write notes on C character Set?
Character Set : The characters that can be used to form words and expressions depends upon the computer to which the program is run
            The Characters in C are
1. Letters A-X, a-z, both upper and lower
2. Digits 0-9
3. Special character, +,-,*,”,;,./,
4. which spaces newline, horizontal tab;,carriage return ,blank space


14.  “C” Tokens: Individual words and punctuation marks are characters. In a “C” program the smallest individual units are known as “C” tokens. It has 6types of tokens.
15.  Keywords : Keywords are reserved words by compiler. Keywords are assigned with fixed meaning and they cannot be used as variable name. No header file is needed to include the keywords. There are 32 keywords Eg : auto, break, double, int, float.
16.  Identifiers : These are the names of variables ,functions and arrays, these are the user defined names Eg : # define NUM 10 # define A 20 “NUM”, “A” are user – defined id
17.  Constants : constants in “C” are applicable to the values which not change during the execution of a program.
18.  Integer Constants : Sequence of numberr 0-9 without decimal points, fractional part or any other symbols. It requires two or four bytes, can be +ve, -ve or Zero the number without a sign is as positive. Eg: -10, +20, 40
19.  Real Constants : Real constants are often known as floating constants. Eg: 2.5, 5.521, 3.14 etc
20.  Character Constants Single character const : A single character constants are given within a pair of single quote mark. Eg : „a, „8, etc.
21.  String Constant : These are the sequence of character within double quote marks Eg : “Straight” “India”, “4”
22.  Variables : This is a data name used for storing a data, its value may be changed during the execution. The variables value keeps changing during the execution of the program Eg : height, average, sum, etc.
23.  Data types: C language is rich in data types ANSI – American National Standard Institute ANSI C Supports Three classes of data types.
1. Primary data type(fundamental)
2. Derived data types
3. User defined data types
24.  All “C” compiler supports 5 fundamental data types
1. Integer (int)
2. Character (char)
3. floating point (float)
4. double-precession (double)
5. void





25. 

26.  Operator: An operator is a symbol that tells the Computer to perform certain mathematical or logical manipulations.

27.  Expression: An expression is a sequence of operands and operators that reduces to single value Eg: 10+25 is an expression whose value is 35

28.  Types of Operators?
ANS:  C operators can be classified into a no. of categories. They include:
1. Arithmetic
2. Relational
3. Logical
4. Assignment
5. Increment and Decrement
6. Conditional
7. Bitwise
8. Special

29.  Arithmetic Operators: C provides all the basic arithmetic operators, they are +, -, *, /, % Integer division truncates any fractional part. The modulo division produces the remainder of an integer division. Eg: a + b a – b a * b -a * b a / b a % b
30.  Relational Operator: These are the operators used to Compare arithmetic, logical and character expressions.the value of a relational express is either one or zero .it is 1 if one is the specified relation is true and zero if it is false For eg: 10 < 20 is true 20<10 is false

31.  Logical operator : Logical Operators are used when we want to test more than one condition and make decisions. here the operands can be constants, variables and expressions Logical operators are &&, ||, ! Eg: a > b && x = = 10 Logical or compound relational Expression Truth Table && ||, !
32.  Assignment Operator: Used to assign the result of an expression to a variable. „= „is the assignment operator. In addition C has a set of „short hand assignment operators of the form
Var Op = Exp
33.  Increment and Decrement Operators: ++ and - - The Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators Eg : ++x or x ++ == > x+=1 == > x=x+1 . -- x or x- - == > x-=1 == > x=x-1
34.  A Profix operator first adds 1 to the operand and then the result is assigned to the variable on left. A postfix operator first assigns the value to the variable on the left and the increments the operand. Eg: 1) m = 5; 2). m = 5 y = ++m; y = m++ O/P m =6, y=6 m=6, y=5
35.  Conditional operator: is used to check a condition and Select a Value depending on the Value of the condition. Variable = (condition)? Value 1 : Value 2: If the Value of the condition is true then Value 1 is e valued assigned to the varable, otherwise Value2. Eg: big = (a>b)? a:b;
36.  Bitwise operator : are used to perform operations at binary level i. e. bitwise. these operators are used for testing the bits, or Shifting them right or left . These operators are not applicable to float or double. Following are the Bitwise operators with their meanings. Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise Exclusive – OR << Left Shift >> Right Shift ~ Complement
37.  consider a = 13 & b = 6 as 8 bit short int (1byte) << Left Shift a = 13 Binary 00001101 b = 6 00000110 Consider a << 2 which Shifts two bits to left , that is 2 zeros are inserted at the right and two bits at the left are moved out. 00001101 Moved 00110100 Finally the result is 00110100 . Deci 52 (13x4)
38.  WAP to illustrate the use of size of operator main ( ) { int x = 2; float y = 2; printf (“ in size of ( x ) is %d bytes “, sizeof ( x )); printf (“ in size of ( y ) is %d bytes “, sizeof ( y )); printf (“ in Address of x = % u and y = % u “, & x, & y); } o/p sizeof ( x ) = 2 sizeof ( y ) = 4
39.  sizeof operator : is used to find the on. of bytes occupied by a variable / data type in computer memory. eg : sizeof (float) returns 4 int m, x [ 50 ] sizeof (m) returns 2 sizeof ( x ) returns 100 ( 50 x 2 )
40.  comma operator : can be used to link the related expressions together. A comma- linked: list of expressions are evaluated left to right and the value of right-most exp is the value of combined expression.
Eg : value = ( x = 10, y = 5, x = y)

41.  Associativity : when there are more than one operator with same precedence [ priority ] then we consider associativity , which indicated the order in which the expression has to be evaluated. It may be either from Left to Right or Right to Left. eg : 5 * 4 + 10 / 2 1 2 = 20 + 5 3 =25
42.  Type Casting: Normally before an operation takes pace both the operands must have the same type. C converts One or both the operands to the appropriate date types by “Type conversion”. This can be achieved in 3 ways.
43.  Implicit Type conversion : In this the data type /Variable of lower type (which holds lower range of values or has lower precision ) is converted to a higher type (which holds higher range of values or has high precision). This type of conversion is also called “promotion”
44.  Assignment Type Conversion: If the two Operands in an Assignment operation are of different data types the right side Operand is automatically converted to the data type of the left side.
45.  Explicit Type Conversion: When we want to convent a type forcibly in a way that is different from automatic type conversion, we need to go for explicit type conversion. (type name) expression; Type name is one of the standard data type. Expression may be a constant variable Or an expression this process of conversion is called as casting a value. Eg: x = (int) 7.5
46.  Escape Sequences with their ASC|| values Escape Sequence Use ASC|| Value \n New line 10 \b Backspace 8 \f Form feed 12 \ Single Quote 39 \\ Back slash 92 \o Null 0 \ t Horizontal tab 9 \ r Carriage return 13 \ a Alert 7 |? Question marks 63 \“ Double Quote 34
47.  a). scanf ( ) function is used to read values using key board. It is used for runtime assignment of variables. The general form of scanf( ) is scanf(“format String “ , list_of_addresses_of_Variables ); The format string contains - Conversion specifications that begin with % sign Eg: Scan f(“ %d %f %c”, &a &b, &c) „& is called the “address” operator. In scanf( ) the „& operator indicates the memory location of the variable. So that the Value read would be placed at that location.
48.  printf( ): function is used to Print / display values of variables using monitor: The general form of printf( ) is printf(“control String “ , list_of_ Variables );
- Characters that are simply printed as they are
- Conversion specifications that begin with a % sign
- Escape sequences that begin with a „\ sign.
      49.  A computer system consists of hardware and software.
Computer hardware is the collection of physical elements that comprise a computer system.
Computer software is a collection of computer programs and related data that provides the instructions for a computer what to do and how to do it. Software refers to one or more computer programs and data held in the storage of the computer for some purposes.




50.
 1. Operating System
The Operating System (OS) is an interface between the compute software and hardware. The most popular and latest operating systems include Windows XP, Mac, UNIX, Linux, Windows Vista, etc.
2. Application Software
The application software is widely used for accomplishment of specific and precise tasks which is a step ahead than the basic operations or running of the computer system. The application software includes printing documents, and permitting access to internet for web and video conferencing activities. The Application software indirectly does the interaction with the machine to perform all these functions.
3. System Software
System software directly interacts with computer hardware. Some of the examples are the device drivers for CPU, Motherboard, Mouse, Printer, Keyboard, etc. The system software takes the responsibility of control, integration and managing individual hardware machine of the computer.

51.
Algorithm:
An algorithm is a description of a procedure which terminates with a result. Algorithm is a step-by-step method of solving a problem.
Properties of an Algorithm:
1) Finiteness: - An algorithm terminates after a finite numbers of steps.
2) Definiteness: - Each step in algorithm is unambiguous. This means that the action specified by the step cannot be interpreted (explain the meaning of) in multiple ways & can be performed without any confusion.
3) Input: - An algorithm accepts zero or more inputs
4) Output:- An algorithm should produce at least one output.
5) Effectiveness: - It consists of basic instructions that are realizable. This means that the instructions can be performed by using the given inputs in a finite amount of time

52.
Flowchart:
A flowchart is a graphical or pictorial representation of an algorithm.
Each step in the process is represented by a different symbol and contains a short description of the process step. The flow chart symbols are linked together with arrows showing the process flow direction.

53.


54.
Program Development Steps:
1. Statement of Problem
a) Working with existing system and using proper questionnaire, the problem should be explained
clearly.
b) What inputs are available, what outputs are required and what is needed for creating workable
solution, should be understood clearly.
2. Analysis
a) The method of solutions to solve the problem can be identified.
b) We also judge that which method gives best results among different methods of solution.
3. Design
a) Algorithms and flow charts will be prepared.
b) Focus on data, architecture, user interfaces and program components.
4. Implementation
The algorithms and flow charts developed in the previous steps are converted into actual programs in the high level languages like C.

55.

General Structure of a C program:
/* Documentation section */
/* Link section */
/* Definition section */
/* Global declaration section */
main() { Declaration part
Executable part (statements) }
/* Sub-program section */
Ø The documentation section is used for displaying any information about the program like the purpose of the program, name of the author, date and time written etc, and this section should be enclosed within comment lines. The statements in the documentation section are ignored by the compiler.
Ø The link section consists of the inclusion of header files.
Ø The definition section consists of macro definitions, defining constants etc,.
Ø Anything declared in the global declaration section is accessible throughout the program, i.e. accessible to all the functions in the program.
Ø main() function is mandatory for any program and it includes two parts, the declaration part and the executable part.

Ø The last section, i.e. sub-program section is optional and used when we require including user defined functions in the program.

56.

Unformatted I/O functions:
1.getchar():Used to read a character
2.putchar():Used to display a character
3.gets():Used to read a string
4.puts():Used to display a string which is passed as argument to the function