110
Class-:B.Tech-I year Solved Question and Answers of C Q1. What are the different functional units of the computer? Ans-: Digital computer-: A digital computer is an electronic Device which can input, store, process raw data and produce meaningful information as output under the program control. Following is the diagram of the Digital Computer A computer system consists of hardware and software. A hardware refers to any physical, electrical, electromechanically components of the computer. For example keyboard, mouse, cabinet of computer is considered as hardware. A software refers to a program or set of instructions that is written to achieve a specified task. A computer system has five basic functional units which are listed below a) Input Unit b) Output Unit c) Control Unit d) Registers central processing unit e) Arithmetic Logic Unit f) Memory unit Input unit: The input device is used to enter data and information into a computer. The devices like keyboard, mouse and scanner are commonly used as input devices. A keyboard is used to enter alphanumeric characters and symbols. The mouse is used to pick or select a command 1

Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

  • Upload
    letu

  • View
    212

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Class-:B.Tech-I yearSolved Question and Answers of C

Q1. What are the different functional units of the computer?

Ans-: Digital computer-: A digital computer is an electronic Device which can input, store, process raw data and produce meaningful information as output under the program control. Following is the diagram of the Digital Computer

A computer system consists of hardware and software. A hardware refers to any physical, electrical, electromechanically components of the computer. For example keyboard, mouse, cabinet of computer is considered as hardware. A software refers to a program or set of instructions that is written to achieve a specified task.

A computer system has five basic functional units which are listed below

a) Input Unitb) Output Unitc) Control Unit d) Registers central processing unite) Arithmetic Logic Unit

f) Memory unitInput unit: The input device is used to enter data and information into a computer. The devices like keyboard, mouse and scanner are commonly used as input devices. A keyboard is used to enter alphanumeric characters and symbols. The mouse is used to pick or select a command from the monitor screen. A scanner is used to scan an image or read a barcode and so on.Central Processing Unit: The processing unit comprises a processor which interprets the program instructions in memory, controls the flow of data and performs arithmetic and logical operations. The program instructions are processed one at a time along with the necessary data. The results are sent to memory and the next instruction is processed. This method is repeated until the program is executed.

Arithmetic and Logic unit: The arithmetic-logic unit (ALU) is the unit of the computer that performs arithmetic and logical operations on the data. This section of the machine can be relatively small consisting of circuits and registers which perform arithmetic (+, -, *, /) and logic (>,<,<=,>=,etc) operations. Arithmetic-logic units which can add and

1

Page 2: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

subtract and perform logical operations form the backbone for the arithmetic and control operations in computers. To perform scientific calculations the floating-point number system is used.

Control unit: The control unit controls the overall activities of the components of the computer. It is mainly used to coordinate the activities among other units. It will send commands signals and controls the sequence of instructions to be executed. The control unit may be defined as “the parts that effect the retrieval of instructions in proper sequence and application of the proper signals to the arithmetic unit and the other parts”. The function of the control circuitry in a general purpose computer is to interpret the instruction words and then sequence the necessary signals to those sections of the computer that will cause it to perform the instructions.

Memory Unit: The memory unit is the unit where all the input data and results stored. The CPU memory is also called as memory register. The memory of a computer is also available in the form of Random Access Memory (RAM). RAM is a semiconductor chip. RAM is considered as a volatile memory, it means as long power is supporting information stored in it remain. Once the power is lost, the information stored in the RAM also get erased. Microcomputers contains read Only Memory (ROM). ROM contains instructions for the microcomputers. Microcomputers use ROM, programmable read only memory (PROM), and erasable programmable read-only memory (EPROM) to store selected application programs. The contents of ROM are determined when the chips are manufactured. The ROM memory is considered as non volatile, means the information is not get erased even when power is failed. The most important ROM chip(s) we should know about is the Basic Input/output system or BIOS. The BIOS is a collection of small computer programs built into a ROM chip.

On computer there are three types of memory. They are 1) Primary memory-:this memory is the main memory of the computer system.

Example is RAM. These are of two types Static and dynamic

2) Secondary Memory-: This memory stores the data permanently in the computer system. Example are hard disk, cd etc.

3) Cache memory -; this is the small memory of the computer system. This is used to speed up the computer

Output Unit:The output device is used to display or print result from a computer.

Monitor, printer and plotter are commonly used output devices. A monitor is used to display the used to plot or print graphical result from a computer. Note that a result displayed in a monitor is temporary and it disappears when the next result is displayed, whereas the output printed using a printer or a plotter is permanent and these printouts can be used for any business correspondence or documentation. Normally soft copy is referred to information that is stored on the storage device. A hard copy refers to a print out showing the information.

2

Page 3: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q2. What is the difference between the flowchart and the algorithm. Explain it with Example

Ans. An algorithm is a precise specification of a sequence of instructions to be carried out in order to solve a given problem. Each instruction tells us what task is to be performed. While flowchart is pictorially representation of any algorithm by the help of some symbols . It may be possible to misunderstand the algorithm due to its ambiguous language but in the flowchart there is a clear understanding of the solution of the problem. But algorithm is the first step for the solution of any problem while the flowchart is the step cam next after the algorithm development . Lets see the flowchart and the algorithm for calculation the average age of the student in the class.

3

Page 4: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q3. What do you mean by data types in C. what are the different data type available in C

Ans Data types-; A data type define the set of values that a variable can store laong with the set of operations that can be carried out on that variable. When we use a particular data type it tells the us the following

How much space is need to store that type of data What is the type of value will be stored in that location

There are following types of Data types

(a) Primary Data types-: There are four types of the primary data types viz int, char and float.

Integer types:

Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32768 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number. To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space.

Syntax:        int <variable name>; likeint num1;short int num2;long int num3;

Example:      5, 6, 100, 2500.

Integer Data Type Memory Allocation4

Data Types

Primary data types Derived data types User defined data types

Page 5: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Floating Point Types:

The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space.

Syntax:          float <variable name>; likefloat num1;double num2;long double num3;

Example:      9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:

Character type variable can hold a single character. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.

Syntax: char <variable name>; likechar ch = ‘a’;

Example:      a, b, g, S, j.

Void Type:

The void type has no values therefore we cannot declare it as variable as we did in case of integer and float.

The void data type is usually used with function to specify its type. Like in our first C program we declared “main()” as void type because it does not return any value. The concept of returning values will be discussed in detail in the C function hub.

5

Page 6: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Derived data types-: The derived data types are those data types which are built in combination with the fundamental data types like long int , short int, double unsigned, signed etc.

User defined Data types-: There are some following data types defined by the user only. Some examples of user defined data types are structures, arrays, enumerated datatypes. Some of them are dicussed below.

Structures-: These are the set of elements of same or different data types stored in the continuous memory locations. Example of structures are as follows

Struct stud

{

int roll;

char name[10];

}

Enumerated Types (enum)

An enumerated data type is a list of possible values, each of which is assigned a sequential number. This allows us to write code that can compare values easily. So, for our Boolean example:

typedef enum {FALSE, TRUE} Boolean;

This tells the compiler that we would like a Boolean type that evaluates to FALSE, or TURE. The compiler will assign the values 0 and 1 to these new types, enabling comparisons such as:

Boolean bResult;// ... Some code ...if (bResult == FALSE) { printf ("False\n"); }

6

Page 7: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q4. What are the different storage classes in c? Explain it with Example.

Ans.4. A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. From C compiler’s point of view, a variable name identifies some physical location within the computer where the string of bits representing the variable’s value is stored. There are basically two kinds of locations in a computer where such a value may be kept— Memory and CPU registers. It is the variable’s storage class that determines in which of these two locations the value is stored.

Moreover, a variable’s storage class tells us:

(a) Where the variable would be stored. (b) What will be the initial value of the variable, if initial value is not specifically

assigned.(i.e. the default initial value). (c) What is the scope of the variable; i.e. in which functions the value of the variable

would be available. (d) What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C:

(a) Automatic storage class (b) Register storage class (c) Static storage class (d) External storage class

Let us examine these storage classes one by one.

Automatic Storage Class

Scope and life of an automatic variable is illustrated in the following program. 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

7

Page 8: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Register Storage Class

A value stored in a CPU register can always be accessed faster than the one that is stored in 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.

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. Why? Because the number of CPU registers are limited, and they may be busy doing some other task.

Static Storage Class

8

Page 9: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

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.

External Storage Class

9

Page 10: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

External variables differ from those we have already discussed in that their scope is global, not local. External variables are declared outside all functions, yet are available to all functions that care to use them. Here is an example to illustrate this fact. int i ; main( ) { printf ( "\ni = %d", i ) ; increment( ) ; increment( ) ; decrement( ) ; decrement( ) ; } increment( ) { i = i + 1 ; printf ( "\non incrementing i = %d", i ) ; } decrement( ) { i = i - 1 ; printf ( "\non decrementing i = %d", i ) ; }

The output would be: i = 0 on incrementing i = 1 on incrementing i = 2 on decrementing i = 1 on decrementing i = 0

As is obvious from the above output, the value of i is available to the functions increment( ) and decrement( ) since i has been declared outside all functions.

Q5. How many types of operators available in C. Explain each of them with Example.

10

Page 11: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Ans. Operators are the verbs in the language that help the user to perform computations on values. The value that can be operated by these operators are called as operands. Different types of operators are as follows-:(a) Unary operators(b) Arithmetic operators(c) Relational operators(d) Logical operators(e) Assignment operators(f) Conditional operator(g) Bitwise operators

(a) Unary operators -: The increment operator ++ and decrement operator – are unary operators with the same precedence as the unary -, and they all associate from right to left. Both ++ and – can be applied to variables, but no to constants or expressions. They can occur in either prefix or postfix position, with possibly different effects occurring. These are usually used with integer data type.

The general syntax is:++variable|--variable| variable++| variable—

Some examples are++count -kk index++ unit_one--

We use the increment and decrement statements in for and while extensively.

Consider the following examplem=5;

y=++m;In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as

m=5;y=m++;

then the value of y would be 5 and m would 6. A prefix operator first adds to 1 to the operand and then the result is assigned to the variable on left. On the other hand, a postfix operator first assigns the value to the variable on left and then increments the operand.

Similar is the case, when we use ++(or--) in the subscripted variables. That is, the statement a[i++]=10;

is equivalent toa[i]=10;i=i+1;

The increment and decrement operators can be used in complex statements. Example

m=n++ -j+10;Old value of n is used in evaluating the expression. n is incremented after the evaluation.

(b) Arithmetic operators -: C provides all the basic arithmetic operators. The operators +,-,* and / all work the same way as they do in other languages. These can operate on any built-in data type allowed in C. The unary minus

11

Page 12: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

operator, in effect, multiplies its single operand by -1. Therefore, a number preceded by a minus sign changes its sign.

Operator Meaning

+ Addition or unary plus- Subtraction or unary minus* Multiplication

/ Division % Modulo division

(c) Relational operators -: We often compare two quantities and depending on their relation, to take certain decisions. For example, we may compare the age of two persons, or the price of two items, and so on. These comparisons can be done with the help of relational operators.

C supports six relational operators in all. These operators and their meanings are shown below

Relational Operators

Operator Meaning

< is less than> is greater than<= is less than or equal to>= is greater than or equal to= = is equal to!= is not equal to

A simple relational expression contains only one relational operator and has the following form:

ae- 1 relational operator ae-2

ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or combination of them.

Given below are some examples of simple relational expressions and their values:

4.5<= 10 TRUE4.5< 10 FALSE -35>= 0 FALSE

10< 7+5 TRUE a+b == c+d TRUE only if the sum of values of a and b is equal to the sum of values of c and d.

(d) Logical Operators-: C has the following three logical operators.&& logical AND|| logical OR! logical NOT

The logical operators && and || are used when we want to test more than one condition and make decisions.Example:

a>b && x == 10

12

Page 13: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression. Like the simple relational expressions , a logical expression also yields a value of one or zero, according to the truth table shown below. The logical expression given above is true only if a>b is true and x==10 is true. If either (or both) of them are false, the expression is false.

Truth Table

Op-1 op-2 Value of the expressionOp-1 && op-2 op-1

|| op-2

Non-zero Non-zero 1 1Non-zero 0 0 10 Non-zero 0 10 0 0 0

Some examples of the usage of logical expressions are:

1. If(age>55 && salary <1000)2. If (number<0 || number>100)

(e) Assignment operators-: The assignment operator = is used to assign values to a particular variable. Like a=10Where 10 is assigned to a

In addition to the usual assignment operator ‘=’ C has a set of assignment operators called shorthand operators.

Some of the shorthand operators are listed below: =

a+= 10 equal to a=a+10 and so on-=*=/=%=>>=<<=

&=^=!=

Conditional operator-: The conditional expression can be used as a shorthand for some if-else statements. The general syntax of the conditional operator is:

<expression1> ? <expression2> : <expression3>

13

Page 14: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

This is an expression, not a statement, so it represents a value. The operator works by evaluating expression1. If it is true (non-zero), it evaluates and returns expression2 . Otherwise, it evaluates and returns expression3.

The classic example of the ternary operator is to return the smaller of two variables.Every once in a while, the following form is just what you needed. Instead of...if (x < y) {min = x;}else {min = y;}

You just say...min = (x < y) ? x : y;

(g) Bitwise operators -: C includes operators to manipulate memory at the bit level. This is useful for writing lowlevel hardware or operating system code where the ordinary abstractions of numbers, characters, pointers, etc... are insufficient -- an increasingly rare need. Bit manipulation code tends to be less "portable". Code is "portable" if with no programmer intervention it compiles and runs correctly on different types of computers. The bitwise operations are typically used with unsigned types. In particular, the shift operations are guaranteed to shift 0 bits into the newly vacated positions when used on unsigned values.

~ Bitwise Negation (unary) – flip 0 to 1 and 1 to 0 throughout& Bitwise And| Bitwise Or^ Bitwise Exclusive Or>> Right Shift by right hand side (RHS) (divide by power of 2)<< Left Shift by RHS (multiply by power of 2)Do not confuse the Bitwise operators with the logical operators. The bitwise connectivesare one character wide (&, |) while the boolean connectives are two characters wide (&&,||). The bitwise operators have higher precedence than the boolean operators. Thecompiler will never help you out with a type error if you use & when you meant &&. Asfar as the type checker is concerned, they are identical-- they both take and produceintegers since there is no distinct boolean type.

14

Page 15: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q6. What do you mean by conditional statements. Explain it with example. What is the difference between the switch and if else statement.

Ans. The programs are generally executed sequentially. It means statements are executed in the same order in which they appear in the program. But there are many times, we want the instructions to be executed in one situation. The ‘c’ language was capable of performing different sets of actions depending on the circumstances. Depending on the circumstances, the program must have the capability to branch out. The C has three major decision making instructions, the if statement , the if-else statement and the switch statement.

If Statement

The general form of if statement looks like

if ( condition) statement;

The keyword if tells the compiler if the condition is true, then statement should be executed. Suppose if the condition is false, then statement has to be skipped. The following table shows the relation operator used in condition.

== equal!= Not equal to> Greater than< Less than<= Less than or equal to>= Greater than or equal to

The three logical operators used are

&& and|| or! not

&& operator return true when all conditions are evaluated to true. Otherwise it return false. For example

((5 > 4) && ( 2 < 3)) return true.

|| operator return true when one of the condition returns true, otherwise it returns false. For example

((5 > 4) || ( 2 > 4)) return true

! operator is used to negate the result. For example(!(5>4)) return false.

Let us see some of the example.

15

Page 16: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Problem : Given two integer numbers, find out the larger of them.

#include <stdio.h>main(){ float x, y;printf(“ input two numbers\n”);scanf(“%f %f “, &x, &y);if ( x > y)printf(“ x is big\n”);if (y > x)printf(“y is big\n”);}

The if-else statement

The if statement by itself will execute a single statement or a group of statements, when the condition following if is true. It does nothing when it is false. The if-else statement provides the option a statement/s can be executed when the condition is false.

The syntax is

if (condition) statement1;elsestatement2;

If the condition is true , the statement1 is executed. If the condition is false, then statement2 under else part is get executed.

Let us consider an example.

Problem : : Find out a number is even or odd

#include <stdio.h>main(){ int x;printf(“input an integer\n”);scanf(“%d”,&x);if ((x % 2) == 0)printf(“it is even number\n”);elseprintf(“it is odd number\n”);}

Switch statement

This is another form of the multi way decision. It is well structured, but can only be used in certain cases where;

16

Page 17: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (int, long, short or char).

Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.

The C switch allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements:

  switch (expression) {

case item1: statement1; break;

case item2: statement2; break;

case itemn: statementn; break;

default: statement; break;

}

In each case the value of itemi must be a constant, variables are not allowed.

The break is needed if you want to terminate the switch after execution of one choice. Otherwise the next case would get evaluated.

The default case is optional and catches any other cases.

For example:-

          

switch (letter){

case `A': case `E': case `I': case `O': case `U':

numberofvowels++; break;

  case ` ':

numberofspaces++; break;

  default:

numberofconstants++; break;

}

17

Page 18: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Difference between the if else and the switch statement

There are some things that you simply cannot do with a switch. These are:

A float expression cannot be tested using a switch Cases can never have variable expressions (for example it is wrong to say case a +3 : ) Multiple cases cannot use same expressions. Thus the following switch is illegal:

switch ( a ) { case 3 : ... case 1 + 2 :

}

(a), (b) and (c) above may lead you to believe that these are obvious disadvantages with a switch, especially since there weren’t any such limitations with if-else. Then why use a switch at all? For speed—switch works faster than an equivalent if-else ladder. How come? This is because the compiler generates a jump table for a switch during compilation. As a result, during execution it simply refers the jump table to decide which case should be executed, rather than actually checking which case is satisfied. As against this, if-elses are slower because they are evaluated at execution time. A switch with 10 cases would work faster than an equivalent if-else ladder. Also, a switch with 2 cases would work slower than if-else ladder. Why? If the 10th case is satisfied then jump table would be referred and statements for the 10 th case would be executed. As against this, in an if-else ladder 10 conditions would be evaluated at execution time, which makes it slow. Note that a lookup in the jump table is faster than evaluation of a condition, especially if the condition is complex.

If on the other hand the conditions in the if-else were simple and less in number then if-else would work out faster than the lookup mechanism of a switch. Hence a switch with two cases would work slower than an equivalent if-else. Thus, you as a programmer should take a decision which of the two should be used when.

18

Page 19: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q7. What do you mean by looping statement . Explain it with Example. Explain the difference between the while and the do while statement.

Ans. The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through loop control instruction. So, . Whenever we want to execute a group of instruction many times, the concept called loop it comes into the picture.

Suppose we want to display "computer" six times on the screen. We may write a program that is given below

#include <stdio.h>main() { printf("computer\n"); printf("computer\n"); printf(“computer\n”); printf("computer\n"); printf("computer\n"); printf("computer\n"); }

But this becomes complicated when we want to print 100 times “computer” messages.

What you really need is some way of repeating the printf statements without having to write it out each time. The solution to this problem is to use loop statements.

C language provides three types of loop, while, do while and for.

The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.

The do while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once.

The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers.

While statement

We use a while statement to continually execute a block of statements while a condition remains true. The following is the general syntax of the while statement.

while (expression) { statement

19

Page 20: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

}

First, the while statement evaluates expression, which must return a boolean value. If the expression returns true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression returns false.

Let us consider a simple example, to calculate the factorial of a number

#include <stdio.h>main(){ int fact, i,n;printf(“input a number\n”);scanf(“%d”,&n);fact=1;i=1;while ( i <= n){ fact=fact*i; ++i;}printf(“ factorial = %d\n”, fact);}

Do while Statement -: Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at the bottom. Thus, the statements within the block associated with a do-while are executed at least onceSyntax:do { statement(s)} while (expression);Let us consider an example to calculate the factorial using do-while loop.

#include < stdio.h>main(){ int n, fact, i;

printf(“input an integer\n”);scanf(“%d”,&n);fact=1;i=1;do { fact=fact*i; ++i; } while ( i <= n);

printf(“factorial = %d\n”, fact);}

20

Page 21: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

for statement:

The for statement provides a compact way to iterate over a range of values. The general form of the for statement can be expressed as follows.

for (initialization; termination; increment) { statement(s)}

The initialization expression initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false, the loop terminates. Finally, increment is an expression that gets invoked after each iteration through the loop. All these components are optional. In fact, to write an infinite loop, you omit all three expressions.

for ( ; ; ) { //infinite loop ...}

Let us consider an example to calculate the factorial of a number using the for loop.

#include <stdio.h>main(){ int n,fact,i;printf(“enter an integer\n”);scanf(“%d”,&n);fact=1;for (i=1; i<=n; ++i)fact=fact*i;printf(“factorial = %d\n”, fact);}

Difference between the While and do while loop

In the case of the while loop before the compound statement is carried out the condition is checked, and if it is true the statement is obeyed one more time. If the condition turns out to be false, the looping isn't obeyed and the program moves on to the next statement. So we can see that the instruction really means while something or other is true keep on doing the statement.

In the case of the do while loop it will always execute the code within the loop at least once, since the condition controlling the loop is tested at the bottom of the loop. The do while loop repeats the instruction while the condition is true. If the condition turns out to be false, the looping isn't obeyed and the program moves on to the next statement

21

Page 22: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q8. What do you mean by flowcharts. Explain it with example.

Ans. A flowchart depicts pictorially the sequence in which instructions are carried out in an algorithm. Flow charts are used not only as aids in developing algorithms but also to document algorithms.. A flowchart is a common type of diagram, that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.

Following are the symbols used in the flowcharts

(i) Parallelograms are used to represent input and output operations.(ii) Rectangles are used to indicate any processing operation such as storage

and arithmetic(iii) Diamond shaped boxes are used to indicate questions asked or

conditions tested based on whose answers appropriate exits are taken by a procedure.

(iv) Rectangles with rounded ends are used to indicate the beginning or end points of a procedure.

(v) A circle is used to join different parts of a flowchart. This is called a connector.

(vi) Arrows indicate the direction to be followed in a flowchart.

Flowchart depicting the largest of three numbers. - A

22

Page 23: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q9. What is the difference between the structures and the arrays. Explain it with Example.

Ans. 9 Both the arrays and structures are classified as structured data types as they provide mechanism that enable us to access and manipulate data in a relatively easier manner. But they differ in number of ways .Difference between the structure and arrays

1. An array is a collection of related data elements of same type (homogenous) while the structure can have different data types(heterogeneous).

2. An array is a derived data type while the structure is a programmer defined data type

3. an array behaves like built in data type. All we have to do is to declare an array variable and use it. But in the case of a structure, first we have to design and declare a data structure before the variables of that type are declared and used.

4. An array element is reference by its position, whereas each element of the structure has a unique name.

Following are the syntax of the array declaration

Data type array_name[index];

Example

int a[10];

Above array is the type of int and having ten members of common nameFollowing are the syntax of the structure declarationstruct struct_name{member 1member2;member3;};Example:

Struct student{

int roll;char name[10];

};Above structure have two elements of different type . Each element having different name.

23

Page 24: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q10. What are the various input and output devices available in computer.

Ans. Following are some input and output units of the computer

Input devices

2.1.1 Keyboard: A keyboard is an input device used to enter data into a computer. The keyboard contains function keys, numeric keys and toggle keys (caps lock, num lock, scroll lock) and so on. Some keyboard supports 100 and some support 104 keys.A keyboard is used to enter data into a computer. The latest keyboard (Windows keyboard) is available with 104 keys. The keyboard contains function keys, numeric keys and toggle key (Caps lock, Num lock, Scroll lock) and so on.

Figure 2.1 shows the diagram of a keyboard with various parts.

It is the most widely used input device. it has keys similar to a typewriter to enter characters and other symbols. The function keys are used to activate a particular feature of software like invoking the help system, selecting a menu and so on.

There is a separate numeric keypad to enter numeric keypad to enter numeric data. When a key is pressed the electric circuitry under the key will change which will be detected by the microprocessor and the binary code for the character is sent to the CPU. Some keyboards have a temporary memory or buffer to store the information typed a little ahead of the need of the computer.2.1.2 Mouse:

A mouse is an input device used to select a command by moving it in any direction on a flat surface. It has two or three buttons to confirm the selection.

Figure 2.2 shows the picture of a mouse.

The software developed with graphical interface requires the mouse. The cursor is moved to the required icon or menu on the monitor and a button is pressed. The control is sent to the CPU to select the command corresponding to the icon or menu item. The latest is the wireless mouse or remote mouse which works on transmission of infrared or radio waves are also available.

The mouse can also be used to open menus, select text for editing, move objects on the screen and draw images or diagrams. The mechanical mouse uses a rubber-coated ball on the underside. The movement of this ball sends electrical signals to the system unit which cause the cursor or pointer to move in a corresponding fashion. An optical mouse uses diodes to emit light onto a metal pad performing the same work but with great accuracy.

24

Page 25: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

2.1.3 Scanners:A peripheral input device used to assist in the entry of data into a computer

system. In desktop publishing, a scanner may be used to digitize artwork or photographs so that they can be merged with text. Scanners are used to scan a printed page or an illustration. These data are then converted into bit patterns for processing storage or output. When an image is scanned, it is converted into light and dark picture elements or pixels. The scanned images are used for word processing and printing multiple copies. Scanners are also useful to scan fingerprints. The scanned fingerprints can be compared with another fingerprint to find probable match in investigative services. Photoelectric scanners are commonly used in supermarkets to read barcodes.

Figure 2.3 shows the diagram of a scanner.

Scanners are available in different sizes. A handheld scanner is used to scan a few lines of text or a small photograph. A page scanner is used to scan a drawing or page.

The scanner is connected to the computer using a cable and controlled by software.

25

Page 26: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

2.2 Output devices:

Hard copy:

The data consisting of text or graphics that is obtained as printouts or microfilm using printers or plotters is known as hardcopy.

For example, the hardcopy of an engineering drawing is obtained using plotters. Some hardcopy devices include dot matrix printer, laser printer, inkjet printer , flatbed pen plotter and drum type inkjet plotter.

A combination of printing, scanning, copying and/or faxing can also obtain a hardcopy. A hardcopy can be used for business correspondence and documentation. A copier machine also comes under hardcopy devices.

Soft copy:

The data that is stored in a storage device such as floppy disk, hard disk, CD-ROM magnetic tape and so on is called softcopy.

The data in a softcopy may be modified using the relevant software. A few softcopy devices are monitor and floppy disk.

2.2.1 Printers:A printer is an output device used to print text or graphics on paper or on

any other hardcopy medium which includes even microfilm. A permanent copy from the computer is produced using the printer. Printers are of two basic types impact and non-impact.

Impact and Non-impact printers:Printers are categorized based on the physical contact of the print head with

the paper to produce a text or an image. An impact printer is one where the print head will be in physical contact with the paper. In a non–impact printer, on the other hand the print head will have no physical contact with the paper. The Dot matrix printer is considered as a Impact printer and Laser printer is considered as Non-impact printer.

The basic operations performed by a printer are:1) Moving the paper to a given line.2) Moving the print head along the line.3) Generating the character or image.4) Producing the character or image on the paper.

2.2.2 Dot Matrix Printer:

The most popular kind of printer for small computers is the dot matrix printer, which forms characters as arrays of dots. Dot matrix printers are compact, reliable and relatively fast. This type of printer is an impact printer. The print head is the important hardware which produces the character using pins arranged in a matrix form. Normally a print head has 9 pins or 24 pins arranged in a matrix form. Combinations of pins strike an ink bed ribbon during the printing process. The print head moves in a line and the pattern of dots required for each character is printed on the paper. After printing a line, the paper rolls to print the next line.

26

Page 27: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Figure 2.4 shows the diagram of a dot matrix printer.

Dot matrix printers produce average quality prints and as generally used in business applications. They are used printing train number, seat number etc on a railway reservation ticket. The speed of printing in dot matrix printer in dot matrix is measured in characters per second (cps).

The advantages in this type of printer is carbon copies can be obtained as printing takes place by physical impact with the paper. It is less of cost and easy to maintain.

The disadvantage is average printing quality and printer ribbon printer ribbon needs to be changed frequently.

2.2.3 Laser Printer:Laser printers are fastest type of non impact electrostatic printers. They

produce high quality prints at high speeds. It operates like a copier machine. In these printers, the controlled beam of intense laser forms images on an electrically charged rotating drum. The drum is rotated near the fine black powder called the toner. These charged images which sticks to the paper due to pressure and heat. The toner consists of oppositely charged ink particles which stick to the drum in the places where the laser has charged.

Figure 2.5 shows the diagram of a laser printer.

The light beam strikes a multi-sided rotating mirror. As the mirror rotates, the side currently in the path of the light beam sweeps the beam across the surface of the

27

Page 28: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

drum. As the beam sweeps across the drum, the light is modulated and a single line is drawn after a line has been drawn, the next side of the mirror is in place and a new line is drawn below the previous line. The quality of the printout is measured by the number of dots per inch (dpi). Since the dots are printed closely, the text or graphics appears very smooth and elegant. The speed is measured in number of pages printed per minute (PPM) which varies between 5 and 25.

The advantages are good quality printouts can be obtained for documentation and business applications. The printing is faster and easy to handle and maintain. The disadvantages are the price is high and higher print cost.

2.2.4 Inkjet printer:

An inkjet is a non impact printer. It sprays tiny drops of ink to form character and graphic images on paper. The text and graphics printed in an inkjet printer are technically similar to that of a dot matrix printer. These type of printers can also be used color printing. The black inkjet printer uses black cartridge filled with black ink whereas the color printer uses four color cartridges namely cyan (blue), magenta (red), yellow and black. These four colors are used in combination to generate any color in the visible spectrum.

The print heads move across the page by the control of software and spray the dots of ink with the required combination of colors. The printer sends electrical pulses to thin resistors at the base of firing chambers behind the nozzle. A thin layer of ink is heated by the resistor which in turn forms a vapour bubble and the expansion forces ink through the nozzle and onto the paper at a rate of about 6000 dots per second. The quality of the printout is equivalent to that of laser printouts. The speed of printing is slower than that of laser printers.

The advantages of this type printer are the cost is low; quality of printing is equivalent to that of laser printing, color printouts are cheaper easy to handle and maintain.

The disadvantages are the ink cartridges may get spoiled if unused for a long time. Some inkjet printers are very expensive.

2.2.5 Plotters:A plotter is an output device used to print engineering drawing or graphics

on large size sheets. These are also used to draw the patterns from which microprocessors, memory chips, and other integrated circuits are manufactured. Plotters are used when highest quality and greatest accuracy are required.

Figure 2.9 shows the diagram of a Plotter.

28

Page 29: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

There are two basic types of plotters: flat bed plotters and drum type plotters. Pen plotter is an example of a flatbed plotter. Laser plotter and inkjet plotter are commonly used drum type plotters.

A pen plotter has a surface where the paper or drawing sheet is properly fixed. It has a pen holder in a movable arm. Under the control of the computer the arm with the pen moves across the paper to draw the picture. A few pens are also placed in a row and the arm will pick the required color pen as per the instruction of the computer.

A drum type plotter uses a drum where the paper will be rolled. It has a print head/pen that moves like the print head in a printer. Drum type plotters are capable of producing longer, continous drawings. Drum type plotters that can produce color plots are available.

The disadvantages are these are expensive than printers. The cost of printing is high. Cost of maintenance is high. High skill of operation is required. Process time of printing is longer.

29

Page 30: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q11. What do you mean by pointers. What are the use of & and * operators. Explain it with example. Also explain the pointer arithmetic.

Ans. Pointers -: A pointer is a variable which stores the address of the another variable. A pointer in C is the address of something. It is a rare case indeed when we care what the specific address itself is, but pointers are a quite common way to get at the contents of something. The unary operator ‘&’ is used to produce the address of an object, if it has one. Thus

int a, b;b = &a;

puts the address of a into b. We can’t do much with it except print it or pass it to some other routine, because we haven’t given b the right kind of declaration. But if we declare that b is indeed a pointer to an integer, we’re in good shape:

int a, *b, c;b = &a;c = *b;

b contains the address of a and ‘c = *b’ means to use the value in b as an address, i.e., as a pointer. The effect is that we get back the contents of a, albeit rather indirectly. (It’s always the case that ‘*&x’ is the same as x if x has an address.)

Consider the declaration,

int i = 3 ;

This declaration tells the C compiler to:

(a) Reserve space in memory to hold the integer value. (b) Associate the name i with this memory location. (c) Store the value 3 at this location.

We may represent i’s location in memory by the following memory map.

We see that the computer has selected memory location 65524 as the place to store the value 3. The location number 65524 is not a number to be relied upon, because some other time the computer may choose a different location for storing the value 3. The important point is, i’s address in memory is a number.

We can print this address number through the following program:

main( ) { int i = 3 ;

30

Page 31: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; }

The output of the above program would be:

Address of i = 65524 Value of i = 3

The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.

Observe carefully the output of the following program:

main( ) { int i = 3 ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", *( &i ) ) ; }

The output of the above program would be:

Address of i = 65524 Value of i = 3 Value of i = 3

Pointer Arithmetic -:

You can perform a limited number of arithmetic operations on pointers. These operations are:

Increment and decrement Addition and subtraction Comparison Assignment

The increment (++) operator increases the value of a pointer by the size of the data object the pointer refers to. For example, if the pointer refers to the second element in an array, the ++ makes the pointer refer to the third element in the array.

The decrement (--) operator decreases the value of a pointer by the size of the data object the pointer refers to. For example, if the pointer refers to the second element in an array, the -- makes the pointer refer to the first element in the array.

You can add an integer to a pointer but you cannot add a pointer to a pointer.

If the pointer p points to the first element in an array, the following expression causes the pointer to point to the third element in the same array:

p = p + 2;

31

Page 32: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

If you have two pointers that point to the same array, you can subtract one pointer from the other. This operation yields the number of elements in the array that separate the two addresses that the pointers refer to.

You can compare two pointers with the following operators: ==, !=, <, >, <=, and >=.

Pointer comparisons are defined only when the pointers point to elements of the same array. Pointer comparisons using the == and != operators can be performed even when the pointers point to elements of different arrays.

You can assign to a pointer the address of a data object, the value of another compatible pointer or the NULL pointer.

Example -;

/* Program to find out the address of the pointer variable before and after incrementing*/

void main(){int a =10, *x;x=&a; printf(“Address of the pointer before incrementing : %u”, x);

x++;

printf(“Address of the pointer after incrementing : %u”, x);

}

Output is

2527

32

Page 33: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q12. What do you mean by typecasting ? how many types of typecasting are there. Explain it by example

Ans. Type casting is conversion of data type into the other allowable data type. There are two types of typecasting are there.

(a) implicit typecasting (b) Explicit typecasting

(a) Implicit typecasting -: this type of typecasting is generally done by the compiler only. Certain rules of Implicit conversion are as follows

An arithmetic operation between an integer and integer always yields an integer result.

An operation between a real and real always yields a real result. An operation between an integer and real always yields a real result. In this

operation the integer is first promoted to a real and then the operation is performed. Hence the result is real.

Example

(b) Explicit typecasting-: this type of typecasting is don manually by the user. One data type is converted into the other allowable data type

For example, consider the following assignment statements. int i ; float b ; i = 3.5 ; b = 30 ;

Here in the first assignment statement though the expression’s value is a float (3.5) it cannot be stored in i since it is an int. In such a case the float is demoted to an int and then its value is stored. Hence what gets stored in i is 3. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in b, since b being a float variable cannot hold anything except a float value.

Instead of a simple expression used in the above examples if a complex expression occurs, still the same rules apply. For example, consider the following program fragment. float a, b, c ; int s ; s = a * b * c / 100 + 32 / 4 - 3 * 1.1 ;

Here, in the assignment statement some operands are ints whereas others are floats. As we know, during evaluation of the expression the ints would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to s it is again demoted to an int and then stored in s.

33

Page 34: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Observe the results of the arithmetic statements shown in below. It has been assumed that k is an integer variable and a is a real variable.

Note that though the following statements give the same result, 0, the results are obtained differently. k = 2 / 9 ; k = 2.0 / 9 ; In the first statement, since both 2 and 9 are integers, the result is an integer, i.e. 0. This 0 is then assigned to k. In the second statement 9 is promoted to 9.0 and then the division is performed. Division yields 0.222222. However, this cannot be stored in k, k being an int. Hence it gets demoted to 0 and then stored in k.

34

Page 35: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q. 13. What do you mean by structured programming.

Ans. Structure programming -:Structured programming (sometimes known as modular programming) is a subset of procedural programming that enforces a logical structure on the program being written to make it more efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBASE are designed with features that encourage or enforce a logical program structure.

Structured programming frequently employs a top-down design model, in which developers map out the overall program structure into separate subsections. A defined function or set of similar functions is coded in a separate module or submodule, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure.

Program flow follows a simple hierarchical model that employs looping constructs such as "for," "repeat," and "while." Use of the "Go To" statement is discouraged.

Structured programming was first suggested by Corrado Bohm and Guiseppe Jacopini. The two mathematicians demonstrated that any computer program can be written with just three structures: decisions, sequences, and loops. Edsger Dijkstra's subsequent article, Go To Statement Considered Harmful was instrumental in the trend towards structured programming. The most common methodology employed was developed by Dijkstra. In this model (which is often considered to be synonymous with structured programming, although other models exist) the developer separates programs into subsections that each have only one point of access and one point of exit.

Almost any language can use structured programming techniques to avoid common pitfalls of unstructured languages. Unstructured programming must rely upon the discipline of the developer to avoid structural problems, and as a consequence may result in poorly organized programs. Most modern procedural languages include features that encourage structured programming. Object-oriented programming (OOP) can be thought of as a type of structured programming, uses structured programming techniques for program flow, and adds more structure for data to the model.

35

Page 36: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q14. What is the difference between the static and dynamic memory allocation . Explain it with Example.

Ans. Difference between the static and dynamic memory allocation

S.No Static memory allocation Dynamic memory allocation1 This memory is allocated

during the compile timeThis memory is allocated during the runtime

2 This is also called as compile time allocation

This also called as runtime allocation

3 The memory requirements are decided by the programmer

The memory requirements are decided by the user.

4 The data is stored in the data segments

The data is stored in the heap

5 It saves the running time It is costly in terms of the running time

6 Memory is allocated by declaring any variable, array or user defined data type like int a;

Memory is allocated by the help of the malloc , calloc funtion

Example of static memory allocation-:

void main(){

int a;a=10;printf(“%d”,a);

}

Example of dynamic memory allocation

void main(){

int *a;a=(int*)malloc(sizeof(int);*a=10;printf(“%d”,*a);

}

36

Page 37: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q15. What do you mean by functions. What is the difference between the call by value and call by reference .

Ans Functions-: A function is a self-contained block of statements that perform a coherent task of some kind. Every C program can be thought of as a collection of these functions. Using a function is something like hiring a person to do a specific job for you. Sometimes the interaction with this person is very simple; sometimes it’s complex..

The function main() is a specially recognized function in C. Every program must have a main function to indicate where the program has to begin its execution. It is possible to code any program utilizing only main function, it leads to a number of problems. The program may become too large and complex and as a result the task of debugging, testing and maintaining becomes difficult. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprograms called ‘functions’ are much easier to understand, debug, and test. Sometimes it is also called “divide and conquer “.

There are times when some type of operation or calculation is repeated at many points throughout a program. In such situations, we may repeat the program statements wherever they are needed. There is another way to design a function that can be called and used whenever required. This saves both time and space.

This approach clearly results in a number of advantages.1. The figure below shows to-down modular programming. In this

programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later.

2. The length of a source program can be reduced by using functions at appropriate places.

3. It is easy to locate and isolate a faulty function for further investigations.4. A function may be used by many other programs.

There are three steps for using a function

(a) Prototyping-: It is used to tell the compiler that a user defined functions is being used in the program. Generally it is done before the main function. The basic syntax of prototyping is

Return type Func_name(parameter list);

Example: int add(int x, int y);

(b) Defination-: It is used to code the function. The actual code is written in this step. Syntax is

Return type func_name(parameter list){statement 1;....statement n;}

37

Page 38: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Example

int add(int x, int y){

int c;c=x + y;printf(“answer is %d”, c);return c;

}

(c) Calling-: Whenever we want to use a function , we have to call that function in the program. The syntax for calling of a function are as follows

Func_name(parameter list);

Example

void main(){

int a,b;a=10; b=20;add(a,b);

}

Complete Example are as follows

int add(int x, int y);void main(){

int a,b;a=10; b=20;add(a,b);

}

int add(int x, int y){

int c;c=x + y;printf(“answer is %d”, c);return c;

}

Call by Value vs. Call by Reference

C passes parameters "by value" which means that the actual parameter values are copied into local storage. The caller and callee functions do not share any memory -- they each have their own copy. This scheme is fine for many purposes, but it has two disadvantages.

1) Because the callee has its own copy, modifications to that memory are notcommunicated back to the caller. Therefore, value parameters do not allow the callee to communicate back to the caller. The function's return value can communicate some information back to the caller, but not all problems can be solved with the single

38

Page 39: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

return value.2) Sometimes it is undesirable to copy the value from the caller to the callee because the value is large and so copying it is expensive, or because at a conceptual level copying\ the value is undesirable. The alternative is to pass the arguments "by reference". Instead of passing a copy of a value from the caller to the callee, pass a pointer to the value. In this way there is only one copy of the value at any time, and the caller and callee both access that one value through pointers.

Some languages support reference parameters automatically. C does not do this – the programmer must implement reference parameters manually using the existing pointer constructs in the language.

Swap ExampleThe classic example of wanting to modify the caller's memory is a swap() function which exchanges two values. Because C uses call by value, the following version of Swap will not work.

void Swap(int x, int y) { // NO does not workint temp;temp = x;x = y; // these operations just change the local x,y,tempy = temp; // -- nothing connects them back to the caller's a,b}

// Some caller code which calls Swap()...int a = 1;int b = 2;Swap(a, b);

Swap() does not affect the arguments a and b in the caller. The function above only operates on the copies of a and b local to Swap() itself. This is a good example of how "local" memory such as ( x, y, temp) behaves -- it exists independent of everything else only while its owning function is running. When the owning function exits, its local memory disappears.

Reference Parameter Technique

To pass an object X as a reference parameter, the programmer must pass a pointer to X instead of X itself. The formal parameter will be a pointer to the value of interest. The caller will need to use & or other operators to compute the correct pointer actual parameter. The callee will need to dereference the pointer with * where appropriate to access the value of interest. Here is an example of a correct Swap() function.

static void Swap(int* x, int* y) { // params are int* instead of intint temp;temp = *x; // use * to follow the pointer back to the caller's memory*x = *y;*y = temp;}// Some caller code which calls Swap()...int a = 1;int b = 2;Swap(&a, &b);

39

Page 40: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q16. what do you mean by sorting and searching. Explain any one technique of sorting and searching by example.

Ans. Sorting-; it is the process of arranging the elements into some logical order. This logical order may be ascending and the descending incase of numeric values or dictionary value order in case of alphanumeric values. Sorting is classified into following categories

(a) Internal sorting-: It deals with the data held in the memory of the computer(b) External Sorting-: It deals with the data stores in the files. This method is

used when the volume of data is very large and cannot be held in computers main memory.

There are so many types of external sorting are there. But here we are discussing the Bubble sort and the selection sort.

Bubble Sort-: It requires n-1 passes to sort an array. In each pass every element a[i] is compared with a[i+1], for i=0 to n-k where k is the pass number and if they are out of order i.e if a[i] > a[i+1] they are swapped. This will cause the largest element move or bubble up. The example of the bubble sorting are as follows-:

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

First Pass:( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.Second Pass:( 1 4 2 5 8 ) ( 1 4 2 5 8 )( 1 4 2 5 8 ) ( 1 2 4 5 8 )( 1 2 4 5 8 ) ( 1 2 4 5 8 )( 1 2 4 5 8 ) ( 1 2 4 5 8 )Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.Third Pass:( 1 2 4 5 8 ) ( 1 2 4 5 8 )( 1 2 4 5 8 ) ( 1 2 4 5 8 )( 1 2 4 5 8 ) ( 1 2 4 5 8 )( 1 2 4 5 8 ) ( 1 2 4 5 8 )Finally, the array is sorted, and the algorithm can terminate.

40

Page 41: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

// Program of bubble sorting

void main{int a, temp, array[5];int n=5;for(a=0;a<n;a++){

printf(“Enter the elements”);scanf(“%d”,&array[a]

}

for(int x=0; x<n; x++)

{

for(int y=0; y<n-1; y++)

{

if(array[y]>array[y+1])

{

temp = array[y+1];

array[y+1] = array[y];

array[y] = temp;

}

}

}

}

Selection sorting-: the selection sorting method also requires n-1 pass to sort an array. In the first pass, find the smallest element from a[0],a[1],..a[n-1] and swap with the first element i.e[a0]. In the second pass, find the smallest element from the elements a[1]…a[n-1] and swap with a[1]. And so on. Here is an example of this sort algorithm sorting five elements:

64 25 12 22 11

11 25 12 22 64

11 12 25 22 64

11 12 22 25 64

11 12 22 25 64

(nothing appears changed on this last line because the last 2 numbers were already in order)

41

Page 42: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

// Program for selection sortvoid selectionSort(int numbers[], int array_size){ int i, j; int min, temp;

for (i = 0; i < array_size-1; i++) { min = i; for (j = i+1; j < array_size; j++) { if (numbers[j] < numbers[min]) min = j; } temp = numbers[i]; numbers[i] = numbers[min]; numbers[min] = temp; }}

Searching-: It is the process of finding the location of given elements in the linear array. The search is said to be successful if the given elements is found the elements does exits in the array, otherwise unsuccessful.There are two approaches of searching

(a) Linear search-: (b) Binary search

Linear search or sequential search-: The Linear Search, or sequential search, is simply examining each element in a list one by one until the desired element is found. The Linear Search is not very efficient. If the item of data to be found is at the end of the list, then all previous items must be read and checked before the item that matches the search criteria is found.

// Program to search an element using linear search

void main{

int a[5], item,i,flag=0;for(i=0;i<5;i++){

Printf(“enter number”);Scanf(“%d”,&a[i]);

}Printf(“Enter the item to be searched”);Scanf(“%d”,&item);for(i=0;i<5;i++){

if(a[i]==item){

printf(“Search is successful”);

exit(0);}

}

printf(“Search is unsuccessful”);}

42

Page 43: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q17. What do you mean by stack and queues. Explain it with proper example.

Ans. Stack-: a stack is a last in, first out (LIFO) abstract data type and data structure. A stack can have any abstract data type as an element, but is characterized by only two fundamental operations: push and pop. The push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A pop either reveals previously concealed items, or results in an empty list.

A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the pop and push operations also means that stack elements have a natural order. Elements are removed from the stack in the reverse order to the order of their addition: therefore, the lower elements are typically those that have been in the list the longest.

So, stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stacks have some useful terminology associated with them:

Push To add an element to the stack Pop To remove an element from the stock Peek To look at elements in the stack without removing them LIFO Refers to the last in, first out behavior of the stack FILO Equivalent to LIFO

Following figure shows the working of stack.

Example of stacks are Function call and return

Perhaps the most important application of stacks is to implement function calls. Most compilers implement function calls by using a stack. This also provides a technique for eliminating recursion from a program: instead of calling a function recursively, the programmer uses a stack to simulate the function calls in the same way that the compiler would have done so. Conversely, we can often use recursion instead of using an explicit stack. Some programming languages provide a mechanism for recursion, but not for calling functions.

43

Page 44: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Queue-: The queue data structure is characterised by the fact that additions are made at the end, or tail, of the queue while removals are made from the front, or head, of the queue. For this reason, a stack is referred to as a FIFO structure (First-In First-Out). Queues occur naturally in situations where the rate at which clients’ demand for services can exceed the rate at which these services can be supplied. For example, in a network where many computers share only a few printers, the print jobs may accumulate in a print queue. In an operating system with a GUI, applications and windows communicate using messages, which are placed in message queues until they can be handled.

The main primitive operations of a queue are known as:

Add adds a new nodeRemove removes a node

Consider the following

44

Page 45: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q18. What do you mean by dynamic memory allocation. Explain its various functions with the example.

Ans. The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this function.

Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management.

Function Task

malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space

calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the memory

free Frees previously allocated space

realloc Modifies the size of previously allocated space.

Memory allocations process:

According to the conceptual view the program instructions and global and static variable in a permanent storage area and local area variables are stored in stacks. The memory space that is located between these two regions in available for dynamic allocation during the execution of the program. The free memory region is called the heap. The size of heap keeps changing when program is executed due to creation and death of variables that are local for functions and blocks. Therefore it is possible to encounter memory overflow during dynamic allocation process. In such situations, the memory allocation functions mentioned above will return a null pointer.

Allocating a block of memory:

A block mf memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:

ptr=(cast-type*)malloc(byte-size);

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

45

Page 46: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Example:

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

On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int

Allocating multiple blocks of memory:

Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:

ptr=(cast-type*) calloc(n,elem-size);

The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.

Releasing the used space:

Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.

free(ptr);

ptr is a pointer that has been created by using malloc or calloc.

To alter the size of allocated memory:

The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :

ptr=realloc(ptr,newsize);

This function allocates new memory space of size newsize to the pointer variable ptr ans returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.

Example is

46

Page 47: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

/*Example program for reallocation*/ #include< stdio.h > #include< stdlib.h > define NULL 0 main() { char *buffer; /*Allocating memory*/ if((buffer=(char *) malloc(10))==NULL) { printf(“Malloc failed\n”); exit(1); } printf(“Buffer of size %d created \n,_msize(buffer)); strcpy(buffer,”Bangalore”); printf(“\nBuffer contains:%s\n”,buffer); /*Reallocation*/ if((buffer=(char *)realloc(buffer,15))==NULL) { printf(“Reallocation failed\n”); exit(1); } printf(“\nBuffer size modified.\n”); printf(“\nBuffer still contains: %s\n”,buffer); strcpy(buffer,”Mysore”); printf(“\nBuffer now contains:%s\n”,buffer); /*freeing memory*/ free(buffer);

47

Page 48: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Q20. What do you mean by macros. Explain it in detail

Ans . Macros -: A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.

You create macros with the `#define' directive. `#define' is followed by the name of the macro and then the token sequence it should be an abbreviation for, which is variously referred to as the macro's body, expansion or replacement list. For example,

#define BUFFER_SIZE 1024

defines a macro named BUFFER_SIZE as an abbreviation for the token 1024. If somewhere after this `#define' directive there comes a C statement of the form

foo = (char *) malloc (BUFFER_SIZE);

then the C preprocessor will recognize and expand the macro BUFFER_SIZE. The C compiler will see the same tokens as it would if you had written

foo = (char *) malloc (1024);

By convention, macro names are written in uppercase. Programs are easier to read when it is possible to tell at a glance which names are macros.

A #define directive is many a times used to define operators as shown below. #define AND && #define OR || main( ) { int f = 1, x = 4, y = 90 ;

if ( ( f < 5 ) AND ( x <= 20 OR y <= 45 ) ) printf ( "\nYour PC will always work fine..." ) ; else printf ( "\nIn front of the maintenance man" ) ; }

The macros that we have used so far are called simple macros. Macros can have arguments, just as functions can. Here is an example that illustrates this fact.

#define AREA(x) ( 3.14 * x * x ) main( ) { float r1 = 6.25, r2 = 2.5, a ; a = AREA ( r1 ) ; printf ( "\nArea of circle = %f", a ) ; a = AREA ( r2 ) ; printf ( "\nArea of circle = %f", a ) ;}

48

Page 49: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

In this program wherever the preprocessor finds the phrase AREA(x) it expands it into the statement ( 3.14 * x * x ). However, that’s not all that it does. The x in the macro template AREA(x) is an argument that matches the x in the macro expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the statement AREA(r1) is equivalent to: ( 3.14 * r1 * r1 )

Macro Versus Function

The difference between the macro and function is significant . In a macro call the preprocessor replaces the macro template with its macro expansion, in a stupid, unthinking, literal way. As against this, in a function call the control is passed to a function along with certain arguments, some calculations are performed in the function and a useful value is returned back from the function.

If we use a macro hundred times in a program, the macro expansion goes into our source code at hundred different places, thus increasing the program size. On the other hand, if a function is used, then even if it is called from hundred different places in the program, it would take the same amount of space in the program.

But passing arguments to a function and getting back the returned value does take time and would therefore slow down the program. This gets avoided with macros since they have already been expanded and placed in the source code before compilation

49

Page 50: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Q21. What do you mean by structures. Explain it with example.

Ans22. . Structures-: It is a group of elements of different data type stored in the continuous memory locations. In other words we can say that it is the collection of heterogeneous type of data. It is a collection of variables referenced under one name , providing a convenient means of keeping related information together. Structure declaration forms a template that may be used to create the structured objects. Structures are the C equivalent of records.

Defining structure

A structure is defined generally at the beginning of the program after the preprocessor declarations. The basic syntax of the structure is the Struct keyword followed by the name of the structure and than the elements.

The basic syntax are as follows

struct Structure_name{member 1;member 2.

};

Where struct is the keyword

Example

Struct Student{int rollnoChar name[10];};

This defines a new type student variables of type student can be declared as follows.

Student st;

50

Page 51: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Accessing Members of a Structure

To return to the examples above, member name of structure st will behave just like a normal array of char, however we refer to it by the name

st.name

Here the dot is an operator which selects a member from a structure.

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 is a pointer to a structure of type Student We would refer to the name member as

st_ptr -> name

Example program-:

#include <stdio.h>#include <conio.h>

struct student {  int id;  char *name;  float percentage;} student1, student2, student3;int main() {  struct student st;  student1.id=1;  student2.name = "Angelina";  student3.percentage = 90.5;  printf(" Id is: %d \n", student1.id);  printf(" Name is: %s \n", student2.name);  printf(" Percentage is: %f \n", student3.percentage);  getch();  return 0;}

51

Page 52: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Q22. What do you mean by arrays. Explain it with example.

Ans. Array-: A group of same data items that share a common name stored in the continuous memory locations is called an array. For example, we can define an array name marks to represent a set of marks obtained by a group of students. A particular value is indicated by writing a number called index number or subscript in brackets after the array name.Example,

Marks[7]

Represents the marks of the 7th student. The complete set of values is referred to as an array, the individual values are called elements. The arrays can be of any data type either int, char or float. The array of characters are also called strings. There are following types of arrays.

One-dimensional array:When a list of items can be given one variable name using only one subscript and

such a variable is called a single-subscripted variable or one dimensional array.

In C language ,single-subscripted variable xi can be represented asx[1],x[2],x[3]……………x[n]

The subscripted variable xi refers to the ith element of x. The subscript can begin with number 0. For example, if we want to represent a set of five numbers, say (57,20,56,17,23), by a array variable num, then we may declare num as follows

int num[5];

And the computer reserves five storage locations as shown below:

Num[0]Num[1]Num[2]Num[3]Num[4]

The values can be assigned as follows:Num[0]=57;Num[1]=20;Num[2]=56;Num[3]=17;Num[4]=23;

The table below shows the values that are stored in the particular numbers.

52

Page 53: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Num[0] Num[1]Num[2]Num[3]Num[4]

Two dimensional arrays:There are certain situations where a table of values will have to be stored. C

allows us to define such table using two dimensional arrays. Two dimensional arrays are declared as follows:

dataType array_name [row_size][column_size]In c language the array sizes are separated by its own set of brackets.

Two dimensional arrays are stored in memory as shown in the table below. Each dimension of the array is indexed from zero to its maximum size minus one; the first index selects the row and the second index selects the column within that row.

Column0 Column1 Column2

[0][0] [0][1] [0][2]

Row 0 210 340 560

[1][0] [1][1] [1][2]

Row 1 380 290 321

[2][0] [2][1] [2][2]

Row2 490 235 240

Row3 [3][0] [3][1] [3][2]

240 350 480

53

57 20561723

Page 54: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Declaration and initialization of arrays:

The arrays are declared before they are used in the program. The general form of array declaration is

Data type variable_name[size];

The type specifies the type of element that will be contained in the array, such as int,float,or char and the size indicates the maximum number of elements that can be stored inside the array.Example:

float weight[40]

Declares the weight to be an array containing 40 real elements. Any subscripts 0 to 39 are valid.

Similarly,int group1[11];

Decalres the group1 as an array to contain a maximum of 10 integer constants.

The C language treats character strings simply as arrays of characters. The size in a character string represents the maximum number of characters that the string can hold.For example:

char text[10];Suppose we read the following string constant into the string variable text.

“HOW ARE YOU”Each character of the string is treated as an element of the array text and is stored in the memory as follows.

‘H’ ‘O’ ‘W’

‘A’ ‘R’ ‘E’

‘Y’ ‘O’ ‘U’ ‘\o’

When the compiler sees a character string, it terminates it with an additional null character. Thus, the element text[11] holds the null character ‘\o’ at the end. When declaring character arrays, we must always allow one extra element space for the null terminator. Example program of one dimensional array

//a program to find average marks obtained by a class of 30 students in a test.

54

Page 55: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

void main( )

{ int avg, sum = 0 ; int i ; int marks[30] ; /* array declaration */ for ( i = 0 ; i <= 29 ; i++ )

{ printf ( "\nEnter marks " ) ;

scanf ( "%d", &marks[i] ) ; /* store data in array */ } for ( i = 0 ; i <= 29 ; i++ ) {

sum = sum + marks[i] ; /* read data from an array*/ }avg = sum / 30 ; printf ( "\nAverage marks = %d", avg ) ;

}

// Program to read and write two dimensional arrays.#include<stdio.h>main(){

int a[10][10]; int i, j row,col;

printf(“\n Input row and column of a matrix:”);scanf(“%d %d”, &row,&col);for(i=0; i<row;i++){ for(j=0;j<col;j++)

{ scanf(“%d”, &a[i][j]);

}}

for(i=0;i<row;i++){

for(j=0;j<col;j++){

printf(“%5d”, a[i][j]);printf(“\n”);

}}}

Q23. Explain the difference between the associatively and precedence of the operators with suitable example.

55

Page 56: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Ans. When two operators of equal priority is found in the expression than which operator is evaluated first is settled down by the associativity of the operators while in an expression which operator will be evaluated first is settled by the precedence of the operators. If the tow operators have the same precedence than it is settled down by the associativity. Let see the example

Precedence operators AssociativityHighest () [] -> :: Left to rightSecond highest ++,--. & Right to LeftThird highest *,/, % Left to rightFourth highest << ,>> Left to rightFifth highest <=, >, >= Left to right

In the above example it is clearly seen that there are different level of priority which is called the precedence and on each level there are different operators. Now which operator will be valuated first on the same precedence level, this is called the associativity of the operators. So For example () [] -> and :: has the highest priority but wich can be evaluated first is decided by the associativity like in the above example these are to be evaluated from Left to right

Q24. What do you mean by link list. How it is different from arrays. Explain it with proper example.

56

Page 57: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Ans. a linked list is a data structure that consists of a sequence of data records such that in each record there is a field that contains a reference (i.e., a link) to the next record in the sequence.

A linked list whose nodes contain two fields: an integer value and a link to the next node

Linked lists are among the simplest and most common data structures, and are used to implement many important abstract data structures, such as stacks, queues, hash tables, symbolic expressions, skip lists, and many more.

The principal benefit of a linked list over a conventional array is that the order of the linked items may be different from the order that the data items are stored in memory or on disk. For that reason, linked lists allow insertion and removal of nodes at any point in the list, with a constant number of operations.

On the other hand, linked lists by themselves do not allow random access to the data, or any form of efficient indexing. Thus, many basic operations — such as obtaining the last node of the list, or finding a node that contains a given datum, or locating the place where a new node should be inserted — may require scanning most of the list elements.Each record of a linked list is often called an element or node.

The field of each node that contains address of the next node is usually called the next link or next pointer. The remaining fields may be called the data, information, value, or payload fields.The head of a list is its first node, and the tail is the list minus that node (or a pointer thereto).

Example of declaring anode of the link list is

Struct stud

{

int marks;

struct stud *ptr

};

Link List VS Arrays

57

Page 58: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Linked lists have several advantages over arrays. Insertion of an element at a specific point of a list is a constant-time operation, whereas insertion in an array may require moving half of the elements, or more. While one can "delete" an element from an array in constant time by somehow marking its slot as "vacant", an algorithm that iterates over the elements may have to skip a large number of vacant slots.

Moreover, arbitrarily many elements may be inserted into a linked list, limited only by the total memory available; while an array will eventually fill up, and then have to be resized — an expensive operation, that may not even be possible if memory is fragmented. Similarly, an array from which many elements are removed may have to be resized in order to avoid wasting too much space.

On the other hand, arrays allow random access, while linked lists allow only sequential access to elements. Singly-linked lists, in fact, can only be traversed in one direction. This makes linked lists unsuitable for applications where it's useful to look up an element by its index quickly, such as heapsort. Sequential access on arrays is also faster than on linked lists on many machines, because they have greater locality of reference and thus profit more from processor caching.

Another disadvantage of linked lists is the extra storage needed for references, which often makes them impractical for lists of small data items such as characters or boolean values. It can also be slow, and with a naïve allocator, wasteful, to allocate memory separately for each new element, a problem generally solved using memory pools.

Q25. What do you mean by preprocessor. Explain in detail.

58

Page 59: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Ans The C preprocessor, often known as cpp, is a macro processor that is used automatically by the C compiler to transform your program before compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs. It is denoted by the # symbol . The C preprocessor provides four separate facilities that you can use as you see fit:

Inclusion of header files. These are files of declarations that can be substituted into your program.

Macro expansion. You can define macros, which are abbreviations for arbitrary fragments of C code, and then the C preprocessor will replace the macros with their definitions throughout the program.

Conditional compilation. Using special preprocessing directives, you can include or exclude parts of the program according to various conditions.

Special directives( Pragma and undef)

Inclusion of the header file-: You request the use of a header file in your program by including it, with the C preprocessing directive `#include'.

Header files serve two purposes.

System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.

Your own header files contain declarations for interfaces between the source files of your program. Each time you have a group of related declarations and macro definitions all or most of which are needed in several different source files, it is a good idea to create a header file for them.

Both user and system header files are included using the preprocessing directive `#include'. It has two variants:

#include <file>This variant is used for system header files. It searches for a file named file in a standard list of system directories.

#include "file"This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>.

Exmaple ;

#include<stdio.h> or #include ”stdio.h”

Macro Expansion: A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two

59

Page 60: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.

You create macros with the `#define' directive. `#define' is followed by the name of the macro and then the token sequence it should be an abbreviation for, which is variously referred to as the macro's body, expansion or replacement list. For example,

#define BUFFER_SIZE 1024

defines a macro named BUFFER_SIZE as an abbreviation for the token 1024. If somewhere after this `#define' directive there comes a C statement of the form

foo = (char *) malloc (BUFFER_SIZE);

then the C preprocessor will recognize and expand the macro BUFFER_SIZE. The C compiler will see the same tokens as it would if you had written

foo = (char *) malloc (1024);

By convention, macro names are written in uppercase. Programs are easier to read when it is possible to tell at a glance which names are macros.

Conditional Compilations: A conditional is a directive that instructs the preprocessor to select whether or not to include a chunk of code in the final token stream passed to the compiler. Preprocessor conditionals can test arithmetic expressions, or whether a name is defined as a macro, or both simultaneously using the special defined operator.

A conditional in the C preprocessor resembles in some ways an if statement in C, but it is important to understand the difference between them. The condition in an if statement is tested during the execution of your program. Its purpose is to allow your program to behave differently from run to run, depending on the data it is operating on. The condition in a preprocessing conditional directive is tested when your program is compiled. Its purpose is to allow different code to be included in the program depending on the situation at the time of compilation

The simplest sort of conditional is

#ifdef MACRO controlled text #endif /* MACRO */

This block is called a conditional group. controlled text will be included in the output of the preprocessor if and only if MACRO is defined. We say that the conditional succeeds if MACRO is defined, fails if it is not.

60

Page 61: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

The controlled text inside of a conditional can include preprocessing directives. They are executed only if the conditional succeeds. You can nest conditional groups inside other conditional groups, but they must be completely nested. In other words, `#endif' always matches the nearest `#ifdef' (or `#ifndef', or `#if'). Also, you cannot start a conditional group in one file and end it in another.

The `#if' directive allows you to test the value of an arithmetic expression, rather than the mere existence of one macro. Its syntax is

#if expression controlled text #endif /* expression */

expression is a C expression of integer type, subject to stringent restrictions. It may contain

Integer constants. Character constants, which are interpreted as they would be in normal code. Arithmetic operators for addition, subtraction, multiplication, division, bitwise

operations, shifts, comparisons, and logical operations (&& and ||). The latter two obey the usual short-circuiting rules of standard C.

Macros. All macros in the expression are expanded before actual computation of the expression's value begins.

Uses of the defined operator, which lets you check whether macros are defined in the middle of an `#if'.

Identifiers that are not macros, which are all considered to be the number zero. This allows you to write #if MACRO instead of #ifdef MACRO, if you know that MACRO, when defined, will always have a nonzero value. Function-like macros used without their function call parentheses are also treated as zero.

Special directives-; The Special directives include the macros like pragma and undef. The use of each of each of them is shown below

(a) #undef-; It undefined the defined macro in a program. Although it is rarely used but the syntax are as follows

Syntax

#undef PI

the above statement undefined the macro PI which is defined earlier

(b) #pragma-: Although there are wide applications of the pragrma but here we are using this directive for suppressing the warning raised by the compilerand for calling the function and the end of the program and startup.

To suppress the warnings we use the syntax as

61

Page 62: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

# pragma warn –par //for parameter not used# pragma warn –rvl // for value not returned# pragma warn –rch //for unreachable code

To call a function before start and after the end of the program, we use the syntax as

# pragma startup fun()//call function fun before the main# pragma exit fun1()// call function fun1 after the program

Q26. What do you mean by operating system ? Explain the various types of operating system. What are the services offered by the operating system.

Ans Operating system -; An operating system is a program which connects the user and the electronic hardware in a computer. It acts as an interface between the user and computer. It is a set of programs which supervise the activities of a computer and

62

Page 63: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

activate the operations of the hardware components such as CPU, main memory, disk drives, keyboard, monitor and printer and so on. Some of the startup programs initially loaded to RAM are stored in ROM, mainly the BIOS programs which are recorded by the manufacturers of the computer system. Service programs available in operating system for operating system for operations like copying a file, deleting a file, formatting a disk, printing a file and so on are usually stored in the disk. Error messages are displayed on the screen if there is any malfunctioning of hardware.

There are many operating system used in computers. Commonly used operating systems are MS-DOS (Microsoft Disk operating System), Windows 95/98/2000, Windows NT, UNIX and so on. Nowadays Windows 2000 operating system is widely used in personal computers, and UNIX is used in Mainframes, Servers, Graphic Workstations and also personal computers. Linux is one of the most popular free operating system.

Types of the operating system-; Following are the types of the operating system

Real-time Operating System: It is a multitasking operating system that aims at executing real-time applications. Real-time operating systems often use specialized scheduling algorithms so that they can achieve a deterministic nature of behavior. The main object of real-time operating systems is their quick and predictable response to events. They either have an event-driven or a time-sharing design. An event-driven system switches between tasks based of their priorities while time-sharing operating systems switch tasks based on clock interrupts.

Multi-user and Single-user Operating Systems: The operating systems of this type allow a multiple users to access a computer system concurrently. Time-sharing system can be classified as multi-user systems as they enable a multiple user access to a computer through the sharing of time. Single-user operating systems, as opposed to a multi-user operating system, are usable by a single user at a time. Being able to have multiple accounts on a Windows operating system does not make it a multi-user system. Rather, only the network administrator is the real user. But for a Unix-like operating system, it is possible for two users to login at a time and this capability of the OS makes it a multi-user operating system.

Multi-tasking and Single-tasking Operating Systems: When a single program is allowed to run at a time, the system is grouped under a single-tasking system, while in case the operating system allows the execution of multiple tasks at one time, it is classified as a multi-tasking operating system. Multi-tasking can be of two types namely, pre-emptive or co-operative. In pre-emptive multitasking, the operating system slices the CPU time and dedicates one slot to each of the programs. Unix-like operating systems such as Solaris and Linux support pre-emptive multitasking. Cooperative multitasking is achieved by relying on each process to give time to the other processes in a defined manner. MS Windows prior to Windows 95 used to support cooperative multitasking.

Distributed Operating System: An operating system that manages a group of independent computers and makes them appear to be a single computer is known as a

63

Page 64: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

distributed operating system. The development of networked computers that could be linked and communicate with each other, gave rise to distributed computing. Distributed computations are carried out on more than one machine. When computers in a group work in cooperation, they make a distributed system.

Embedded System: The operating systems designed for being used in embedded computer systems are known as embedded operating systems. They are designed to operate on small machines like PDAs with less autonomy. They are able to operate with a limited number of resources. They are very compact and extremely efficient by design. Windows CE, FreeBSD and Minix 3 are some examples of embedded operating systems.

Services provided by the Operating system-: Following are the services provided the operating system

Program Execution and command interpretation

The purpose of a computer systems is to allow the user to execute programs. So the operating systems provides an environment where the user can conveniently run programs. The user does not have to worry about the memory allocation or multitasking or anything. These things are taken care of by the operating systems.

Running a program involves the allocating and deallocating memory, CPU scheduling in case of multiprocess. These functions cannot be given to the user-level programs. So user-level programs cannot help the user to run programs independently without the help from operating systems.

 I/O Operations

Each program requires an input and produces output. This involves the use of I/O. The operating systems hides the user the details of underlying hardware for the I/O. All the user sees is that the I/O has been performed without any details. So the operating systems by providing I/O makes it convenient for the users to run programs.

For efficiently and protection users cannot control I/O so this service cannot be provided by user-level programs.

 File System Manipulation

The output of a program may need to be written into new files or input taken from some files. The operating systems provides this service. The user does not have to worry about secondary storage management. User gives a command for reading or writing to a file and sees his her task accomplished. Thus operating systems makes it easier for user programs to accomplished their task.

64

Page 65: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

This service involves secondary storage management. The speed of I/O that depends on secondary storage management is critical to the speed of many programs and hence I think it is best relegated to the operating systems to manage it than giving individual users the control of it. It is not difficult for the user-level programs to provide these services but for above mentioned reasons it is best if this service s left with operating system.

 Communications

There are instances where processes need to communicate with each other to exchange information. It may be between processes running on the same computer or running on the different computers. By providing this service the operating system relieves the user of the worry of passing messages between processes. In case where the messages need to be passed to processes on the other computers through a network it can be done by the user programs. The user program may be customized to the specifics of the hardware through which the message transits and provides the service interface to the operating system.

 Error Detection

An error is one part of the system may cause malfunctioning of the complete system. To avoid such a situation the operating system constantly monitors the system for detecting the errors. This relieves the user of the worry of errors propagating to various part of the system and causing malfunctioning.

This service cannot allowed to be handled by user programs because it involves monitoring and in cases altering area of memory or deallocation of memory for a faulty process. Or may be relinquishing the CPU of a process that goes into an infinite loop. These tasks are too critical to be handed over to the user programs.  A user program if given these privileges can interfere with the correct (normal) operation of the operating systems.

Process management-; It is responsible for managing the process of the computer system

Q27. Write a short note on

(a) Compiler(b) Interpreter(c) Assembler(d) Linker(e) Loader

65

Page 66: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Ans. (a) compiler-: Compilers convert the program instructions from human understandable form to the machine understandable form and the translated program instruction is called object code. Compiler is nothing but a language translator used to translate the entire program of the high level language into machine language. Every programming language requires its own compiler to translate the program. For example, the programming language PASCAL requires PASCAL compiler and C uses C compiler.

(b) Interpreter -: Interpreters also convert the source program to machine language instruction but executes each line as it is entered. The translation of the source program takes place for every run and is slower than the compiled code. An interpreter must accompany the object code to run a program. Programming languages BASIC and LISP use interpreters.

© Assembler -: A low level first generation computer language, popular during early 1960s, which uses abbreviations or mnemonic codes ( mnemonic means mind full) for operation codes and symbolic addresses. This symbolic instruction language is called Assembly language. One of the first step in improving the program preparation was to substitute mnemonics for operation codes. The mnemonics are different among makes and models of computer. Second step was symbolic addressing to express an address in terms of symbols convenient to the programmer. Another improvement was the programmer turned the work of assigning and keeping track of instruction addresses over to the computer. The programmer merely told the machine the storage address number of the first program instruction and the assembly language software the automatically stored all others in the sequence from that point.

The mnemonics are converted into binaries with the help of a translator known as Assembler.

66

CompilerHigh level language

Machine language

InterpreterHigh level language

Machine language

Page 67: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

The program written using mnemonics is called Source program or assembly language program , the binary form of the source program equivalent is called Object Program.

(d) Linker-: A computer program that takes one or more objects generated by a compiler and combines them into a single executable program. The compiler automatically invokes the linker as the last step in compiling a program. The linker inserts code (or maps in shared libraries) to resolve program library references, and/or combines object modules into an executable image suitable for loading into memory.

It does the merging of individual modules so that they can communicate with each other.

Types of Linker

(a) Linking loader -; the linking loader performs all linking and relocation operations and loads the linked program directly into the main memory for execution

(b) Linking editor -; a linkage editor produces a linked version of the program called as load module or an executable image. This load module is written onto a file or library for later execution

(c) Dynamic Linker -; This scheme postpones the linking functions until execution time. Any subroutine is loaded and linked to the rest of the program when it is first called. This type of linking is called as dynamic linking

(e) Loaders -: Loader is responsible for loading, linking and relocation. The basic function of the loader is

(1) to assign a load time storage area to program -; storage allocation(2) Making a program to execute properly form its load time storage area-; program

relocation(3) Keeping the program into assigned memory area-Loading(4) Linking of programs with each other-: linking

Types of the Loaders-:

(1) Absolute Loader -; It is a primitive type of loader which does only the loading function. It loads the object program from the translation time address and simply transfers control to it. It does not perform the linking and program relocation

67

AssemblerAssembly language

Machine language

Page 68: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

(2) Bootstrap Loader-: when the computer is turned on, absolute loader is executed. This loader is responsible for loading the operating system and transferring the control to it.

(3) Relocatable loader-: this loader is responsible for relocation and loading

Q28.What is the difference between the multiprogramming and multitasking.

Ans. In computing, multitasking is a method by which multiple tasks are performed by the user also known as processes, share common processing resources such as a CPU. CPU is actively executing more than one task at a time. Multitasking solves the problem by scheduling the tasks instructions. Which task may be the one running at any given time, when another waiting task gets a turn. These requests are managed by

68

Page 69: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

reassigning a CPU from one task to another one is called a context switch. Even on computers with more than one CPU (called multiprocessor machines), multitasking allows many more tasks to be run than there are CPUs.

Multiprogramming:The method of Multiprogramming systems took place in the 1960s. In that process several different programs in batch were loaded in the computer memory, and the first one began to run. One program after another executed when the first program reached an instruction waiting for a device that has a message, the context of this program was stored away, and the second program in memory was given a chance to run. The process continued until all programs finished running.

In Multiprogramming programs may have delay; the very first program may very well run for hours without needing access to a peripheral. As there were no users waiting at an interactive terminal, this was no problem.

Q32.What do you mean by recursion. Explain it with Example.

Ans 32. Recursion-: The C language allows programmer to write functions that calls themselves and this is called Recursion. It is a programming technique that allows the programmer to express operations in terms of themselves. A useful way to think of recursive functions is to imagine them as a process being performed where one of the

69

Page 70: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

instructions is to "repeat the process". This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping.

Following are the Example of the recursion where the program is used to compute the factorial of a given number.

int fact(int n){int x,y;if(n==0)return 1;x=n-1;y=fact(x);return n*y;}

void main(){int x;clrscr();printf(“\nEnter the integer whose factorial value you want :-“);scanf(“%d”,&x);printf(“\nThe facorial value is:-%d”,fact(x));getch();}

In the statement y=fact(x) the function calls itself and this is an essential ingredient of a recursive function. However the programmer must ensure that this does not lead to an endless series of calls.

Q33. What do you mean by C tokens.

Ans 33. C tokens: The smallest individual units are known as C tokens. C has 6 types of tokens. The below diagram shows the types of C tokens with examples.

70

Page 71: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Keywords-: All keywords have fixed meanings and these meanings cannot be changed. These serve as basic building blocks for program statements. All keywords must be written in lowercase. Examples of keyword is int, while, for, enum, extern etc.

Identifiers-: Identifiers refer to the names of variables, functions and arrays. These are user defined names and consist of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted, although lowercase letters are commonly used. The underscore character is also permitted in identifiers. It is usually used as a link between two word in long identifiers. Rules for naming identifiers.

1. The identifier must always begin with a letter. Some systems permit underscore as the first character.

2. ANSI standard recognizes a length of 31 characters. However, the length should not be normally mare than eight characters. Since first eight characters are treated as significant by many compilers.

3. Uppercase and lowercase are significant. That is ,the variable Rate is not the same as rate

4. The identifier name should not be a keyword.5. White space is not allowed.

Strings-:A string is a group of Characters terminated by ‘\0’. Example of strings are “ Mohit”, “134ramesh”.

Constants-:Data items that don not change their values while the program executes are called constants. C allows following types of constants.

(a) Integer constants(b) Character constants(c) Floating point constants(d) String constants

Integer constants-: An integer constant refers to a sequence of digits. There are three types of integers, namely decimal, octal and hexadecimal. Decimal integers

71

C tokens

KeywordsEx: while, for

IdentifiersEx: count

StringsEx: “Rahul”

Special SymbolsEx: { }

OperatorsEx: +,-

ConstantsEx: 23,

445.145.1

Page 72: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

consist of a set of digits 0 through 9, preceded by an optional – or + sign. Some examples of decimal integer constants are 123, -431, 0, 34567An octal integer constant consists of any combination of digits from the set 0 through 7 with a leading 0. Some examples are: 037, 0435A sequence of digits preceded by 0x is considered as hexadecimal integer. Some examples are 0x2,0x9F.

Floating-point constants: Integer numbers are inadequate to represent quantities that vary continuously, such as distances ,heights ,temperatures ,prices and so on. These quantities are represented by numbers containing fractional parts like 23.78. Such numbers are called floating-point constants or real constants. Examples for floating-point constants are given below 0.5,23.6

Character Constants: A character constant contains a single character enclosed within a pair of single quote marks. Examples of character constants are: ‘5’ ‘X’

String constants: A string constant is a sequence of characters enclosed in double quotes. The letters may be numbers, special characters and blank space. Example are as follows “THANK YOU”

Operators-: An operator is one which work on data items and performs some mathematical calculation or change the data. C provides six types of the operators.

(a) Arithmetical operators Example +,=*,%(b) Relational operators Example <, >,==(c) Logical operators Example &&, ||(d) Assignment operator Example =(e) Bitwise operators Example &, |(f) Special operators Example sizeof

Q. 34.Explain the basic structure of a C program.

Ans 34. Structure of a C program: The basic structure of a C program is shown below:

72

Page 73: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Documentation Section---------------------------------------------- Link Section----------------------------------------------Definition Section----------------------------------------------Global Declaration Sectionmain() Function Section{

Declaration Part ------------------------ Executable Part}-------------------------------------------------------------------------------------------------------Subprogram section

Function 1 Function 2 ------------- . . . Function n

Documentation Section-: The documentation section consists of a set of comment lines giving the name of the program, the name author and other details which the programmer would like to use later.

Link Section-:The link section provides instructions to the compiler to link functions from the system library.

Definition Section-: The definition section all symbolic constants.

Other sections :There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section. Every C program must have one main() function section. This section contains two parts declaration part and executable part. The declaration part declares all the variables used in the executable part. There should be at least one statement in the executable part. These two parts must appear between the opening and the closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function section is logical end of the program. All statements in the declaration and executable parts end with a semicolon.

73

Page 74: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

Subprogram section-: The subprogram section contains all the user-defined functions that are called in the main function. The main function is very important compared to other sections.

Example Program-:

// Program to add two number

#include< stdio.h>

void add();void main(){printf(“main function”);

add();

}

void add(){ int a ,b,c; a=10; b=20; c=a+b; printf(“Answer is %d”,c);}

Q35. Write down the function of the following statements/functions(f) sizeof()(g) Realock(h) Exit()(i) Continue

74

Page 75: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

(j) Break

Ans. (a) sizeof()-:The operator size gives the size of the data type or variable in terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier.

Example

m = sizeof (sum); n = sizeof (long int); k = sizeof (235L);

The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program.

Example

void main()

{

int a=10;

float b;

printf(“Size of integer is %d”, sizeof(a));

printf(“size of float is %d”, sizeof(float));

}

output of the above program is

Size of integer is 2

Size of float is 4

(b) Reallock-: The realloc() function changes the size of a block of memory that was previously allocated with malloc() or calloc(). The function prototype is

void *realloc(void *ptr, size_t size);

The ptr argument is a pointer to the original block of memory. The new size, in bytes, is specified by size. There are several possible outcomes with realloc():

75

Page 76: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

If sufficient space exists to expand the memory block pointed to by ptr, the additional memory is allocated and the function returns ptr.

If sufficient space does not exist to expand the current block in its current location, a new block of the size for size is allocated, and existing data is copied from the old block to the beginning of the new block. The old block is freed, and the function returns a pointer to the new block.

If the ptr argument is NULL, the function acts like malloc(), allocating a block of size bytes and returning a pointer to it.

If the argument size is 0, the memory that ptr points to is freed, and the function returns NULL.

If memory is insufficient for the reallocation (either expanding the old block or allocating a new one), the function returns NULL, and the original block is unchanged.

Listing below demonstrates the use of realloc().

Using realloc() to increase the size of a block of dynamically allocated memory.1: /* Using realloc() to change memory allocation. */2:3: #include <stdio.h>4: #include <stdlib.h>5: #include <string.h>6:7: main()8: {9: char buf[80], *message;10:11: /* Input a string. */12:13: puts("Enter a line of text.");14: gets(buf);15:16: /* Allocate the initial block and copy the string to it. */17:18: message = realloc(NULL, strlen(buf)+1);19: strcpy(message, buf);20:21: /* Display the message. */22:23: puts(message);24:25: /* Get another string from the user. */26:27: puts("Enter another line of text.");28: gets(buf);29:30: /* Increase the allocation, then concatenate the string to it. */31:32: message = realloc(message,(strlen(message) + strlen(buf)+1));33: strcat(message, buf);

76

Page 77: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

34:35: /* Display the new message. */36: puts(message);37: return(0);38: }Enter a line of text.This is the first line of text.This is the first line of text.Enter another line of text.This is the second line of text.This is the first line of text.This is the second line of text.

ANALYSIS: This program gets an input string on line 14, reading it into an array of characters called buf. The string is then copied into a memory location pointed to by message (line 19). message was allocated using realloc() on line 18. realloc() was called even though there was no previous allocation. By passing NULL as the first parameter, realloc() knows that this is a first allocation.

Line 28 gets a second string in the buf buffer. This string is concatenated to the string already held in message. Because message is just big enough to hold the first string, it needs to be reallocated to make room to hold both the first and second strings. This is exactly what line 32 does. The program concludes by printing the final concatenated string

© Exit -: The "exit" function terminates program execution and returns the status value to the system. Exit causes the program to end and supplies a status code to the calling environment. Library: stdlib.h

Prototype: void exit(int status);

Syntax: main()

{ exit(0); /* Clean exit */

}(d) Continue -: The continue statement can be used to skip the rest of the body of an iterative loop. The use of a continue statement violates the rules of structured programming, however, and a section of code which uses a continue statement can always be rewritten to omit the continue.It provides a convenient way to force an immediate jump to the loop control statement.Example are as follows-:

#include <stdio.h>#include <stdlib.h>

int main () { unsigned x;

77

Page 78: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

x = 0; while (x < 10) { ++x; if (x % 2 == 0) { continue; } printf ("%i is an odd number.\n", x); }

return 0;}

Output is

1 is an odd number.3 is an odd number.5 is an odd number.7 is an odd number.9 is an odd number.

(e) Break-: the break command allows you to terminate and exit a loop (that is, do, for, and while) or switch command from any point other than the logical end. You can place a break command only in the body of a looping command or in the body of a switch command. The break keyword must be lowercase and cannot be abbreviated.

In a looping statement, the break command ends the loop and moves control to the next command outside the loop. Within nested statements, the break command ends only the smallest enclosing do, for, switch, or while commands.

In a switch body, the break command ends the execution of the switch body and gives control to the next command outside the switch body

Example

#include <stdio.h>#include <math.h>

78

Page 79: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

void main() {

int i, n, prime=1; // prime is true printf("Input natural number :"); scanf("%d", &n); for( i=2; i<= n-1; i++) { if( n % i == 0 ) { // also possible to state if(!(n % i))

prime =0; // prime is now false break;

} } if( prime )

printf("%d is prime number !\n", n); else

printf("%d isn’t prime number!\n", n);

}

79

Page 80: Q1 - Wikispaces · Web viewa>b && x == 10 An expression of this kind which combines two or more relational expression is termed as a logical expression or a compound relational expression

Developed by Pawan Agarwal, Computer Engg. Dept. Hindustan college of Science and Technology, Mathura

80