Introduction to Programming - Introduction to Programming-TestPaper2

advertisement

END TERM EXAMINATION

SECOND SEMESTER [B.TECH.] MAY-JUNE-2014

Model Paper-II

Subject Facilitator: Shipra Varshney

Paper code: ETCS108

Time: 3 Hrs

Subject: Introduction to Programming

Maximum Marks: 75

Note: Attempt five questions including Q.no.1 which is compulsory.

Select one question from each unit.

Q1: Short answer type: a) What is the difference between structure and unions in C?

Ans:

[5*5=25]

Structure Union i. Access Members

We can access all the members of structure at anytime.

Only one member of union can be accessed at anytime. ii. Memory Allocation

Memory is allocated for all variables.

Allocates memory for variable which variable require more memory. iii. Initialization

All members of structure can be initialized iv. Keyword

Only the first member of a union can be initialized.

1

'struct' keyword is used to declare structure. v. Syntax struct struct_name

{

structure element 1;

structure element 2;

----------

----------

structure element n;

}struct_var_nm; vi. Example

'union' keyword is used to declare union. union union_name

{

union element 1;

union element 2;

----------

----------

union element n;

}union_var_nm; struct item_mst

{

int rno;

char nm[50];

}it; union item_mst

{

int rno;

char nm[50];

}it; b) What is an operator? List down different types of operators in C.

Ans: An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators:

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Misc Operators

This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Arithmetic Operators

Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:

Operator Description

+ Adds two operands

Example

A + B will give 30

2

-

*

/

%

++

--

Subtracts second operand from the first

Multiplies both operands

Divides numerator by de-numerator

A - B will give -10

A * B will give 200

B / A will give 2

Modulus Operator and remainder of after an integer

B % A will give 0 division

Increments operator increases integer value by one A++ will give 11

Decrements operator decreases integer value by one A-- will give 9

Relational Operators

Following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20, then:

Operator Description

==

Example

Checks if the values of two operands are equal or

(A == B) is not true. not, if yes then condition becomes true.

!=

>

<

>=

<=

Checks if the values of two operands are equal or not, if values are not equal then condition becomes (A != B) is true. true.

Checks if the value of left operand is greater than the value of right operand, if yes then condition (A > B) is not true. becomes true.

Checks if the value of left operand is less than the value of right operand, if yes then condition (A < B) is true. becomes true.

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then (A >= B) is not true. condition becomes true.

Checks if the value of left operand is less than or equal to the value of right operand, if yes then (A <= B) is true. condition becomes true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then:

Operator Description

&&

Example

Called Logical AND operator. If both the operands

(A && B) is false. are non-zero, then condition becomes true.

||

Called Logical OR Operator. If any of the two

(A || B) is true. operands is non-zero, then condition becomes true.

3

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true !(A && B) is true. then Logical NOT operator will make false.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows: p q p & q p | q p ^ q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C language are listed in the following table. Assume variable

A holds 60 and variable B holds 13, then:

Operator Description

&

Example

Binary AND Operator copies a bit to the result if it (A & B) will give 12, which is exists in both operands. 0000 1100

|

^

~

Binary OR Operator copies a bit if it exists in either (A | B) will give 61, which is operand. 0011 1101

Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49, which is one operand but not both. 0011 0001

Binary Ones Complement Operator is unary and (~A ) will give -61, which is 1100 has the effect of 'flipping' bits. 0011 in 2's complement form.

4

<<

>>

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the

A << 2 will give 240 which is

1111 0000 right operand.

Binary Right Shift Operator. The left operands value is moved right by the number of bits

A >> 2 will give 15 which is

0000 1111 specified by the right operand.

Assignment Operators

There are following assignment operators supported by C language:

<<=

>>=

&=

^=

|=

Operator Description

=

+=

Example

Simple assignment operator, Assigns values from C = A + B will assign value of A right side operands to left side operand + B into C

Add AND assignment operator, It adds right operand to the left operand and assign the result to

C += A is equivalent to C = C +

A left operand

-=

*=

/=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the C -= A is equivalent to C = C - A result to left operand

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the

C *= A is equivalent to C = C *

A result to left operand

Divide AND assignment operator, It divides left operand with the right operand and assign the result C /= A is equivalent to C = C / A to left operand

%=

Modulus AND assignment operator, It takes modulus using two operands and assign the result

C %= A is equivalent to C = C %

A to left operand

Left shift AND assignment operator

Right shift AND assignment operator

C <<= 2 is same as C = C << 2

C >>= 2 is same as C = C >> 2

Bitwise AND assignment operator bitwise exclusive OR and assignment operator bitwise inclusive OR and assignment operator

C &= 2 is same as C = C & 2

C ^= 2 is same as C = C ^ 2

C |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary

There are few other important operators including sizeof and ? : supported by C Language.

Operator Description sizeof() Returns the size of an variable.

Example sizeof(a), where a is integer, will return 4.

5

&

*

? :

Returns the address of an variable.

Pointer to a variable.

Conditional Expression

&a; will give actual address of the variable.

*a; will pointer to a variable.

If Condition is true ? Then value

X : Otherwise value Y c): Give the general format of preprocessor statement. Define. How it is useful?

Ans: The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do required pre-processing before actual compilation. We'll refer to the C

Preprocessor as the CPP.

All preprocessor commands begin with a pound symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in first column. Following section lists down all important preprocessor directives:

Directive Description

#define

#include

#undef

#ifdef

#ifndef

#if

#else

#elif

#endif

#error

Substitutes a preprocessor macro

Inserts a particular header from another file

Undefines a preprocessor macro

Returns true if this macro is defined

Returns true if this macro is not defined

Tests if a compile time condition is true

The alternative for #if

#else an #if in one statement

Ends preprocessor conditional

Prints error message on stderr

#pragma Issues special commands to the compiler, using a standardized method d) What are the advantages of pointer in C?

Ans: Advantages

Pointers are more efficient in handling arrays and data tables. They can be used to return multiple values from a function via function arguments. Pointers permit references to functions and thereby facilitating passing of functions as arguments to other functions. The use of po0inter arrays to character strings results in saving of data storage space in memory. pointers allow C to support dynamic memory management. Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees. Pointers reduce

6

length and complexity of programs. They increase the execution speed and thus reduce the program execution time. e) What are the different types of errors in running a C Program? Explain.

Ans:- Basically there are three types of errors in c programming: o o o

1.

2.

3.

Runtime Errors

Compile Errors

Logical Errors

C Runtime Errors

C runtime errors are those errors that occur during the execution of a c program and generally occur due to some illegal operation performed in the program.

Examples of some illegal operations that may produce runtime errors are:

Dividing a number by zero

Trying to open a file which is not created

Lack of free memory space

It should be noted that occurrence of these errors may stop program execution, thus to encounter this, a program should be written such that it is able to handle such unexpected errors and rather than terminating unexpectedly, it should be able to continue operating. This ability of the program is known as robustness and the code used to make a program robust is known as guard code as it guards program from terminating abruptly due to occurrence of execution errors.

Compile Errors

Compile errors are those errors that occur at the time of compilation of the program. C compile errors may be further classified as:

Syntax Errors

When the rules of the c programming language are not followed, the compiler will show syntax errors.

For example, consider the statement,

7

1 int a,b:

The above statement will produce syntax error as the statement is terminated with : rather than ;

Semantic Errors

Semantic errors are reported by the compiler when the statements written in the c program are not meaningful to the compiler.

For example, consider the statement,

1 b+c=a;

In the above statement we are trying to assign value of a in the value obtained by summation of b and c which has no meaning in c. The correct statement will be

1 a=b+c;

Logical Errors

Logical errors are the errors in the output of the program. The presence of logical errors leads to undesired or incorrect output and are caused due to error in the logic applied in the program to produce the desired output.

Also, logical errors could not be detected by the compiler, and thus, programmers has to check the entire coding of a c program line by line.

Unit-I

Q2 a): Draw a flowchart or algorithm that input three numbers and print output the greatest amongst them. (6)

Ans : Flowchart of Greatest of three numbers:

8

Algorithm: of Greatest of three numbers

Step 1: Start

Step 2: Declare variables a,b and c.

Step 3: Read variables a,b and c.

Step 4: If a>b

If a>c

Display a is the largest number.

Else

Display c is the largest number.

Else

If b>c

Display b is the largest number.

Else

Display c is the greatest number.

Step 5: Stop b): What are the characteristics of an algorithm?

Ans: - The characteristics of a good algorithm are:

(4)

Precision – the steps are precisely stated (defined).

Uniqueness – results of each step are uniquely defined and only depend on the input and the result of the preceding steps.

Finiteness – the algorithm stops after a finite number of instructions are executed.

9

Input – the algorithm receives input.

Output – the algorithm produces output.

Generality – the algorithm applies to a set of inputs. c) What are the advantages of drawing flow chart?

Ans: -

(2.5) a) Easy to analyze the program b) Especially for c language where structure is important it helps a lot. c) Focus in logic. d) Without a good flowchart you cannot write software. e) Conditional statements are easy to analyze. f) Occupies less paper compared to a large programs having huge statements.

Q3 a) Differentiate between short integer, integer and long integer type of variable. (6)

Ans:

=> Integers , long and short:

 The range of an integer constant depends upon the compiler.

 For a 16 bit Compiler like Turbo C or Turbo C++ the range is -32768 to 32767.

 For a 32 bit compiler like Visual Studio or gcc the range would be -2147483648 to

2147483647.

 C offers a variation of the Integer data type i.e short and long integer values.

 The intention of providing these variations is to provide Integers with different ranges whenever possible.

10

Each compiler can decide appropriate sizes of int , long and short depending on the operating system and hardware , for which it is being written, subject to following Rules:

 shorts are atleast 2 bytes big.

 longs are atleast 4 bytes big.

 shorts are never bigger than ints.

 ints are never bigger than longs.

Compiler short int long

16-bit (Turbo C/C++) 2 2 4

32-bit (Visual Studio ) 2 4 4 b) List some vi editing command and corresponding action. (6.5)

Ans:

Inserting or Adding Text

The following commands allow you to insert and add text. Each of these commands puts the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the entry of text and to put the vi editor back into command mode.

* i insert text before cursor, until <Esc> hit

I insert text at beginning of current line, until <Esc> hit

* a append text after cursor, until <Esc> hit

A append text to end of current line, until <Esc> hit

* o open and put text in a new line below current line, until <Esc> hit

* O open and put text in a new line above current line, until <Esc> hit

Changing Text

The following commands allow you to modify text.

11

* r

R cw replace single character under cursor (no <Esc> needed) replace characters, starting with current cursor position, until <Esc> hit change the current word with starting with the character under cursor, until <Esc> hit new text, cNw change N words beginning with character under cursor, until <Esc> hit;

e.g., c5w changes 5 words

C cc change (replace) the characters in the current line, until change (replace) the entire current line, stopping when

<Esc>

<Esc>

hit

is hit

Ncc or cNc change (replace) the next N lines, starting with the current line, stopping when <Esc> is hit

Deleting Text

The following commands allow you to delete text.

* x delete single character under cursor

Nx dw

delete N characters, starting with character under cursor

delete the single word beginning with character under cursor dNw delete N words beginning with character under cursor;

e.g., d5w deletes 5 words

delete the remainder of the line, starting with current cursor position D

* dd delete entire current line

Ndd or dNd delete N lines, beginning with the current line;

Cutting and Pasting Text

The following commands allow you to copy and paste text. yy copy (yank, cut) the current line into the buffer

12

Nyy or yNy copy (yank, cut) the next N lines, including the current line, into the buffer p put (paste) the line(s) in the buffer into the text after the current line

UNIT II

Q4: a) Illustrate the order of precedence of operators in c?

Ans:

(6.5) b) : Explain in brief all bitwise operators in C? (5.5)

Ans: - The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:

13

Operator Description

&

Example

Binary AND Operator copies a bit to the result if it (A & B) will give 12 which is exists in both operands. 0000 1100

|

^

~

Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is operand. 0011 1101

Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is operand but not both. 0011 0001

(~A ) will give -61 which is

Binary Ones Complement Operator is unary and has 1100 0011 in 2's complement the effect of 'flipping' bits. form due to a signed binary number.

<<

>>

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the

A << 2 will give 240 which is

1111 0000 right operand.

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by

A >> 2 will give 15 which is

0000 1111 the right operand.

Example

Try the following example to understand all the bitwise operators available in C programming language:

#include <stdio.h> main()

{

unsigned int a = 60;

unsigned int b = 13;

int c = 0;

/* 60 = 0011 1100 */

/* 13 = 0000 1101 */

c = a & b; /* 12 = 0000 1100 */

printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */

printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */

printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */

printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */

printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */

14

printf("Line 6 - Value of c is %d\n", c );

}

When you compile and execute the above program it produces the following result:

Line 1 - Value of c is 12

Line 2 - Value of c is 61

Line 3 - Value of c is 49

Line 4 - Value of c is -61

Line 5 - Value of c is 240

Line 6 - Value of c is 15

Q5: What do you understand by looping? Explain various loops in C with examples. (12.5)

Ans:- There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages:

C programming language provides the following types of loop to handle looping requirements.

Click the following links to check their detail.

15

Loop Type while loop for loop do...while loop nested loops

Description

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

Like a while statement, except that it tests the condition at the end of the loop body

You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements. Click the following links to check their detail.

Control Statement break statement continue statement goto statement

Description

Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.

The Infinite Loop:

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.

#include <stdio.h> int main ()

{

for( ; ; )

{

printf("This loop will run forever.\n");

}

return 0;

}

16

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

Program/Example to illustrate Loop Concept:- a.

For loop:-

#include <stdio.h> int main ()

{

/* for loop execution */

for( int a = 10; a < 20; a = a + 1 )

{

printf("value of a: %d\n", a);

}

return 0;

}

When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 b.

while loop:-

Example:

#include <stdio.h> int main ()

{

/* local variable definition */

int a = 10;

/* while loop execution */

while( a < 20 )

{

printf("value of a: %d\n", a);

a++;

}

return 0;

}

17

When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 c.

do…while loop

Example:

#include <stdio.h> int main ()

{

/* local variable definition */

int a = 10;

/* do loop execution */

do

{

printf("value of a: %d\n", a);

a = a + 1;

}while( a < 20 );

return 0;

}

When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 d.

nested loop

Example:

The following program uses a nested for loop to find the prime numbers from 2 to 100:

18

#include <stdio.h> int main ()

{

/* local variable definition */

int i, j;

for(i=2; i<100; i++) {

for(j=2; j <= (i/j); j++)

if(!(i%j)) break; // if factor found, not prime

if(j > (i/j)) printf("%d is prime\n", i);

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

2 is prime

3 is prime

5 is prime

7 is prime

11 is prime

13 is prime

17 is prime

19 is prime

23 is prime

29 is prime

31 is prime

37 is prime

41 is prime

43 is prime

47 is prime

53 is prime

59 is prime

61 is prime

67 is prime

71 is prime

73 is prime

79 is prime

83 is prime

89 is prime

97 is prime

UNIT III

Q6: What do you understand by function prototype, function definition, function declaration? Explain with the help of examples. (12.5)

Ans: - Function Declarations

A function declaration tells the compiler about a function name and how to call the function.

The actual body of the function can be defined separately.

19

A function declaration has the following parts: return_type function_name( parameter list );

For the above defined function max(), following is the function declaration: int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so following is also valid declaration: int max(int, int);

Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.

Calling a Function:

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its functionending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:

#include <stdio.h>

/* function declaration */ int max(int num1, int num2); int main ()

{

/* local variable definition */

int a = 100;

int b = 200;

int ret;

/* calling a function to get max value */

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

}

/* function returning the max between two numbers */ int max(int num1, int num2)

{

/* local variable declaration */

20

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

While running final executable, it would produce the following result:

Max value is: 200

Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function:

Call Type

Call by value

Call by reference

Description

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

Function Prototype:-

A function prototype or function interface in C. While a function definition specifies what a function does, a function prototype can be thought of as specifying its interface.

In a prototype, argument names are optional (and have function prototype scope, meaning they go out of scope at the end of the prototype), however, the type is necessary along with all modifiers (e.g. if it is a pointer or a const argument).

21

In C, if a function is not previously declared and its name occurs in an expression followed by a left parenthesis, it is implicitly declared as a function that returns an int and nothing is assumed about its arguments. In this case the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems. The following code illustrates:-

#include <stdio.h>

/* If this prototype is provided, the compiler will catch the error in

* int main(). If it is omitted, then the error may go unnoticed.

*/

int fac(int n); /* Prototype */

int main(void) { /* Calling function */

printf("%d\n", fac()); /* Error: forgot argument to fac */

return 0;

}

int fac(int n) { /* Called function definition */

if (n == 0)

return 1;

else

return n * fac(n - 1);

}

Explanation of the code:-

The function fac expects an integer argument to be on the stack or in a register when it is called.

If the prototype is omitted, the compiler will have no way of enforcing this and fac will end up operating on some other datum on the stack (possibly a return address or the value of a variable that is currently not in scope). By including the function prototype, you inform the compiler that the function fac takes one integer argument and you enable the compiler to catch these kinds of errors and make the compilation process run smoothly. Please also note that implicit function declarations are removed from the C99 standard, thus omission of at least function prototype will result in compile error.

Q7:- Differentiate between the following (along with examples):-

(i) Array of pointers & pointer to an array (6.5)

Ans: Array of pointers:Before we understand the concept of arrays of pointers, let us consider the following example, which makes use of an array of 3 integers:

#include <stdio.h> const int MAX = 3; int main ()

{

int var[] = {10, 100, 200};

22

int i;

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

{

printf("Value of var[%d] = %d\n", i, var[i] );

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

Value of var[0] = 10

Value of var[1] = 100

Value of var[2] = 200

There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer: int *ptr[MAX];

This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. Following example makes use of three integers, which will be stored in an array of pointers as follows:

#include <stdio.h> const int MAX = 3; int main ()

{

int var[] = {10, 100, 200};

int i, *ptr[MAX];

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

{

ptr[i] = &var[i]; /* assign the address of integer. */

}

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

{

printf("Value of var[%d] = %d\n", i, *ptr[i] );

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

Value of var[0] = 10

Value of var[1] = 100

Value of var[2] = 200

23

You can also use an array of pointers to character to store a list of strings as follows:

#include <stdio.h> const int MAX = 4; int main ()

{

char *names[] = {

"ABC",

"EDF",

"IGHJY",

"KIOP",

};

int i = 0;

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

{

printf("Value of names[%d] = %s\n", i, names[i] );

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

Value of names[0] = ABC

Value of names[1] = EDF

Value of names[2] = IGHJY

Value of names[3] = KIOP

And Pointer to an array:-

An array name is a constant pointer to the first element of the array. Therefore, in the declaration: double balance[50]; balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance : double *p; double balance[10]; p = balance;

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].

24

Once you store the address of first element in p, you can access array elements using *p, *(p+1),

*(p+2) and so on. Below is the example to show all the concepts discussed above:

#include <stdio.h> int main ()

{

/* an array with 5 elements */

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

double *p;

int i;

p = balance;

/* output each array element's value */

printf( "Array values using pointer\n");

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

{

printf("*(p + %d) : %f\n", i, *(p + i) );

}

printf( "Array values using balance as address\n");

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

{

printf("*(balance + %d) : %f\n", i, *(balance + i) );

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

Array values using pointer

*(p + 0) : 1000.000000

*(p + 1) : 2.000000

*(p + 2) : 3.400000

*(p + 3) : 17.000000

*(p + 4) : 50.000000

Array values using balance as address

*(balance + 0) : 1000.000000

*(balance + 1) : 2.000000

*(balance + 2) : 3.400000

*(balance + 3) : 17.000000

*(balance + 4) : 50.000000

(ii) Actual and formal parameters (6)

Ans:- Actual and Formal Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

25

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function:

Call Type

Call by value

Call by reference

Description

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments.

Difference between these two is:-

Actual arguments:

The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function.

Formal arguments:

The formal arguments are the parameters/arguments in a function declaration. The scope of formal arguments is local to the function definition in which they are used. Formal arguments belong to the called function. Formal arguments are a copy of the actual arguments. A change in formal arguments would not be reflected in the actual arguments.

Unit IV

Q8:- What are strings in C? List various string library functions. (12.5)

Ans: - In C programming, array of character are called strings. A string is terminated by null character /0 . For example:

"c string tutorial"

Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null character at the end of string.

26

Declaration of strings

Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type. char s[5];

Strings can also be declared using pointer. char *p

Initialization of strings

In C, string can be initialized in different number of ways. char c[]="abcd";

OR, char c[5]="abcd";

OR, char c[]={'a','b','c','d','\0'};

OR; char c[5]={'a','b','c','d','\0'};

String can also be initialized using pointers char *c="abcd";

Reading Strings from user.

Reading words from user.

char c[20]; scanf("%s",c);

String variable c can only take a word. It is beacause when white space is encountered, the scanf() function terminates.

Sample Program/Example:- A C program to illustrate how to read string from terminal.

27

#include <stdio.h> int main(){

char name[20];

printf("Enter name: ");

scanf("%s",name);

printf("Your name is %s.",name);

return 0;

}

Output

Enter name: Dennis Ritchie

Your name is Dennis.

Another example: - Reading a line of text

C program to read line of text manually.

#include <stdio.h> int main(){

char name[30],ch;

int i=0;

printf("Enter name: ");

while(ch!='\n') // terminates if user hit enter

{

ch=getchar();

name[i]=ch;

i++;

}

name[i]='\0'; // inserting null character at end

printf("Name: %s",name);

return 0;

}

Various C –String Library Functions:-

All the string handling functions are prototyped in:

#include <string.h>

The common functions are described below: char *stpcpy (char *dest,const char *src) -- Copy one string into another. int strcmp(char *string1,const char *string2) - Compare string1 and string2 to determine alphabetic order. char *strcpy(char *string1,const char *string2) -- Copy string2 to stringl. char *strerror(int errnum) -- Get error message corresponding to specified error number. size_t strlen(const char *string) -- Determine the length of a string. char *strncat(char *string1, char *string2, size_t n) -- Append n characters from string2 to stringl.

28

int strncmp(char *string1, char *string2, size_t n) -- Compare first n characters of two strings. char *strncpy(char *string1,const char *string2, size_t n) -- Copy first n characters of string2 to stringl . int strcasecmp(const char *s1, const char *s2) -- case insensitive version of strcmp() . int strncasecmp(const char *s1, const char *s2, int n) -- case insensitive version of strncmp() .

The use of most of the functions is straightforward, for example: char *str1 = "HELLO"; char str2[10]; int length; length = strlen("HELLO"); /* length = 5 */

(void) strcpy(str2,str1);

Note that both strcat() and strcpy() both return a pointer to the first char in the destination array. Note the order of the arguments is destination array followed by source array which is sometimes easy to get the wrong around when programming.

The strcmp() function lexically compares the two input strings and returns:

Less than zero

-- if string1 is lexically less than string2

Zero

-- if string1 and string2 are lexically equal

Greater than zero

-- if string1 is lexically greater than string2

Q9:- What are files in C? Explain various file handling functions & prototypes. (12.5)

Ans:- C File Handling - File Pointers

C communicates with files using a new datatype called a file pointer. This type is defined within stdio.h, and written as FILE *. A file pointer called output_file is declared in a statement like

FILE *output_file;

Opening a file pointer using fopen

Your program must open a file before it can access it. This is done using the fopen function, which returns the required file pointer. If the file cannot be opened for any reason then the value

NULL will be returned. You will usually use fopen as follows

29

if ((output_file = fopen("output_file", "w")) == NULL)

fprintf(stderr, "Cannot open %s\n", "output_file");

fopen takes two arguments, both are strings, the first is the name of the file to be opened, the second is an access character, which is usually one of:

"r" Open file for reading

"w" Open file for writing

"a" Open file for appending

Closing a file using fclose

The fclose command can be used to disconnect a file pointer from a file. This is usually done so that the pointer can be used to access a different file. Systems have a limit on the number of files which can be open simultaneously, so it is a good idea to close a file when you have finished using it. This would be done using a statement like fclose(output_file);

If files are still open when a program exits, the system will close them for you. However it is usually better to close the files properly.

Input and Output using file pointers

Having opened a file pointer, you will wish to use it for either input or output. C supplies a set of functions to allow you to do this. All are very similar to input and output functions that you have already met.

Character Input and Output with Files

This is done using equivalents of getchar and putchar which are called getc and putc. Each takes an extra argument, which identifies the file pointer to be used for input or output. putc(c, getc (fp) fp)

Formatted Input Output with File Pointers

Similarly there are equivalents to the functions printf and scanf which read or write data to files.

These are called fprintf and fscanf.

The functions are used in the same way, except that the fprintf and fscanf take the file pointer as an additional first argument. fprintf ( output_file, "This is a listing file\n" ) ; fscanf ( input_file, "%d", &counter ) ;

30

Formatted Input Output with Strings

These are the third set of the printf and scanf families. They are called sprintf and sscanf. sprintf sscanf puts formatted data into a string which must have sufficient space allocated to hold it.

This can be done by declaring it as an array of char. The data is formatted according to a control string of the same form as that for p rintf. takes data from a string and stores it in other variables as specified by the control string.

This is done in the same way that scanf reads input data into variables. sscanf is very useful for converting strings into numeric v values.

Whole Line Input and Output using File Pointers

Predictably, equivalents to gets and puts exist called fgets and fputs. The programmer should be careful in using them, since they are incompatible with gets and puts. gets requires the programmer to specify the maximum number of characters to be read. fgets and fputs retain the trailing newline character on the line they read or write, wheras gets and puts discard the newline.

When transferring data from files to standard input / output channels, the simplest way to avoid incompatibility with the newline is to use fgets and fputs for files and standard channels too.

For Example, read a line from the keyboard using

fgets(data_string, 80, stdin); and write a line to the screen using

fputs(data_string, stdout);

EOF, The End of File Marker

EOF is a character which indicates the end of a file. It is returned by read commands of the getc and scanf families when they try to read beyond the end of a file.

When you are reading from a file it is useful to be able to check whether or not you have reached the end, without just failing to read. The function feof can be used to find out if you have hit the end : if ( feof (input_file ) ) printf ( "The End!\n" ) ;

31

This function returns the value 0 if the end of the file has not been reached, and another value if it has. It takes a FILE pointer as a parameter.

************************************************************************************

The END

32

Download