+ All Categories
Home > Documents > UNIT-2-pscp

UNIT-2-pscp

Date post: 18-Feb-2016
Category:
Upload: ranga231980
View: 214 times
Download: 0 times
Share this document with a friend
Description:
C language unit-II
Popular Tags:
56
UNIT - II Problem solving: Problem solving is a mental process that involves discovering, analyzing, and solving problems. The ultimate goal of problem solving is to overcome obstacles and finding the solution that best resolves the issue. That is process of finding solutions for difficult and complex problems. There are 6 steps that should be followed in order to solve a problem: 1. Understand the Problem 2. Formulate a Mathematical Model 3. Development of an Algorithm 4. Representation of an algorithm. 5. Program development (Coding) 6. Testing and debugging 1: Understand the Problem: Success in solving any problem is only possible after we fully understand the problem what we are trying to solve. Specifying the problem requirements forces you to state the problem clearly and unambiguously and to give a clear understanding of what is required for its solution. The main objective of identifying the problem is to eliminate unimportant aspects and to focus on the root problem. This primary investigation of problem understanding is also called as problem definition phase. During problem definition phase, we have to think about “what must be done rather than how to do it”. 2. Formulate a Mathematical Model: The main objective of this phase is to understand the processing part of the problem. Try to think of all possible solutions for the given problem. To find the solution, consider similar problems which are related to our problem and analyze how you have solved them. Formulate the fundamental conservation laws to mathematically describe what is physically occurring. Also define the necessary constitutive relationships (relate variables based on observations) and boundary conditions and/or compatibility constraints.
Transcript
Page 1: UNIT-2-pscp

UNIT - IIProblem solving:

• Problem solving is a mental process that involves discovering, analyzing, and solving problems.• The ultimate goal of problem solving is to overcome obstacles and finding the solution that best

resolves the issue. That is process of finding solutions for difficult and complex problems.

There are 6 steps that should be followed in order to solve a problem: 1. Understand the Problem 2. Formulate a Mathematical Model 3. Development of an Algorithm 4. Representation of an algorithm.5. Program development (Coding)6. Testing and debugging

1: Understand the Problem:

• Success in solving any problem is only possible after we fully understand the problem what we are trying to solve.

• Specifying the problem requirements forces you to state the problem clearly and unambiguously and to give a clear understanding of what is required for its solution.

• The main objective of identifying the problem is to eliminate unimportant aspects and to focus on the root problem.

• This primary investigation of problem understanding is also called as problem definition phase.• During problem definition phase, we have to think about “what must be done rather than how to

do it”.

2. Formulate a Mathematical Model:

• The main objective of this phase is to understand the processing part of the problem.• Try to think of all possible solutions for the given problem.• To find the solution, consider similar problems which are related to our problem and analyze how

you have solved them.• Formulate the fundamental conservation laws to mathematically describe what is physically

occurring. Also define the necessary constitutive relationships (relate variables based on observations) and boundary conditions and/or compatibility constraints.

• Use the laws of physics to develop the governing equations like Algebraic equations, and Integral equations (mathematical equations).

• Now, solve the resulting mathematical equations using Analytical solutions, Numerical or discrete solutions.

• Finally verify how well you have solved the problem by comparing to measurements. (Finding the best mathematical solution).

3. Develop an Algorithm:

Algorithm is basically a set of instructions that (if correct and followed carefully) produce some desired result.

An algorithm is a step by step procedure for solving the problem. If the procedure is formally defined, then it must be implemented using some formal language,

and such a language is often known as a programming language(C, C++, JAVA…….). It is common to have a multiple algorithms(procedures) to tackle the same problem, but the

choice of a particular algorithm must depend on the time complexity and space complexity.

Page 2: UNIT-2-pscp

KEY FEATURES OF AN ALGORITHM:

Any algorithm has a finite number of steps and some steps may involve decision making, repetition, etc. Broadly speaking, an algorithm exhibits three key features that can be given as:

1. Sequence2. Decision3. Repetition

Sequence:Sequence means that each step of the algorithm is executed in the specified order.

Example: An algorithm to add two numbers. This algorithm performs the steps in a purely sequential order.

Step 1: Input the first number as AStep 2: Input the second number as BStep 3: SET SUM = A + BStep 4: PRINT SUMStep 5: ENDFigure D .1 Decision:Decision statements are used when the outcome of the process depends on some condition.

The general form of IF construct can be given asIF condition then process

A condition in this context is any statement that may evaluate either to a true value or a false value. In the above syntax, if the condition is true then the process is executed.For example, IF x = y, then print "EQUAL".

A decision statement can also be stated in the following manner.IF condition

Then process1ELSE process2

This form is popularly known as the if-else construct. Here, if the condition is true then process1 is executed else process2 is executed.

Example: An algorithm that checks if two numbers are equal.

Step 1: Input the first number as AStep 2: Input the second number as BStep 3: IF A = B

Then PRINT "EQUAL" ELSE

PRINT "NOT EQUAL"Step 4: END

2. Write an algorithm to find the largest of two numbers.Step 1: Input first number as AStep 2: Input second number as BStep 3: IF A>B

then PRINT AELSE IF A < B

Page 3: UNIT-2-pscp

then PRINT B ELSE PRINT "The numbers are equal"

Step 4: ENDRepetition:

Repetition which involves executing one or more steps for a number of times can be implemented using constructs like the while, do-while and for loops. These loops execute one or more steps until some condition is true.

Example: An algorithm that prints the first 10 natural numbers.

Step 1: [INITIALIZE] SET I = 0, N = 10Step 2: Repeat Step while I<=NStep 3: PRINT IStep 4: END

4. Representation of an algorithm:

The two most common representations of an algorithm are pseudo code and flowcharts.

FLOWCHARTING

• A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem.

• Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people.

• These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems.

• Once the flowchart is drawn, it becomes easy to write the program in any high level language.

GUIDELINES FOR DRAWING A FLOWCHART• Flowcharts are usually drawn using some standard symbols; however, some special symbols can

also be developed when required.• Some standard symbols, which are frequently, required for flowcharting many computer

programs are shown in below.

Flow chart symbols

Page 4: UNIT-2-pscp

GUIDELINES FOR DRAWING A FLOWCHART

• In drawing a proper flowchart, all necessary requirements should be listed out in logical order.• The flowchart should be clear, neat and easy to follow. There should not be any room for

ambiguity in understanding the flowchart.• The usual direction of the flow of a procedure or system is from left to right or top to bottom.• Only one flow line should come out from a process symbol. • Only one flow line should enter a decision symbol, but two or three flow lines, one for each

possible answer, should leave the decision symbol.• Only one flow line is used in conjunction with terminal symbol.• Write within standard symbols briefly. As necessary, you can use the annotation symbol to

describe data or computational steps more clearly. • If the flowchart becomes complex, it is better to use connector symbols to reduce the number of

flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication.

• Ensure that the flowchart has a logical start and finish.• It is useful to test the validity of the flowchart by passing through it with a simple test data.

ADVANTAGES OF USING FLOWCHARTS• Communication: Flowcharts are better way of communicating the logic of a system to all

concerned.• Effective analysis: With the help of flowchart, problem can be analysed in more effective way.• Proper documentation: Program flowcharts serve as a good program documentation, which is

needed for various purposes • Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and

program development phase.• Proper Debugging: The flowchart helps in debugging process.• Efficient Program Maintenance: The maintenance of operating program becomes easy with the

help of flowchart. It helps the programmer to put efforts more efficiently on that part

LIMITATIONS OF USING FLOWCHARTS

• Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy.

• Alterations and Modifications: If alterations are required the flowchart may require re-drawing completely.

• Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.

• The essentials of what is done can easily be lost in the technical details of how it is done.

Page 5: UNIT-2-pscp

EXAMPLE: ON FLOWCHARTING

1. Draw a flowchart to find the sum of first 50 natural numbers.

2. Draw a flowchart to find the largest of three numbers A, B, and C.

3. Draw a flowchart for computing factorial N (N!)

Page 6: UNIT-2-pscp

5. Program development(coding):

In order for a computer to carry out some task, it has to be supplied with a program, which is an implementation of an algorithm.

This is expressed in a computer programming language; however it is possible (and desirable) to talk and reason about algorithms in higher-level terms.

Developing a correct algorithm can be a significant intellectual challenge – by contrast, coding it should be straightforward.

Coding is implementing the solution of given problem statement which is suitable and selected best problem solution using programming language instructions.

It is an effective, systematic approach to problem solving. By following each step consciously, you can ensure that generating solutions is a fact-driven, objective, and reliable process.

It encourages you to dig deeper to the root cause, allows you to get input from others, to be creative when finding solutions, and to monitor your solutions to make sure they’re working.

The source code consists of the programming statements that are created by a programmer with a text editor or a visual programming tool and then saved in a file.

Example:

/* C program to find largest number using if statement only */ #include <stdio.h> int main(){

float a, b, c; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if(a>=b && a>=c)

printf("Largest number = %.2f", a); if(b>=a && b>=c) printf("Largest number = %.2f", b); if(c>=a && c>=b) printf("Largest number = %.2f", c); return 0; }

6. Testing & Debugging:

Testing is a process used to identify the correctness, completeness, and quality of developed computer software.

It includes a set of activities conducted with the intent of finding errors in software so that it could be corrected before the product is released to the end users. Debugging is the process of correcting the errors that are identified by the testing. Debugging is done by the programmer.Testing is done by the tester.

In simple words, software testing is an activity to check whether the actual results match the expected results and to ensure that the software system is defect free.

There are two fundamental purposes of testing: verifying procurement specifications and managing risk.

First, testing is about verifying that what was specified is what was delivered: It verifies that the product (system) meets the functional, performance, design, and implementation requirements identified in the procurement specifications.

Page 7: UNIT-2-pscp

Second, testing is about managing risk for both the acquiring agency and the system’s vendor/developer/integrator.

The testing program is used to identify when the work has been “completed” so that the contract can be closed, the vendor paid, and the system shifted by the agency into the warranty and maintenance phase of the project.

Test case for finding Factorial of a number:Factorial (n) = 1*2*3 … * n

Example:• Factorial of 5 = 1*2*3*4*5 = 120

Note: Factorial of zero = 1 

What is C?

The C programming language is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs.

Why to use C?

C was initially used for system development work, in particular the programs that make up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:

Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Databases Language Interpreters Utilities

Form of a C Program: (STRUCTURE OF A ‘C’ PROGRAM)

The structure of a C program is a protocol (rules) to the programmer, while writing a C program.

Documentation section (comments)Header file section (processor statements)Global Declarationmain() //Function header statement {

Declaration part; //variable declaration statement (Local declaration)Executable part; //Executable statement

}User defined functions{

Stmt 1;Stmt 2;

Page 8: UNIT-2-pscp

.

.

.Stmt n;

}

1. Documentation Section:

It consists of set of comment lines which include name of a program, author name, creation date and other information. Comments are not necessary in program. These are useful for documentation. Comments are placed in between the delimiters /* and */. The compiler does not execute comments.

a. Single line comments// this is a single line comment

/* This is a single line comment*/

b. Multiline comments

/* This is first line Second line Third line */

Preprocessor statements: (link section)

The preprocessor statement begins with # symbol and is also called the preprocessor directive. These statements instruct the compiler to include C preprocessors such as header files and symbolic constants before compiling the C program. Some of the preprocessor statements are listed below.

Global Declarations

The variables are declared before the main ( ) function as well as user defined functions is called global variables. These global variables can be accessed by all the user defined functions including main ( ) function. This section must be declared outside of all functions.

Main function:

Each and Every C program should contain only one main ( ). The C program execution starts with main ( ) function. No C program is executed without the main function. The main ( ) function should be written in small (lowercase) letters and it should not be terminated by semicolon. Main ( ) executes user defined program statements, library functions and user defined functions and all these statements should be enclosed within left and right braces.

Page 9: UNIT-2-pscp

Declaration Part:

It is used to declare local variables. The declaration part declares all variables that are used in the execution part. Initialization of variables is also done in the section. Variables are declared by using data types. Not only variables, we can also declare arrays, functions, pointers etc. These variables can also be initialized with basic data types.

Executable Part (Program statements):

These statements are building blocks of a program. They represent instructions to the computer to perform a specific task (operations). An instruction may contain input-output statements, arithmetic statements, control statements, simple assignment statements and any other statements. Each executable statement should be terminated with semicolon.

User-Defined Functions:

These are subprograms, generally, a subprogram is a function and these functions are written by the user are called user; defined functions. These functions are performed by user specific tasks and this also contains set of program statements. They may be written before or after a main () function and called within main () function. This is an optional to the programmer.

‘ C’ Character Set:

A character refers to the digit, alphabet or special symbol used to data representation.1. Alphabets: A….Z, a…z2. Digits: 0….93. Special Characters: ~! @ # $ % ^ & * ( ) _ + { } [ ] < > , . / ? \ | : ; " '4. White Spaces: Horizontal tab, Carriage return, new line, form feed

Tokens:

The smallest individual units in a program are known as tokens.

C has the following tokensKeywordsIdentifiersConstantsOperatorsPunctuations

Keywords:

Definition: Keywords are the system defined identifiers (reserved identifiers) and cannot be as the names of the program variables or other user defined program elements (user defined function names).

1. All keywords have fixed meanings that do not change.2. White spaces are not allowed in keywords.3. Keyword may not be used as an identifier.4. It is strongly recommended that keywords should be in lower case letters.

Page 10: UNIT-2-pscp

5. There are totally 32(Thirty Two) keywords used in a C programming.

Identifiers:

Identifiers refer to the names of variables, functions, labels, arrays, structures and various other user-defined elements created by the programmer.

Identifier is the name of a variable that is made up from combination of alphabets, digits and underscore.

The length of these identifiers can vary from one to several characters. The first character must be a letter (alphabet) or an underscore, and subsequent characters must be

letters, digits, or underscores. Here are some correct and incorrect identifier names:

Correct Incorrectcount 1counttest23 test!2gross_sal gross-sal

In C, identifiers may be of any length. However, not all characters will necessarily be significant. C defines two kinds of identifiers: external and internal. An external identifier will be involved in an external link process. These identifiers, called

external names, include function names and global variable names that are shared between source files.

If the identifier is not used in an external link process, then it is internal. This type of identifier is called an internal name and includes the names of local variables.

In C89, at least the first 6 characters of an external identifier and at least the first 31 characters of an internal identifier will be significant.

In an identifier, upper- and lowercase are treated as distinct. Hence, count , Count, and COUNT are three separate identifiers.

An identifier cannot be the same as a C keyword and should not have the same name as functions that are in the C library.

Constants:

Integer Constants:

1. An integer constant must have at least one digit. 2. It must not have a decimal point. 3. It can be either positive or negative. 4. If no sign precedes an integer constant it is assumed to be positive. 5. No commas or blanks are allowed within an integer constant. 6. The allowable range for integer constants is -32768 to 32767.

Page 11: UNIT-2-pscp

Truly speaking the range of an Integer constant depends upon the compiler. For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767. For a 32-bit compiler the range would be even greater.

Ex.: 426 +782 -8000 -7605

Real Constants:

Real constants are often called Floating Point constants. The real constants could be written in two forms—Fractional form and Exponential form.

Following rules must be observed while constructing real constants expressed in fractional form:

A real constant must have at least one digit. It must have a decimal point. It could be either positive or negative. Default sign is positive. No commas or blanks are allowed within a real constant.

Ex.: +325.34 426.0 -32.76 -48.5792

The exponential form of representation of real constants is usually used if the value of the constant is either too small or too large.

In exponential form of representation, the real constant is represented in two parts. The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called exponent.

Following rules must be observed while constructing real constants expressed in exponential form:

1. The mantissa part and the exponential part should be separated by a letter e. 2. The mantissa part may have a positive or negative sign. 3. Default sign of mantissa part is positive. 4. The exponent must have at least one digit, which must be a positive or negative integer. Default

sign is positive. 5. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.

Ex.: +3.2e-5 4.1e8 -0.2e+3 -3.2e-5

Character Constants:

A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to the left.

The maximum length of a character constant can be 1 character.

Page 12: UNIT-2-pscp

Ex.: 'A' 'I' '5' '='

Operators :

Operator is a symbol that is used to perform mathematical operations.

The Assignment Operator:

It is used to assign a value to variable.The general form of the assignment operator is

variable_name = expression;

where an expression may be as simple as a single constant or as complex as you require. C uses asingle equal sign to indicate assignment. The target, or left part, of the assignment must be an object, such as a variable, that can receive a value.

Arithmetic Operators:

It is used to perform arithmetical operations. These operators operate on two operands.It is also called as 'Binary operators'.

Unary minus:

The unary minus multiplies its operand by –1. That is, any number preceded by a minus signswitches its sign.

The Increment and Decrement Operators

The increment operator, ++ adds 1 to its operand and decrement operator, –- subtracts 1to its operand. These are unary operators. (An operator which operates on a single operand is called unary operator)

In other words:

x = x+1; is the same as ++x; and x = X–1; is the same as x––;

Relational operators:

Page 13: UNIT-2-pscp

In the term relational operator, relational refers to the relationships that values can have with one another.

The relational operators allow us to compare two values to see whether they are equal to each other, unequal, or whether one is greater than the other.

It is also used to check conditions. These operators return 1 if condition is true otherwise 0.

Logical operators:

In the term logical operator, logical refers to the ways these relationships can be connected. Sometimes, we have to check more than one condition at a time. In such case logical operators

allow to check more than one condition at a time. C allows usage of three logical operators, namely, &&, || and !. These are to be read as ‘AND’

‘OR’ and ‘NOT’ respectively.

In C, true is any value other than zero. False is zero. Expressions that use relational or logical operators return 0 for false and 1 for true.

The truth table for the logical operators is shown here using 1's and 0's.

The ! Operator (Logical NOT) :

This operator reverses the result of the expression it operates on. For example, if the expression evaluates to a non-zero value, then applying ! operator to it results into a 0. Vice versa, if the expression evaluates to zero then on applying ! operator to it makes it 1, a non-zero value.

Bitwise Operators:

Page 14: UNIT-2-pscp

Bitwise operators are used for manipulation of data at a bit level. These operations are applied to the individual bits of the operands.

They can be directly applied to char, short int and long. Bitwise operations are not used on float , double, long double, void , or other more complex types.

Bitwise Operators

Bitwise operators are used for manipulation of data at a bit level. These operations are applied to the individual bits of the operands.They can be directly applied to char, short int and long. Bitwise operations are not used on float , double, long double, void , or other more complex types.

Ternary operator (The ? Operator):

C contains a powerful and convenient operator that replaces certain statements of the if-then-else form is the ternary operator.

The ternary operator? takes the general form

Exp1? Exp2: Exp3;Where

Exp1 is condition, Exp2is statement followed if condition is true, and Exp3 is statement followed if condition is false.

Page 15: UNIT-2-pscp

The Dot (.) and Arrow (–>) Operators:

In C, the dot (.) and the –> (arrow) operators access individual elements of structures and unions.

sizeof:

sizeof is a unary compile-time operator that returns the length, in bytes, of the variable or parenthesized type specifier that it precedes. For example, assuming that integers are 4 bytes and doubles are 8 bytes, this fragment will display 8 4.

double f;printf("%d ", sizeof f);printf(''%d", sizeof(int));

The & and * Pointer Operators:

A pointer is the memory address of an object. A pointer variable is a variable that is specifically declared to hold a pointer to an object of its specified type.

The first pointer operator is &, a unary operator that returns the memory address of its operand.

The second pointer operator is *, which is the complement of &. The * is a unary operator that returns the value of the object located at the address.

Punctuation and special characters:

The punctuation and special characters in the C character set have various uses, from organizing program text to defining the tasks that the compiler or the compiled program carries out. They do not specify an operation to be performed. Some punctuation symbols are also operators. The compiler determines their use from context.

Examples:

[ ] ( ) { } * , : = ; ..... #

These characters have special meanings in C. The pound sign (#) can occur only in pre-processing directives.

Data Types:

The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted

A data type defines a set of values that a variable can store along with a set of operations that can be performed on that variable.

The types in C can be classified as follows:

S.no Types Data Types

Page 16: UNIT-2-pscp

1 Basic data types int, char, float, double, void

2 User defined data types Enum, structure, union

3 Derived data type array, pointer,function

C89 defines five foundational data types: character, integer, floating-point, double floating-point, and valueless. These are declared using char, int, float, double, and void, respectively.

These types form the basis for several other types. The size and range of these data types may vary among processor types and compilers.

Basic data types in C:

1. Integer data type:

Integer data type allows a variable to store numeric values. “int” keyword is used to refer integer data type.

The storage size of integer data type is 2 or 4 or 8 byte.

It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2 byte (16 bit) of memory will be allocated for int data type.

Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit processor is allocated for int datatype.

int (2 byte) can store values from -32,768 to +32,767

int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.

If you want to use the integer value that crosses the above limit, you can go for “long int” and “long long int” for which the limits are very high.

Note:

We can’t store decimal values using int data type. If we use int data type to store decimal values, decimal values will be truncated and we will get only

whole number.

In this case, float data type can be used to store decimal values in a variable.

Character data type:

Character data type allows a variable to store only one character. Storage size of character data type is 1 byte. We can store only one character using character data type.

“char” keyword is used to refer character data type.

For example, ‘A’ can be stored using char data type. You can’t store more than one character using char data type.

Following table gives you details about standard integer types with its storage sizes and value ranges:

Page 17: UNIT-2-pscp

Type Storage size Value rangechar 1 byte -128 to 127unsigned char 1 byte 0 to 255signed char 1 byte -128 to 127int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295short 2 bytes -32,768 to 32,767unsigned short 2 bytes 0 to 65,535long 4 bytes -2,147,483,648 to 2,147,483,647unsigned long 4 bytes 0 to 4,294,967,295void 0 bytes Value less

Floating point data type:

Floating point data type consists of 2 types. They are,

float double

1. float:

Float data type allows a variable to store decimal values. Storage size of float data type is 4 bytes. This also varies depend upon the processor in the CPU as “int”

data type.

We can use up-to 6 digits after decimal using float data type.

For example, 10.456789 can be stored in a variable using float data type.

2. double:

1. Double data type is also same as float data type which allows up-to 10 digits after decimal.

2. Storage size of float data type is 8 bytes.

Following table gives you details about standard floating-point types with storage sizes and value ranges and their precision:

Type Storage size Value range Precisionfloat 4 bytes 1.2E-38 to 3.4E+38 6 decimal placesdouble 8 bytes 2.3E-308 to 1.7E+308 15 decimal placeslong double 10 bytes 3.4E-4932 to 1.1E+4932 19 decimal places

The void Type

Void is an empty data type that has no value. The void type specifies that no value is available. This can be used in functions and pointers.

It is used in three kinds of situations:

S.N. Types and Description1 Function returns as void

Page 18: UNIT-2-pscp

To specify the return type of a function (when the function returns no value). A function with no return value has the return type as void. For example: void exit (int status);

2Function arguments as voidTo specify the parameters of the function. A function with no parameter can accept as a void. For example, int rand(void);

3

Pointers to void To create generic pointers (void*) For example, a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type.

Type Modifiers:

Except type void, the basic data types may have various modifiers preceding them.

A type modifier alters the meaning of the base type so that it more precisely fit a specific need.

The list of data type modifiers is shown here: signed unsigned long short

The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed and unsigned can be applied to char, and long can be applied to double.

The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int.

Signed and unsigned integers differ in the way that the high-order bit of the integer is interpreted. If you specify a signed integer, the compiler generates code that assumes the high-order bit of an integer is to be used as a sign flag. If the sign flag is 0, the number is positive; if it is 1, the number is negative.

In general, negative numbers are represented using the two's complement approach, which reverses all bits in the number (except the sign flag), adds 1 to this number, and sets the sign flag to 1.

The following sets of type specifiers are equivalent:

Variable:

Page 19: UNIT-2-pscp

Variable is used to store data and the value of a variable may change during program execution. It is opposite to constant.

Variable name is a name given to memory location of a computer where data is stored. All variables must be declared before they can be used.

The general form of a declaration istype variable_list;

Here, type must be a valid data type plus any modifiers, and variable_list may consist of one or more identifier names separated by commas.

Examples:

int i, j, l;short int si;unsigned int ui;double balance, profit, loss;

Rules for variables:

1. Only alphabetic characters, digits and underscores are permitted.2. First character should be letter or alphabet.3. Keywords are not allowed to use as a variable name.4. White space is not allowed.5. C is case sensitive i.e. UPPER and lower case letters are distinct.6. Only underscore, special symbol is allowed between two characters.7. The length of identifiers may be up to 31 characters but only the first 8 characters are significant

by compiler.

C Scopes:

A scope (in any programming) is a region of the program where a variable can have its existence and outside the region that variable cannot be accessed. Therefore scopes are used to determine the visibility of an identifier.

C scopes are divided into 4 types:

Block scope:

In C, block is represented as an area between opening curly brace i.e., { and closing curly brace i.e.,}. However, block scope also extends to function parameters in a function definition. That is, function parameters are included in a function's block scope. Variables with block scope are local to their block.

Page 20: UNIT-2-pscp

In the above code there are three blocks block1,block2 and block3. In the above code one more block which is main function block. If a variable or function has scope only within the block where it has declared then scope of variable or function is called as block scope.

Function prototype scope:

Identifiers declared in a function prototype are visible within the prototype.

Function scope:

Function scope begins with the opening curly brace ‘{‘ of a function and ends with its closing curly brace ‘}’. Function scope applies only to labels. A label is used as the target of a goto statement, and that label must be within the same function as the goto.

Example:#include<stdio.h>void display();int main(){    printf("In MAIN");       goto xyz;    return 0;}void display(){    xyx:;    printf("In DISPLay");}Output: Compilation error

File scope: Starts at the beginning of the file and ends with the end of the file. It refers only to those

identifiers that are declared outside of all functions. File scope identifiers are visible throughout the entire file. Variables that have file scope are global.

Local & Global variables:

In C, variables are divided into two categories based on their scopes:1. local variables2. global variables

Page 21: UNIT-2-pscp

Local variables:

Variables that are declared inside the function of block are called local variables. They can be used only by the statements that are inside the function or block of code and local

variable cannot be accessed by the statements outside the function. That is local variable scope is confined within the block or function where it is declared.

When a local variable is defined, it is not initialized by the system; it has to be initialized by the programmer.

Global variables:

A global variable is a variable that is declared outside of all functions, usually on top of the program.

That is global variable is defined at the top of the program file and it can be visible and modified by any function that may reference (used) it. So, global variables can be accessed by all functions throughout the program.

Global variables are initialized automatically by the system.

Example:

#include<stdio.h>

// Global variablesint A;int B;

int Add(){

return A + B;}

int main(){

int result; // Local variableA = 5;B = 7;result = Add();printf("%d\n",result);return 0;

}

As you can see two global variables are declared, A and B. These variables can be used in main() and Add(). The local variable ‘result’ can only be used in main().

Example 2:

/* Demonstrating Global variables and local variables */#include <stdio.h>int add_numbers( void ); /* function prototype */

/* These are global variables and can be accessed by functions from this point on */

Page 22: UNIT-2-pscp

int value1, value2, value3;

int add_numbers( void ){

auto int result;result = value1 + value2 + value3;return result;

}

main(){

auto int result; //local variablevalue1 = 10;value2 = 20;value3 = 30;result = add_numbers();printf("The sum of %d + %d + %d is %d\n",

value1, value2, value3, final_result);}

Sample Program OutputThe sum of 10 + 20 + 30 is 60

Type Qualifiers:

C defines type qualifiers that control how variables may be accessed or modified. C defines two of these qualifiers: const and volatile. The type qualifiers must precede the type names that they qualify.

const:

Variables of type const may not be changed by your program. (A const variable can be given aninitial value, however.) The compiler is free to place variables of this type into read-only memory (ROM). For example, const int a=10;

The const qualifier is used to tell C that the variable value can not change after initialisation.

const float pi=3.14159;

Now pi cannot be changed at a later time within the program.

Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage.

#include<stdio.h>void main(){const int a=10;printf(“a=%d”,a);}Output: a=10

#include<stdio.h>

Page 23: UNIT-2-pscp

void main(){const int a=10;printf(“a=%d”,a);a=20; //compile error , here a is constant so it does not change its value.}

Output: compile error.

Volatile:

The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program.

For example, a global variable's address may be passed to the operating system's clock routine and used to hold the system time. In this situation, the contents of the variable are altered without any explicit assignment statements in the program.

This is important because most C compilers automatically optimize certain expressions by assuming that a variable's content is unchanging if it does not occur on the left side of an assignment statement; thus, it might not be reexamined each time it is referenced. Also, some compilers change the order of evaluation of an expression during the compilation process. The volatile modifier prevents these changes.

You can use const and volatile together. For example, if 0x30 is assumed to be the value of a port that is changed by external conditions only, the following declaration would prevent any possibility of accidental side effects:

const volatile char *port = (const volatile char *) 0x30;

Storage Classes in C:

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.

Scope: The Scope of a variable is the part of a program in which the variable may be visible or available.

Visibility: The program ability to access a variable from the memory.

Life time: The Lifetime of a variable is the duration of time in which a variable exists in the memory

during execution.

C supports four storage class specifiers:

1. auto2. register3. static4. extern

These specifiers tell the compiler how to store the subsequent variable.

The general form of a variable declaration that uses storage class is shown here:

storage_specifier type var_name;

Page 24: UNIT-2-pscp

Note that the storage specifier precedes the rest of the variable declaration

Storage class is type modifier or qualifier of data types which decides:

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

Automatic Storage Class (auto):

Automatic variables are declared inside a function in which they are to be utilized.

They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic.

Automatic variables are therefore private (local) to the function in which they are declared . Because of this property, automatic variables are also referred to as local or internal variables

“auto” is the default storage class for local variable. An auto variable cannot be declared globally.

Features of an auto variable:

Storage : Memory. Default initial value: An unpredictable value, which is often called a garbage value. Scope: Local to the block in which the variable is defined. Life: Till the control remains within the block in which the variable is defined.

Following program shows how an automatic storage class variable is declared, and the fact that if the variable is not initialized it contains a garbage value.

main( ) {

auto int i, j ; printf ( "\n%d %d", i, j ) ;

} The output of the above program could be... 1211 221

where, 1211 and 221 are garbage values of i and j. Garbage values are unpredictable. Note that the keyword for this storage class is auto, and not automatic.

Scope and life of an automatic variable is illustrated in the following program.

Page 25: UNIT-2-pscp

main( ) {

auto int i = 1 ; {

{ {

printf ( "\n%d ", i ) ; } printf ( "%d ", i ) ;

} printf ( "%d", i ) ;

} }

The output of the above program is: 1 1 1

This is because, all printf( ) statements occur within the outermost block (a block is all statements enclosed within a pair of braces) in which i has been defined. It means the scope of i is local to the block in which it is defined. The moment the control comes out of the block in which the variable is defined, the variable and its value is permanently lost.

To catch my point, go through the following program. main( ) {

auto int i = 1 ; {

auto int i = 2 ; {

auto int i = 3 ; printf ( "\n%d ", i ) ;

}

Page 26: UNIT-2-pscp

printf ( "%d ", i ) ; } printf ( "%d", i ) ;

}

The output of the above program would be: 3 2 1

Note that the Compiler treats the three i’s as totally different variables, since they are defined in different blocks. Once the control comes out of the innermost block the variable i with value 3 is lost, and hence the i in the second printf( ) refers to i with value 2. Similarly, when the control comes out of the next innermost block, the third printf( ) refers to the i with value 1.

Register Storage Class:

A register is a small amount of storage available on the CPU whose contents can be accessed more quickly than storage available elsewhere.

The register storage specifier originally applied only to variables of type int, char, or pointer types.A value stored in a CPU register can always be accessed faster than the one that is stored in main memory. Therefore, if a variable is used at many places in a program it is better to declare its storage class as register.

A good example of frequently used variables is loop counters. We can name their storage class as register.

The features of register storage class are as follows:

Storage : CPU registers. Default initial value: Garbage value Scope: Local to the block in which the variable is defined. Life: Till the control remains within the block in which the variable is defined.

Example:main( ) {

register int i ; for ( i = 1 ; i <= 10 ; i++ )

printf ( "\n%d", i ) ; }

Here, even though we have declared the storage class of i as register, we cannot say for sure that the value of i would be stored in a CPU register. Because the number of CPU registers are limited, and they may be busy doing some other task. In that case variable works as an auto storage class.

Static Storage Class:

As the name suggests, the value of static variables persists until the end of the program. A variable can be declared static using the keyword static like.

static datatype variable_name;

Page 27: UNIT-2-pscp

Static variables may be either an internal type or an external type depending on the place of declaration.

Internal static variables (Local) are those which are declared inside a function. The scope of internal static variables extends up to the end of the function in which they are defined. Internal static variables are similar to auto variables, except that they remain in existence throughout the remainder of the program.

External static variables (Global) are declared outside of all functions and are available to all the functions in that program. The difference between a static external variable and a simple external variable is the static external variable is available only within the file where it is defined while the simple external variable can be accessed by other files.

The features of a variable defined to have a static storage class are as under:

Storage :MemoryDefault initial value: Zero Scope: Local to the block in which the variable is defined.Life: Value of the variable persists between different function calls.

Compare the two programs and their output given below to understand the difference between the automatic and static storage classes.

Page 28: UNIT-2-pscp

The programs above consist of two functions main( ) and increment( ). The function increment( ) gets called from main( ) thrice. Each time it increments the value of i and prints it. The only difference in the two programs is that one uses an auto storage class for variable i, whereas the other uses static storage class.

Like auto variables, static variables are also local to the block in which they are declared.

“The difference between them is that static variables don’t disappear when the function is no longer active. Their values persist. If the control comes back to the same function again the static variables have the same values they had last time around.

In the above example, when variable i is auto, each time increment( ) is called it is re-initialized to one. When the function terminates, i vanishes and its new value of 2 is lost. The result: no matter how many times we call increment( ), i is initialized to 1 every time.

On the other hand, if i is static, it is initialized to 1 only once. It is never initialized again. During the first call to increment( ), i is incremented to 2. Because i is static, this value persists.

The next time increment( ) is called, i is not re-initialized to 1; on the contrary its old value 2 is still available. This current value of i (i.e. 2) gets printed and then i = i + 1 adds 1 to i to get a value of 3.

When increment( ) is called the third time, the current value of i (i.e. 3) gets printed and once again i is incremented. In short, if the storage class is static then the statement static int i = 1 is executed only once, irrespective of how many times the same function is called.

If declared a static variable or function globally then its visibility will only the file in which it has declared not in the other files.

For example:

(a)#include<stdio.h>static float a=144.0f; //global to all functionint main(){    {                                 printf("%d",a); //variable a is visible here.       //printf("%d",b); variable b is not visible here.    }                           printf("%d",a);   //variable a is visible here.    //printf("%d",b);    variable b is not visible here.    return 0;}static int b=5;    //Global to only calculation functionvoid calculation(){    printf("%d",a);   //variable a is visible here.    printf("%d",b);   //variable b is visible here.}   (b) Consider a c program which has written in two files named as one.c and two.c:

//one.c

Page 29: UNIT-2-pscp

#include<conio.h>static int i=25;static int j=5; 

void main(){     sum();   }

//two.c

#include<stdio.h>extern int i; //Declaration of variable i.extern int j; //Declaration of variable j./**Above two lines will search the initialization statement of variable i and j either in two.c (if initialized variable is static or extern) or one.c (if initialized variable is extern) */extern void sum(){    int s;    s=i+j;    printf("%d",s);}

Compile and execute above two file one.c and two.c at the same time:Output: Compilation error: Unknown symbol i and j.

Hence we can say variable i and j which has initialized into two.c is not visible in file one.c. This example proves visibility (scope) of globally declared static variable is file.

Note: In the above example function sum which was declared and defined in two.c has also storage class extern. So we can call from other file (one.c).If it will static then we cannot call function sum since static storage class is only visible to the file where it has declared.

External Storage Class (extern):

‘extern’ is the default storage class of all global variables as well as functions. The life and scope of the extern (global) variable is throughout the program.

Unlike local variables global variables can be accessed by any function in the program. External variables are declared outside a function.

The features of a variable whose storage class has been defined as external are as follows:

Storage: MemoryDefault initial value: Zero Scope (visibility): Global. Life: As long as the program’s execution doesn’t come to an end.

1. Default initial value of extern integral type variable is zero otherwise null. For example:

Page 30: UNIT-2-pscp

#include <stdio.h>char c;int i;float f;char *str;  int main(){

    printf("%d %d %f %s",c,i,f,str);     return 0;

}

Output: 0 0 0.000000 (null)

2. When we use extern modifier with any variables it is only declaration i.e. memory is not allocated for these variable. Hence the following program shows compilation error unknown symbols i.

#include <stdio.h>extern int i;    //extern variableint main(){    printf("%d",i);    return 0;}

Page 31: UNIT-2-pscp

Output: Compilation error, undefined symbol i.

3. To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables.

#include <stdio.h>extern int i=10;    //extern variableint main(){    printf("%d",i);     return 0;}

Output: 10

4. We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally.

#include <stdio.h>int main(){extern int i=10; //Try to initialize extern variable                 //locally.    printf("%d",i);    return 0;}Output: Compilation error: Cannot initialize extern variable.

5. If we declare any variable as extern variable then it searches that variable either it has been initialized or not. If it has been initialized which may be either extern or static* then it is ok otherwise compiler will show an error.

(a)#include <stdio.h>

int main(){

Page 32: UNIT-2-pscp

    extern int i; //It will search the initialization of                  //variable i.    printf("%d",i);    return 0;}int i=20;    //Initialization of variable i.

Output: 20

(b)#include <stdio.h>int main(){extern int i; //It will search the any initialized              //variable i which may be static or               //extern.printf("%d",i);    return 0;}extern int i=20; //Initialization of extern variable i.

Output: 20(c)#include <stdio.h>int main(){extern int i; //It will search the any initialized              //variable i which may be static or               //extern.    printf("%d",i);    return 0;}static int i=20; //Initialization of static variable i.

Output: 20

(d)#include <stdio.h>int main(){    extern int i;   //variable i has declared but not                    //initialized    printf("%d",i);    return 0;}

Output: Compilation error: Unknown symbol i.

6. A particular extern variable can be declared many times but we can initialize at only one time.

Page 33: UNIT-2-pscp

(a)extern int i; //Declaring the variable i.int i=25;     //Initializing the variable.extern int i; //Again declaring the variable i.#include <stdio.h>int main(){    extern int i; //Again declaring the variable i.    printf("%d",i);    return 0;}

Output: 25

(b)

extern int i; //Declaring the variableint i=25;     //Initializing the variable#include <stdio.h>int main(){         printf("%d",i);    return 0;}int i=20; //Initializing the variable

Output: Compilation error: Multiple initialization variable i.

7. We cannot write any assignment statement globally.

#include <stdio.h>

extern int i;int i=10;   //Initialization statementi=25;       //Assignment statementint main(){    printf("%d",i);    return 0;}

Page 34: UNIT-2-pscp

Output: Compilation error

8. If declared an extern variables or function globally then its visibility will whole the program which may contain one file or many files.

For example consider a c program which has written in two files named as one.c and two.c:

//one.cint i=25; //By default extern variableint j=5;  //By default extern variable

//Above two line is initialization of variable i and j.

void main(){        sum();    }

//two.c#include<stdio.h>extern int i; //Declaration of variable i.extern int j; //Declaration of variable j./* Above two lines will search the initialization statement of variable i and j either in two.c (if initialized variable is static or extern) or one.c (if initialized variable is extern)  */

Page 35: UNIT-2-pscp

void sum(){    int s;    s=i+j;    printf("%d",s);}

Compile and execute above two file one.c and two.c at the same time:

Output: 30

Hence we can say variable i and j which has initialized into two.c is also visible in file one.c. This example proves visibility (scope) of globally declared extern variable is program.

Note: In the above example function sum which was declared and defined in two.c has also storage class extern. So we can call from other file (one.c).If it will static then we cannot call function sum since static storage class is only visible to the file where it has declared.

9. An extern variables or functions have external linkage. An external linkage variables or functions are visible to all files.

Table : scope (visibility) and life of a storage classes:

Storage class How it has declared Scope Life timeauto Locally Block Block

Globally - -register Locally Block Block

Globally - -static Locally Block Program

Globally File Program extern Locally Block Program

Globally Program Program

Unformatted console I/O in C

            Unformatted I/O functions works only with character datatype (char). The unformatted Input functions used in C are getch(), getche(), getchar(), gets().

getchar() :it is a simplest console I/O function, which reads a single character from the key board. getchar() accepts one character type data from the keyboard.

Syntax : int getchar(void);

Page 36: UNIT-2-pscp

getchar() function waits until a key is pressed and then returns its value. The key pressed also echoed (displayed) on to the screen.

The getchar() echo’s the character on to the screen, but unfortunately enter key to be typed following the input character.

Example:

void main(){ char ch; printf(“enter the character “); ch=getchar(); //will echo character on the screen ,must be followed by enter key printf(“%c”,ch);}

Problem with getchar()

1. The getchar() is implemented in such a way that , it buffers input until ENTER key is pressed. This is called line-buffered input. (you have to press ENTER before any character is returned).2. getchar() inputs only one character each time it is called, line buffering may leave one or more characters waiting in the input queue.

getch () :

getch() accepts only single character from keyboard. The character entered through getch() is not displayed in the screen (monitor).

syntax : int getch(void);

the getch() function waits for a key press, after which it returns character immediatey.

Example: void main(){ char ch; printf(“enter the character “); ch=getch(); //will not echo character on the screen and no need of enter key printf(“%c”,ch);}

getche() :

Like getch(), getche() also accepts only single character from the keyboard, but unlike getch(), getche() displays the entered character in the screen.

Syntax : int getche(void);

Example: void main()

Page 37: UNIT-2-pscp

{ char ch; printf(“enter the character “); ch=getch(); //will not echo character on the screen and no need of enter key printf(“%c”,ch);}

gets()   :

gets() accepts (reads) string of characters including spaces from the standard Input device (keyboard). gets() stops reading character from keyboard only when the enter key is pressed.

Syntax : char*  gets(char *str);

Where str is a pointer to a character array that receives the characters entered by the user.

Example:

void main(){char str[50];printf(“enter the string”);gets(str);printf(“%s”,str);}

Putchar():

Putchar() writes a character to the screen at the current cursor position. That is putchar() displays one character at a time to the Monitor.

putchar(char ch);

Example: void main(){ char ch; printf(“enter the character “); ch=getchar(); putchar(ch); //display the character on to the screen.}

puts() :

puts displays a single / paragraph of text to the standard output device.

int puts(const char *s);

Example:

void main(){

Page 38: UNIT-2-pscp

char str[50];printf(“enter the string”);gets(str);puts(str);}

Differentiate between global and local variables?

Local Variable Global VariableLocal variables are declared inside a function. Global Variables are declared before the main

function (outside the function).Local Variables cannot be accessed outside the function.

Global Variables can be accessed in any function.

Local Variables are alive only for a function. Global Variables are alive till the end of the program.

They are recreated each time a function is executed or called.

They do not get recreated if the function is recalled.

They are normally implemented using a stack They are implemented by associating memory locations with variable names

What is pseudo code?Pseudo code is an informal program description that does not contain code syntax or underlying

technology considerations.

Pseudo code is an artificial and informal language that helps programmers develop algorithms. Pseudo code is a "text-based" detail (algorithmic) design tool.

The rules of Pseudo code are reasonably straightforward. All statements showing "dependency" are to be indented. These include while, do, for, if, switch. Examples below will illustrate this notion.

Examples:

1.. If student's grade is greater than or equal to 60

Print "passed"else

Print "failed"

Define type modifier:

The data types have some modifiers preceding them. The use of these modifiers changes the meaning of the base type.

On the basis of properties of modifier we can categories the modifier in following eight groups.

1. Size modifier (short and long)2. Signed modifier (signed and unsigned)3. Constant modifier (const)4. Volatile modifier (volatile)5. Storage class (auto, register, static, extern)

Page 39: UNIT-2-pscp

6. Pointer modifier (near, far, huge)7. Function modifier (pascal,cdecl)8. Interrupt (interrupt, not_interrupt*)

What is meant by type castingTypecasting is simply a mechanism by which we can change the data type of a variable, no matter

how it was originally defined. When a variable is typecasted into a different type, the compiler basically treats the variable as of the new data type.

Example

#include<stdio.h>

int main(void){

int a=5,b=8;float c = 0, d = 0;

c = a/b;printf("\n [%f] \n",c);

d = (float)a/(float)b;printf("\n [%f] \n",d);

return 0;}

The output of the above program :[0.000000]

[0.625000]

Explanation:

In the above example, first we divide 'a' by 'b' without typecasting. While in the second attempt we typecast both 'a' and 'b' to float and then divide them.

So, what happens is, in the first attempt, the compiler knows both 'a' and 'b' are integers so it ignores the floating part of the result and stores the result of a/b in a temporary integer variable and then assign the value of this temporary integer variable to 'c'. So despite of 'c' being a float, the final value that 'c' gets is an integer ie '0' in this case.

While in the second attempt, as both 'a' and 'b' are individually typecasted as 'float', so this typecasting makes compiler think as if both 'a' and 'b' are floats, so the compiler retains the floating part of the result and assigns the float value to 'c'.

What is syntax error.

Syntax error is a kind of error which occurs due to spelling, grammar, and rules violation. A syntax error is an error in the source code of a program.For compiled languages syntax errors occur strictly at compile-time. A program will not compile until all syntax errors are corrected.

Page 40: UNIT-2-pscp

Difference between testing and debugging

Testing Debugging

The purpose of testing is to find the error and misconception that led to the programs failure.

The purpose of debugging is to correct the errors which are identified by testing.

Testing starts with known conditions, uses predefined procedures and has predictable outcomes.

Debugging starts from possibly unknown initial conditions and the end cannot be predicted except statistically.

Testing can and should be planned, designed and scheduled.

Procedure and duration of debugging cannot be so constrained.

Testing is a demonstration of error or apparent correctness. Debugging is a deductive process.

Testing proves a programmer's failure. Debugging is the programmer's vindication (Justification).

Testing, as executes, should strive to be predictable, dull, constrained, rigid and inhuman.

Debugging demands intuitive leaps, experimentation and freedom.

Much testing can be done without design knowledge.

Debugging is impossible without detailed design knowledge.

Testing can often be done by an outsider. Debugging must be done by an insider.

Much of test execution and design can be automated. Automated debugging is still a dream.

List out the differences between interpreter and compiler.

COMPILER INTERPRETER

Compiler translates the high level instruction into machine

the interpreter translates the high level instruction into an intermediate code

The compiler executes the entire program at a time. the interpreter executes each and every line (instruction) individually

In a compiler the analyzing and processing time of the program is more.

An interpreter spends less time for the program analyzing and processing.

In case of compiler, the resulting code is executed by the computer.

In an interpreter; another program interprets the resulting code.

The resulting code of the compiler is in the form of machine code or binary.

In case of interpreter the resulting code is in the form of the intermediate code.

Page 41: UNIT-2-pscp

In case of compiler, the resulting code is executed by the computer.

In an interpreter; another program interprets the resulting code.

The execution of the program is fast in the compiler.

In an interpreter the program execution speed is comparatively slow.

Errors are displayed after entire program is checked Errors are displayed after every instruction is interpreted.

Example : C Compiler Example : BASIC

What are escape sequence characters? Explain them?

An escape sequence is a sequence of characters that does not represent itself when used inside a character or string, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly.

In C, all escape sequences consist of two or more characters, the first of which is the backslash, \; the remaining characters determine the interpretation of the escape sequence. For example, \n is an escape sequence that denotes a character.

An escape sequence refers to a combination of characters beginning with a back slash (\) followed by letters or digits. Escape sequences represent non-printable and special characters in character and literal strings.

The following escape sequences are defined in standard C. However, these escape sequences can be used on any system with a C compiler, and may map to different values if the system does not use a character encoding based on ASCII.

Escape sequence

Character represented

\" Double quotation mark

\' Single quotation mark

\? Question mark

\\ Backslash

\a Alarm(beep,bell)

\b Backspace

\f Formfeed

\n New line (Line Feed)

\r Carriage return

Page 42: UNIT-2-pscp

Escape sequence Character represented

\t Horizontal tab

\v Vertical tab

\n is called newline and it takes the cursor to the next line. The new line character '\n' moves to the start of the next line. This character is often mapped to 012 (LF) on ASCII systems.

The horizontal tab character '\t' moves to the next horizontal tabulation on the current line. If currently at or past the last tab, it results in unspecified behavior (Often, this can include moving to the end of the current line, or the start of the next, or to the first tab on the next line.). This character is often mapped to 011 on ASCII.

The vertical tab character '\v' moves to the beginning of the line at the next vertical tabulation. If currently at or past the last vertical tab, it results in unspecified behaviour. This character is often mapped to 013 on ASCII.

\b moves the cursor one position to the left of its current position. The backspace character \b moves to the previous position within the line. This character is often mapped to 010 on ASCII systems.

\r takes the cursor to the beginning of the line in which it is currently placed. The carriage return character '\r' moves to the start of the current line. This character is often mapped to 015 on ASCII.

\a alerts the user by sounding the speaker inside the computer. The alert character '\a' produces an audible or visible alert when output. This character is often mapped to 007 on ASCII systems.

Form feed advances the computer stationery attached to the printer to the top of the next page. The form feed character '\f' starts a new page. This character is often mapped to 014 on ASCII.

Characters that are ordinarily used as delimiters... the single quote, double quote, and the backslash can be printed by preceding them with the backslash.


Recommended