Sei sulla pagina 1di 62

GE6151 Computer Programming Question Bank

UNIT I - INTRODUCTION
PART A (2 MARKS)
1. Define computers?
A computer is a programmable machine or device that performs pre-defined or programmed
computations or controls operations that are expressible in numerical or logical terms at high speed and with
great accuracy.
(Or)
Computer is a fast operating electronic device, which automatically accepts and store input data,
processes them and produces results under the direction of step by step program.

2. What are the basic operations of Computer?

It accepts data or instructions by way of input

It stores data.

It can process data as required by the user.

It gives results in the form of output.

It controls all operations inside a computer.

3. What are the characteristics of computers? (JAN 2009)


Speed, Accuracy, Automation, Endurance, Versatility, Storage, Cost Reduction.
4. How will you classify computer systems? (JAN2009)
Based on physical size, performance and application areas, we can generally divide computers into four
major categories:

Micro computer
Mini Computer
Mainframe computer
Super Computer

5. Expand ENIVAC, ABC, EDVAC, EDSAC and UNIVAC. (JAN2010)


ENIAC

- Electronic Numerical Integrator and Calculator.

ABC

- Atanasoff and Berry Computer.

EDVAC

- Electronic Discrete Variable Automatic Calculator.

EDSAC

- Electronic Delay Storage Automatic Calculator.

UNIVAC

- UNIversal Automatic Computer.

6. What are the components of the computer systems?

Basic components of the computer system are Input Unit, Central Processing Unit, Secondary Storage Unit
and Output Unit.

7. What is an ALU?
Arithmetic logic unit, the part of a computer that performs all arithmetic computations, such as addition and
multiplication, and all logical operations such as comparison operations. The ALU is one component of the
CPU (central processing unit).
8. What are the functions in the input unit?
An input device is a device that is used to input data or information into a computer. Some examples of input
devices include:

Keyboards.
Computer mice
Light Pen.

Digitizer.

Touchpad.

9. What are the functions in the output unit?


In computers, a unit which delivers information from the computer to an external device or from internal
storage to external storage.

Speakers.
Printer.
Headphone

10. Define Mainframe computer?


Mainframes are computers used mainly by large organizations for critical applications, typically bulk data
processing such as census, industry and consumer statistics, enterprise resource planning, and financial
processing. The term probably had originated from the early mainframes, as they were housed in enormous,
room-sized metal boxes or frames.
11. Define super computer?
The fastest type of computer. Supercomputers are very expensive and are employed for specialized
applications that require immense amounts of mathematical calculations. For example, weather
forecasting requires a supercomputer. Other uses of supercomputers include animated graphics, fluid
dynamic calculations, nuclear energy research, and petroleum exploration.
12. What is a volatile and non-volatile memory?

Volatile memory: also known as volatile storage is computer memory that requires power to maintain the
stored information, unlike non-volatile memory which does not require a maintained power supply. It has
been less popularly known as temporary memory.
Non-volatile memory: nonvolatile memory, NVM or non-volatile storage, is computer memory that can
retain the stored information even when not powered.
13. Write the binary and octal equivalent of hexadecimal number 7BD? (APR2009)
Binary Equivalent of 7BD = (0111 1011 1101)2
Octal Equivalent of 7BD = (011 110 111 101) = (3675)8
14. Convert binary number 100110 into its octal equivalent? (JAN2009)
Octal equivalent of 100110 = (100 110) = (46)8
15. What are registers? (JAN2009)
A special, high-speed storage area within the CPU. All data must be represented in a register before it can be
processed.
For example, if two numbers are to be multiplied, both numbers must be in registers, and the result is also
placed in a register.
16. Differentiate analog and digital computers? (JAN2010) Analog Computer Digital Computer
Sl.No

Analog Computer

Digital Computer

Process measured data

Process discrete data

Analog computers are not precise

Digital computers are more precise

Processing speed is low

Processing speed is high.

Less accuracy

More accuracy.

17. Find the decimal equivalent of hexadecimal number 4D.C8 (JAN2010)


4D.C8 = 4 X 161 + 13 X 162 + 12 X 16-1 + 8 X 16-2
= 64 + 13 +0.75 + 0.03125
= (77.78)2
18. Convert hexadecimal number into binary equivalent of EBC (JAN2010)
Binary equivalent of EBC = (1110 1011 1100)2
19. What is algorithm? (JAN2009)
Algorithm means the logic of a program. It is a step-by-step description of how to arrive at a solution of a
given problem.
20. What are the steps to solve the problem in a computer system?
Problem must be analyzed thoroughly.

Solution method is broken down into a sequence of small tasks.


Based on this analysis, an algorithm must be prepared to solve the problem.
The algorithm is expressed in a precise notation. This notation is known as Computer Program.

The Computer program is fed to the computer.


The instruction in the program executes one after another and outputs the expected result.

21. What are the characteristics of an algorithm?

In algorithms each and every instruction should be precise.


In algorithms each and every instruction should be unambiguous.
The instructions in an algorithm should not be repeated infinitely.

Ensure that the algorithm will ultimately terminate.

The algorithm should be written in sequence.

It looks like normal English.

22. What is Flowchart?


A Flowchart is a pictorial representation of an algorithm. It is often used by programmer as a program
planning tool for organizing a sequence of step necessary to solve a problem by a computer.
23. What is the need of Flowchart symbols?
Each symbol of different shapes denotes different shapes denote different types of instructions. The
program logic through flowcharts is made easier through the use of symbol that has standardized
planning.
24. What is pseudo code?
Pseudo means imitation of false and code refers to the instruction written in the programming
language. Pseudo code is programming analysis tool that is used for planning program logic.

25. Draw the flowchart to find the maximum among three numbers (JAN2009)

UNIT-II
1. Define Compilation process.
Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object'
file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the
machine language instructions that correspond to the source code file that was compiled.
2. What do you meant by linking?
Linking refers to the creation of a single executable file from multiple object files. In this step, it is
common that the linker will complain about undefined functions (commonly, main itself). During
compilation, if the compiler could not find the definition for a particular function, it would just assume
that the function was defined in another file. If this isn't the case, there's no way the compiler would know it
doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at
multiple files and try to find references for the functions that weren't mentioned.
3. Define Constants in C. Mention the types.
The constants refer to fixed values that the program may not alter during its execution. These fixed values
are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their
definition.
4. What are the different data types available in C?
There are four basic data types available in C.
1. int
2. float
3. char
4. double
5. What is meant by Enumerated data type.
Enumerated data is a user defined data type in C language.
Enumerated data type variables can only assume values which have been previously declared.
Example :
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
6. What are Keywords?
Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can
be used only for their intended purpose.

7. What do you mean by variables in C?

A variable is a data name used for storing a data value.


Can be assigned different values at different times during program execution.
Can be chosen by programmer in a meaningful way so as to reflect its function in the program

Example: Sum
8. Difference between Local and Global variable in C.
Local
These variables only exist inside the specific function that creates them. They are unknown to other
functions and to the main program. As such, they are normally implemented using a stack. Local
variables cease to exist once the function that created them is completed. They are recreated each time a
function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are
implemented by associating memory locations with variable names. They do not get recreated if the
function is recalled.
9. What are Operators? Mention their types in C.
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 following type of operators:

Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Special Operators

10. What is the difference between = and == operator?


Where = is an assignment operator and == is a relational operator.
Example:
while (i=5) is an infinite loop because it is a non zero value and while (i==5) is true only when i=5.
11. What is type casting?
Type casting is the process of converting the value of an expression to a particular data type.
Example:
int x,y;
c = (float) x/y; where a and y are defined as integers. Then the result of x/y is converted into float.
12.What is the difference between ++a and a++?

++a

means

do

the

increment

before

the

operation

(pre

increment)

a++ means do the increment after the operation (post increment)

Example:
a=5;
x=a++;
y=a;
x=++a;
3. Distinguish between while..do and do..while statement in C. (JAN 2009)
While
Executes the statements within the while block if only the
condition is true.

DO..while

The condition is checked at the starting of the loop (Entry

The condition is checked at the end of the

Controlled Statement)

loop (Exit Control Statement)

Executes the statements within the while


block at least once.

14. Mention the various Decisions making statement available in C.


Statement
if statement
if...else statement

nested if statements

Description

An if statement consists of a boolean expression followed by one or more s

An if statement can be followed by an optional else statement, which exec


when the boolean expression is false

You can use one if or else if statement inside another if or else if statemen
switch statement

A switch statement allows a variable to be tested for equality against a list o


You can use one swicth statement inside another switch statement(s).

nested switch statements

15.What do you meant by conditional or ternary operator?


? : If Condition is true ? Then value X : Otherwise value Y
16. What is the use of sizeof() operator in C.
Sizeof operator is used to return the size of an variable.
Example : sizeof(a), Where a integer, will return 4.
17. Define Looping in C .
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages
18. What are the types of looping statements available in C
C programming language provides following types of loop to handle looping requirements.
while loop

Repeats a statement or group of statements while a given condition is true.


It tests the condition before executing the loop body.
for loop
do...while loop
nested loops
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
loop.

can

use

one

or

more

loop

inside

any

19. What are the types of I/O statements available in C?


There

are

two

types

of

I/O

statements

available

in

C.

Statements
20. Write short notes about main ( ) function in C program. (MAY 2009)

m execution starts from the opening brace { and ends with closing brace }, within
which executable part of the program exists.
21. Define delimiters in C.
Delimiters Use
: Colon
; Semicolon
( ) Parenthesis
[

Square
}

Curly

Bracket
Brace

# Hash
, Comma
22. Why header files are included in C programming?
This section is used to include the function definitions used in the program. Each header file has h
extension and include using # include directive at the beginning of a program.
23.What is the output of the programs given below?
main()

main()

float a;

float a;

int x=6, y=4;

int x=6, y=4;

a=x\y;

a=(float) x\y;

printf(Value of a=%f, a);

printf(Value of a=%f,a);

Output:

Output:

1.

1.500000

24.What is the difference between scanf() and gets() function?


In scanf() when there is a blank was typed, the scanf() assumes that it is an end. gets() assumes the enter key
as end. That is gets() gets a new line (\n) terminated string of characters from the keyboard and replaces
the \n with \0.
25.What are the Escape Sequences present in C
\n - New Line
\b - Backspace
\t - Form feed
\ - Single quote
\\ - Backspace
\t - Tab
\r - Carriage return
\a - Alert
\ - Double quotes
26.What is the difference between if and while statement?
If

While

(i) It is a conditional statement

(i) It is a loop control statement

(ii) If the condition is true, it


executes

(ii) Executes the statements within the


while block if the condition is true.

some statements.
(iii) If the condition is false the control is
(iii) If the condition is false then it
stops
the execution the statements.

transferred to the next statement of the loop.

27.Differentiate between formatted and unformatted you input and output functions? Formatted I/P functions:
These functions allow us to supply the input in a fixed format and let us obtain the output in the specified
form. Formatted output converts the internal binary representation of the data to ASCII characters which are
written to the output file.
Unformatted I/O functions:
There are several standard library functions available under this category-those that can deal with a string of
characters. Unformatted Input/Output is the most basic form of input/output. Unformatted input/output
transfers the internal binary representation of the data directly between memory and the file.

UNIT II
(16 Marks)
1. Define C language. Mention the basic structure of C programs with explanation. (16)
C programs are essentially constructed in the following manner, as a number of well defined sections.
/* HEADER SECTION
*/
/* Contains name, author, revision number*/
/* INCLUDE SECTION
/* contains #include statements

*/
*/

/* CONSTANTS AND TYPES SECTION


/* contains types and #defines

*/
*/

/* GLOBAL VARIABLES SECTION


*/

*/ /* any global variables declared here

/* FUNCTIONS SECTION
/* user defined functions

*/
*/

/* main() SECTION

*/

int
{
----}

main()

A Simple Program
The following program is written in the C programming language.
#include <stdio.h>
Void main()
{
printf(Programming
}

in

is

easy.\n);

INITIALISING DATA VARIABLES AT DECLARATION TIME


In C, variables may be initialized with a value when they are declared. Consider the following
declaration, which declares an integer variable count which is initialized to 10. int count = 10;
SIMPLE ASSIGNMENT OF VALUES TO VARIABLES
The = operator is used to assign values to data variables. Consider the following statement, which assigns the
value 32 an integer variable count, and the letter A to the character variable letter
count = 32;
letter = A
Variable Formatters
%d decimal integer %c character
%s
string
%f float
%e double

or

character

array

HEADER FILES
Header files contain definitions of functions and variables which can be incorporated into any C
program by using the pre-processor #include statement. Standard header files are provided with each
compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading
of variables. To use any of the standard functions, the appropriate header file should be included. This is
done at the beginning of the C source file. For example, to use the function printf() in a program, the line
#include <stdio.h> should be at the beginning of the source file, because the definition for printf() is
found in the file stdio.h All header files have the extension .h and generally reside in the /include
subdirectory.
#include <stdio.h>
#include mydecls.h
The use of angle brackets <> informs the compiler to search the compilers include directory for the
specified file. The use of the double quotes around the filename inform the compiler to search in the
current directory for the specified file.
2. Discuss about the various data types in C. (MAY 2009)
The four basic data types are
a. INTEGER
These are whole numbers, both positive and negative. Unsigned integers (positive values only) are
supported. In addition, there are short and long integers.
The keyword used to define integers is,

int
An example of an integer value is 32. An example of declaring an integer

variable called sum is,

int sum;
sum = 20;
b. FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword used to define
float variables is, float An example of a float value is 34.12. An example of declaring a float variable
called money is,
float

money;

money = 0.12;
c. DOUBLE
These are exponentional numbers, both positive and negative. The keyword used to define double
variables is, double
An example of a double value is 3.0E2. An example of declaring a double

variable called big is,

double big;
big = 312E+7;
d. CHARACTER
These are single characters. The keyword used to define character variables is,char An example of a
character value is the letter A. An example of declaring a character variable called letter is, char letter;
letter = A;
Note the assignment of the character A to the variable letter is done by enclosing the value in single
quotes.
Example:
#include

<

stdio.h

>

main()
{
int sum;
float

money;

char

letter;

double pi;

sum = 10;

/* assign integer value */

money = 2.21; /* assign float value */


letter = A;

/* assign character value */

pi = 2.01E6;

/* assign a double value */

printf(value of sum = %d\n, sum );


printf(value

of

money

%f\n,

money

);

printf(value

of

letter

%c\n,

letter

);

pi

pi

);

printf(value

of

%e\n,

}
Sample program output
value of sum = 10
value of money = 2.210000 value of letter = A
value of pi = 2.010000e+06
3. What are Operators? Explain the various operators available in C. (16)
An ex pr e ss io n is a sequence of operators and operands that specifies computation of a value, or that
designates an object or a function, or that generates side effects, or that performs a combination thereof.
ARITHMETIC OPERATORS:
The symbols of the arithmetic operators are:Operation Operator Comment
Multiply
Divide

Value of Sum before Value of sum after

sum = sum * 2;
sum = sum / 2;

4
4

8
2

Addition

sum = sum + 2;

Subtraction

sum = sum -2;

Increment

++

++sum;

Decrement

--

--sum;

Modulus

Example:

sum = sum % 3;

#include
main()
{
int sum 50;
float modulus;
modulus = sum % 10;
printf("The
%%
}

<stdio.h>

of

%d

by

10

is

%f\n",

sum,

modulus);

PRE/POST INCREMENT/DECREMENT OPERATORS


PRE means do the operation first followed by any assignment operation. POST means do the operation after
any assignment operation. Consider the following statements
++count;
count++;

/* PRE Increment, means add one to count */


/* POST Increment, means add one to count */

THE RELATIONAL OPERATORS


These allow the comparison of two or more variables.
n
equal to
!=not
<less than
<=less than or equal to >greater than
>=greater than or equal to

equal

Example:
#include <stdio.h>
main()
/*
Program
introduces
the
for
statement,
counts
{
int count;
for( count = 1; count <= 10; count = count + 1 ) printf("%d ", ount ); printf("\n");
}
LOGICAL (AND, NOT, OR, EOR)

to

ten

Combining more than one condition


These allow the testing of more than one condition as part of selection statements. The symbols are

LOGICAL AND &&


Logical and requires all conditions to evaluate as TRUE (non-zero).

*/

LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
LOGICAL NOT !
logical not negates (changes from TRUE to FALSE, vsvs) a condition.
LOGICAL EOR ^
Logical error will be executed if either condition is TRUE, but NOT if they are all true.

THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR


This conditional expression operator takes THREE operators. The two symbols used to denote this operator
are
the ? and the :. The first operand is placed before the ?, the second operand between the ? and the :, and the
third after the :. The general format is,
condition ? expression1 : expression2
If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the evaluation
becomes the result of the operation. If the condition is FALSE (zero), then expression2 is evaluated and its
result becomes the result of the operation. An example will help,
s = ( x < 0 ) ? -1 : x * x;
If x is less than zero then s = -1
If x is greater than zero then s = x * x

BIT OPERATIONS

C has the advantage of direct bit manipulation and the operations available are,

Operation

Operator Comment

AND

&

sum = sum & 2;

OR

sum = sum | 2;

Exclusive OR

sum = sum ^ 2;

1's Complement

sum = ~sum;

Left Shift

<<

sum = sum << 2;

Value of Sum before Value of sum after


4

-5
4

Right Shift

>>

16

sum = sum >> 2;

Example:
/*

Example

program
#include <stdio.h>

illustrating

<<

and

>>

*/

main()
{
int n1 = 10, n2 = 20, i = 0;
i
=
n2
<<
four
times
i = n1 >> 5; /* n1 shifted right
five
times
}
4.

Explain

in

detail

about

4;
*/

/*

n2
shifted
printf("%d\n",

*/
managing

printf("%d\n",
the

Input

Output

left
i);
i);

Operations.

(16)

Printf ():
printf() is actually a function (procedure) in C that is used for printing variables and text. Where text
appears in double quotes "", it is printed without modification. There are some exceptions however. This has
to do with the \ and % characters. These characters are modifier's, and for the present the \ followed by the n
character represents a newline character.

Example:
#include <stdio.h>
main()
{
printf("Programming
in
printf("And
so
}
O/P:
Programming in C is easy. And so is Pascal.

is

easy.\n");
Pascal.\n");

is

Scanf ():
Scanf () is a function in C which allows the programmer to accept input from a keyboard.
Example:
#include <stdio.h>
main()
{
int number;

/*

printf("Type
printf("The
}

in
number

program

which

number
you

introduces

\n");
typed

was

keyboard

input

scanf("%d",
%d\n",

*/

&number);
number);

ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD Getchar, Putchar


getchar() gets a single character from the keyboard, and putchar() writes a single character from the keyboard.
Example:
The following program illustrates this:
#include <stdio.h>
main()
{
int i; int ch;
for(
{
ch
putchar(ch);
}
}

1;

i<=
=

5;

++i

)
getchar();

The program reads five characters (one for each iteration of the for loop) from the keyboard. Note that
getchar() gets a single character from the keyboard, and putchar() writes a single character (in this case, ch)
to the console screen

5. Explain the various decision making mechanism in C. (16) IF STATEMENTS


The if statements allows branching (decision making) depending upon the value or state of variables. This
allows statements to be executed or skipped, depending upon decisions. The basic format is,

if( expression )
program statement;
Example:
if(
++student_count;

students

<

65

IF ELSE
The general format for these is,
if( condition 1 ) statement1;
else if( condition
2 ) statement2;
else if( condition
3 ) statement3;
else statement4;
The else clause allows action to be taken where the condition evaluates as false (zero).
The following program uses an if else statement to validate the users input to be in the range 1-10.
Example:
#include <stdio.h>
main()
{
int number; int valid = 0;
while( valid == 0 ) {
printf("Enter a number between 1 and 10 -->"); scanf("%d",&number); if( number < 1 )
{
printf("Number
is
below
1.
Please
re-enter\n");
valid
}
else
if(
number
>
10
{
printf("Number
is
above
10.
Please
re-enter\n");
valid
}
else
valid
=
}

0;
)

0;
1;

printf("The number is %d\n", number );


}
NESTED IF ELSE
/* Illustates nested if else and multiple arguments to the scanf function. */
Example:
#include <stdio.h>
main()
{
int
invalid_oper
ator = 0;
char
operator;
float number1, number2, result;
printf("Enter
two
numbers
and
the
format\n");
printf("
number2\n");
scanf("%f %c %f", &number1, &operator, &number2);
if(operator == '*')
result = number1
* number2; else if(operator
==
result =
number1
/
+ number2; else if(operator
==
result
else
invalid_operator = 1;
if( invalid_operator != 1 )
printf("%f
%c
else
printf("Invalid operator.\n");

an
number1

operator

in
operator

'/')
number2;
else
result = number1

if(operator

==

'+')

'-')
=

%f

number1

is

%f\n",

number1,

operator,

number2;

number2,

result

);

6. With example explain the Branching and Looping mechanism in C (16) ITERATION, FOR LOOPS
The basic format of the for statement is,
for(

start

condition;
continue
program statement;

condition;

re-evaulation

Example:
/* sample program using a for statement
*/ #include <stdio.h>
main()
/*
{
int count;

Program

introduces

the

for

statement,

counts

to

ten

*/

for( count = 1; count <= 10; count = count + 1 ) printf("%d ", count );
printf("\n");
}
The program declares an integer variable count. The first part of the for statement
for( count = 1;
initialises the value of count to 1. The for loop continues whilst the condition
count <= 10;
evaluates as TRUE. As the variable count has just been initialised to 1, this condition is TRUE and so the
program statement printf("%d ", count ); is executed, which prints the value of count to the screen,
followed by a space character.
Next, the remaining statement of the for is executed
count = count + 1 );
which adds one to the current value of count. Control now passes back to the conditional test,
count <= 10;
which evaluates as true, so the program statement
printf("%d ", count );
is executed. Count is incremented again, the condition re-evaluated etc, until count reaches a value of
11.
When this occurs, the conditional test
count <= 10;
evaluates as FALSE, and the for loop terminates, and program control passes to the statement
printf("\n");
which prints a newline, and then the program terminates, as there are no more statements left to
execute.
THE WHILE STATEMENT
The while provides a mechanism for repeating C statements whilst a condition is true. Its format is,
while( condition )
program statement;

Somewhere within the body of the while loop a statement must alter the value of the condition to allow the
loop to finish.
Example:
/* Sample program
including
#include <stdio.h>

while

*/

main()
{
int loop = 0;
while(
{
printf("%d\n",

loop

<=

10

)
loop);

++loop;
}
}
The above program uses a while loop to repeat the statements
printf("%d\n", loop);
++loop;
while the value of the variable loop is less than or equal to 10.
Note how the variable upon which the while is dependant is initialised prior to the while statement (in this case
the previous line), and also that the value of the variable is altered within the loop, so that eventually the
conditional test will succeed and the while loop will terminate.
This program is functionally equivalent to the earlier for program which counted to ten. THE DO WHILE
STATEMENT
The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The
loop is executed as least once.
Example:
/* Demonstration of
DO...WHILE */
#include <stdio.h>
main()
{
int value, r_digit;
printf("Enter the number to be
reversed.\n"); scanf("%d", &value);

do {
r_digit
10;
r_digit); value
value / 10;
} while( value !=
0
}

= value %
printf("%d",
=
);

printf("\n");

The above program reverses a number that is entered by the user. It does this by using the modulus %
operator to extract the right most digits into the variable r_digit. The original number is then divided by 10,
and the operation repeated whilst the number is not equal to 0.
SWITCH CASE:
The switch case statement is a better way of writing a program when a series of if elses occurs. The general
format for this is,
switch ( expression )
{ case value1:
program
statement;
program statement;
break;
case valuen:
program statement;
break;
default:
break;
}
he keyword break must be included at the end of each case statement. The default clause is optional,
and is executed if the cases are not met. The right brace at the end signifies the end of the case
selections.
Example:
#include <stdio.h>
main()
{
int menu, numb1, numb2, total;
printf("enter

in

&numb1,

&numb2

printf("1=addition\n");
scanf("%d", &menu );

two

numbers
);

-->");
printf("enter

scanf("%d
in

%d",
choice\n");

printf("2=subtraction\n");

switch( menu )
{
case

1:

total

numb2;

break;

numb1

numb2;

default:

break;

case

printf("Invalid

2:

total
option

numb1

selected\n");

if( menu == 1 )
printf("%d plus %d is %d\n", numb1, numb2, total ); else if( menu == 2 ) printf("%d minus %d is %d\n",
numb1, numb2, total );
}
The above program uses a switch statement to validate and select upon the users input choice, simulating a
simple menu of choices.
7.C programs related to problem solving.
8..C programs related to scientific problem solving.

UNIT -III
2 MARKS
1. What is an array?
An array is a group of similar data types stored under a common name. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of the same
type.
Example:
int a[10];
Here a[10] is an array with 10 values.
2.

What

are

the

main

elements

of

an

array

declaration?

Type

and

3. How to initialize an array?


You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we declare for
the array between square brackets [ ]. Following is an example to assign a single element of the array:

4. Why is it necessary to give the size of an array in an array declaration?


When an array is declared, the compiler allocates a base address and reserves enough space in the
memory for all the elements of the array. The size is required to allocate the required space. Thus, the size must
be mentioned.
5. What is the difference between an array and pointer?
Difference between arrays and pointers are as follows.
Array
1.Array allocates space automatically
2.It cannot be resized.
3.It cannot be reassigned.
4.Size of(array name) gives the
number of bytes occupied by the array.

Pointer
1.Pointer is explicitly assigned to point to an allocated
space.
2.It can be resized using realloc ().
3.Pointers can be reassigned.
4.Sezeof(pointer name) returns the number of bytes
used to store the pointer variable
6. List the characteristics of Arrays.

All elements of an array share the same name, and they are distinguished form one another with help of
an element number. Any particular element of an array can be modified separately without disturbing
other elements.
7. What are the types of Arrays?
1.One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array
8. Define Strings.
Strings:
The group of characters, digit and symbols enclosed within quotes is called as Stirng (or) character
Arrays. Strings are always terminated with \0 (NULL) character. The compiler automatically adds \0 at
the end of the strings.
Example:
char name[]={C,O,L,L,E,G,E,E,\0};

9. Mention the various String Manipulation Functions in C.


Function & Purpose
strcpy(s1, s2);
strcat(s1, s2);
strlen(s1);
strcmp(s1, s2);
greater than 0 if s1>s2.
strchr(s1, ch);
string s1.
strstr(s1, s2);
s1.

Copies string s2 into string s1.


Concatenates string s2 onto the end of string s1.
Returns the length of string s1.
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
Returns a pointer to the first occurrence of character ch in
Returns a pointer to the first occurrence of string s2 in string

10. What is the use of atoi() function?


C allows us to manipulate characters the same way we do with numbers. Whenever a character
constant or character variable is used in an expression, it is automatically converted into integer value by the
system.
For eg, if the machine uses the ASCII representation, then,
x = a; printf(%d \n,x);
will display the number 97 on the screen.
The C library supports a function that converts a string of digits into their integer values. The
function takes the form
x = atoi(string)
11. What is the use of typedef?
It is used to create a new data using the existing type.
Syntax: typedef data type name;
Example:
typedef int hours: hours hrs;/* Now, hours can be used as new datatype */
12. What is meant by Sorting?
Sorting refers to ordering data in an increasing or decreasing fashion according to some linear relationship
among the data items. Sorting can be done on names, numbers and records.
13. What are the types of sorting available in C?

uick

Sort.

14. Define Heap Sort.


A sorting algorithm that works by first organizing the data to be sorted into a special type of
binary tree called a heap. The heap itself has, by definition, the largest value at the top of the
tree, so the heap sort algorithm must also reverse the order. It does this with the following steps:

1. Remove the topmost item (the largest) and replace it with the rightmost leaf. The topmost item is stored in
an array.
2. Re-establish the heap.
3. Repeat steps 1 and 2 until there are no more items left in the heap.

15. Define Bubble sort.


A simple but popular sorting algorithm. Bubble sorting is used frequently as a programming exercise
because it is relatively easy to understand. It is not, however, particularly efficient. Other sorting
algorithms, such as heap sorts, merge sorts and quick sorts, are used more often in real applications.
16. Define Searching.
Searching for data is one of the fundamental fields of computing. Often, the difference between a fast
program and a slow one is the use of a good algorithm for the data set. Naturally, the use of a hash table
or binary search tree will result in more efficient searching, but more often than not an array or linked list
will be used. It is necessary to understand good ways of searching data structures not designed to support
efficient search.
17.

Mention

the

various

types

of

searching

techniques

in

18. What is linear search?


In Linear Search the list is searched sequentially and the position is returned if the key element to be
searched is available in the list, otherwise -1 is returned. The search in Linear Search starts at the
beginning of an array and move to the end, testing for a match at each item.
19. What is Binary search?
A binary search, also called a dichotomizing search, is a digital scheme for locating a specific object in a large
set. Each object in the set is given a key. The number of keys is always a power of 2. If there are 32 items in
a list, for example, they might be numbered 0 through 31 (binary 00000 through 11111). If there are, say,
only 29 items, they can be numbered 0 through 28 (binary 00000 through 11100), with the numbers 29
through31 (binary 11101, 11110, and 11111) as dummy keys.

UNIT III
16 MARKS
1. Define array. Explain the array types with an example program for each type.
Arrays are data structures which hold multiple variables of the same data type. Consider the case where a
programmer needs to keep track of a number of people within an organization. So far, our initial attempt will
be to create a specific variable for each user.
This might look like,
int

name1

101;

int

name2

232;

int name3 = 231;


It becomes increasingly more difficult to keep track of this as the number of variables increase.
Arrays offer a solution to this problem. An array is a multi-element box, a bit like a filing cabinet, and
uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like
other variables in C, must be declared before they can be used. The replacement of the above example
using arrays looks like,
int names[4];
names[0]

101;

names[1]

232;

names[2]

231;

names[3] = 0;
We created an array called names, which has space for four integer variables. You may also see that we
stored 0 in the last space of the array. This is a common technique used by C programmers to signify the
end of an array. Arrays have the following syntax, using square brackets to access each indexed value
(called an element).x[i]
so that x[5] refers to the sixth element in an array called x. In C, array elements start with 0. Assigning values
to array elements is done by, x[10] = g; and assigning array elements to a variable is done by, g = x[10]; In the
following

example,

character

based

array

named

word

is

declared,

and

each

element is assigned a character. The last element is filled with a zero value, to signify the end of the
character string (in C, there is no string type, so character based arrays are used to hold strings). A printf
statement is then used to print out all elements of the array.

/* Introducing array's, 2 */
#include <stdio.h>
main()
{
char
word[0]
word[1]
word[2]
word[3]
word[4]
word[5] = 0;
printf("The
contents
}

word[20];
'H';
'e';
'l';
'l';
'o';

=
=
=
=
=
of

word[]

is

-->%s\n",

word

);

2. Explain about multi dimensional array with example.


Multi-dimensioned arrays have two or more index values which specify the element in the array.
multi[i][j];
In the above example, the first index value i specifies a row index, whilst j specifies a column index.
DECLARATION
int m1[10][10];
static int m2[2][2] = { {0,1}, {2,3} }; sum = m1[i][j] + m2[k][l];
NOTE the strange way that the initial values have been assigned to the two-dimensional array m2. Inside the
braces are,
{ 0, 1 },
{ 2, 3 }
Remember that arrays are split up into row and columns. The first is the row, the second is the column.
Looking at the initial values assigned to m2, they are,
m2[0][0] = 0
m2[0][1]

m2[1][0]

m2[1][1] = 3

Example:
#include

<stdio.h>

main()
{
static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} }; int row, column, sum;
sum = 0;
for( row = 0; row < 4; row++ )
for( column = 0; column < 3; column++ ) sum = sum + m[row][column];
printf("The

total

is

%d\n",

sum

);

}
3. Explain String Array with example program.
CHARACTER

ARRAYS

[STRINGS]

Consider

the

following

program,

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

char

name1[]

{'H','e','l','l','o'};

static

char

name2[]

"Hello";

printf("%s\n", name1);
printf("%s\n", name2);
}
The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in
name2[5], whilst name1 has not. To insert a null at the end of the name1 array, the initialization can be
changed to, static char name1[] = {'H','e','l','l','o','\0'};
Consider the following program, which initialises the contents of the character based array word during the
program, using the function strcpy, which necessitates using the include file string.h
Example:
#include <stdio.h>
#include
main()
{
Char word[20]; Char word[20]; strcpy(word, "hi there." )
printf("%s\n", word );
}

<string.h>

4. Explain the standard string functions with example to support each type.
Strings:
The group of characters, digits and symbols enclosed within quotes is called as strings or character arrays.
Strings are always terminated with \0 character(NULL).
Example:
char name[ ] = {H,E,L,L,O};
Standard String Functions:
strlen( )

strcpy(

strncpy( )
stricmp( )

strcmp(

strncmp(

strcat( )
strrev( ) etc.,
Example:Program
/*Illustration of string- handling functions*/ #include<string.h>
main()
{
char s1[20],s2[20],s3[20]; int x, l1, l2, l3;
printf(Enter two string constants \n); printf(?);
scanf(%s %s, s1, s2); x = strcmp(s1, s2); if(x != 0)
printf(Strings are not equal \n); strcat(s1, s2);

else
printf(Strings are equal \n); strcpy(s3,s1); l1 = strlen(s1);

l2

strlen(s2);

l3 = strlen(s3);
printf(\ns1 = %s \t length = %d characters \n,s1, l1); printf(\ns2= %s \t length = %d characters \n,s2, l2);
printf(\ns3 = %s \t length = %d characters \n,s3, l3);
}
OUTPUT
Enter two string constants

? New York
Strings are not equal
s1 = New York

length = 7 characters

s2 = York

length = 4 characters

s3 = New York

length = 7 characters

Enter two string constants


? London London
Strings are equal
s1 = London
s2 = London
s3 = London

length = 6 characters
length = 6 characters
length = 6 characters

5. Write a C program to do the matrix addition using C.


C program for addition of two matrices using arrays source code. Matrix addition in c language:
Example Program:
#include<stdio.h>
int main(){
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the First matrix->"); for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);

printf("\nEnter the Second matrix->"); for(i=0;i<3;i++)


for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is\n");

for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
printf("\nThe Second matrix is\n"); for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",b[i][j]);
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nThe Addition of two matrix is\n"); for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
return
}
6. Write a program for matrix multiplication in c
#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;
printf("\nEnter the row and column of first matrix"); scanf("%d %d",&m,&n);
printf("\nEnter the row and column of second matrix");

0;

scanf("%d %d",&o,&p);
if(n!=o)
{
printf("Matrix mutiplication is not possible");
printf("\nColumn

of

first

matrix

must

be

same

as

row

of

second

matrix");

}
Else
{
printf("\nEnter the First matrix->"); for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->"); for(i=0;i<o;i++)
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is\n"); for(i=0;i<m;i++){
printf("\n");
for(j=0;j<n;j++){
printf("%d\t",a[i][j]);
}
}
printf("\nThe Second matrix is\n"); for(i=0;i<o;i++){
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++)
for(j=0;j<p;j++)
c[i][j]=0;
for(i=0;i<m;i++){ //row of first matrix
for(j=0;j<p;j++){

//column

sum=0;
for(k=0;k<n;k++)
sum=sum+a[i][k]*b[k][j]; c[i][j]=sum;

of

second

matrix

}
}
printf("\nThe multiplication of two matrix is\n"); for(i=0;i<m;i++){
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",c[i][j]);
}
}
return
}

0;

7. Write a C program to find out transport of a matrix.


Program:
#include<stdio.h>
int main(){
int a[10][10],b[10][10],i,j,k=0,m,n;
printf("\nEnter the row and column of matrix"); scanf("%d %d",&m,&n);
printf("\nEnter the First matrix->"); for(i=0;i<m;i++)
for(j=0;j<n;j++
scanf("%d",&a[i][j]);
printf("\nThe matrix is\n");
for(i=0;i<m;i++){
printf("\n");
for(j=0;j<m;j++){
printf("%d\t",a[i][j]);
}
}
for(i=0;i<m;i++)
for(j=0;j<n;j++)
b[i][j]=0;

for(i=0;i<m;i++){
for(j=0;j<n;j++){
b[i][j]=a[j][i];
printf("\n%d",b[i][j]);
}

}
printf("\n\nTraspose of a matrix is -> "); for(i=0;i<m;i++){
printf("\n");
for(j=0;j<m;j++){
printf("%d\t",b[i][j]);
}
}
return
}

UNIT IV
2 MARKS
n

Page 87

0;

UNIT V
2 MARKS
1. Compare arrays and structures.
Comparison of arrays and structures is as follows.
Arrays

Structures

An array is a collection of data items of same data A structure is a collection of data items of different
type.Arrays can only be declared.

data types. Structures can be declared and defined.

There is no keyword for arrays.

The keyword for structures is struct.

An array name represents the address of the starting

A structrure name is known as tag. It is a

element.
Shorthand notation of the declaration.
An array cannot have bit fields.

A structure may contai

2. Compare structures and unions.


Structure

Union

Every member has its own memory.

All members use the sa

The keyword used is struct.

The keyword used is u

All members occupy separate memory location, hence different interpretations of the

Different interpretatio

same memory location are not possible.

location are possible.

Consumes more space compared to union.

Conservation of memo

Page 88

3. Define Structure in C.
C Structure is a collection of different data types which are grouped together and each element in a C
structure is called member.
structure members in C, structure variable should be declared.
each separately.
structure members.
4. What you meant by structure definition?
A structure type is usually defined near to the start of a file using a typedef statement. typedef defines and
names a new type, allowing its use throughout the program. typedefs usually occur just after the #define and
#include statements in a file.
Here is an example structure definition.
typedef struct {
char

name[64];

char

course[128];

int age;
int

year;

} student;
This defines a new type student variables of type student can be declared as follows.
student st_rec;
5. How to Declare a members in Structure?
A struct in C programming language is a structured (record) type [1] that aggregates a fixed set of labeled
objects, possibly of different types, into a single object. The syntax for a struct declaration in C is:
Page 89

struct tag_name
{
type

attribute;

type

attribute2;

/* ... */
};
6. What is meant by Union in C.?
A union is a special data type available in C that enables you to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a value
at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.
7. How to define a union in C.
To define a union, you must use the union statement in very similar was as you did while defining
structure. The union statement defines a new data type, with more than one member for your program. The
format of the union statement is as follows:
union [union tag]
{
member

definition;

member definition;
member definition;
} [one or more union variables];

8. How can you access the members of the Union?


To access any member of a union, we use the member access operator (.). The member access operator is
coded as a period between the union variable name and the union member that we wish to access. You would
use union keyword to define variables of union type.

Page 90

9. What are the pre-processor directives?

10. What are storage classes?


A storage class defines the scope (visibility) and life time of variables and/or functions within a C
Program.
11. What are the storage classes available in C?
There are following storage classes which can be used in a C Program

12. What is register storage in storage class?


Register is used to define local variables that should be stored in a register instead of RAM. This means that
the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&'
operator applied to it (as it does not have a memory location).
{
register

int
}

13.What is static storage class?

Page 91

Miles;

Static is the default storage class for global variables. The two variables below (count and road) both have a
static storage class.
static int Count;
int Road;
{
printf("%d\n",

Road);

}
14. Define Auto storage class in C.
auto is the default storage class for all local variables.
{
int Count;
auto

int

Month;

}
The example above defines two variables with the same storage class. auto can only be used within
functions, i.e. local variables.

15. Define pre-processor in C.


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. We'll refer to the C Preprocessor as the
CPP.
Example:
#define Substitutes a preprocessor macro
#include Inserts a particular header from another file

Page 92

16. Define Macro in C.


A macro definition is independent of block structure, and is in effect from the #define directive
that defines it until either a corresponding #undef directive or the end of the compilation unit is
encountered.
Its format is:

#define identifier replacement

Example:
#define
int
int table2[TABLE_SIZE];

TABLE_SIZE

100
table1[TABLE_SIZE];

17. What are conditional Inclusions in Preprocessor Directive?


Conditional inclusions (#ifdef, #ifndef, #if, #endif, #else and #elif)
These directives allow including or discarding part of the code of a program if a certain condition is met.
#ifdef allows a section of a program to be compiled only if the macro that is specified as the parameter has
been defined, no matter which its value is.
For example:
1

#ifdef TABLE_SIZE

int table[TABLE_SIZE];

3 #endif

18. What you meant by Source file Inclusion in Preprocessor directive?


Source file inclusion (#include)
This directive has also been used assiduously in other sections of this tutorial. When the preprocessor finds
an #include directive it replaces it by the entire content of the specified file. There are two ways to specify a
file to be included:
1 #include "file"
2 #include <file>

Page 93

19. What is Line control?


Line control (#line)
When we compile a program and some error happens during the compiling process, the compiler shows an
error message with references to the name of the file where the error happened and a line number, so it is easier
to find the code generating the error.
The #line directive allows us to control both things, the line numbers within the code files as well as the file
name that we want that appears when an error takes place. Its format is:
#line number "filename"
Where number is the new line number that will be assigned to the next code line. The line numbers of
successive lines will be increased one by one from this point on.
UNIT V
16 MARKS
1. Define Structures. Explain structures in detail.

(JAN 2009 / MAY2009)

A structure is a collection of one or more variables of different data types grouped together under a single
name. It contains different data types. C Structure is a collection of different data types which are grouped
together and each element in a C structure is called member.

cture variables can be declared for same structure and memory will be allocated for
each separately.
structure members.
Syntax:
struct
{
type variable 1;
Page 94

struct-name

type variable 2;
type variable n;
} structure_variables;

Example program for C structure:


This program is used to store and access id, name and percentage for one student. We can also store and
access these data for many students using array of structures. You can check C - Array of Structures
to know how to store and access these data for many students.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char

name[20];
float percentage; };

int
{
struct student record = {0}; //Initializing to null

main()

record.id=1;
strcpy(record.name,
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf("
Percentage
return 0;
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

Page 95

"Raju");

is:

%f

\n",

record.percentage);

2. Explain Array of structure in C.


Since structures are data types that are especially useful for creating collection items, why not make a
collection of them using an array? Let us now modify our above example object1.c to use an array of
structures rather than individual ones.
Example Program:
1.

#include <stdio.h>

2.

#include <stdlib.h>

3.
4.

struct object {

5.

char id[20];

6.

int xpos;

7.

int ypos;

8.

};

9.
10.

struct object createobj(char id[], int xpos, int ypos);

11.
12.

void printobj(struct object obj);

13.
14.

void main() {

15.
16.

int i;

17.

struct object gameobjs[2];

18.

gameobjs[0] = createobj("player1", 0, 0);

19.

gameobjs[1] = createobj("enemy1", 2, 3);

20.
21.
22.

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


printobj(gameobjs[i]);

23.
24.

//update enemy1 position

25.

gameobjs[1].xpos = 1;

26.

gameobjs[1].ypos = 2;

Page 96

27.
28.

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

29.
30.

printobj(gameobjs[i]);
}

31.
32.

struct object createobj(char id[], int xpos, int ypos) {

33.

struct object newobj;

34.

strcpy(newobj.id, id);

35.

newobj.xpos = xpos;

36.

newobj.ypos = ypos;

37.

return newobj;

38.

39.
We create an array of structures called gamobjs and use the createobj function to initilize it's elements.
You can observer that there is not much difference between the two programs. We added an update for
the enemy1's position to show how to access a structure's members when it is an element within an array.
Output:

3. How can pass a structure to function in C.


A structure can be passed to any function from main function or from any sub function. Structure definition
will be available within the function only.

Page 97

It wont be available to other functions unless it is passed to those functions by value or by


address(reference).
Else, we have to declare structure variable as global variable. That means, structure variable should be
declared outside the main function. So, this structure will be visible to all the functions in a C program.
Passing structure to function in C:
It can be done in below 3 ways.
1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
3. No need to pass a structure - Declare structure variable as global
program - passing structure to function in C by value:
In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can be
accessed from called function. This concept is very useful while writing very big programs in C.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char

name[20];
float percentage; };

void func(struct student record);


int main()
{
struct student record;
record.id=1;
strcpy(record.name,
record.percentage = 86.5;
Page 98

"Raju");

func(record);
return 0;
}
void
func(struct
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf("
Percentage
}

student

is:

%f

\n",

record)

record.percentage);

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

4. How can you insert structure with in another structure?


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

Page 99

structure_nm
element

1;

structure_nm
element

1;

element

n;

Example Program :
Program to demonstrate nested structures.
#include <stdio.h>
#include <conio.h>
struct

stud_Res

{
int rno;
char std[10];
struct

stud_Marks

{
char

subj_nm[30];
int subj_mark; }marks;

}result;
void

main()

{
clrscr();
printf("\n\t Enter Roll Number : "); scanf("%d",&result.rno);
printf("\n\t Enter Standard : "); scanf("%s",result.std);
printf("\n\t

Enter

Subject

scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",result.rno);
printf("\n\n\t Standard : %s",result.std);
printf("\nSubject Code : %s",result.marks.subj_nm);
00

Code

");

printf("\n\n\t Marks : %d",result.marks.subj_mark);


getch();
}
Output :
Enter Roll Number : 1
Enter Standard : MCA(Sci)-I
Enter Subject Code : SUB001
Enter Marks : 63
Roll Number : 1
Standard

Subject

Code

MCA(Sci)-I
:

SUB001

Marks : 63
5. Explain the concept of pointer to structure.
C structure can be accessed in 2 ways in a C program. They are,
1. Using normal structure variable
2. Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to
access the data using pointer variable. You have learnt how to access structure data using normal variable
in C - Structure topic. So, we are showing here how to access structure data using pointer variable in
below C program.

01

Example program for C structure using pointer:


In this program, record1 is normal structure variable and ptr is pointer structure variable. As you
know, Dot(.) operator is used to access the data using normal structure variable and arrow(->) is used to access
data using pointer variable.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char

name[30];
float percentage; };

int
{
int i;
struct student record1 = {1, "Raju", 90.5}; struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}

02

main()

Output:
Records of STUDENT1:
Id

is:

Name

is:

Raju

Percentage is: 90.500000

6. Define Union. Explain Union in detail. (JAN 2009)


Union is a collection of variables similar to structure. The union requires bytes that are equal to number of
bytes required for the largest number.
Example:
union

student

{
char name[20];
int

rollno,m1,m2,m3,tot;

float avg;
}s1;
Union of structure
Union can be nested with another union.
Example program:
#include
#include <string.h>

<stdio.h>

union student
{
char name[20];
char subject[20];
float percentage; };
int
{
union student record1;
03

main()

union student record2;


// assigning values to record1 union variable strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths"); record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name
: %s \n", record1.name);
printf(" Subject
: %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
// assigning values to record2 union variable printf("Union record2 values example\n"); strcpy(record2.name,
"Mani");
printf(" Name
: %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject
: %s \n", record2.subject);
record2.percentage = 99.50;
printf("
Percentage
return 0;
}

%f

\n",

record2.percentage);

Output:
Union
Name :
Subject :
Percentage : 86.500000

record1

Union record2 values example Name : Mani


Subject : Physics
Percentage : 99.500000

04

values

example

7. What are storage classes? Explain each with example.


A storage class defines the scope (visibility) and life time of variables and/or functions within a C
Program.
There are following storage classes which can be used in a C Program

extern
auto - Storage Class
auto is the default storage class for all local variables.
{
int Count;
auto

int

Month;

}
The example above defines two variables with the same storage class. auto can only be used within
functions, i.e. local variables.
register - Storage Class
register is used to define local variables that should be stored in a register instead of RAM. This means that
the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&'
operator applied to it (as it does not have a memory location).
{
register

int
}

Miles;

Register should only be used for variables that require quick access - such as counters. It should also be
noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register - depending on hardware and implementation restrictions.
static - Storage Class
static is the default storage class for global variables. The two variables below (count and road) both have a
static storage class.
static

int

Count;

int Road;
{
printf("%d\n",

Road);

}
static variables can be 'seen' within all functions in this source file. At link time, the static variables
defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initialized at run time but is not
reinitialized when the function is called. This inside a function static variable retains its value during
various calls.
void func(void);
static count=10; /* Global variable - static is the default */
main()
{
while
{
func();
}

(count--)

}
void

func(

void

{
static

5;

i++;
printf("i

is

%d

and

count

is

%d\n",

i,

count);

}
This will produce following result
i is 6 and count is 9
i

is

and

count

is

is

and

count

is

is

and

count

is

is

10

and

count

is

is

11

and

count

is

is

12

and

count

is

is

13

and

count

is

is

14

and

count

is

i is 15 and count is 0
8. Describe in detail about the Preprocessors in C. (MAY 2009)
THE PREPROCESSOR
The define statement is used to make programs more readable, and allow the inclusion of macros.
Consider the following examples,
#define TRUE 1 /* Do not use a semi-colon , # must be first character on line */ #define FALSE 0
#define
#define AND &

NULL

#define OR |
#define

EQUALS

==

game_over = TRUE;
while( list_pointer != NULL )
MACROS
Macros are inline code which is substituted at compile time. The definition of a macro, which accepts an
argument when referenced,
#define SQUARE(x) (x)*(x) y = SQUARE(v);
In this case, v is equated with x in the macro definition of square, so the variable y is assigned the square of v.
The brackets in the macro definition of square are necessary for correct evaluation.
The expansion of the macro becomes y = (v) * (v);
Naturally, macro definitions can also contain other macro definitions,
#define IS_LOWERCASE(x) (( (x)>='a') && ( (x) <='z') )
#define TO_UPPERCASE(x) (IS_LOWERCASE (x)?(x)-'a'+'A':(x))
while(*string)
{
*string

TO_UPPERCASE

(*string);

++string;
}
CONDITIONAL COMPILATIONS
These are used to direct the

compiler

to

compile/or

not

compile

the

lines

that

follow
#ifdef
#define
#define SP 32

NULL
NL

10

#endif
In the preceding case, the definition of NL and SP will only occur if NULL has been defined prior to the
compiler encountering the #ifdef NULL statement. The scope of a definition may be limited by
#undef NULL
This renders the identification of NULL invalid from that point onwards in the source file.
Typedef
This statement is used to classify existing C data types, eg,
typedef int counter; /* redefines counter as an integer */
counter j, n; /* counter now used to define j and n as integers */ typedef struct {
int

month,

} DATE;
DATE todays_date; /* same as struct date todays_date */

day,

year;

Potrebbero piacerti anche