Coding Notes For Sems
Coding Notes For Sems
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
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.
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.
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.
A.L.U.
Input Device Output Device
Control Unit
Memory Unit
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.
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
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.
####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:
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.
Identifiers are names given to program elements such as variables, arrays and
functions.
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;
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: - >, <, <=, >=, = =, ! =.
Logical Operator: Logical operators are used to compare or evaluate logical and
relational expressions.
Example: &&, ||, !
Conditional operators are sometimes called ternary operator because they take three
operands or arguments.
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
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
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);
Infinite Loop
for (; ; )
{
printf(“XYZ”);
}
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.
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.
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.
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.
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.
“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.
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.
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.
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.
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.
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:
#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, ….);
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);
}
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.