You are on page 1of 27

Programming for Problem Solving (ES-CS-201)

Some Theories and Solutions

Definition of Computer: The term Computer comes from the word compute. A
computer is an electronic device that takes data and instructions from the user as an
input, processes those data according to the supplied instructions and produces
desired result known as output. The cycle of operation is known as input-process-
output cycle.

History of Computer: The use of computing technique is almost 5000 years old. In
China, Babylon people used numerical methods for surveying of lands and collection
of taxes. But the computing history starts with the development of the device called
ABACUS. Since the number system undergoes so many changes and has been used in
different forms of computing, the most significant development in computing was the
formulation of decimal numbers and logarithm. The 1 st accounting machine was built
by Pascal, known as Pascaline. Later on Leibnitz developed calculator. The origin of
modern computer can be traced back to 1834, when an English mathematician
Babbage designed analytical engine, 1 st programmable digital mechanical computer.
This machine contained all the major parts of the modern computer system, that’s
why Babbage is called the father of computer. Lady Lovelace was one of the strong
supporters of Babbage’s work. She presented some key elements of programming and
program design. She is considered to be the 1 st computer programmer.

Generation of Computer:
1st Generation:
a. Uses vacuum tubes to build the circuitry.
b. Magnetic drum was used for the memory.
c. Large in size.
d. Consumed a great deal of electricity and generated a large amount of heat.
2 Generation:
nd

a. Uses transistor.
b. Size and cost, both had been decreased.
c. Used stored program concept.
3 Generation:
rd

a. Uses IC (Integrated Circuit).


b. Used keyboard and monitor.
c. Size and cost, both had been decreased as compared to 2 nd generation.
4th Generation:
a. Uses IC and VLSI technique.
b. Used semiconductor memories.
c. Networking concept was introduced to pair in between two PC’s.

Classification of Computers:
Micro: A computer that has a microprocessor as its CPU.
Mini: A medium sized computer that is more powerful than micro, designed to serve
multiple users simultaneously.
Mainframe: It is used to help in handling the information processing of various
organizations like banks, hospitals and railways. These computers are placed on a
central location and are connected to several terminals.
Super: Most powerful and expensive and fastest used for complex scientific
applications, which need a higher level of processing.

Use of Computer:
1. Text, data & image processing.
2. Voice recognition, Message communication & Numerical computing.
3. Graphics & Multimedia.
4. Space research & Weather Forecasting, Banking Sector, AI.

Basic Anatomy of Computer System:


A digital computer consists of four main components: Input Unit, Output Unit, CPU
and Memory/Storage Unit. They are shown below with their functionalities.

Input & Output Unit: The user can enter instructions & data into memory through
devices such as keyboard or simple switches, called input devices. The results can be
displayed by a device called output device. These devices may be printer or monitors.

Functions of Input & Output Unit:


Input Unit: Reads the instructions & data given by the users & converts these
instructions & data in computer acceptable form & supplies these converted data &
instructions to the computer system for further processing.
Output Unit: Accepts the results produced by computer which is in coded form &
converts these coded results to our understandable form. It also supplies the
converted results to outside world.

Storage Unit: The specific functions of the storage unit are to store –
1. All the data to be processed & the instructions required for
processing.
2. Intermediate results of processing.
3. Final results of processing before these results are released to an
output device.

Central Processing Unit (CPU):


CPU has two major parts – 1. Control Unit & 2. Arithmetic/Logic Unit
The parts of the CPU are usually connected by an electronic component referred to as
bus, which acts as an electronic highway between them.
1. Control Unit: The control unit keeps track of processing. It processes the input
exactly as per the instructions given.
Function: By selecting, interpreting & seeing to the execution of the program
instructions, the control unit is able to maintain the order & direct the
operations of the entire system.
2. ALU: ALU is a place where the actual execution of the instructions takes place
during the processing operations. As the name suggests this unit conducts the
arithmetic & logical functions on the input.
Function: ALU’s are designed to perform the four basic arithmetic operations: -
1. Addition 2. Subtractions 3. Multiplication 4. Division & logic operations or
comparisons such as – 1. Less than 2.Equal to or 3. Greater than.
C. P.U.

A.L.U.
Input Device Output Device

Control Unit

Memory Unit

Block Diagram of Conventional Digital Computer System

Computer Hardware & Software: Hard-ware comprises the tangible parts of the
computer, such as the Monitor, Keyboard etc. Anything that can be stored
electronically is Soft-ware. Soft-ware consists of instructions & data that the computer
manipulates to perform various data processing tasks. It is the intangible part of the
computer system. The hard-ware part of the computer can’t work by itself without the
help of software.

System Software: Software that consists of programs used to operate the computer is
called System Software.
Example: Operating System.

Application Software: Software that is designed to handle a particular task required


by the end user is called Application Software.
Example: Microsoft-Office 97.

Primary & Secondary Memory:


The specific functions of the storage unit are to store –
1. All the data to be processed & the instructions required for
processing.
2. Intermediate results of processing.
3. Final results of processing before these results are released to an
output device.
The Term Computer Memory is defined as one or more sets of chips that store
Data/program instructions, either temporarily or permanently. It is critical processing
component in any computer. The PCs use several different types. They are:
• Main Memory / Primary Memory units
– Two most important are
• RAM (Random Access Memory)
• ROM (Read-only Memory)
– They work in different ways and perform distinct functions
– CPU Registers
– Cache Memory
Primary memories are used to store data temporarily and they are volatile in nature
(except ROM).
• Secondary Memory/Auxiliary Memory
Also termed as ‘auxiliary’ or ‘backup’ storage, it is typically used as a supplement to
main storage. It is much cheaper than the main storage and stores large amount of
data and instructions permanently. Hardware devices like magnetic tapes and disks
fall under this category.

Cache Memory:
The speed of processor is higher than main memory. It is placed in between primary
memory and microprocessor. To synchronise / co-ordinate between the main memory
and processor, a very high speed, small, costly memory is used, called Cache Memory.
Processor 1st searches the data for processing from the cache, but if the data are not
available there one copy of the data will be kept in cache for future reference and
another copy will be handled by processor itself.

Problem: A magnetic disk pack has 12 surfaces out of which 10 are readable. Each
surface has 50 tracks and each track is divided into a number of sectors. If the total
capacity of the disk pack is 50000 K bytes and the capacity of each sector is 512 bytes
then
(a) How many cylinders are present in the disk pack?
(b) How many sectors are present on each track? [WBUT Question]
Solution:
(a) Number of Cylinders = Number of Tracks per surface = 50.
Here only 10 surfaces are readable. Total capacity of the disk pack is 50000 K
bytes and the capacity of each sector is 512 bytes. So the capacity of a track =
50000/10 = 5000KB.
Total capacity per track = 5000 / 50 = 100 KB = 100 * 1024 Bytes.
(b) Number of Sectors on a track = 100 * 1024 / 512 = 200 Sectors

Definition of Operating System: An operating system is a program that acts as an


intermediary between the user of a computer and the computer hard ware. The
purpose of an operating system is to provide an environment in which a user can
execute programs in a convenient and efficient manner.

Functions:
1. Command Interpretation: - A command keyed in by a user has to be translated
to binary code for the CPU to understand it. An Operating System performs this
task.
2. Memory Management: - An Operating System has to take care of allocating
memory to the various applications running on the system. It has to allocate
optimum memory to the applications and clean up unnecessary data from the
memory.
3. Peripheral Management: - An Operating System has to take care of devices
(peripherals) attached to the computer. For example, it handles communication
between the CPU and the printer or the modem.
4. Process Management: - Processing the jobs, deciding on the job scheduling
technique and how long a job is to be processed, releasing the processor when
the jobs are terminated.

Types of Operating System:


1. Batch processing operating system: It allows only one program to run at a time.
This operating system would be best suited for a company wishing to automate
their payrolls.
2. Time sharing Operating system: It is used in computer networks which allows
different users to access the same data and application programs on the same
network.
3. Multitasking operating system: In this operating system, more than one
process can be executed concurrently. Ex: - Windows XP.
4. Multiprocessor Operating System: It can incorporate more than one processor
dedicated to running processes.
5. Real time Operating System: Real time operating systems are designed to
respond to an event within a predetermined time.
6. Embedded Operating System: An embedded operating system refers to the
operating system that is self-contained in the device and resident in ROM.

DOS vs. WINDOWS:


1. DOS is only single tasking while WINDOWS is multitasking.
2. DOS is based on plain interface while WINDOWS is based on Graphical user
interface (GUI).
3. DOS is difficult to learn and understand while WINDOWS is easy to learn and
understand.
4. Limited users can work on DOS while in WINDOWS there are many users.
5. We cannot see mouse in DOS while in WINDOWS we can see and use mouse to
click on icons or links.
6. In DOS new hardware cannot work properly while in WINDOWS it can detect
and installs software automatically.
7. Application and system software’s did not work properly in DOS while in
WINDOWS it runs at a great speed.
8. DOS is not user friendly while WINDOWS operating system is user friendly.
9. DOS perform operations speedily as compared with WINDOWS operating
system.

####from the above comparative study in between DOS and WINDOWS we can write
the short notes on DOS and WINDOWS [WBUT Question] ####

UNIX:
UNIX is a Multi user, multi-tasking operating system. It is a layered operating system
having hardware, Kernel and shell, one above the other. The kernel is the core of UNIX
and shell acts as an interface between kernel and the user. Every UNIX user has to
have a login name and password to access the UNIX system and execute the program.
Each user logs on the system executes programs and exits (logout) the system.
Introduction to Programming: Programming is an art of writing instructions for the
computer to do the specific task. These instructions are written using programming
languages. There are mainly three types of programming languages, namely, High
level, Low level and Assembly level Programming Language.

Comparative Study:

High Level Low Level Assembly Level


Each instruction is Each instruction is Mnemonic/Symbolic
English like statements. sequence of 0’s and 1’s. instructions.
Machine independent. Machine dependent. Machine dependent.
Less efficient. Efficient. Efficient.
Can’t be directly executed. Can be directly executed. Can’t be directly executed.
Easy to understand, write Difficult to understand, Easy to understand, write
and debug. write and debug. and debug.
Standardized. Not standardized. Standardized.
Compiler/Interpreter is No translator is required. Assembler is used in
used in translation translation process.
process.

Comparative study between Translators, Assemblers, Compilers & Interpreters:

A translator is a program that takes as input a program written in one programming


language (the source language) & produces as output a program in another language
(the object or target language).

Compiler Interpreter
A language translator that takes entire A language translator that takes one
program written in high level language statement of a high-level language &
and convert it into its equivalent translates it into a machine instruction
machine language. which is immediately executed.
Easy debugging for errors. Difficult debugging for errors.
Large amount of memory spaces are Small amount of memory spaces are
required. required.
Faster. Slower.
Costlier. Cheaper.

Assembler: There are several other important types of translators, besides compilers.
If the source language is assembly language & the target language is machine
language, then the translator is called an Assembler.

Structured Programming Language:


1. Consists of unique module for each function.
2. Easy to test and easy to debug.
3. Reuse of modules is possible.
4. Uses a top-down design model.
1. What is header file in C? Mention its advantages.
OR
Write Short Notes on Header File in C.
Solution:
When working with large projects, it is often desirable to make sub-routines and store
them in a different file known as header file. Conventionally, header files names ends
with a “.h” extension and its name can use only letters, digits, dashes, and
underscores. While some standard header files are available in C, but the programmer
may also create his own user defined header files.

Advantages: The advantage of header files can be realized when


a) The programmer wants to use the same subroutines in different programs. b) The
programmer wants to change, or add, subroutines, and have those changes be
reflected in all other programs.

2. Write Short Notes on Object File.


Solution:
 Object files are generated by the compiler as a result of processing the source
code file.
 Object files contain compact binary code of the function definitions. Linker uses
this object file to produce an executable file (.exe file) by combining the of object
files together.
 Object files have a “.o” extension, although some operating systems including
Windows and MS-DOS have a “.obj” extension for the object file.

3. Explain Keywords, Identifiers, Variables and Constants in C.


Solution:
Keywords are reserved words, assigned some fixed meaning, known to the compiler. C
has a set of 32 keywords. By convention all keywords must be written in lowercase
(small) letters. Example: for, while, do-while etc.

Identifiers are names given to program elements such as variables, arrays and
functions.

A variable is defined as a meaningful name given to the data storage location in


computer memory. When using a variable, we actually refer to address of the memory
where the data is stored. To declare a variable specify data type of the variable
followed by its name. Example: float salary;

Constants are identifiers whose value does not change. Constants are used to define
fixed values. To declare a constant, precede the normal variable declaration with const
keyword and assign it a value. Example: const float pi = 3.14;

4. Write short notes on the following:


Arithmetic Operator
Relational Operator
Logical Operator
Bitwise Operator
Special Operator
Precedence and Associativity of Operators
Solution
Arithmetic Operator: These operators perform arithmetic operations. The arithmetic
operators can operate on any built-in data type. Example: +, -, *, /, and %.
When an arithmetic operator is applied on two integer operands, the arithmetic is
called Integer Arithmetic. Floating point arithmetic involves operands on real type in
decimal or exponential notation. If either of the operands is real and the arithmetic
operator is applied on them, the arithmetic is called mixed mode arithmetic.
Example:
Operator Action Example Return Value
+ Addition 4+3 7
- Subtraction 4-1 3
* Multiplication 4*3 12
/ Division 8/4 2
% Modulo Division 8%4 0

Relational Operator: Relational Operators are used to distinguish between two values
depending on their relations. These operators provide the relationship between the two
expressions. If the relation is true then it returns a value 1 otherwise 0 for false
relation.
Examples: - >, <, <=, >=, = =, ! =.

Operator Action Example Return Value


> Greater than 4>3 1
< Less than 3<4 1
<= Less than or equal to 10<=10 1
>= Greater than or equal to 11>=5 1
== Equal to 2= =3 0
!= Not equal to 3! = 3 0

Logical Operator: Logical operators are used to compare or evaluate logical and
relational expressions.
Example: &&, ||, !

Operator Action Example Return Value


&& Logical AND 4>3 && 4>2 1
|| Logical OR 3<4 || 7<5 1
! Logical NOT !0 1

Bitwise Operator: C supports some operators known as Bitwise Operator, for


manipulation of data at bit level. These operators are used for testing the bits, or
shifting them right or left. Bitwise Operators may not be applied to float or double.
Examples: - &, |, ^, <<, >>.

Operator Action Example Output


& Bitwise AND z=x&y If x = 4, y = 4 then z = 4
| Bitwise OR z=x|y If x = 4, y = 4 then z = 4
^ Bitwise X-OR z=x^y If x = 4, y = 4 then z = 0
<< Bitwise Left Shift z = x << 2 If x = 4 then z = 16
>> Bitwise Right Shift z = x >> 2 If x = 4 then z = 1
Special Operator: Two Special Operators are comma, sizeof( ).
Working Principles: -
1. Comma: It can be used to link the related expressions together. Comma-linked
lists of expressions are evaluated left to right and the value of right most
expression is the value of the combined expression.
Example: - z = (x= 10, y = 20, x+y); Output: - 30.
2. sizeof: A compile time operator that returns the number of bytes the operand
occupies. The operand may be a variable, expression or a data type qualifier.
Example: - x = sizeof(y);
Output: - The number of bytes occupied by y will be returned to x.

Precedence and Associativity of Operators: C treats the operators with different


importance called precedence. On the other hand when an arithmetic expression
contains two different operators of equal precedence then we have to apply a rule
called associativity.
Example 1: - The expression a+b*c will be evaluated as a+(b*c) not (a+b)*c as the
precedence of operator * is higher than the operator +.
Example 2: - The expression r = x / y * z consists two different operators (/ and *)
having same precedence. This tie can be resolved to apply the associativity rule.

5. Give examples of Unary and Binary Operators.


Solution:
Unary Operator: Unary operators act on single operands. Example: Increment (++),
and Decrement (--) Operator.
Binary Operator: Binary operators act on two operands. Example: Multiplication (*)
Operator

6. What is Conditional Operator? Why is it called Ternary Operator?


Solution:
The operator pair (? :) is called Conditional Operator.
Syntax - exp1? exp2 : exp3
Here, exp1 is evaluated first. If it is true then exp2 is evaluated and becomes the result
of the expression, otherwise exp3 is evaluated and becomes the result of the
expression.
Example: - z = (x>y) ? x : y;

Conditional operators are sometimes called ternary operator because they take three
operands or arguments.

7. Explain Increment and Decrement Operator. What is the difference between


i++ and ++i?
Solution:
The increment operator is a unary operator that increases the value of its operand by
1. Similarly, the decrement operator decreases the value of its operand by 1.
Syntax: ++ <variable name> -- <variable name> //Pre Increment and Decrement
<variable name> ++ <variable name> --// Post Increment and Decrement

i++ ++i
Nature of operation: - Post Nature of operation: - Pre
Increment Increment
(1st assignment then increment) (1st increment then assignment)
i++ means, 1st we have to use the ++i means, 1st we have to
current value of i, then we have to increment i by 1, then to use
add 1 with that value. that value.
Example: - Example: -
int x, i=5; int x, i=5;
x=i++; x=++i;
printf(“%d%d”, i, x); printf(“%d%d”, i, x);
O/P – 6 5 O/P – 6 6

8. Explain Type Conversion and Typecasting with examples.


Solution: Type conversion and type casting of variables refers to changing a variable of
one data type into another.

Type conversion is done when the expression has variables of different data types. So
to evaluate the expression, the data type is promoted from lower to higher level where
the hierarchy of data types can be given as: double, float, long, int, short and char.

Type casting is also known as forced conversion. It is done when the value of a higher
data type has to be converted in to the value of a lower data type. For example, we
need to explicitly type cast an integer variable into a floating point variable.
float salary = 10000.00;
int sal;
sal = (int) salary;
Typecasting can be done by placing the destination data type in parentheses followed
by the variable name that has to be converted.

9. What is the difference between for, while and do-while loop? Explain with
example.
Solution:
Name while for do-while
Nature Entry controlled Entry controlled Exit controlled
for (initialization; condition;
while (condition) increment/decrement/upda do
{ te) {
Structure
statement_block; { statement_block;
} statement block; } while (condition);
}
Controlling
Controlling condition Controlling condition
Controlling condition appears
appears at the start of the appears at the end of
Condition at the start of the
loop. the loop
loop
int i=0, s=0; int i, s; int i=0, s=0;
while(i<=10) for(i=0, s=0; i<=10; i++) do
Example { { {
s=s+i; s=s+i; s=s+i;
i++; } i++;
} }while(i<=10);
May or may not
No. of May or may not execute at Must execute at least
execute at least
execution least one time one time
one time

Note: The while loop is used to repeat one or more statements while a particular
condition is true. In the while loop, the condition is tested before any of the statements
in the statement block is executed. The loop, for, is used to repeat a task until a
particular condition is true and it supports multiple initializations. The do-while loop
is similar to the while loop. The only difference is that in a do-while loop, the test
condition is tested at the end of the loop. The major disadvantage of using a do while
loop is that it always executes at least once, so even if the user enters some invalid
data, the loop will execute.

10. What is the difference between break and continue? Explain with
examples.
Solution:
break continue
1. In some programming situations we
1. We often come across situations
want to take the control to the
where we want to jump out of a
beginning of the loop, bypassing the
loop instantly, without waiting to
statements inside the loop which have
get back to the conditional test.
not yet been executed. The keyword
The keyword ‘break’ allow us to
‘continue’ allows us to do this.
do this.
2. When the keyword ‘break’ is 2. When the keyword ‘continue’ is
encountered inside any loop, encountered inside the loop, the
control automatically passes to control automatically passes to the
the 1st statement after the loop. beginning of the loop.

3. Example: - 3. Example: -
for(i=1; i<=2; i++) for(i=1; i<=2; i++)
{ {
for(j=1; j<=2; j++) for(j=1; j<=2; j++)
{ {
if(i = = j) if(i = = j)
break; continue;
printf(“%d%d”, i, j); printf(“%d%d”, i, j);
} }
} }
Output: - 21 Output: - 1221

11. Write short notes on goto statement and exit function.


Solution:
The goto statement is used to transfer control to a specified label. Here label is an
identifier that specifies the place where the branch is to be made. Label can be any
valid variable name that is followed by a colon (:). Whenever the goto statement is
encountered the control is immediately transferred to the statements following the
label. Statement goto breaks the normal sequential execution of the program.
Syntax: - goto label;
-------------
-------------
label: statement;

The exit( ) function is a standard library function which terminates the execution of
the program. This function causes immediate termination of the entire program,
forcing a return to the operating system.
Syntax: - void exit ( int return code);

12. Give examples of infinite and odd loop.


Solution:
Odd loop: The loops that we have used so far executed the statements within them a
finite number of times. However, in real life programming one comes across a situation
when it is not known beforehand how many times the statements in the loop are to be
executed. This situation can be programmed as shown below:
/* Execution of a loop an unknown number of times */
main( )
{
char another ;
int num ;
do
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
} while ( another = = 'y' ) ;
}
In this program the do-while loop would keep getting executed till the user continues
to answer y. The moment he answers n, the loop terminates, since the condition
(another == ‘y’) fails. Note that this loop ensures that statements within it are
executed at least once even if n is supplied first time itself.

Infinite Loop
for (; ; )
{
printf(“XYZ”);
}

13. What is Function? Why do we need function?


Solution:
Function: A function is a self-contained block of statements that perform a coherent
task of some kind. Every C program can be thought of as a collection of these
functions.

We need function as
1. Function modularizes and divides the work of a program. Dividing the program
into separate well defined functions facilitates each function to be written and
tested separately. This simplifies the process of getting the total program to
work.
2. Function avoids the repetitions of the same code.
3. Use of function makes the code easy to test and easy to debug. The code
becomes easy to understand. Understanding, coding and testing multiple
separate functions are far easier than doing the same for one huge function.

14. What is function prototype?


Solution:
The function declaration is a single statement written before any function definition
and is terminated by semicolon. Function declaration is a declaration statement that
identifies a function with its name, a list of arguments that it accepts and the type of
data it returns.

Syntax: - <return type> <function name> (data type, data type, …….. , data type);
Example: - int f(int, int);

15. What is the difference between standard library function and user defined
function?
Solution:
Standard Library Function User Defined Function
This type of functions are defined in the
This type of functions are declared and
language and provided along with the
defined by the user.
compiler.
Example: - main ( ) and any other user
Example: - printf( ), scanf ( ) etc.
defined function.
Generally related to input and output. Not related to input and output.

16. Write the difference between local and global variable with example.
Solution:
Local Variable Global Variable
Local variables are defined within the Global variables are defined outside the
body of the function or the block. The main ( ) function. Multiple functions can
variable defined is local to that function use them.
or block only. Other functions cannot
access these variables.
Example: - Example: -
void main ( ) int b = 10, c = 5;
{ void f( );
int b = 10, c = 5; void main( )
printf(“%d%d”, a, b); {
f( ); printf(“%d%d”, b, c);
} f( );
f( ) b++;
{ c--;
int b=20, c=10; printf(“%d%d”, b, c);
printf(“%d%d”, b, c); }
} void f( )
{
b++;
c--;
printf(“%d%d”, b, c);
O/P: - }
10 5 20 10 O/P: -
10 5 11 4 12 3

17. What is recursion? What are the advantages & disadvantages of recursion?
Distinguish between recursion & iteration.
Solution:
Recursion: It is the name given to the ability of a function to call it in terms of itself
until some desired condition is satisfied. There must be an exclusive stopping condition
within the body of recursive function otherwise the function enters into an infinite loop.

Advantages:
1. Recursive function is shorter and simpler than iterative function.
2. For certain problems a recursive solution often leads to short and elegant code.

Disadvantage:
1. Recursion can be expensive in both processing time & memory space.
2. Not all programming language (like FORTRAN, COBOL) supports recursion.

Recursion Iteration
It is the name given to the technique of It is a process of executing a statement or
defining something in terms of itself. set of statements repeatedly, until some
specified condition is satisfied.
There will be an exclusive stopping This process involves four clear cut parts.
condition within the body of recursive They are initialization, decision,
function. computation and updation.
Not all iterative programs can be solved All recursive programs can be solved
recursively. iteratively.
It is usually worse in terms of It is more efficient in terms of memory
performance as compared to iterative utilization and execution speed.
process.
Not all compilers support Recursion. Almost all compilers support Iteration.
18. Comments on the following: - “Recursion is a feature of a programming
language, but not a direct feature supported by an operating system”.
Solution:
Several functionalities of operating system are implemented by the recursive features
of a program inbuilt in the operating system. For an example the kernel of an
operating system, which is the core program, has several recursive methods and
procedures. So the operating system does not explicitly provide any recursive feature.

19. Explain Ackermann Function. Write a C Program to implement Ackermann


Function.
Solution:
Ackerman function is recursively described as follows:
𝑛+1 𝑖𝑓 𝑚 = 0
( )
𝐴 𝑚, 𝑛 = { 𝐴( 𝑚 − 1, 1) 𝑖𝑓 𝑚 > 0 𝑎𝑛𝑑 𝑛=0
𝐴(𝑚 − 1, 𝐴(𝑚, 𝑛 − 1)) 𝑖𝑓 𝑚 > 0 𝑎𝑛𝑑 𝑛 > 0
Following above definition we can calculate A (1, 2) and get the value 4.

C-Program to implement Ackermann Function


#include<stdio.h>
int ack(int m, int n)
{
if(m==0)
return (n+1);
else if(m>0 && n==0)
return (ack(m-1,1));
else
return (ack(m-1, ack(m,n-1)));
}
void main()
{
int a, b, c;
printf("\nEnter two numbers");
scanf("%d%d",&a, &b);
c=ack(a,b);
printf("\nThe result is %d",c);
}

20. Explain Call by Value and Call by Address in brief.


Solution:
Call-By-Value: When a calling function calls a function with the value of a variable
via actual argument, the value of the actual argument is copied into formal argument
of the called function. So two copies values of the variable now exists – one inside the
calling function and another inside the called function. A change of value inside the
called function is only confined to that area and is not reflected in the calling function.
This technique of passing the value of an argument to a function is known as call by
value.

Disadvantages: (a) Consumes more memory space. (b) Takes more time for execution.
Example:
#include<stdio.h>
void swap(int, int);
void main( )
{
int a,b;
scanf(“%d%d”, &a, &b);
printf(“%d%d”, a, b);
swap(a,b);
printf(“%d%d”, a, b);
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
printf(“%d%d”, x,y);
}
Output: - if the value of a is 10 and value of b is 20, then 1 st printf( ) inside main ( )
will print 10 20, 2nd printf ( ) inside the function swap ( ) will print 20 10 and last
printf ( ) inside main ( ) function will print 10 20.

Call-By-Address: When a calling function calls a function with address of a variable,


address of the actual argument is copied into formal argument of the called function.
The called function now computes directly on the data items of the calling function.
Just one copy of the data items exists and all the modifications made by the called
function is visible to the calling function also. This technique of function calling is
known as call by address.

Advantages: (a) Consumes less memory space. (b) Takes less time for execution.
Example:
#include<stdio.h>
void swap(int *, int *);
void main( )
{
int a,b;
scanf(“%d%d”, &a, &b);
printf(“%d%d”, a, b);
swap(&a,&b);
printf(“%d%d”, a, b);
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“%d%d”, *x,*y);
}
21. What are the different storage classes available in C? Explain each of them
in brief.
Solution:
A variable’s storage class tells us:
(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e. the default initial value).
(c) What is the scope of the variable; i.e. in which functions the value of the variable
would be available.
(d) What is the life of the variable; i.e. how long would the variable exist.

Storage Storage Default Scope Life Example


Class Initial
Value
Automatic Memory Garbage Local to the Till the main( )
Storage value. block in control {
Class which the remains auto int i, j ;
variable is within the printf ( "\n%d
defined. block in %d", i, j ) ;
which the }
variable is
defined.
Register CPU Garbage Local to the Till the main( )
Storage registers value. block in control {
Class which the remains register int i ;
variable is within the for ( i = 1 ; i <=
defined. block in 10 ; i++ )
which the printf ( "\n%d",
variable is i);
defined. }

Static Memory Zero. Local to the Value of the main( )


Storage block in variable {
Class which the persists f( ) ;
variable is between f( ) ;
defined. different f( ) ;
function calls. }
f( )
{ static int i = 1
;
printf ( "%d\n",
i);
i=i+1;
}
External Memory Zero. Global. As long as the int x = 21 ;
Storage program’s main( )
Class execution {
doesn’t come extern int y ;
to an end. printf ( "\n%d
%d", x, y ) ;
}
int y = 31 ;

22. State the features of C-preprocessor. What is the difference between macro
and function?
Solution:
Features of C-preprocessor:
1. A preprocessor is a program that processes the code before it passes through
the compiler.
2. The preprocessor offers several features called preprocessor directives.
Preprocessor directives are distinguished by # (hash) symbol. The directives can
be placed anywhere in a program but are most often placed at the beginning of
a program, before the first function definition.
3. There are two types of preprocessor directives, namely (a) Unconditional (b)
Conditional.

Macro Function
During compilation macro is replaced by In functions, the program control moves
its definition. to the function every time the function is
called.
During compilation, the compiler does not During compilation, the compiler checks
check the data types of the arguments. the data types of the arguments.
Macro does not have any return type. Functions must have a valid return type.

23. What is an array? Explain “C does not support bound checking”.


Solution:
 An array is a collection of similar data types/elements, where each element is
unique one and located in separate memory location.
 The elements of the array are stored in consecutive memory locations and are
referenced by an index (also known as the subscript).
 Arrays are declared using the following syntax:
type name[size];

“C does not support bound checking”: In C there is no check to see if the subscript
used for an array exceeds the size of the array. Data entered with a subscript
exceeding the array size will simply be placed in memory outside the array; probably
on top of other data, or on the program itself. This will lead to unpredictable results, to
say the least, and there will be no error message to warn you that you are going
beyond the array size. In some cases the computer may just hang. Thus, the following
program may turn out to be suicidal.

void main( )
{
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
{
num[i] = i ;
}
}
Thus, to see to it that we do not reach beyond the array size is entirely the
programmer’s botheration and not the compiler’s.

24. What is string? How string is represented in memory? Name any five
string functions whose prototype is defined in string.h header file. Explain
the working principle of any two of them.
Solution:
String: String is defined as arrays of characters terminated with a Null (‘\0’)
character.

Representation of string in memory: Let us consider a string “HELLO”. Consider a


array of characters say ‘str[ ] ‘ that will hold the string “HELLO”. That is char str [ ] =
“HELLO”;
The memory representation is as follows: -
H E L L O \0

Say the address of the 1st element into the array is 9001. If every character elements
reserves 1-bytes of memory space in memory then the address of the 2 nd element is
9002, 3rd is 9003 and so on.

String Syntax Working Principle Example


functions
strlen strlen (s1) Returns the length of string s1. char str [ ] = “hello”;
int l1;
l1 = srlen (str);
strcpy strcpy (s2, Copy the content of s1 into s2. char str [ ] = “hello”;
s1) char str1 [ ] =
“india”;
strcpy (str1, str);
strcmp strcmp (s1, Compare two strings s1 and s2. char str [ ] = “hello”;
s2) Returns < 0 if s1<s2. char str1 [ ] =
Returns 0 if s1 = s2. “india”;
Returns > 0 if s1 > s2. strcmp (str, str1);
strcat strcat (s1, s2) Concatenate strings s1 and s2. char str [ ] = “hello”;
char str1 [ ] =
“india”;
strcat (str, str1);
strrev strrev (s1) Reverses the string s1. char str [ ] = “hello”;
strrev (str);

25. Write short notes on: - String handling in C.


Solution:
For this answer declare a string, take input, print the string and show the memory
representation and examples with 2 or 3 string functions.

26. What is structure? Write short notes on Array of structure. What is union?
What is bit field? What is the difference between structure and union? What
is enum?
Solution:
Structure: A structure is a collection of one or more variables of different data types,
grouped together under a single name. By using structures we can make a group of
variables of variables, arrays, pointers etc. Structure is basically a user defined data
type that can store related information (even of different data types) together.

Array of structure: We know array is a collection of similar elements. In the same


way we can also define the array of structure. In such type of array every element is of
structure type.
Syntax:
struct time
{
int second;
int minute;
int hour;
} t [30];
In this example t [30] is an array of 30 elements containing 3 objects of time structure.
Each element of t [30] has structure of time with 3 members that are second, minute
and hour.
Example:
#include<stdio.h>
struct t
{
int x, y;
};
void main( )
{
int i;
struct t t1[30];
for(i = 0; i<10; i++)
{
scanf (“%d%d”, &t1[i].x, &t1[i].y);
}
for(i = 0; i<10; i++)
{
printf (“%d%d”, t1[i].x, t1[i].y);
}
}

Union: It is a variable, which is similar to structure. It contains number of members


like structure but it holds only one object at a time. Members of the unions have same
memory locations. It can accommodate one member at a time in a single area of
storage.
Features: (a) Prevents memory fragmentations. (b) Each member shares the same
memory location. (c) A union can hold any one of its members but only at different
times. (d) Its declaration is similar as structure. (e) Nested union may be used. (f)
Array of unions, pointer to a union and function with union as its arguments are
possible.
Bit field: It provides exact amount of bits required for storage of values. If a variable 1
or 0 we need a single bit to store it. In the same way if the variable is expressed
between 0 and 3 then 2 bits are sufficient for storing these values. Similarly if a
variable assumes values between 0 and 7 then 3-bits will be sufficient to hold the
variable and so on. The number of bits required for a variable is specified by non-
negative integer followed by colon.
Example:
struct vehicle
{
unsigned type : 3;
unsigned fuel : 2;
unsigned model : 3;
};
Explanation: ‘:’ indicates the bit field to compiler and the number after it indicates how
many bits are required to allot to the field.

Structure Union
Every member has its own memory. Each member shares the same memory.
Consumes more space as compared to Prevents memory fragmentation.
union.
Different interpretations of the same Different interpretations of the same
memory location are not possible. memory location are possible.

Note: The only difference between a structure and a union is that in case of unions, you
can only store information in one field at any one time.

enum: enum is short of enumerated data. The user defines a type of data which is
made up of a fixed set of words, instead of numbers or characters. The compiler
automatically assigns integer values beginning with 0 to these words.
Syntax:
enum abc { a, b, c};
Explanation: in the syntax a, b, c are set of words which are known as enumeration
contents and the values are a = 0, b = 1, c = 2.

27. What is pointer? Why we use pointer? What is void pointer? What is a
const pointer? What is NULL pointer?
Solution:
Pointer:
1. A pointer is an entity which contains a memory address.
2. A pointer is a variable that contains the address of another variable.
Syntax: <data type> * <pointer name> ; Like: - int * p;

Use:
1. Pointers offer tremendous flexibility in the creation of dynamic variables,
accessing & manipulating the contents of memory locations, and releasing the
memory occupied by the dynamic variables which are no longer in use.
2. Accessing array elements.
3. Passing arguments to functions by reference.
4. Passing arrays & strings to functions.
5. Creating data structures such as linked list, trees, graphs & so-on.
6. Obtaining memory from the system dynamically.

void pointer: Pointers defined to be a specific data type cannot hold the address of
any other type of variable. It is syntactically incorrect in C to assign the address of,
say, an integer variable to a pointer of type float as given below:
float *f_ptr;
int a;
f_ptr=&a; /* Error*/
An exception to this restriction is a general purpose pointer type called the void
pointer.
Declaration: void * v_ptr; /* declare a pointer to void */
Pointers declared in this manner don’t have any type associated with them & can
contain the address of any type of variable (int, char, float, etc).
Example:
#include<stdio.h>
void main()
{
int i=100;
float f=200.5;
void *p;
p=&i;
printf("%d\n", *((int *)p));
p=&f;
printf("%f", *((float *)p));
}
O/P: - 100
200.500000

const pointer: A const pointer is not the pointer to constant, it is the constant. For
example, int* const ptr; indicates that ptr is a pointer, which is a constant. A pointer
is preceded by ‘*’. In the above example it is not, Hence it is not the pointer to
constant. The ptr cannot be used to point to another integer. The integer pointed by
ptr can be changed. The const pointer cannot be changed to point to other memory
location, because the pointer is constant.

Null pointer: It is a special pointer which does not point to any valid memory address.
To declare a null pointer we may use a predefined constant NULL.

Example: int *p=NULL;

28. What is static and dynamic memory allocation? Explain with examples.
Solution:
Static Memory Allocation: Memory is allocated for the declared variable by the
compiler. The address can be obtained by using ‘address of’ operator and can be
assigned to a pointer. The memory is allocated during compile time. Since most of the
declared variables have static memory, this kind of assigning the address of a variable
to a pointer is known as static memory allocation.
Example: - Array supports static memory allocation.

Dynamic Memory Allocation: Allocation of memory at the time of execution (run


time) is known as dynamic memory allocation. The functions calloc() and malloc()
support allocating of dynamic memory. Dynamic allocation of memory space is done
by using these functions when value is returned by functions and assigned to pointer
variables.
Example: - Linked List supports dynamic memory allocation.

29. Give an example of dynamic memory allocation using malloc( ).


Solution:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
void main()
{
int *p,n,i;
printf("Enter the number of elements to be inserted");
scanf("%d",&n);
p=(int *)malloc(n*sizeof(int));
if(p==NULL)
{
printf("Out of memory");
exit(1);
}
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
printf("\nDisplay");
for(i=0;i<n;i++)
{
printf("%d",*(p+i));
}
getch();
}

30. Write short notes on the following:


Array of Pointer
Pointer to an Array
Pointer to Pointer
Pointer Arithmetic
Function returning a Pointer
Pointer to a Function
Solution
Array of Pointer: An array of Pointers is a collection of addresses. These can be
addresses of ordinary isolated variables or of array elements. These elements of an
array of pointers are stored in the memory just like the elements of any other kind of
array. All rules that apply to other arrays also apply to the array of pointers.
Example:
void main()
{
int a[3]={1,2,3};
int i;
int *p[3]; /*Array of pointers*/
for(i=0; i<3; i++)
p[i]=&a[i];
for(i=0; i<3; i++)
printf("%u\n%d\n", p[i], *p[i]);
}

Pointer to an Array: The way we have a pointer to an integer, or a pointer to a float,


we can also have a pointer to an array. Normally we use a pointer to point 0 th element
of the array initially, but we can also declare a pointer that can point to the whole
array instead of only one element of the array. This pointer is useful when we are
talking about multidimensional arrays.
Declaration: int (*q) [4]; // q is a pointer to an array of 4 integers

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
int *p;
int (*q)[4]; // pointer to an array
p=(int *)a;
q=a;
printf("\nAddresses are %u %u", p, q);
p++;
q++;
printf("\nAddresses are %u %u", p, q);
getch();
}
O/P:
Addresses are 1000 1000
Addresses are 1002 1008
Note: Base address is assumed as 1000 and size of integer is 2 bytes.

Pointer to Pointer: We know that pointer is a variable that can contain memory
address. The pointer variable takes some space in memory and hence it also has an
address. We can store the address of a pointer variable in some other variable, which
is known as a pointer to pointer variable and this concept can be extended to any limit
but in practice only pointer to pointer is used. Pointers to pointers offer flexibility in
handling arrays, passing pointer variables to functions, etc.
General format: <data type> ** <ptr_to_ptr>; /* Here ptr_to_ptr is a pointer to a pointer
pointing to a data object of the type <data type> */
Example:
int a=5;
int *p=&a; //p is an integer pointer holding address of integer variable a
int **q=&p; //q is a pointer to pointer holding address of pointer p

Pointer Arithmetic: All types of arithmetic operations are not possible with pointers.
The valid operations are as follows:
(a) Addition of an integer to a pointer and increment operation. (b) Subtraction of in
integer from a pointer and decrement operation & (c) Subtracted of one pointer from
another pointer of the same types. [Subtraction of one pointer from another pointer of
the same base type returns an integer]
Pointer arithmetic is somewhat different from ordinary arithmetic. Here all arithmetic
is performed relative to the size of base type of pointer.

Example 1 [for (a) and (b)]:


int a=5, *p;
p=&a; //suppose address of a is 1000 and size of int is 2
p=p+1; // p=1000 + (1*2)=1002 (since int is of size 2)
p=p-3; // p=1002 - (3*2) = 996

Example 2[for (c)]


#include<stdio.h>
#include<conio.h>
void main()
{
static int arr[]={10,20,30,45,67,56,74};
int *i, *j;
i=&arr[0]; // say base address of the array is 100, which is assigned into i
j=&arr[5]; // say size of int is 2, hence address of 6 th element is 110
printf("%d", j-i);
getch();
}
O/P: 5
Invalid Operations:
 Additions, Multiplications, Divisions of two pointers.
 Multiplication between pointer and any number.
 Division of a pointer by any number.

Function returning a pointer: Function can return a pointer. However, to make a


function return a pointer it has to be explicitly mentioned in the calling function as
well as in the function definition.

Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int *f(int *, int *);
void main()
{
int a, b, *p;
printf("Enter two values");
scanf("%d%d",&a, &b);
p=f(&a,&b);
printf("\na=%d\nb=%d\nlargest=%d",a,b,*p);
getch();
}
int *f(int *x, int *y)
{
if(*x>*y)
return x;
else
return y;
}

In the above program our objective is find out largest among two numbers. Here the
function f( ) returns the address of the largest number. So we can say that the
function here is used to return a pointer.

Pointer to a function:
Declaration: return type (*ptr_name) (type1, type2, ….);

Example: float (*fp) (int);


Here fp is a pointer that can point to any function that returns a float value & accepts
an integer value as an argument.

31. Write alternative definitions of three standard string functions with the
help of pointer.
Solution:
Only Function Definition is given here:
Alternative function of strlen( )
xstrlen (char *s)
{
int l=0;
while(*s != ‘\0’)
{
l++;
s++;
}
return (l);
}

Alternative function of strcpy( )


xstrcpy (char *t, char *s)
{
while(*s != ‘\0’)
{
*t = *s;
s++;
t++;
}
*t = ‘\0’;
}

Alternative function of strcmp( )


xstrcmp (char *s1, char *s2)
{
while(*s1 = = *s2)
{
if (*s1 = = ‘\0’)
return (0);
s1++;
s2++;
}
return (*s1 - *s2);
}

32. State the basic features of structured programming. What are the
disadvantages of machine language?
Solution:
Basic Features of structured programming:
1. A technique which enforces a logical structure on the programs to make them
more efficient.
2. Uses a top down design model and there is a separate module for each function.
3. Modules can be reused. Code can be loaded into memory more efficiently due to
modularity.

Disadvantages of machine language:


1. Not portable for different hard wares.
2. It is very difficult for human being to remember codes and develop programs
using machine language.

You might also like