Вы находитесь на странице: 1из 47

Binty, Brinda, Ami F.Y.

BCA- (B)

SOLUTION OF THE UNIVERCITY


PAPER – APRIL 2008
PROGRAMMING IN ‘C’ LANGUAGE

Time: 3 Hours Marks: 70

[Question-1]

Q-1. Attempt the following (Any 7). Marks-14

(1) Give the differences between compiler and interpreter.


Ans: -
 Error finding is much easier in Interpreter because it checks and
executes each statement at a time. So wherever it fines some error it
will stop the execution. Where compiler first checks all the statement
for error and provide lists of all the errors in the program.

 Interpreter take more time for the execution of a program compared to


compilers because it translated and executes each statements one by
one.

(2) Draw and explain any four symbols used in flowchart.


Ans: - There are five symbols as follows.

(1) Start/End =

 Used to display starting and ending point of the program.


It usually contains words start/end.

(2) Action/Process =
Binty, Brinda, Ami F.Y.BCA- (B)

 Used to display single step which represents processing


or operation.

(3) Flow line = (↓)

 Used to indicate the sequence of steps and direction of flow.

(4) Input Output =

 Used to display information that is entering or leaving the system.

(5) Decision/Condition =

 Used to display decision at any point.

(3) Give two features which makes ‘C’ a very popular language.
Ans:-

(i) It is a robust language whose reach set of built in function and operator
can be used to write complex programs.

(ii) C language combines the capabilities of an assembly language with


features of high level language hence it is used for writing system software
and business applications.

(iii) Programs written in ‘C’ are efficient and fast. It has verity of data types
and powerful operators.

(iv)There are only thirty-two key words and several built in functions which
are used for developing programs.

(v) ‘C’ is highly portable. This means that ‘C’ programs written for one
computer can be run on another computer with little or no modification.
Binty, Brinda, Ami F.Y.BCA- (B)

(vi) Demodular structure of ‘C’ makes program debugging (error checking),


testing and maintained easy.

(vii) An importance feature of ‘C’ is its ability to extend its self. We can
continuously add our own functions to the ‘C’ library.

(4) What is an assembler?


Ans: -
 Which represents certain actions as computer understand only
Machine language instructions a program written in Assembly
language must be translated into Machine languages. Before it can be
executed this translation if done by another program called
ASSEMBLER. This assembler will translate mnemonic codes into
Machine languages.

(5) Explain procedural language and problem-oriented language.


Ans: - (1) Procedural language:-
A computer language that requires
programming discipline, such as C/C++, Java, COBOL, FORTRAN, Perl,
JavaScript. Also called an “imperative language” programmers writing in
such languages must develop a proper order of action in order to solve the
problem based on knowledge of data processing and programming.

(2)Problem-oriented language:-

A computer language designed to handle a


particular class of problem. For example, COBOL was designed for
business. FORTRAN for scientific and GPSS for simulation.

(6) Explain enum data type with an example.


 Ans: - enum data type is provided by ANSI standard.
Binty, Brinda, Ami F.Y.BCA- (B)

 It is defined as follows,
enum identifier(value1,value2,…,valuen);

 The “identifier” is a user-defined enumerated data type which can be


used to declare variables that can have one of the values enclosed
within the braces(known as enumeration constants). After this
definition, we can declare variables to be of this ‘new’ type as below:

enum identifier v1,v2,…, vn;

The enumerated variables v1, v2,…, vn can only have one of the values
value1, value2,…,valuen.

 The assignments of the following types are valid:


v1 = value3;
v5 = value1;

An example;

enum day{Monday, Tuesday,…,Sunday};


enum day week_st, week_end;
week_st = Monday;
week_end = Friday;
if(week_st==Tuesday)
week_end=Saturday;

The compiler automatically assigns integer digits beginning with 0 to all the
enumeration constants. This is, the enumeration constants value 1 is assigned
0, value2 is assigned 1, and so on. However, the automatic assignments can
be overridden by assigning values explicitly to the enumeration constants.

(7) Find X, if X= ((-25<13)? (7%10): (10%7))

Ans: - X=7.
Binty, Brinda, Ami F.Y.BCA- (B)

(8) State two features of a higher-level language. Give an example.


 Ans: - High level languages are not system specific: the same high
level program can be run on many different systems.

 High level languages support the use of complex expressions.

Example:

X+Y*Z/(W+1)

 High level supports the use of control structures.

Example:

While(x>0)
{
Total = Total + Item[x];
x=x-1;
}

(9) Classify the basic constants available in ‘C’.


Ans: -
 Constants in C refer to fixed values that do not change during
execution of a program.

Constants
Binty, Brinda, Ami F.Y.BCA- (B)

Numeric Character

Integer Real Single String


Character Characters

 Integer constants:-
An integer constant refers to sequence of digits. There
are three types of integer.

(1)Decimal
(2) Octal
(3) Hexadecimal

(1) Decimal integer:-

Decimal integer consist of zero to nine digits


preceded an optional – or + sign. Spaces, commas and non digit
characters are not permitted between digits. Example, 123, 0, -321.

(2) Octal integer:-


Octal integer consists of any combination of digits
from the set 0 to 7 with leading ‘0’. Example, 037, 0, 0435.

(3) Hexadecimal integer:-


Hexadecimal integer is a sequence of digits
preceded by 0x and 0X. Example, 0X2, 0xbcd.
Binty, Brinda, Ami F.Y.BCA- (B)

 Real constants:-

Integer numbers are not efficient to represent quantities


that change continuously like distance, height, temperature, price, etc.

These quantities are represented by numbers containing


fractional parts/Decimal parts. Such numbers are called real or floating point
constants.

Example, 8.9, -400.36, etc.

(1)Single character constants:-

A single character constant contains a


single character and closed within a pair of single quotation marks.
Example, ‘5’, ‘x’, ‘ ‘.

(2) String character constants:-

A string constant is a sequence of


characters enclosed in double quotes. Example, “x”, “HELLO”,”….”, etc.

The character may be a letters,


numbers, special characters or symbols and blank space.

(10) Give the limitations of lower level languages.


Ans: - We can’t able to write program with combination of key word

 Program written in this language can’t be run on a way computer with


different architecture with no modification.

 This language does not contain set of words and symbols.

[Question-2(A)]
Binty, Brinda, Ami F.Y.BCA- (B)

Q-2(A)Write algorithm for the following (Any 2). Marks-6


(1) To generate first 10 natural number of Fibonacci series, which is
given as 0, 1, 1, 2, 3, 5, 8,…

(1)Start
(2)Define t1=1, t2=0, t3, n, i;
(3)Read n;
(4) i =1;
(5) if(i<=n); Yes go to (6)
No go to (10)
(6) t3 =t1+t2;
(7) t1 =t2;
(8) t2 =t3;
(9)print t3;
(10)Stop.

(2) To read a number and find the sum of digits.

(1) Start
(2) define a, b, sum;
(3) Read a, b;
(4) Sum = a+b;
(5) print sum;
(6) Stop

(3) To read a year and find out whether it is leap year or not.

(1) Start
(2) Define year;
(3) Read year;
(4) If ((year%4==0&&year%100!=0)||(year%400==0));Yesgoto(5)
Nogoto(7)
(5) Print a year is leap year;
Binty, Brinda, Ami F.Y.BCA- (B)

(6) Go to (8)
(7) Print a year is not leap year;
(8) Stop.

(4) To read three numbers and find their average.

(1) Start
(2) define a, b, c, Sum, Average;
(3) Read a, b, c;
(4) Sum = a + b + c;
(5) Average = sum/3;
(6) Print average
(7) Stop.

[Question-2(B)]

Q-2(B) Draw flowchart for the following (Any 2). Marks-8


Binty, Brinda, Ami F.Y.BCA- (B)

(1) To read n from the user and compute the sum and average of first n
numbers.

(2) To display the n sum of the series for n terms, where n is read from
the user and the series is given as
Sum=1+8+27+64+…
Binty, Brinda, Ami F.Y.BCA- (B)

(4) To read principal amount (p), rate of interest(r) and number of


years (n) from the user and compute simple interest. The formula for
simple interest is given as (p*r*n)/100.
Binty, Brinda, Ami F.Y.BCA- (B)

[Question-3(A)]

Q.3(A) Give difference between the following.

(1) Array and Structure

Array Structure

(1) An array is a collection 1) Structure can have


Of related data elements elements of different
of same data type. types.
2) An array is derived 2) A structure is a prog-
data type. rammer defined one.
3) An array behaves like 3) In case of structure
a built-in data type. first we have to
All we have to do is design and declare
Binty, Brinda, Ami F.Y.BCA- (B)

declare an array a data structure


variable and use it. before the variable
of that type are
declared and used.

2) Entry controlled loop and exit controlled loop.

Entry controlled loop Exit controlled loop

1) In this loop first condi- 1) In this loop the prog-


tion will be checked ram proceeds to
and if it is true, then evaluate the body of
the body of loop is the loop first and at
executed. The end of loop the
condition will be
checked.
2) In this loop if conditi- 2) In this loop the body
on is wrong there will of the loop is always
be nothing to display. Executes at least
Once.
3) While is an entry cont- 3) Do-While is an exit
rolled loop. Controlled loop.

3) Break and Continue

Break Continue

1) In certain situations 1) In certain situations


We have to break the we have to skip certain
Loop even though the portion inside the loop
Loop is not complete. but we don’t want to
Due to same improper exit the loop. In such
Condition. To perform situations we use
Binty, Brinda, Ami F.Y.BCA- (B)

Such kind of operations continues statement.


We have to use break
Statement.
2) When break statement 2) When the continue is
Is encountered inside encountered it will not
The loop will be turmi- break the loop but skip
Nated. The statements that
Are up to the end of
Loop and once again
It will continue with
The next value of the
Loop.

4) Pass by Value and pass by Reference.

Pass by Value Pass by Reference

1) In pass by value, values 1) in pass by reference the address


of actual parameters of the actual parameter is
are copied to the variable passed to the variable in the
in the parameters list parameter list of the called
Of the called function. Function.
2) The called function works 2) in here called function works
On the copy not on origin- on the original value of the
nal value of the actual actual parameters.
Parameters.
3) In a called by value you can 3) in call by reference you can
Return one value at a time. Return more then one value
At a time.
4) In pass by value the 4) in a pass by reference original
original data in the value can be changed by called
called function cannot function.
be changed accidentally.
Binty, Brinda, Ami F.Y.BCA- (B)

[Question-3(B)]

Q-3(B) Attempt the following (Any 2). Marks-8

(1) Give the output of the following ‘C’ code:

int x=10,y=20,sum=0,val=0;
while(sum<20)
{
Y+=5;
If(y%2==0)
Sum=sum+x;
else
Val=val-10;
}
printf(“%d%d%d%d”,x,y,sum,val);

Output:-

x = 10
y = 40
Sum = 20
Val = -20

(2) Give the output of the following:

int comp(int,int);
void main()

{
int u=20,v=30,a,b;
a=comp(u,v);
Binty, Brinda, Ami F.Y.BCA- (B)

b=comp(a,comp(v,u));
printf(“%d%d\n”,a,b);
}

int comp(int x,int y)


{
If(x<y)
return(x+y);
else
return(x-y);
}

Output:-

10
20
-205040
5040
5040

(3) Find the error in the following program:

Solution
#include<stdio.h>
#include<conio.h>
Void main()
{
Char ch;
printf(“enter the character”);
scanf(“%d”,ch); : scanf(“%c”,&ch);
If(ch=’a’||ch=’z’)
Printf(“Last or first alphabet); : printf(“Last or first alphabet”);
if isdigit(ch)
Then : Remove Then
Binty, Brinda, Ami F.Y.BCA- (B)

Printf(“Digit”);
}

(4) Find the error in the following program:

Solution

#include<stdio.h>
void MAIN() : void main()
{
int a1,b1;
print(“enter 2 numbers”); : printf(“enter 2 numbers”);
scanf(“%f%s”,&a1,&b1); : scanf(“%d%d”,&a1,&b1);
printf(“%2d\n%2d”,a1,b1);
}

[Question-4(A)]

Q-4(A) Discuss in detail (Ant 3): Marks-9

(1) Explain the following string functions with syntax and example.
Strcat(), Stecmp() and Strcpy().

Ans: -

(i)Strcat function:-

 The strcat function joins two strings together. It takes the following
form:

Strcat(string1, string2);
Binty, Brinda, Ami F.Y.BCA- (B)

 String1 and string2 are character arrays. When the function strcat
is executed, string2 is appended to string1. It does so by removing
the null character at the end of string1 and placing string2 from
there. The string at string2 remains unchanged. For example,
consider the following three strings:

Part 1= 0 1 2 3 4 5 6 7 8 9 0 1
V E R Y \0

Part 2= 0 1 2 3 4 5 6
G 0 0 D \0

Part 3= 0 1 2 3 4 5 6
B A D \0

 Execution of the statement


Strcat(part1,part2);

 Will result in:

Part 1= 0 1 2 3 4 5 6 7 8 9 0 1 2
V E R Y G 0 0 D \0

Part 2= 0 1 2 3 4 5 6
G 0 0 D \0

Strcat(part1,part3);

 Will result in:

Part 1= 0 1 2 3 4 5 6 7 8 9 0 1 2
V E R Y B A D \0
Binty, Brinda, Ami F.Y.BCA- (B)

Part 3= 0 1 2 3 4 5 6
B A D \0

 We must make sure that the size of string1 (to which string2 is
appended) is large enough to accommodate the final string.

 Strcat function may also append a string constant to a string


variable. The following is valid:

Strcat(part1,”GOOD”);

 C permits nesting of strcat function.

Strcat(strcat(string1,string2),string3);
Is allowed and concatenates all the three strings together. There
results string is stored in string1.

(ii) STRCMP function:-

 The strcmp function compares two strings identified by the


arguments and has a value 0 if they are equal. If they are not, it has
the numeric difference between the first nonmatching characters in
the string. It takes the form:

Strcmp(string1,string2);

 String1 and string2 may be string variables or string constants. For


example are:

Strcmp(name1,name2);
Strcmp(name1,”John”);
Strcmp(“Rom”,”Ram”);
Binty, Brinda, Ami F.Y.BCA- (B)

 Our major problem is to determine whether the strings are equal; if


not, which is alphabetically above. The value of the mismatch is
rarely important. For example, the statement

Strcmp(“their”,”there”);
Will return a value of -9 which is the numeric difference between
ASCII “i” and ASCII “r”. That is “i” minus “r” in ASCII code is -9. If
the value is negative, string1 is alphabetically above string2.

(iii) STRCPY function:-

 The srtcpy function works almost like a string-assignment


operator. It takes the form

Strcpy(string1,string2);

And assigns the content of string2 to string1. String2 may be a


character array variable or a string constant. For example, the
statement

Strcpy(city,”Delhi”);

Will assign the contents of the string variable string2 to the string
variable city1. The size of the array city1 should be large enough to
receive the contents of city2.

(2) Explain singly linked list, doubly linked list and circular linked list.

Ans: - In other word we can say that An Array is a list refers to a set of
items organized sequentially.

 We can use the index for accessing and manipulation of array


elements.
Binty, Brinda, Ami F.Y.BCA- (B)

 One major problem with the array is that the size of an array must
be specified precisely at the beginning.

 “ A different way to represent a list of structure that made up form


connection with each other (link)is called Link list”.

 Each structure of the List is called node

 Node having two fields one is containing and other is address of


other node( next node)

 These fields are connected by address / reference / pointer that are


understand by above figure.

 According to the process there are four main types of link list.

• Linear list ( simple link list):


Natural link list that is simple

• Circular linked list:


A link list that has no beginning and no end is known as
circular link list.
Binty, Brinda, Ami F.Y.BCA- (B)

• Two way link list( Doubly link list ):


A link list that use double set of pointer with each next
/ previous nodes is known as double link list.

 “A link list is a dynamic data structure”

 Advantages :-
 Link list can grow or shrink in size during the execution of a
program.(but array can’t)
 Link list can be made just as long as it required(Array has some fix
size at declare)
 Link list does not waste memory space (Array can)
 Link list provide very much flexibility to add, insert, delete node in
list(Array can’t)
 Link list can access by reference (pointer) (Array doesn’t need)

 Disadvantages :-
 Arbitrary items accessing cumbersome and time consuming.
 When we know the length of list it is better to use an array then
link list.
 Little bit difficult to provide accessing by pointer.

(3) Explain the following file function with syntax and example.
Rewind(), fclose( ) and fopen( ).

Ans:- Rewind( fp ):
Rewind takes a file pointer and resets the position to the
start of the file.For examp;e the statement:
Binty, Brinda, Ami F.Y.BCA- (B)

Rewind( fp );
N=ftell( fp ):
Would assign to fp because the file position has been set the start of the file
by rewin.This function helps us in reading a file more than once.Without
having to close and open the file.

fclose( ):
A file must be closed as soon as all operations on it have been
completed. This ensures that all outstanding information associated with the
file is flushed out from the buffers and all links to the file are broken.It also
prevents any acidental misuse of the file. In case, there is a limit to the
number of files that can be kept open simultaneously, closing of unwanted
files might help open the required files.Another instance where we have to
close a file is when we this for us.It takes the following form:

fclose ( file _pointer);


This would close the file associated with the FILE pointer file _pointer.
Look at the following segment of a program.

.....
.....
FILE *p1, *p2;
p1 = fopen (" INPUT", "w");
P2 = fopen(" OUTPUT", "r");
.....
.....
fclose( p1 );
fclose( p2 );
.....
This program opens two files and closes them after all operations on them
are completed.Once a file is closed, its file pointer can be reused for another
file.
As a matter of fact all files are closed automatically whenever a program
terminates.However, closing a file as soon as you are done with it is a good
programming habit.
Binty, Brinda, Ami F.Y.BCA- (B)

fopen( ):
Where file _name and file _type are strings that representes the
name of the data file and the manner in which the data file will be utilized,
respectively.The name chosen for the file name must be consistent within the
rules for naming files, as determined by the computer's operating system.
The file_type must be one of the strings shown in the following table:

FILE _type Meaning


"r" Open an existing file for reading only.
"w" Open a new file for writing only.If the file with
specified
File _name currently exist it will be destroyed and new
File is created in its place.
“a” Open an existing file for appending.A new file will be
Created if the file with the specific file_name does not
Exist.
“r+” Open an existing file for both reading and writing.
“w+” Open a new file for both reading and writing.If a file
with
The specified file_name currently exist,it will be
destroyed
And a new file is created in its place.
“a+” Open and existing file for reading and writing.A new
file
Will be created if the file with the specified file_name
does
Not exist.

Consider the following statements:


FILE *p1 , *p2;
P1 = fopen( “data” , “r”);
P2 = fopen( “results” , “w”);

We can open and use a number of files at a time. This number however
Binty, Brinda, Ami F.Y.BCA- (B)

depends on the system we use.

(4) What is macro substitution? Explain different types of macro


substitution.

Ans:- Macro substitution is a process where an indiferent in a program is


replaced by a predefined string composed of one or more tokens.The
preprocessor accomplishes this task under the direction of #define
statements.This statement,usually known as a macro definition (or simply a
macro) takes the following general form:

#define identifier string

If this statement is included in the program at the beginning,then the


preprocessor replaces every occurrence of the identifier in the source code
by the string.The keyword #define is written just as shown (starting from the
first column) followed by the identifier and a string,with at least one blank
space between them.Note that the definition is not terminated by a
semicolon.The string may be any text,while the identifier must be a valid C
name.
There are different forms substitutions.
1. Simple macro substituon.
2. Argumented macro substitution.
3. Nested macro substotuon.

Simple Macro Substituon:


Simple string replacement is commonly used to define constants. Examples
of definition of constants are:

#define COUNT 100


#define FALSE 0
#define SUBJECTS 6
#define PI 3.1445926
Binty, Brinda, Ami F.Y.BCA- (B)

#define CAPITAL "DELHI"

Notice that we have written all macros (identifiers) in capitals.It is a


converntion to write all macros in capitals to identify them as symbolic
constants.A definition, such as

#define M 5
Will replace all occurrences of M with 5, starting from the line of definition
to the end of the program.However, a macro inside a string does not get
replaced. Consider the following two lines:

Total = M * value;
printf(" M = %d\n" , M);

These two lines would be changed during preprocessing as follows:

total = 5 * value;
printf(" M = %d\n" , 5)
Notice that the strings "M=%d\n" is left unchanged.
A macro definition can include more than a simple constant value. It
can include expressions as well.Following are valid definitions:

#define AREA 5 * 12.46


#define SIZE sizeof(int) * 4
#define TWO-PI 2.0 * 3.1415926

Whenever we use expressions for replacement, care should be taken to


prevent an unexpected order of evaluation. Consider the evaluation of the
equaton
Ratio = D/A;

Where D and A are macros defined as follows:

#define D 45 – 42
#define A 78 + 32
Binty, Brinda, Ami F.Y.BCA- (B)

The result of the preprocessor’s substitution for D and A is:

Ratio – 45-22 / 78 + 32;

This is certainly different from the expected expression

(45 – 22)/ (78 + 32)

Correct results can be obtained by using parentheses around the strings as;

#define D (45 – 22)


#define A (78 + 32)

It is a wise practice to use parentheses for expressions used in macro


definitions.
As mentioned earlier, the preprocessor performs a literal text
substitution, whenever the defined name occurs. This explains why we
cannot use a semicolon to terminate the #define statement. This also suggests
that we can use a macro to define almost anything. For example, we can use
the definitions

#define TEST if ( x > y )


#define AND
#define PRINT print (“Very Good. \n”)

To built a statement as follows :

TEST AND PRINT

The preprocessor would translate this line to

If ( x>y ) print f (“ Very Good. \n”) ;


Some tokens of C syntax are confusing or are error-prone. For
example, a common programming mistake is to use the token = in place of
Binty, Brinda, Ami F.Y.BCA- (B)

the token == in logical expressions. Similar is the case with the token &&.
Following are a few definitions that might be useful in building error free
and more readable programs:

#define EQUALS ==
#define AND &&
#define OR II
#define NOT_EQUAL !=
#define START main () {
#define END }
#define MOD %
#define BLANK LINE printf(“\n”);
#define INCREMENT ++

An example of the use of synthetic replacement is;

START
……..
……..
If(total EQUALS 240 AND average EQUALS 60)
INCREMENT count;
……..
…….
END

MACROS WITH ARGUMENTS:


The preprocessor permits us to define more complex and more useful form
of replacements.It takes the form:

#define identifier(f1 , f2 . . . . . fn) string

Notice that there is no space between the macro identifier and the left
parentheses.The identifiers f1, f2,… … .,fn are the formal macro arguments
that are analogous to the formal arguments in a function definition.
Binty, Brinda, Ami F.Y.BCA- (B)

There is a basic difference between the simple replacement discussed


above and the replacement of macros with arguments.Subsequent occurrence
of a macro with arguments is known as a macro call( similar to a function
call). When a macro is called, the preprocessor substitutes the string,
replacing the formal parameters with the actual parameters.Hence,A strings
behaves like a template.
A simple example of a macro with arguments is

#define CUBE(x) (x*x*x*)


If the following statement appears later in the program

Volume = CUBE( side );


Then the preprocessor would expand this statement to:

Volume = ( side * side * side );


Concider the following statement:

Volume = CUBE( a+b );


This would expand to:

Volume = (a+b * a+b * a+b);


This would obviously not produce the correct results. This is because the
preprocessor performs a blind test substitution of the argument a+b in place
of x. This shortcoming can be corrected by using parentheses for each
occurrence of a formal argument in the string.
Example:

#define CUBE( x ) ( (x) * (x) * (x) )


This would result in correct expansion of CUBE(a+b) as:

Volume = ( (a+b) * (a+b) * (a+b) );


Remember to use parentheses for each occurrence of a formal argument,as
well as the whole string.
Some commonly used definitions are:
Binty, Brinda, Ami F.Y.BCA- (B)

#define MAX(a,b) ((a)>(b)) ? (a) : (b))


#define MIN(a,b) ((a)<(b)) ? (a) : (b))
#define ABS(x) ((x)>0) ? (x) :
(-(x)))
#define STREQ(s1,s2) (strcmp( s1,)
(s2))==0)
#define STRGT(s1,s2) (strcmp(s1,)
(s2))>0)
The argument supplied to a macro can be any series of characters. For
example,the definition

#define PRINT (variable,format) printf(“variable=


%format\n”,variable)can be called-in by

PRINT(price * quantity);
Note that the actual paramaters are substituted for formal parameters in a
macro call, although they are within a string. This definition can be used for
printing integers and character strings as well.

Nesting of macros:

We can also use one macro in the definition of another macro. That is, macro
definitions may be nested. For instance, consider the following macro
definitions.

#define M 5
#define N M+1
#define SQUARE(x) ( (x) * (x) )
#define CUBE(x) (SQUARE (x) * (x) )
#define SIXTH (CUBE(x) * CUBE(x) )
The preprocessor expands each #define macro, until no more macros
appear in the text. For example, the last definition is expanded into

( (SQUARE(x) * (x) ) * (SQUARE(x) * (x) ) )


Since SQUARE (x) is still a macro,it is further expanded into
Binty, Brinda, Ami F.Y.BCA- (B)

( ( ( (x)*(x) ) * (x) ) * ( ((x) * (x)) * (x)) )


Which is finally evaluated as x6 .
Macro can also be used as parameters of other macros. For example.given
the definitions of M and N, we can define the following macro to given the
maximum of these two:

#define MAX(M,N) (( (M)>(N) )? (M) : (N))


Macro calls can be nested in much the same fashion as function calls.
Example:

#define HALF(x) ( (X)/2.0)


#define Y HALF(HALF(x))
Similarly, given the definition of MAX (a,b)we can use the following nested
call to give the maximum of the three values x,y, and z:

MAX(x, MAX(y,z) )

Undefining a Macro:
A define macro can be undefined, using the statement

#undef identifier
This is useful when we want to restrict the definition only to a particular part
of the program.

(5) List all the operators available in"C".

Ans:- "C" supports a rich set of operaters.An operator is a symbol that is


computer to perform certain mathematical or logical operations C operators
can classified into following categories.
• Arethmatic operators
• Relational operators
• Logical operators
Binty, Brinda, Ami F.Y.BCA- (B)

• Assignment operators
• Increment and decrement operators
• Conditional operators
• Bitwise operators
• Special operators

1. Arithmetic operators:-

"C" provides all basic arithmatic operators.This operators


can work on any built in data type.

{+} Addition or unary plus


{-} Substraction or minus
{*} Multiplication
{/} Devidation
{%} Modular or Reminder after integer division

Examples (Suppose A=10 and B=3)

Expression Values
A+B 13
a-b 7
A*B 30
A/B 3
A%b 1

2. Relational operators:

 There are four relational operators in "c".They are:

< Less than


<= Less than or equal to
> Grater than
>= Grater than or equal to the associatively of these
Binty, Brinda, Ami F.Y.BCA- (B)

An operator is left-to-right. Closely associated with the relational operators


are the following two equality operators:
== Equal to
! = Not equal to
Suppose that I, j and k integer variable whose values are1,2 and 3
respectively, Seven logical expression involving these variables are shown
below:

Expression Interpretation Value


I<j True 1
(I+j)>k True 1
(j+k)>(I+5) False 0
K!=3 False 0
J=2 True

3. Logical operatoprs:

"C"provides three logical operators.They are:

Operators Meaning
& AND
II OR
! NOT

These operators are reffered to as logical AND logical OR NOT


respectively.

The foiiowing table shows the results of the combined expressions


depending on the value of the
Expression:

Operands Results
Exp1 Exp2 Exp1&Exp2 Exp1 II Exp2
0 0 0 0
Binty, Brinda, Ami F.Y.BCA- (B)

0 Non-zero 0 1
Non-zero 0 0 1
Non-zero Non-zero 1 1
4. Assignment operators:

Assignments are used to assign the result of an expression to a variable.

In addition to equal to (=) operator "C" also supports hand assignment
operators.
Identifier =Expression
a=a+1 a+=1
a=a-1 a- =1
a=a/(n-1) a/=(n-1)
a=a%10 a%=10

5. Increment & decrement operators:

 ++&_ _

’C’ allows two very useful operators :(++&_ _)

The operator (++) adds one to the opernal while operator ( _ _ )


substracts one to the opernal.

Examples:
++a & a++ (writting form)
m=5 m=5
y=+m y=++
In this case value of y and m will be six(6)
In this case value of y will be 5 and m will be 6
A prefix operator first adds one to the opernal & them the result
is assign to the variable on left.
A prefix operator first assigns a value to the variable in left &
than increment the opernal.
Binty, Brinda, Ami F.Y.BCA- (B)

6. Conditional operator:

Simple conditional operators can be carried out with the conditional


operator (?:)An expression that makes the use of the conditional operator is
called a conditional expression.Conditional operators are also known as
turnery operators.
Syntax:
(Condition)? true:false
Exp1 ? Exp:Exp 3

Here if condition is evaluated as true then value of exp2 will be return and if
condition is evaluated as false then exp 3 will be return.

Example:
T=(I<0)? 0 : 100
If I variable value less then O then condition is evaluated as true
Y will be assigned with ) but if I variable value is greater then condition is
evaluated as false and 100 will be assign to variable T.

Example:
Printf("%d", (I<0) ? 0:100)

6. Bitwise operators:-
C has a distinction of supporting special operators known as
bitwise operators for manipulation of data at bit level.These operators are
used for testing the bits, or shifting them right or left.Bitwise operators may
not be applied to float or double.

Example:
Operators Meaning
& bitwise AND
I bitwise OR
^ Bitwise exlusive OR
Binty, Brinda, Ami F.Y.BCA- (B)

<< Shift left


>> shift right

7. Special operators-

 C supports some special operators of interest such as comma operator,


sizeof operator, pointer operators (& and *) and member selection operators
(. and ->). The comma and sizeof operators are discussed in this section.

The Size operators:


The size of the operator is a compile time operator and when
used with an opernal it returns the number of bytes that the opernal occupies.

Eg:-int a[10]
size of (a); 20 bytes

(6) Explain nested if and else-if ladder.

Ans:-
• Nested of If…else statement:-

 When a series of decisions are involved, we may have to


Use more than one if….else statement in nested for Shown
below:
 The logic of execution is illustrated in figure. If
The condition-1 is false, the statement-3 will be
Executed; otherwise it continues to perform the
Second test. If the condition-2 is true,
Binty, Brinda, Ami F.Y.BCA- (B)

 The statement-1 will be evaluate; otherwise the statement-2 will be


evaluated and then control is transferred to the statement-X.

 Example. A commercial bank has introduced an incentive policy of


giving bonus to all its deposit
Holders. The policy is as follows:
A bonus of 2 percentage of the balance held on
31st December is given to everyone, irrespective
Of their balance, and 5 percentage is given to
Female account holders if their balance is more
Than 5000. Topic logic can be coded as follows:

………….
If(sex is female)
{
if(balance>5000)
bonus=0.05*balance;
else
bonus=0.02*balance;
}
else
Binty, Brinda, Ami F.Y.BCA- (B)

{
bonus=0.02*balance;
}
balance=balance+bonus;
……………
……………

• The Else-If Ladder:-

 A multipath. Decision is a chain of ifs in which the


statements associated with each else is an if. It takes the
following general form:

 This construct is known as the else if ladder. The conditions


are evaluated from the top, downwards.
 As soon as a true condition is found, the statement associated
with it is executed and the control is transferred to the
statement-X (skipping the rest of the ladder).
 When all the n conditions become false, then the final else
containing the default-statement will be executed.
Binty, Brinda, Ami F.Y.BCA- (B)

 Let us consider an example of grading the students in an


academic institution. The grading is done according to the
following rules:
Avarage marks Grades
80 to 100 Honours
60 to 79 First division
50 to 59 second division
40 to 49 third division
0 to 39 fail
 This grading can be done using the else if ladder as
follows:
if (marks>79)
grade=”Honours”;
else if (marks>59)
grade=”First division”;
else if (marks>49)

grade=”Second class”;
else if (marks>39)
grade=”Third division”;
else
grade=”fail”;
printf(“%s\n”,grade);

[Question-4(B)]

Q-4(B) Answer in short (Any 5): Marks-5


Binty, Brinda, Ami F.Y.BCA- (B)

(1) Give application area of a linked list.


Ans:-create a dynamic list it is very useful in list we can access any element
from any position very easily and add, delete and update any information in
a linked list very easily, create a this type of applications linked list is useful.

(2) What is a counter controlled loop?

Ans: - When we know in advance exactly how many times the loop will be
executed, we use a counter controlled loop. This loop is called counter
controlled loop.

(3)List the storage classes available in ‘C’.


Ans:- A variable in C can have any one of the four storage classes:

Storage class Meaning

Auto Local variable known only to the function in which it is


declared. Default is auto.
Static Local variable which exists and retains its value even after
the control is transferred to the calling function.
Extern Global variable known to all functions in the file.
Register Local variable which is stored in the register.

(4)What is prototyping?
Ans:-A function declaration is called as a function prototype or function
signature. So, it would be used to reduce the compiling time.

(5) What is scale factor?

Ans:-When we increment a pointer, its value is increased by the ‘length’ of


the data type that is point to. This length called the scale factor.
Binty, Brinda, Ami F.Y.BCA- (B)

(6) What is implicit conversion?

Ans:- If the operands are of different types, the lower type is automatically
converted to higher type and the result is of higher type. This automatic
conversion is known as implicit type conversions

(7)What is the output of sizeof () function?


Ans:-In a size of function we can pass datatype or variable in a
function and it will give the size of the datatype or variable.
Ex.sizeof(int) that will give us two as a result. Two bytes is a size of
an integer.
[Question-5(A)]

Q-5(A) Write ‘C’ program for the following:

(1)Read a number and find out whether it is palindrome or not.

Ans:-
#include<stdio.h>
#include<conio.h>
void main()
{
int num,sum=0;
printf(“Enter the number : ”);
scanf(“%d”,&num);

while(num>0)
{
sum=sum*10+num%10;
num=num\10;
}

If(sum==num)
Binty, Brinda, Ami F.Y.BCA- (B)

{
Printf(“the number is palindrome”);
}
Else
{
Printf(“the number is not palindrome”);
}

getch();
}

(2)Read a string and find out the following without using any string
function.

(a) Length of string.

Ans:-
#include<stdio.h>
main()
{
int len=0;
clrscr();
char s[10];

printf(“Enter a string”);
scanf(“%[^\n]”,s);

while(s[len]!=’\0’)
{len++;}
printf(“Length : %d”,len);
}

(b) Number of vowels in the string. (a, e, i, o, u are called vowels)


Binty, Brinda, Ami F.Y.BCA- (B)

Ans:-
#include<stdio.h>
#include<ctype.h>
main()
{
char s[40],ch;
int len=0,I,c=0;

printf(“Enter original string :”);


scanf(“%[^\n]”,s);

while(s[len]!=’\0’)len++;
for(i=0;i<len;++i)
{
ch=toupper(s[i]);
if(ch==’A’||ch==’I’||ch==’O’||ch==’U’)c++;
}
printf(“Total count :”,c);
}

(3) Read 10 numbers in an array and find maximum from those


numbers.
Ans:-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int num[10], i, max=0,n;

printf(“How many elements ? ”);


scanf(“%d”,&n);
printf(“Enter %d elements \n”,n);
Binty, Brinda, Ami F.Y.BCA- (B)

for(i=0;i<n;++i)
{
Scanf(“%d”,&num[i]);
If(num[i]>max)
{
Max=num[i];
}
}
Printf(“Maximum=%d”,max);
getch();
}

(4)Create a structure called “emp_data which would have the


following member:
Emp_name,which stores name of the employee,
Emp_basic, which stores the basic salary of the employee,
Emp_da, which stores the amount of deaeness allowance paid
to the employee.
Emp_total, which is the sum of employee’s basic salary and
deaeness allowance.
Create an array of 10 such records and read the data for
emp_name and emp_basic from the keyboard. Computer
emp_da, which is 90% of basic salary and emp_total. Display
all records.

#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
float basic;
float da;
float total;
Binty, Brinda, Ami F.Y.BCA- (B)

}st[10];

void main()
{
int i;

for(i=1;i<=10;i++)
{

printf("Emploee name:");
scanf("%s",&st[i].name);

printf("employee basic:");
scanf("%f",&st[i].basic);
}

for(i=1;i<=10;i++)
{
st[i].da=0.9*st[i].basic;
st[i].total=st[i].basic+st[i].da;
}
printf("********************************************");
printf("emp_name\t emp_basic\t emp_da\t emp_total\n");
for(i=1;i<=10;i++)
{
printf("%s\t %f\t %f\t
%f\n",st[i].name,st[i].basic,st[i].da,st[i].total);
}
getch();
}

(5)Generate the following pattern for n number of rows, where


n is read from the user.
Binty, Brinda, Ami F.Y.BCA- (B)

Ans:-
#include<stdio.h>
#include<conio.h>
Void main()
{
Int i,j,n=4;

For(i=1;i<=n;++i)
{
For(j=1;j<=I;j++)
{
Printf(“%d”,i);
}
Printf(“\n”);
}
}

(6) Compute the factorial of a number using recursion:

Ans:-
#include<stdio.h>
#include<conio.h>
Void main()
{
int n,i,sum=0,k=1;
printf(“Enter n : ”);
scanf(“%d”,&n);

for(i=1;i<=n;i++)
{
K=k*I;
Sum=sum+k
}

Printf(“sum=%d”,sum);
Binty, Brinda, Ami F.Y.BCA- (B)

getch();
}

[Question-5(B)]

Q-5(B) Give one word for the following:

(1)A data structure, which allows storing multiple items of the same
data type:- Structure

(2) A derived data type, which allows storing the memory addresses:-
Pointer.

Вам также может понравиться