UNIT I INTRODUCTION TO COMPUTERS

squealingmunsterSoftware and s/w Development

Oct 30, 2013 (3 years and 11 months ago)

90 views





11UCK102

-

FUNDAMENTALS OF COMPUTING & C
PROGRAMMING


Question Bank


UNIT I


INTRODUCTION TO COMPUTERS


1.

Define Computer


The computer is an electronic device which converts raw data into valid or
meaningful
information.


2.

What is Program?



A
device to manipulate the d
ata according to the programmed i
nstructions.




An intelligent machine that solves problems by accepting data, performing certain
operation and producing the result under the direction of step by step instruction called
program.



3.

Define Data

Data is information that has been translated into a form that is more convenient to
process.


4.

What is
Information
?


The processed data is called the information.


5.


What is
Information Processing
Cycle?



Using a computer to convert data into useful information is referred to as
information
processing (also called data processing). Processing data into information
involves four basic
functions:




Input
-

data entered into a computer for processing




Processing
-

the manipulation of data according to program instructions




Output
-

the creation of information resulting from processing




Storage
-

the retention of processed data on a storage medium for future use


Collectively, these steps are
known as the information processing cycle.


6.

What are the Characteristics of Computers?


Some of the characteristics of computers, which make them an essential part of every
emerging
technology, are speed, accuracy, diligence, portability, resource sharing, reliability,
versatility, strorage capacity.




7.

Write about various speed levels in computer.


1 nano seconds = 1 X 10
-
9 Sec


1 pico

seconds = 1 X 10
-
12 Sec




Computer process data at an extremely fast rate
-

Millions of instructions per second.



The speed of a computer is calculated in MHz (Megahertz
) that

is one million
i
nstructions
per second.



Present computer can perform billions of operations in just one second


1 milli seconds = 1 X 10
-
3 Sec


1 micro seconds = 1 X 10
-
6 Sec


1 nano seconds = 1 X 10
-
9 Sec


1 pico seconds = 1 X 10
-
12 Sec


8.

What
do

yo
u mean by Accuracy?




Besides efficiency, Computers are accurate as well.



The level of accuracy depends on the instructions and the type of machine being used.



Computers are extremely accurate when accurate programs and data are entered
and
processed correctly.



The popular expression garbage
-
in, garbage
-
out (GIGO) means that if inaccurate
programs
and data are entered into a computer for processing, the resulting output will
also be
inaccurate


9.

What do
yo
u mean b
y Diligence?





A computer does not suffer from the human traits of tiredness and lack of
concentration.



If 4 million calculations have to be performed, then the computer will perform the last
four
-

millionth calculation with the same accuracy and speed as the first calculation.


10.

What do
you mean by Reliability?





It is the measurement of performance of a computer, which is measured against
some
predetermined standard for operation without any failure.



Computer have built in diagnostic capabilities, which help in continuous monitoring
of the
system


11.

What is a Storage Capacity?




Computers can store large amounts of d
ata and can recall the required
information



Main memory of the computer is relatively small and it can hold only a certain
amount of information, therefore the data is stored on secondary storage devices such as
magnetic
tape or disks.



Small Sections of the data ca be accessed quickly and brought into the storage devices,
as

and when required for processing


12.

What is Versatility?




Computes are quite versatile in nature.




They can perform multiple tasks simultaneously with great ease.




For example, at one moment it can be used to draft a letter, another moment it can be
used
to play music and in between, one can print a document as well.




13.

What do
yo
u mean by Resource Sharing?




In the initial stages of development
, computers used to be isolated
machines.




Sharing of costly resources like printers are possible




Apart from device sharing, data and information can also be shared among groups
of
computers


14.


Difference between Computer and human


S.N
O


1


2


3


4


5


6


7.


Characteristics


Speed


Accuracy


Performance


Instructions


Remember


Different
Situations


Diligence


Computer


Fast and excellent


Makes no error


Very good


Follow
perfect


Accurate and exact


Makes good


High


Human


Very slow


High possibility of
errors


Poor


Chance for imperfect


inaccurate


difficult


low


15.


Comparison between computer and calculator


S.NO

Characteristics

Calculator

Computer


1.

S p eed

Fast

Much fast


2.

Performance

Simple

calculation

and Complex problem and non

numeric processing

numeric processing


3.

Memory

Less internal memory and Large internal memory and

no

permanent

storage, large

permanent

storage

temporary storage only

available


4

Machine

Electronic Device

Electronic Device


5.

Operation

Arithmetic

Arithmetic and logical




16.


Name some Applications of computer


1. In business


2. in industry


3. in home


4. in education


5. in training


6. for entertainment


7. in science and engineering


8. in mathematics


9. In Medicine and Health care.


17.

When to use a computer?


1. When accuracy to be improved


2. When delays are to be minimized


3. When high volume of data is required to store


4. When efficiency and economy is required


18.

Evolution of computers:


Abacus:


Napier device:


Slide rule:


Pascaline:


Stepped
Reckoner.


Charles Babbage's Engines


Hollerith's Card reading machine:


Mark I digital Computers:


ENIAC


EDVACEDSAC


UNIVAC


LARC Machine


Microprocessor


VLSI




VLSI
-

Very Large Scale Integration design


19.


What are the
Generations of
computers
?


In computer terminology the word generation is described as a stage of technological development

or
innovation.
According to technology used there are 5 generations of computers


Vacuum Tube


T
ransistor


Integrated Circuit


Microprocessor


Super Large Scale Integrated (SLSI)


20.

What are the
Classification
s

of Computers
?



Computers also differ based on their data processing abilities. Based on physical size, performance
and
application areas we generally divide computers into four major categories


i. Micro Computers


ii. Mini Computers


iii. Mainframe Computers


iv. Super Computers


21.


What is a Micro Computer?





A Micro computer is a sma
ll, low cost digital
computer, w
hich usually consists of a micro

processor, a storage unit, an input channel and an output channel all of which may be on
one chip
inserted into one or several PC Boards.



The addition of a power supply and connecting cables, appropriate peripherals
(keyboard,
monitor, printer and disk drivers ), an operating system and other software
programs can provide a
complete micro computer system
.




Examples IBM
-
PC, Pentium 100, IBM
-
PC Pentium 200 and Apple macintosh



Micro computers includes

a) Desktop Computer

b) Laptop

c) Hand
-
held


22.

What is Desktop Computer?




Also known as Personal Computer

(PC)



Standalone system used by an individual



These are the most common type
of micro computers
. T
hey consist

of a system unit, a
display monitor, a keyboard, internal hard
disk storage and peripheral devices
.



Main reason behind the importance of the PCs is that they are not very
expensive
for the individuals or the small businesses.



Some of the major personal computer manufacturers are APPLE, IBM, Del.


23.


What do
yo
u mean by portable computers
?




A portable computer, that is, a user can carry it around.




Since the laptop computer resembles a notebook, it is also known

as

"notebook"




Small computers which enclosing all the basic features of a normal

desktop

computers.




Advantage:


i
) Can use anywhere and at anytime, especially when one is traveling.


ii) They do not need external power supply as a rechargeable battery is

completely self contained in them





Disadvantage:


i) Expensive compared to desktop computers


24.

What is
Hand
-
Held Computer?




A hand
-
held, also called personal digital assistant (PDA) is a computer that can
conveniently be stored in a pocket (of sufficient size) and used while the user is
holding it.




They are slightly bigger than the common calculators.




A PDA user generally uses a pen or electronic stylus instead of keyboard for
input.




Since these computers are easily fitted on the palm, they are also known as
palmtop
computers.




They usually have no disk drive, rather they use small cards to store programs
and data.




However they can be connected to printer or a disk drive to generate output or
store data.


Disadvantage: It has limited memory and are less powerful as compared
to

desktop computers




Examples: Apple newton, casio cassiopeia and franklin eBookMan
26 Mini Computers




In the early 1960s, Digital Equipment Corporation (DEC) started shipping its PDP series
computer,
which the press described and referred as mini computers.




The mini computer is a small digital computer whose process and storage capacity is
lesser than
that of a mainframe, but more than that of micro computer.




Its speed of processing data is in between that of a mainframe and a micro computer.


25.

What is
Mainframe Computer
?





A mainframe is an ultra
-
high performance computer made for high
-
volume,
processor
-
intensive computing.




It consists of a high
-
end comp
uter processor, with related peripheral devices,
capable of
supporting large volumes of data processing, high performance online
transaction processing
systems, and extensive data storage and retrieval.




It is able to process and store more data than a mini computer and far more than a
micro
computer.




It is designed to perform at a faster rate than a mini computer and at even more
faster rate
than a micro computer. Mainframes are the second largest (in

capability
and size) of the computer
family, he largest being super computers.




Mainframes can usually execute many programs simultaneously at a high speed


26.

What do
yo
u mean by Super Computers?




Super computers are the special purpose machines, which are specially designed to
maximize
the numbers of FLOPS (Floating Point Operation per Second).




Any computer below one gigaflop / sec is not considered a super computer.




A super computer can pr
ocess a great deal of information and make extensive
calculations
very quickly.


27.

What are

the basic operations of a computer
?


A computer performs basically five major operations or functions irrespective of their size
and
make.


1. Input

2. Storage


3. Processing


4. Output


5. Controlling


28.

Write about Input Unit
.


Data and instructions are entered into the memory of a computer through input devices.




It captures information and translates it into a form that can be processed by CPU.




Computer accepts input in two ways


1. Manually


2. Directly




Manually: The user enters data into the computer by hand. E.g. Keyboard, mouse etc




Directly: Information is fed into the computer automatically from a source document(like
barcode.).


29.

Write about Storage Unit
.





The process of saving data and instructions permanently is known as storage.




Data has to be fed into the system before the actual processing starts. It is because the
processing
speed of Central Processing Unit (CPU) is so fast that the data has to be provided
to CPU with the same
speed.




Therefore the data is first stored in the storage unit for faster access and processing.




The storage unit performs the following major functions:


Data and instructions required for processing (received from input
devices)


Intermediate results of processing


Final results of processing, before they are released to an output device


30.

What do
yo
u mean by Primary storage?


Also known as main memory.


Used to hold running program instructions


Used to hold data, intermediate results, and results of ongoing processing of
job(s)


Fast in operation


Small Capacity


Expensive


Volatile (looses data on power dissipation)


Primary memory can be further classified into


1. RAM (Random Access Memory)


2. ROM (Read only Memory)


31.


W
hat is Secondary storage?




Also known as auxiliary memory or external memory.




Used to hold stored program instructions




Used to hold data and information of stored jobs




Slower than primary storage




Large Capacity




Lot cheaper that primary storage




Non volatile (Retains data even without power)


32.


W
rite about
Arithmetic and logic unit
.





Arithmetic Unit: Contains circuitry that is responsible for performing the actual computing
and
carrying out the arithmetic calculations such as addition, subtraction, multiplication and
division. It can
perform these operations at a very high speed.




Logic Unit: Perform logical operation based on the instruction. The operations are logical
c
omparisons between data items. This unit can compare numbers, letters or special
characters.
Logic unit can test for 3 conditions: equal
-
to condition, Less
-
than condition and
Greater
-
than condition.


33.

What are the functions of Control unit (
Controlling)
?




This unit checks the correctness of sequences of operations.




It fetches program instruction from primary storage unit known as fetching, interpret them
and
ensure correct execution of the program known as decoding.




The time required to fetch and decode an instruction is called instruction time, or I
-
time.




It

also controls the input/output devices and directs the overall functioning


34.

What are the functionalities of Central processing unit?




T
he Central Processing Unit (CPU) takes data and instructions from the storage unit and
makes all sorts of
calculations based on the instructions given and the type of data provided. It is then sent back to the storage
unit.


The CPU consists of a control unit, an arithmetic/logic unit (ALU), and registers.
CPU, the brain of
a
ny
computer sys
tem.


It is just like brain that takes all major decisions, makes all sorts of calculations and directs
different parts of
the computer functions by activating and controlling the operations.



35.

Define cache memory?


A small memory between CPU and main memory is called cache. The speed is equal to the CPU.
Cache memory acts as a high speed buffer between CPU and Main memory.


36.

Define ROM?


ROM is a non
-
volatile memory that contains permanent data.


37.


Define booting and what are the types of booting?


The process of loading an operating system program into the computer memory is called the booting.
The types of booting are cold booting and warm booting.


38.

What are the different types of ROM?




Masked ROM,



PROM



EPROM



EEPROM



Flash ROM


39.


Define RAM?


RAM is a volatile memory that contains temporary data that can be accessed at high speed.



40.


Define system software.


A set of program that governs the operation of a computer system and makes the hardware works. It
c
ontrols the internal operations of the computer.


41.

What is software?


Software is a set of instruction or program, which are useful for performing a task.


42.


Define operating system?


A collection of program used to control the entire operation of the computer. It co
-
ordinates the
h
ardware and software.


43.

What is application software?


Software which is used to solve a specific task is called application software.


44.


What is meant by software piracy?


Software piracy is the illegal distribution of any software.


45.

Define compiler.


It is a program used to convert the high level language program into machine language.

46.


Define Assembler.


It is a program used to convert the assembly language program into machine language.


47.


Define Interpreter.


It is a program used to convert the high level language program into machine language line by line.


48.


What are the types of programming language?




Machine language



Assembly language



High level language





























UNIT
II

PROBLEM

SOLVING


1.

What are the various phases

Software Development Steps?




Requirements



Analysis



Design



Testing



Implementation


2.


What is a Requirement Phase?


The process of collecting the required data for the design is called the requirement phase.

3.


What is a Design phase?


The process of representing the collected data in a high level programming language is called
designing.


4.


What is Algorithm?


Algorithm means the logic of a program. It is a step by step description of a program.

It
can be defined as finite set of unambiguous instructions.



5.


List out the way how algorithm may be represented?




Normal English



Flow chart



Pseudocode



Decision table


6.

What is a decision table?


A decision table is a table containing the selection of condition to be tested and how those conditions
should be nested to arrive at the proper action.


7.


Define flow chart.


Flow chart is the pictorial representation of a program.


8.


List out the basic design structure?




Sequence structure



Selection structure



Loop structure



9.


List out the any three advantages of flowchart.




Better communication



Effective synthesis



Effective analysis



10.


Name some Benefits of flowchart?


1.
Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.


2. Effective analysis: With the help of flowchart, problem can be
analysed in more effective
way.


3. Proper documentation: Program flowcharts serve as a good program documentation, which
is needed for various purposes.


4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis
and pro
gram development phase.


5. Proper Debugging: The flowchart helps in debugging process.


6. Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part


11.

What is pseudocode?

Pseudocode

is set of instructions written in normal English, but in a structured way.












































UNIT II




INTRODUCTION TO C




1.

What is
C

Programming
?

C

programming

describes the task of writing computer applications based upon the
C

programming

language. The
C

programming

language is largely based upon mathematical constructs, and requires
considerable training in order to master.

2.

What is a
basic

structure of a
c

program
?

Basic structure of a C program is

Documentation section


Link section


Definition section


Global declaretion section


Function section

(return type) (function name) (arguments...)

void main()

{

Declaration part

Executable part (statements)

}


Sub
-
program section


3.

What is a Compiler?

A program that
translates another program written in a high
-
level language into machine language

so
that it can be executed.

Ex. Turbo C, Borland C


4.

What is a variable?

In C programming, input and data are stored in variables. There are severa
l different types of
variables. It is necessary to

include the data type along with the name of the variable. Several basic
types include char, int, and float. Each type can store different types

of data.
A variable of type char
stores a single character, variables of type int

store integers (numbers without decimal places), and
variables of type float store numbers with decimal places.

Here are some variable declaration examples:

int x;

char letter;


float the_float


5.


What is the difference between declaring a variable and d
efining a variable?

Declaration of a variable in C hints the compiler about the type and size of the variable in compile
time. Similarly, declaration of a function hints about type and size of function parameters. No space
is reserved in memory for any var
iable in case of declaration.

Example: int a;

Here variable 'a' is declared of data type 'int'

Defining a variable means declaring it and also allocating space to hold it. We can say "Definition =
Declaration + Space reservation".Example: int a = 10;

Here variable "a" is described as an int to the compiler and memory is allocated to hold value 10.

6.

What does ‘main’ refer in C programming?

Every full C program begins inside a function called "main". A function is simply a collection of
commands that do
"something". The main function is always called when the program first e
xecutes.
From main,
other functions

can be called
, whether they
may
be written by us or by others or use
built
-
in language features.

7.

Why it is necessary to include header files?

To acc
ess the standard functions that comes with the compiler, it is necssary to include a header files
with the #include directive.

8.

What is called pre
-
processor directive?

#include and # define are pre processor directives.

The #inclu
de

tells the compiler to pu
t code from the header
file

into
the

program before actually
creating the executable.

Ex. #include<stdio.h>

The #define is used to define the symbolic constant.

Ex #define VALUE 100

The symbolic constant variable VALUE will be replaced by 100 wherever it i
s found in the
program.

9.

What is a Linker?

C language has a function that contains the object code for predefined functions.

F
or example, the
printf() is a library function.

I
f the C program uses any of the library functions, the object code
produced for
the source code should be combined with the object code of the library functions to
generate the final executable code.

T
his process is called linking and it is performed by a 'linker'.

10.

What is the difference in use of define and const variable?

#define si
mply replaces whate
ver is defined by the text that

want
s to be

replace
d
.

const variable's value cannot be manipulated during the course of the program.

T
ype checking

is possible

in const
but it is

not a par
t o
f #define.

11.

What is the meaning of percent d i
n c language?

This is found in the printf and scanf family of functions. The % is just a flag that says that the next
character specifies a variable type.

%d signed integers

12.

What is the default return type of main?

'Main' is not at all associated with the
return type. Specifying a function as main means that the
function is to be executed first
,
when the class is executed. A program can have only one 'main'
function.

13.

What are differences between linker and loader in C?

Neither linker nor loader is part of
the C language; they are platform
-
dependent utility programs.

Linker (or binder) creates an executable from object modules and libraries; loader loads these
executables into memory, resolves their shared
-
library
-
dependencies, and initiates their execution.

14.

What is meant by tokens in C?

C tokens
--
> all the identifiers and keywords used in c. for example

int,

char,

a,

b,

printf,

scanf,

etc.

15.

What is a storage qualifier in c?

static, extern, auto, register (and typedef, but only formally)
.

16.

What is an
Enumeration Constant?

Enumeration is a data type. We can create our own data type and define values that the variable can
take. This can help in making program more readable. enum definition is similar to that of a
structure.

Example: consider light_status

as a data type. It can have two possible values
-

on or off. enum
light_status

{

on, off

};

enum light_status bulb1, bulb2;

/* bulb1, bulb2 are the variables */


Declaration of enum has two parts:

a) First part declares the data type and specifies the pos
sible values, called 'enumerators'. b) Second
part declares the variables of this data type.

We can give values to these variables:

bulb1 = on;

bulb2 = off;







17.


What is meant by global variable?


The variable that is used in more than one function throughout the program are called global
variables and declared outside of all the function.


18.

Define logical and data errors


Logical errors: These are the errors, in which the conditional and control statements cannot end their
match after some sequential execution.


Data errors: These are the errors, in which input data given, is not in syntax as specified in the input
stateme
nt.



19.

. List out the characteristics of a program.




Clarity



Integrity



Simplicity



Efficiency



Generality


20.


What are Keywords?


Keywords are reserved words that have standard and pre
-
defined meaning in C .These keywords can
be used only for their intended purpose.


21.

What are the types of input statements available in C?




Formatted I/O statements



Unformatted I/O statements


22.

Define getchar () function.


The getchar

() function reads a single character from a standard input device. This function do not
requires any arguments.


23.

What is meant by local variable?


The variables which are defined inside a function block or inside a compound statement of a
function sub
-
program are called local variables.


24.

Define constant.


The items whose values cannot be changed during the execution of program are called constants.


25.

Define statements.


Statements can be defined as set of declarations or sequence of action. Statement causes the program
to perform some action.




UNIT

I
V


CONTROL STATEMENTS, ARRAYS & POINTERS


1.


What is if else in c programming language?

It is a
Statement. Typical usage:


if (<condition>) <statement>;

else <statement>;

2.

Define do
-
while loop.


It is a repetitive control structure and executes the body of the loop once irrespective of the condition
then it checks the condition and continues the ex
ecution until the condition become false.


3.

What is meant by break statement?


The break statement is used to terminate the loop. When the keyword break is used inside any loop,
the control automatically get transferred to the first statement after the loop.


4.

What is meant by continue statement?


Continue statement is used to trans
fer the control back to the beginning of the loop, before executing
the rest of the statements inside the loop.


5.

Define goto statement.


The goto statement transfers the control unconditionally from one place to another place in the
program.


6.

What are
conditional operators in C language?

The conditional operator in C (and C++, C# and other languages) consists of two symbols, '?' and ':'.
Together, they can be used to form an expression from three sub expressions:

e1

?
e2

:
e3

The conditional operator i
s evaluated in two steps; first, the expression e1 is evaluated, if it has a true
value, then e2 is evaluated and its value is returned as the result of the entire expression, otherwise (if
e1 is false) e3 is evaluated and its value is returned as the resu
lt of the entire expression.

7.

What is meant by derived data type in C?

Derived data types are based on fundamental data types. i.e. a derived data types is represented in the
memory as a fundamental data type.

8.

What is the difference between if

and while loop?

if
-
else

is not a loop;
while, for

and
do
-
while

are loops.

if
-
else just run once, but do
-
while run many times.

9.

What is the difference between 'break' and 'continue' statements? Differences between
'break' and 'continue' statements.

break i
s a keyword used to terminate the loop or exit from the block. The control jumps to next
statement after the loop or block.

Syntax:

{

Statement 1; Statement 2; Statement n; break;

}

continue is a keyword used for skipping the current iteration and go to ne
xt iteration of the loop

Syntax:

{

Statement 1; continue; Statement 2;

}

break can be used with for, while, do
-

while, and switch statements. When break is used in nested
loops i.e. within the inner most loop then only the innermost loop is terminated.

Exa
mple:

i = 1, j = 0;

while(i<=5)

{

i=i+1;

if(i== 2)

This statement when occurs in a loop does not terminate it but skips the statements after this continue
statement. The control goes to the next iteration. continue can be used with for, while and do
-
while.

Example:

i

= 1, j = 0;

while(i<=5)

{

i=i+1;

if(i== 2)

break;

j=j+1;

}

continue;

j=j+1;

}

10.

What is the difference between 'for' and 'while' loops?

for

loop: When it is desired to do initialization, condition check and increment/decrement in a single
statement of an iterative loop, it is recommended to use 'for' loop.

Syntax:

for(initialization;condition;increment/decrement)

{

//block of statements incre
ment or decrement

}

Program: Program to illustrate for loop

#include<stdio.h>

int main() {

int i;

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

//print the number printf("
\
n %d", i);

}

return 0;

}

Output:

1

2

3

4

5

Explanation:

The loop repeats for 5 times and prints value
of 'i' each time. 'i' increases by 1 for every cycle of loop.

while loop: When it is not necessary to do initialization, condition check and increment/decrement in
a single statement of an iterative loop, while loop could be used. In while loop statement,
only
condition statement is present.

Syntax:

#include<stdio.h>

int main() {

int i = 0, flag = 0;

int a[10] = { 0, 1, 4, 6, 89, 54, 78, 25, 635, 500 };

//This loop is repeated until the condition is false.

while (flag == 0) {

if (a[i] == 54) {

//as element
is found, flag = 1,the loop terminates flag = 1;

}

else {

i++;

}

}

printf("Element found at %d th location", i);

return 0;

}

Output:

Element found at 5th location

Explanation:

Here flag is initialized to zero. 'while
' loop repeats until the value of flag is zero, increments i by 1.
'if' condition checks whether number 54 is found. If found, value of flag is set to 1 and 'while' loop
terminates.

11.

Why we use do
-
while loop in c?

It is also called as post tested l
oop. It is used when it is necessary to execute the loop at least one
time. Syntax:

do {

Loop body

} while (Expression);

12.

Why we avoid

goto


statement in c?

It

interferes in the flow of programmer.

Once

goto’ is used to jump to a label, all previous
references to dynamically allocated memory is lost.

13.

How do you write a program using goto statement?


int main (void)

{

LABEL:puts ("Hello");

goto LABEL;

return 0;


}

14.

What is
case

and
switch

in
c

programming
?

Keywords.

15.

What are the similarities between if else and switch case?

If else and switch case both are used to control the flow of program
.

16.

What is the difference between switch and if else statements in C?


Both can be used as condition based statements but their syntax is different. Switch is used when a
variable is to be compared with different constants.

17.

When ‘switch’ is needed in C programming? Give its Structure.

Switch is used when a variable is to be
compared with different constants.

Switch statement has the
syntax as :

switch(choice)

{

case 1: statements

break;


case 2': statements

break;

.

.

case 'n': statements

break;

default: statements

break;

}

where choice is an integer or character variable.


if else statements take the form:

if(cond1)

{

statements;

}

else if(cond2)

{

statements;

}

.

.

else {

statements;

}

where cond1 and cond 2 are

any valid arithmetic, logical or relational expression.



18.

Define one
-

dimensional array.


The collection of d
ata item can be stored under a one variable name using only one subscript , such a
variable is called one
-

dimensional array.


19.

Give any two features of pointers.



Pointer reduces the length and complexity of the program



Pointers are efficient way of handling data associated with arrays.


20.

Write a c program to print Hello world without using any semicolon.

Explanation:

Solution: 1

void main(){

if(printf("Hello world")){

}

}


Solution: 2

void main(){

while(!printf
("Hello world")){

}

}


Solution: 3

void main(){

switch(printf("Hello world")){

}

21.

What is a static variable?

A static variable is a special variable that is stored in the data segment unlike the default automatic
variable that is stored in stack. A static
variable can be initialized by using keyword static before
variable name.

Example:

static int a = 5;

A static variable behaves in a different manner depending upon whether it is a global variable or a
local variable. A static global variable is same as an
ordinary global variable except that it cannot be
accessed by other files in the same program / project even with the use of keyword extern. A static
local variable is different from local variable. It is initialized only once no matter how many times
that

function in which it resides is called. It may be used as a count variable.

Example:

#include <stdio.h>

//program in file f1.c void count(void) { static int count1 = 0; int count2 = 0; count1++;

count2++;

printf("
\
nValue

of count1 is %d, Value of count2 is %d", count1, count2);

}

/*Main function*/ int main(){ count();

count(); count(); return 0;

}

Output:

Value of count1 is 1, Value of count2 is 1

Value of count1 is 2, Value of count2 is 1

V
alue of count1 is 3, Value of c
ount2 is 1

22.

What is a register variable?

Register variables are stored in the CPU registers. Its default value is a garbage value. Scope of a
register variable is local to the block in which it is defined. Lifetime is till control remains within the
block i
n which the register variable is defined. Variable stored in a CPU register can always be
accessed faster than the one that is stored in memory. Therefore, if a variable is used at many places
in a program, it is better to declare its storage class as regi
ster

Example:

register int x=5;

Variables for loop counters can be declared as register. Note that register keyword may be ignored by
some compilers.

23.


Where is an auto variables stored?

Main memory and CPU registers are the two memory locations where auto
variables are stored. Auto
variables are defined under automatic storage class. They are stored in main memory. Memory is
allocated to an automatic variable when the block which contains it is called and it is de
-
allocated at
the completion of its block ex
ecution.

Auto variables:

Storage : main memory.

Default value : garbage value.

Scope : local to the block in which the variable is defined.

Lifetime : till the control remains within t
he block in which the variable is
defined.

24.


What is scope & storage allocation of extern and global variables?

Extern variables: belong to the External storage class and are stored in the main memory. extern is
used when we have to refer a function or vari
able that is implemented in other file in the same
project. The scope of the extern variables is Global.

Example:

/*************** Index: f1.c

****************/

#include <stdio.h>

extern int x;

int main() {

printf("value of x %d", x);

return 0;

}

Index:
f2.c

****************/

int x = 3;

Here, the program written in file f1.c has the main function and reference to variable x. The file f2.c
has the declaration of variable x. The compiler should know the datatype of x and this is done by
extern definition.

G
lobal variables: are variables which are declared above the main( ) function. These variables are
accessible throughout the program. They can be accessed by all the functions in the program. Their
default value is zero.

Example:

#include <stdio.h>

int x =
0;

/* Variable x is a global variable.

It can be accessed throughout the program */

void increment(void) {

x = x + 1;

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

}

int main(){

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

increment();

return 0;

}

25.

What is scope & storage allocation
of register, static and local variables?

Register variables: belong to the register storage class and are stored in the CPU registers. The scope
of the register variables is local to the block in which the variables are defined. The variables which
are use
d for more number of times in a program are declared as register variables for faster access.

Example: loop counter variables. register int y=6;

Static variables: Memory is allocated at the beginning of the program execution and it is reallocated
only afte
r the program terminates. The scope of the static variables is local to the block in which the
variables are defined.

Example:

#include <stdio.h> void decrement(){ static int a=5;

a
--
;

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

}

int main(){ decrement(); return 0;

}

He
re 'a' is initialized only once. Every time this function is called, 'a' does not get initialized. so
output would be 4

3 2 etc.,

Local variables: are variables which are declared within any function or a block. They can be
accessed only by function or blo
ck in which they are declared. Their default value is a garbage value.

26.

What are storage memory, default value, scope and life of Automatic and Register
storage class?

1. Automatic storage class:

Storage : main memory.

Default value :

garbage value.

Scope : local to the block in which the variable is defined.

Lifetime : till control remains within the block.

2. Register storage class:

Storage : CPU registers.

Default
value : garbage value.

Scope : local to the block in which the variable is defined.

Lifetime : till control remains within the block.

27.


What are storage memory, default value, scope and life of Static and
External storage
class?

1. Static storage class:

Storage : main memory.

Default value : zero

Scope : local to the block in which the variable is defined.

Lifetime : till the value of
the variable persists between different function calls.

2. External storage class:

Storage : main memory

Default value : zero

Scope : global

Lifetime : as long as the program execution

doesn't come to an end.

28.

What is an Array?

An Array is a data type that stores multiple values in one variable. It can be thought of as a bunch of
values that are related to one another and will be used together. Every value in the array is called an
array

element. They can be referred to or accessed by using the
ir index position in the array.

29.

What is a pointer in C?

A pointer is a special variable in C language meant just to store address of any other variable or
function. Pointer variables unlike ordinary

variables cannot be operated with all the arithmetic
operations such as '*','%' operators. It follows a special arithmetic called as pointer arithmetic.

A pointer is declared as:

int *ap;

int a = 5;

In the above two statements an integer a was declared an
d initialized to 5. A pointer to an integer
with name ap was declared.

Next before ap is used ap=&a;

This operation would initialize the declared pointer to int. The pointer ap is now said to point to a.

Operations on a pointer:

Dereferencing operator ' *
': This operator gives the value at the address pointed by the pointer . For
example after the above C statements if we give

printf("%d",*ap);

Actual value of a that is 5 would be printed. That is because ap points to a.

Addition operator ' + ': Pointer ar
ithmetic is different from ordinary arithmetic.

ap=ap+1;

Above expression would not increment the value of ap by one, but would increment it by the number
of bytes of the data type it is pointing to. Here ap is pointing to an integer variable hence ap

is
incremented by 2 or 4 bytes depending upon the compiler.

30.

What are the advantages of using pointers?

Pointers are special variables which store address of some other variables.

Syntax: datatype *ptr;

Here * indicates that ptr is a pointer variable which

represents value stored at a particular address.

Example: int *p;

'p' is a pointer variable pointing to address location where an integer type is stored.

Advantages:

1. Pointers allow us to pass values to functions using call by reference. This is useful
when large
sized arrays are passed as arguments to functions. A function can return more
than one value by
using call by
reference.

2. Dynamic allocation of memory is possible with the help of pointers.

3. We can resize data structures. For instance, if
an array's memory is fixed, it cannot be resized.
But in case of an array whose memory is created out of malloc can be resized.

4. Pointers point to physical memory and allow quicker access to data.

31.
What are the differences between malloc() and calloc
()?

Allocation of memory at the time of execution is called dynamic memory allocation. It is done using
the standard library functions malloc() and calloc(). It is defined in "stdlib.h".

malloc(): used to allocate required number of bytes in memory at runt
ime. It takes one argument, viz.
size in bytes to be allocated.

Syntax:

void * malloc(size_t size);

Example:

a = (int*) malloc(4);

4 is the size (in bytes) of memory to be allocated.

calloc(): used to allocate required number of bytes in memory at runtime.

It needs two arguments
viz.,

1. total number of data and

2. size of each data.

Syntax:

void * calloc(size_t nmemb, size_t size);

Example:

a = (int*) calloc(8, sizeof(int));

Here sizeof

indicates the size of the data type and 8 indicates that we want to reserve space for
storing 8 integers.

Differences between malloc() and calloc() are:

1. Number of arguments differ.

2. By default, memory allocated by malloc() contains garbage values. Wh
ere
as memory allocated by
calloc()
contains all zeros.

32.
How to use realloc() to dynamically increase size of an already allocated array?

realloc(): This function is used to increase or decrease the size of any dynamic memory which is
allocated using mal
loc() or calloc() functions.

Syntax: void *realloc(void *ptr, size_t newsize);

The first argument 'ptr' is a pointer to the memory previously allocated by the malloc or calloc
functions. The second argument 'newsize' is the size in bytes, of a new memory r
egion to be allocated
by realloc. This value can be larger or smaller than the previously allocated memory. The realloc
function adjusts the old memory region if newsize is smaller than the size of old memory.

If the newsize is larger than the existing mem
ory size, it increases the size by copying the contents of
old memory region to new memory region. The function then deallocates the old memory region.
realloc function is helpful in managing a dynamic array whose size may change during execution.

Example:

a program that reads input from standard input may not know the size of data in advance.
In this case, dynamically allocated array can be used so that it is possible allocate the exact amount
of memory using realloc function.

5. What is the equivalent po
inter expression for referring an element a[i][j][k][l], in a four
dimensional array?

33.
Consider a multidimensional array a[w][x][y][z].

In this array, a[i] gives address of a[i][0][0][0] and a[i]+j gives the address of a[i][j][0][0] Similarly,
a[i][j] g
ives address of a[i][j][0][0] and a[i][j]+k gives the address of a[i][j][k][0] a[i][j][k] gives
address of a[i][j][k][0] and a[i][j][k]+l gives address of a[i][j][k][l]

Hence a[i][j][k][l] can be accessed using pointers as *(a[i][j][k]+l)

where * stands fo
r value at address and a[i][j][k]+l gives the address location of a[i][j][k][l].

Program: Example program to illustrate pointer denotation of multi
-
dimensional arrays.

#include<stdio.h>

#include<string.h>

int main() {

int a[3][3][3][3];

//it gives address
of a[0][0][0][0] . printf("
\
n address of array a is %u", a);

printf("
\
n address of a[2][0][0][0] is %u ,given by a[2], %u given by a+2", a[2], a + 2);

printf("
\
n address of a[2][2][0][0] is %u ,given by a[2][2], %u given by a[2]+2", a[2][2], a[2] + 2);

pr
intf("
\
n address of a[2][2][1][0] is %u ,given by a[2][2][1] , %u given by a[2][2]+1", a[2][2][1],
a[2][2] + 1);

return 0;

}

Output:

address of array a is 65340

address of a[2][0][0][0] is 65448, given by a[2] , 65448 given by a+2 address of a[2][2][0][0]
is
65484, given by a[2][2] ,65484 given by a[2]+2 address of a[2][2][1][0] is 65490, given by a[2][2][1]
, 65490 given by a[2][2]+1

Explanation:

This output may differ from computer to computer as the address locations are not same for every
computer.

34
.


What is the value of sizeof(a) /sizeof(char *)

in a code snippet:

char *a[4]={"sridhar","raghava","shashi","srikanth"};

Explanation:

Here a[4] is an array which holds the address of strings. Strings are character arrays themselves.

Memory required to stor
e an address is 4 bits. So memory required to store 4 addresses is equal to
4*4=16 bits. char *; is a pointer variable which stores the address of a char variable.

So sizeof(char *) is 4 bits. Therefore sizeof(a) /sizeof(char *) = 16/4 = 4 bytes.

35.
What
are the differences between the C statements below:

char *str = "Hello";

char arr[] = "Hello";

char *str="Hello";

"Hello" is an anonymous string present in the memory. 'str' is a pointer variable that holds the
address of this string.

char arr[]="Hello";

T
his statement assigns space for six characters: 'H' 'e' 'l' 'l' 'o' '
\
0' . 'arr' is the

variable name assigned
to this
array of characters.

str[4] and arr[4] also have different meanings.

str[4]: adds 4 to the value of 'str' and points to the address same
as value of str + 4. arr[4]: points to
the fourth element in array named 'arr'.

36.
Whether following statements get complied or not? Explain each statement. arr++;

*(arr + 1) = 's';

printf("%s",arr);

'arr' is variable name of an array. A variable name can

not be incremented or decremented. Hence
arr++ is an invalid statement and would result in a compilation error.

*(arr+1)='s';

'arr' is the name of a character array that holds string "Hello". Usually, name of an array points to its
base address. Hence val
ue of arr is same as &arr[0].

arr+1 is address of the next element: &arr[1]

Character 's' is assigned to the second element in array 'arr', thereby string changes from "Hello" to
"Hsllo". printf("%s",arr );

This statement prints the string stored in
character array 'arr'.

37.
What are merits and demerits of array in c?

Merits:

(a) We can easily access each element of array.

(b) Not necessity to declare too many variables.

(c) Array elements are stored in continuous memory location.

Demerit:

(a)

Wastage of memory space. We cannot change size of array at the run time.

(b) It can store only similar type of data.

38.
What is and why array in c?

An array is derived data type in c programming language which can store similar type of data in
continuous memory location. Data may be primitive type (int, char, float, double…), address of
union, structure, pointer, function or another array.

Example of array declaration:

int arr[5];

char arr[5];

float arr[5];

long double arr[5];

char * arr[5];

int

(arr[])();

double ** arr[5];


Array is useful when:

We have to store large number of data of similar type. If we have large number of similar kind of
variable then it is very difficult to remember name of all variables and write the program.

39.
List out

the
Advantage
s

of using array:

1. An array provides singe name .So it easy to remember the name of all element of an array.

2. Array name gives base address of an array .So with the help increment operator we can visit one
by one all the element of an arr
ay.

3. Array has many application data structure.

40.
W
hat is
Array of pointers in c
?

Array whose content is address of another variable is known as array pointers. For example:

int main(){

float a=0.0f,b=1.0f,c=2.0f;

float * arr[]={&a,&b,&c};

b=a+c;

printf("%f",arr[1]);

return 0;

}

41.
What is NULL pointer?

Literal meaning of NULL pointer is a pointer which is pointing to nothing. NULL pointer points the
base address of segment.

Examples of NULL pointer:

1. int *ptr=(char *)0;

2. float *ptr
=(float *)0;

3. char *ptr=(char *)0;

4. double *ptr=(double *)0;

5. char *ptr=’
\
0’;

6. int *ptr=NULL;

42.
What is size of void pointer?

Size of any type of pointer in c is independent of data type which is pointer is pointing i.e. size of all
type

of pointer (near) in c is two byte either it is char pointer, double pointer, function pointer or null
pointer. Void pointer is not exception of this rule and size of void pointer is also two byte.

43.
What is difference between uninitialized pointer and
null pointer?

An uninitialized pointer is a pointer which points unknown memory location while null pointer is
pointer which points a null value or base address of segment.

.44.
What is the difference between array of pointers and pointer to an ar
ray?

An array of pointers is that for eg if we have array of 10 int pointers ie int *a[10] then each element
that which is stored in array are pointed by pointers. here we will have ten pointers. In pointer to an
array for eg int(*a)[10] here all the eleme
nts that is all the ten elements are pointed by a single
pointer.





UNIT
-
V




FUNCTIONS & STRUCTURES


1.


What is meant by user defined function?


The function defined by the user according to their requirements is called user defined function.


2.


Define call by value.


When the value is passed directly to the function it is called call by value. In call by value only a
copy of the variable is only passed so any changes made to the variable does not reflects in the
calling function.


3.

Define call by reference.


When the address of the value is passed to the function it is called call by reference. In call by reference since
the address of the value is passed any changes made to the value reflects in the calling function
.


4.


What is meant by recursion and name two application?


This is where a function repeatedly calls itself to perform calculations. Typical applications are games and
Sorting trees and lists.


5.

Explain command line arguments of main function?

In C, we can
supply arguments to 'main' function. The arguments that we pass to main ( ) at
command prompt are called command line arguments. These arguments are supplied at the time of
invoking the program.

The main ( ) function can take arguments as: main(int argc, c
har *argv[]) { }

The first argument argc is known as 'argument counter'. It represents the number of arguments in the
command line. The second argument argv is known as 'argument vector'. It is an array of char type
pointers that points to the command line

arguments. Size of this array will be equal to the value of
argc.

Example: at the command prompt if we give: C:
\
> fruit.exe apple mango

then

argc would contain value 3

argv [0] would contain base address of string " fruit.exe" which is the command name th
at invokes
the program. argv [1] would contain base address of string "apple"

argv [2] would contain base address of string "mango"

here apple and mango are the arguments passed to the program fruit.exe

Program:

#include <stdio.h>

int main(int argc, char *
argv[]) {

int n;

printf("Following are the arguments entered in the command line");

for (n = 0; n < argc; n++) {

printf("
\
n %s", argv[n]);

}

printf("
\
n Number of arguments entered are
\
n %d
\
n", argc);

return 0;

}

Output:

Following are the arguments entered
in the command line

C:
\
testproject.exe apple

mango

Number of arguments entered are

3


6.

What is pass by value in functions?

Pass by Value: In this method, the value of each of the actual arguments in the calling function is
copied into

corresponding formal a
rguments of the called function. In pass by value, the changes
made to formal arguments in the called function have no effect on the values of actual arguments in
the calling function.

Example:

#include <stdio.h>

void swap(int x, int y) {

int t;

t = x; x =

y; y = t;

}

int main() {

int m = 10, n = 20;

printf("Before executing swap m=%d n=%d
\
n", m, n);

swap(m, n);

printf("After executing swap m=%d n=%d
\
n", m, n);

return 0;

Output:

Before executing swap m=10 n=20

After executing swap m=10 n=20

Explanation:

In the main function, value of variables m, n are not changed though they are passed to function
'swap'. Swap function has a copy of m, n and hence it can not manipulate the actual value of
arguments passed to it.

7.


What is pass by reference in functions?

P
ass by Reference: In this method, the addresses of actual arguments in the calling function are
copied into formal arguments of the called function. This means that using these addresses, we would
have an access to the actual arguments and hence we would b
e able to manipulate them. C does not
support Call by reference. But it can be simulated using pointers.

Example:

#include <stdio.h>

/* function definition */ void swap(int *x, int *y) { int t;

t = *x; /* assign the value at address x to t */

*x = *y; /* p
ut the value at y into x */

*y = t; /* put the value at to y */

}

int main() {

int m = 10, n = 20;

printf("Before executing swap m=%d n=%d
\
n", m, n);

swap(&m, &n);

printf("After executing swap m=%d n=%d
\
n", m, n);

return 0;

}

Output:

Before executing swap
m=10 n=20

After executing swap m=20 n=10

Explanation:

In the main function, address of variables m, n are

sent as arguments to the function 'swap'. As swap
function has the access to address of the arguments, manipulation of passed arguments inside swap
function would be directly reflected in the values of m, n.

8.

What is dangling pointer in c?

I
f any p
ointer is pointing the memory address of any variable but after some variable has deleted
from that memory location while pointer is still pointing such memory location. Such pointer is
known as dangling pointer and this problem is known as dangling pointe
r problem.

9.

What is the meaning of prototype of a function?

Declaration of function is known as prototype of a function. Prototype of a function means

(1) What is return type of function?

(2) What parameters are we passing?

(3) For example prototyp
e of printf function is:

int printf(const char *, …);

I.e. its return type is int data type, its first parameter constant character pointer and second parameter
is ellipsis i.e. variable number of arguments.

10.
Can arrays be passed to functions?

Yes, if
the programming language allows that, like most of high
-
level languages do. For example, in
Java, arrays are defined by placing square brackets after type definition:

public int[] arrayOfIntegers = { 1, 2, 5, 10 };

public String[] someStrings = { "Hello",
"World" };

public void thisMethodAcceptsArraysOfIntegers( int[] argument ) { }

public String andThoseStrings( String[] s ) { }

11.
What are the two common problems with pointers?

Memory leakage, problems with tracking and managing.

12.

What is the difference be
tween a function pointer and a pointer to a function?


Nothing, both refer
pointer to function
.

13.

What is recursion in C?

Recursion, in any programming language, refers to, most commonly, a call to a function inside that
function, (i.e

a function calling itself)
.

14.

What is the difference between actual and formal arguments used in functions in C
language?

The arguments passed to the functions while the function is called is known as the actual arguments,
whereas the arguments declared in
the function header is called as formal arguments.


Ex. Suppose sum() is a function.


int sum(int x, int y) /*Here x and y are called formal arguments*/

{...}


void main()

{

int ans;

....


ans = sum(3,5); /*Here the arguments 3 and 5 are called act
ual arguments*/


...


getch();

}

15.

What is the difference between call by value call by reference in c?


When a function is called and a copy of values of actual parameters is passed to the called function,
it's called as call by value.

When the address
of actual parameter is passed to the called function, it's called as call by reference.

e.g.

if
int a,b;

is a declaration in a calling function and a function call to a function having prototype,
int
add(int, int
) is made i.e.

add(a,b) ;

then it's call
by value.


And if function call to a function having prototype,
voidadd(int* , int*

) is made i.e.

add(&a,&b) ;

then it's call by referenc
e.
Call
-
by
-
reference

is achieved
using pointers.

16.

What is the advantage of using call by reference over call by value
?

Call by reference can reduce memory copy operations and allow multiple return values without using
code that impedes portability.

17.

How can you swap values of two variables using c language without using arithmetic
operators?


int a,b,temp;

printf("enter
the values of a & b"); //could be done in diff. two lines for the input//

scanf("%d %d",&a,&b);

printf("the values of a=%d & b=%d before swapping",a,b);

// swapping without using arithmetic operators.....

temp=a;

a=b;

b=temp;

printf("the values of a=%d & b
=%d after swapping",a,b);

getch();


18.

What is a structure?

A structure is a collection of pre
-
defined data types to create a user
-
defined data type. Let us say we
need to create records of students. Each student has three fields:

int roll_number; char name[3
0]; int total_marks;

This concept would be particularly useful in grouping data types. You could declare a structure
student as:

struct student { int roll_number; char name[30]; int total_marks;

} student1, student2;

The above snippet of code would declare

a structure by name student and it initializes two objects
student1, student2. Now these objects and their fields could be accessed by saying
student1.roll_number for accesing roll number field of student1 object, similarly student2.name for
accesing name

field of student2 object.

19.

What are the differences between a structure and a union?

Structures and Unions are used to store members of different data types.

STRUCTURE UNION

a)
Declaration:


struct

{

data type member1;

data type member2;

};

a)Declaration:


union

{

data type member1;

data type member2;

};



b)Every structure member is allocated memory when a structure variable is defined.

Example:

b)The memory equivalent to the la
rgest item is allocated commonly for all members.

Example:

s
truct emp { char name[5]; int age;

float sal;

};

struct emp e1;

Memory allocated for structure is 1+2+4=7 bytes. 1 byte for name, 2 bytes for age and 4 bytes for
sal.

c)All structure variables can

be initialized at a time struct st {

int a;

float b;

};

struct st s = { .a=4, .b=10.5 };

Structure is used when all members are to be independently used in a program.

union emp1 { char name[5]; int age;

float sal;

};

union emp1 e2;

Memory allocated to a
union is equal to size of the largest member. In this case, float is the largest
-
sized data type. Hence memory allocated to this union is 4 bytes.

c)Only one union member can be initialized at a time

union un {

int a;

float b;

};

union un un1 = { .a=10 };

Union is used when members of it are not required to be accessed at the same time.

20.

What are the advantages of unions?

Union is a collection of data items of different data types. It can hold data of only one member at a
time though it has members of differ
ent data types. If a union has two members of different data
types, they are allocated the same memory. The memory allocated is equal to maximum size of the
members. The data is interpreted in bytes depending on which member is being accessed.

Example: uni
on pen { char name; float point;

};

Here name and point are union members. Out of these two variables, 'point' is larger variable which
is of float data type and it would need 4 bytes of memory. Therefore 4 bytes space is allocated for
both the variables.
Both the variables have the same memory location. They are accessed according
to their type. Union is efficient when members of it are not required to be accessed at the same time.

21.

How can typedef be to define a type of structure?

typedef declaration helps

to make source code of a C program more readable. Its purpose is to
redefine the name of an existing variable type. It provides a short and meaningful way to call a data
type. typedef is useful when the name of the data type is long. Use of typedef can re
duce length and
complexity of data types.

Note: Usually uppercase letters are used to make it clear that we are dealing with our own data type.

Example:

struct employee { char name[20]; int age;

};

struct employee e;

The above declaration of the structure would be easy to use when renamed using typedef as:

struct employee { char name[20]; int age;

};typedef struct employee EMP; EMP e1, e2;

22.

What are the differences between getchar() and scanf() functions for reading
strings?

Differences between getchar and scanf functions for reading strings:

scanf getchar

1. Entering of each character should be followed

by return key.

1. Need not type return
key.

2. Continuous stream of characters cannot be directly supplied using scanf function.

3. Scanf function can be used to provide data at execution time irrespective of its type(int, char,
float)
.

Example:

#include<stdio.h>

int main() { char a[10]; printf("Enter a:
\
n"); scanf("%s",a); return 0;

}

2. Continuous stream of characters can be directly supplied using getchar function

3. getchar() function is used only with character type. Example:

#in
clude<stdio.h>

int main() {

char a;

printf("Enter any character:
\
n");

a = getchar();

printf("Character entered:%c
\
n",a);

return 0;

}

4
. scanf() returns the number of items read successfully. A return value 0 indicates that no fields
were read. EOF(end of

file) is returned in case of an error or if end
-
of
-
file/end
-
of
-
string character is
encountered.

4. getchar() returns the character entered as the value of the function. It returns EOF in case of an
error. It is recommeded to use getchar instead of scanf.