Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

G.L. Bajaj Institute of Technology & Management, Gr.

Noida
CCP IMPORTANT QUESTIONS
SOLUTION
Computer Concepts & Programming in C (NCS-101)
UNIT-1

1.Draw a neat block diagram of a digital computer and explain briefly each part.

Ans. Definition of computer: Computer is an electronic device that is designed to accept data, perform the required mathematical and logical
operations at high speed and output the result.

Basic architecture of computer:

Output unit

CPU

INPUT UNIT ALU GP Registers MEMORY

CU

Computer has four main components:


Input unit, Memory, Central processing unit and output unit

1. Input unit: The input provides a way of man to man machine communication. An input device reads the data and program into the computer
.for eg: Keyboard, Mouse, joystick etc .
2. Memory: This part of computer is used as a storage for program and data. The memory can both be external as well as internal .The internal
memory known as main memory is directly accessible to the CPU. The external memory ,generally known as a secondary memory.
Note:- The main differences between primary and secondary storage is that primary storage is directly accessible by CPU and is volatile in
nature whereas secondary storage is non volatile and not directly accessible to the CPU. The term volatile means the content of main memory
are lost as soon as power is switched off .The main memory or primary storage is so organized that the time of access of data is independent
of location in memory therefore the memory is called Random access memory.

3. Central processing Unit (CPU): The main purpose of CPU is to execute the program stored in main memory by performing following tasks:
(a)Fetch instructions from main memory
(b)Interpret the fetched instruction to determine what is needed.
(c)Fetch data either from memory or input device.
(d)Perform arithmetic or logical operation on data.
(e)Write data if required to a Memory location or an output device.

The main components of CPU are CU(control unit) ,ALU(Arithmetic and logic unit) and set of registers.

CONTROL UNIT: It is responsible for the movement of data and instructions in and out of memory and CPU.
ALU (Arithmetic logic unit):It perform arithmetic and logic operations on data. It can perform addition, subtraction, division, multiplication,
comparison etc.
4. OUTPUT UNIT : These devices are required to deliver results to the user of computer system. For eg: Printer, Plotter.

MEMORIES:
Memory is important part of computer system that holds program as well as data. Each memory chip contains thousands of storage locations
called cells . A cell is the smallest part of memory which can be accessed by the CPU. Each cell has an address by which it can be referenced.
Each cell in the memory can store data ,this memory is also called as main memory .It is a volatile memory means as soon as power is turned
off data is lost .Program which is currently executing firstly load into main memory then only it can execute. : Tapes and disks are two principal
storage devices in computer system. They are used for variety of purposes such as to store files, hold data temporarily, storage of program etc.
The main advantage of such a device is that it provides a means of retaining information on permanent basis.

Page 1
2.What is memory? Discuss the memory hierarchy within computer system.

MEMORIES:
Memory is important part of computer system that holds program as well as data. Computer system is usually designed with hierarchy of
memories as shown below:

CPU CACHE MAIN Secondary


MEMORY storage
Registers

(a) CPU registers (b) Cache memory (c)Primary storage (d)Secondary storage

(a) CPU registers: They are the part of CPU number of registers in the CPU is minimum 8 to 32.

(b) Primary Memory:


Each memory chip contains thousands of storage locations called cells . A cell is the smallest part of memory which can be accessed by the
CPU. Each cell has an address by which it can be referenced. Each cell in the memory can store data ,this memory is also called as main
memory .It is a volatile memory means as soon as power is turned off data is lost .Program which is currently executing firstly load into main
memory then only it can execute,
NOTE:- Each memory cell can be directly read or written in the same length of time, irrespective of its physical location in the memory
.Therefore memory is also known as random access memory.(RAM).
It is of mainly two types RAM and ROM

RAM(Random access Memory) and ROM(Read only memory):


RAM:- It is called RAM because any location in it may be accessed in the same amount of time irrespective of its physical location in the
memory .It is a read/write memory in the sense that it is possible to both read from or write to locations within RAM..RAM is a volatile
memory as it loses the contents when the power is switched off or interrupted.
RAM is categorized into two main category i.e Static RAM(SRAM) and Dynamic RAM(DRAM). SRAM are large in physical size, expensive and
fast memories. Dynamic RAM are smaller in physical size, cheaper and slower memories Because data stored in them needs to be constantly
refreshed making CPU to wait for data.

ROM(Read only memory):-This is a nonvolatile semiconductor random access memory used for permanent storage .It is a read only memory in
the sense that data is placed in the ROM at the time of its manufacture and cannot be changed thereafter.
There are some variations of ROM are given below:
a. Programmable Read only Memory(PROM): This ROM is programmed even after its manufacture .Each bit in PROM can be individually
programmed to a 1 or 0 by burning a fusible link. The main disadvantage of PROM is that it cannot be reprogrammed.
b. Erasable programmable Read only Memory(EPROM):This is a type of ROM Better than PROM in a way that it can be reprogrammed . For
erasing the data EPROM is exposed to ultraviolet light. Once erased EPROM can be reprogrammed
c. Electrically Erasable programmable read only memory(EEPROM):It can be repeatedly erased and programmed by electrical signals. During
the power failure the contents of RAM are lost .When power is returned the content of EEPROM are copied back into the RAM and computer
resumes normal working .

(c). Cache Memory:

CPU Main
Memory

Cache
memory

Page 2
Cache memory is basically use to mapping the speed mismatch of CPU and Main memory.CPU is a extremely fast device as compare to main
memory but it cannot work in isolation. In the system it has to depend upon the main memory for fetching the instructions.
The cache is a very fast and small memory designed to do one thing speed up the CPU access to frequently used data.

(d). Secondary memory (storage devices) :Tapes and disks are twp principal storage devices in computer system. They are used for variety of
purposes such as to store files, hold data temporarily ,storage of program etc. The main advantage of such a device is that it provides a means
of retaining information on permanent basis. Therefore these devices being external to CPU and main memory are also termed as secondary
storage devices. The main memory is semiconductor memory while the secondary memory is a magnetic memory.

3.What is operating system? Explain the types and functions of operating system.

OPERATING SYSTEM:-

Definition of operating system: Operating system is system software which acts as a interface between user of computer and its hardware.

User

Operating system
Hardware

Operating system is a collection of systems programs that tells the computer what to do under variety of conditions. The other software gets
loaded after loading system software in the memory. Operating system is designed to serve two basic purposes,
1. It controls allocation and use of computing system resources among various tasks.
2. It provide an interface between computer hardware and programmer
BASIC FUNCTIONS OF OPERATING SYSTEM:-

1. Process Management: - Process is a program in execution .A program is a passive entity while process is an active entity .Operating
system is responsible for the following activities of process management:-
a. Creating and destroying user and system processes.
b. Allocating hardware resources among processes.
c. Controlling progress of process
d. Providing mechanisms for process communications like IPC(Inter process communication)
2. Memory Management: - Memory management is concerned with following functions:-
1. Keeping track of status of each location of memory ie each memory location is free or allocated.
2. Determining allocation policy for memory
3. File management: - File is a logical collection of information .A file may contain report, executable program ori of set of commands to
Operating system. Operating system is responsible for following activities related to file management: -
1. Creating and deleting of files
2. Mapping of files onto secondary storage
3. Supporting primitives for manipulating files and directories
4. Organizing ,storing, retrieving, naming and protecting all files.
4. Device management:-

A computer system use different devices such as keyboard, mouse, monitor. All devices are managed by Operating system .In case of device
failure Operating system detects it and inform the same to user.

TYPES OF OPERATING SYSTEM: -

1. Single processing System:- The simplest of all computer systems is a single use single processor system. It has single processor runs a single
program and interacts with a single user at a time. But CPU is not utilized to its full potential, Because it sits idle for most of the time

2. Multiprogramming operating system :- This type of operating system allows two or more users to run programs at same time. The main
objective of multiprogramming operating system is to increase system utilization efficiency. When some Input output is being performed by
the currently executing job of batch ,CPU sits idle without any work to do. Multiprogramming operating system tries to eliminate such idle
times. This is achieved by keeping multiple jobs in the main store (main memory).Some examples of operating system are given below:

Page 3
UNIX, Windows, etc

3. Multiprocessing system:- Multiprocessing refer to utilization of multiple CPU in a single computer system. This is also called parallel
processing. A computer system composed of several independent processors or CPU is known as multiprocessor architecture. This operating
system also has capability of support more than one process at the same time.

4. Multitasking operating system:- Multitasking is a technique where in single job may contain two or more independent tasks that can execute
concurrently in multiprogramming mode. On a system having only one CPU concurrent processing means that when one task is being executed
the other waits .However rapid task switching may give illusion to the user as if the tasks are being executed simultaneously.

4.Conversions: do yourself

5.Differentiate between the following:

a.High level language and low level language

Low level programming language;>

(a)Difficult to use;>It is difficult to understand and develop a program using machine language.
(b)Machine dependent:->Programmer has to remember Machine characteristics while preparing a program. As internal design of computer is
different which in turn is determined by actual design or construction of ALU,CU and Machine language is vary from computer to computer
High level programming language->
(a)Readability;>Programs written in these languages are more readable than those written in assembly and machine language
(b)Portability;>High level programming languages can be run on different machines.
(c)Ease in the development of software;>Since the commands of these programming languages are closer to English language,software can be
developed with ease.
b. Compiler and interpreter

DIFFERENCES BETWEEN COMPILER AND INTERPRETER:

COMPILER INTERPRETER

1.Scan the entire program before translating 1.Translate and execute program
it into machine code line by line.
2.Converts the entire program to machine 2 Interpreter executes one line at
Code and executes program only when all a time , after checking and
syntax errors are removed correcting its syntax errors and
3.Slow in debugging or in removal of mistakes then converting it into machine code
from program 3.Good for fast debugging
4.Program execution time is less 4..Program execution time is more
6.Write short notes on flowchart .Explain difference between flowchart and algorithm.

Ans: FLOWCHART is a graphical or symbolic presentation of process. when designing a flowchart each step in a process is depicted by different
symbol. Symbols in the flowchart are linked together with arrows to show the flow of logic in the process.

SYMBOLS IN THE FLOWCHART INCLUDE;>

1.Start and End;>

are also known as terminal symbols. These symbols are always the first and last symbol in the flowchart .

2.Arrow;

Page 4
It depict the flow of control of the program. They illustrate the exact sequence in which instruction are executed.

3.Processing step;>

Also called as activity step and is represented using rectangle .Activity include instructions such as add to B,save the result.

4.Input- output symbol->

are represented using parallelogram and are used to get Input from users or display results to them

5.Conditional or decision symbol;>

Used to depict a yes/no question or true/false test.

ALGORITHM:- An algorithm is a part of plan for computer program. In fact an algorithm is a effective procedure for solving problem in a finite
number of steps.
Key features of algorithm ;>
1.Sequence;>Sequence means that each step or process in the algorithm is executed in the specified order otherwise algorithm always gives
logical error.
2.Decision constructs;>In algorithms outcome of decision is either true or false ,there is no state in between . the outcome of decision is based
on some condition that can only result in true or false value For eg;>if today is Friday then collect pay ,Decision can also be stated as :if
proposition then process1 else process2.,This is the if -----then ------else form of the decision .this means that if the proposition is true then
execute process1, else or otherwise execute process2.
3.Repetition Constructs;>
Repetition can be implemented using constructs like repeat loop ,while loop
4.Termination ;>The definition of algorithms cannot be restricted to procedures that eventually finish. algorithm might include procedures that
could run forever without stopping .But algorithm has to terminate if you want to sol ve a particular problem.
5.Correctness;>The prepared algorithm needs to be verified for its correctness. Correctness means how easily its logic can be argued to meet
the algorithm primary goal.
UNIT-2

1.Explain in detail about fundamental data types in ‘C’ language, mentioning their range, space they occupy in memory and keyword
used for their representation in programming.

Fundamental data types

Data Type Keyword Used Size in Bytes Range Use


Character char 1 -128 to 127 To store character
Integer int 2 -32768 to 32767 To store integers
numbers
Floating Point float 4 3.4e-38 to 3.4e+38 To store floating point
number
Double double 8 1.7e-308 to 1.7e+308 To store big floating
numbers
Valueless Void 0 Valueless -

Page 5
2.What is an operator? What are the various types of relational operator ,logical operator ,bitwise operator ,unary operator and
conditional operators? Clearly state their meaning and example of each.

Ans: Operator->An operator is defined as a symbol that specifies the mathematical ,logical or relational operation to be performed.C language
supports lot of operatorsto be used in expressions .These oporrators can be categorized into the following major groups:

Relational Operator:- These operator also known as comparison operator, is one that compares two values. Relational operators return
true or false value.

Operator Meaning Example (let’s assume a and b are to integer variables )


< Less than a < b ; returns 1 if a is smaller than b otherwise return 0
<= Less than or equal to a <= b ; returns 1 if a is smaller than or equal to b otherwise
return 0
> Greater than a > b ; returns 1 if a is greater than b otherwise return 0
>= Greater than or equal to a >= b ; returns 1 if a is greater than or equal to b otherwise
return 0
== Equal to a == b ; returns 1 if a and b both operands are equal otherwise
return 0
!= Not equal to a != b ; returns 1 if a and b both operands are not equal
otherwise return 0

Logical Operators:-C language supports three logical operators logicalAND(&&), logical OR(||), and logical NOT(!).
logical AND (&&) operator is used to simultaneously evaluate two conditions or expressions with relational operators. If expression on both
the side (left and right side)of the logical operator is TRUE than the whole expression is TRUE.
Truth table for logical AND (&&)
A B a&&b
0 0 0
0 1 0
1 0 0
1 1 1
e.g. (a < b) && (b > c)

left right
the whole expression is TRUE only if both expressions (left and right) are TRUE.

logical OR (||) operator is used to simultaneously evaluate two conditions or expressions with relational operators. If one or both the
expression on the left side and right side of the logical operator is TRUE than the whole expression is TRUE
Truth table for logical OR (||)
A B A||b

0 0 0

0 1 0

1 0 0

1 1 1

e.g. (a < b) || (b > c)

left right
the whole expression is TRUE only if either b is greater than a or b is greater than c.
logical NOT (!) operator take a single expression and negates the value of the expression. Logical NOT produces a zero if the expression
evaluates to a non-zero and produces a one if the expression produces a zero.
Truth table for logical NOT (!)
A !a
1 0
0 1
Bitwise operator :- The bitwise operators expect their operands to be integers and treat them as a sequence of bits. These are those
operators that perform operations at the bit level.
Bitwise AND (&):- it performs operations on bits instead of bytes, chars, integers, etc .When we use the bitwise AND operator, the bit in the
first operand is ANDed with the corresponding bit in the second operand. For example

Page 6
10101010 & 01010101 = 00000000
Or int a = 6, b = 5, c;
c=a&b
Bitwise OR (|):- it performs operations on bits instead of bytes, chars, integers, etc .When we use the bitwise OR operator, the bit in the first
operand is ORed with the corresponding bit in the second operand. For example
10101010 | 01010101 = 11111111
Or int a = 6, b = 5, c;
c=a|b
Bitwise XOR (^):- it performs operations on individual bits of the operands. When we use the bitwise XOR operator, the bit in the first operand
is XORed with the corresponding bit in the second operand. For example
10101010 ^ 01010101 = 11111111 (Note:- if both bits are same then XORed
of those bits is 0 and if both bits are different then XORed of those bits as 1)
Or int a = 6, b = 5, c;
c=a^b
Bitwise shift operator:- There are two bitwise shift operators. They are shift left (<<) and shift right (>>). These operations are responsible for
shifting bits either to left or to the right. The syntax for shift operation
operand op num
where the bits in operand are shifted left or right depending on the operator op (either << or >>) by the number of places denoted by num.
For example,
x = 0001 1101, then x << 2 produces 0111 0100 (bitwise left shift by 2 places)
x = 0001 1101, then x >> 2 produces 0100 0111(bitwise right shift by 2 places)
Unary Operators:-
1. Unary ‘-‘operator negates the value of its operand. There is no Unary ‘+’ operator.
2. Unary increment and decrement operators: - the unary ‘++’ and ‘--’operators increment or decrement the value in a variable by 1.
var++ increment ‘post’ variant and var- decrement ‘post’ variant
++ var increment ‘pre’ variant and --var decrement ‘pre’ variant
We can understand the working of post and pre increment & decrement by the
following piece of program-
int i , j ;
i = 10;
j = i++; // post increment
printf(“ %d %d ”, i, j); output: i=11 , j=10

int i , j ;
i = 10;
j = ++i; // post increment
printf(“ %d %d ”, i, j); output: i=11 , j=11

3. The sizeof operator:- this unary operator used to calculate the size of data types.
Syntax: sizeof(data type name); or
sizeof(variable); or
sizeof(expression);
Conditional Operator(Ternary Operators):- The conditional operator or the ternary operator (? : ) is just like if-else statement that can be
within expressions.
The syntax of conditional operator is
exp1 ? exp2 : exp3
exp1 is evaluated first. If it is true, than exp2 is evaluated otherwise exp3 is evaluated for the result.
Eg. z= x < y ? x : y ;

3.What are the different types of storage classes? Explain.

Ans.Storage class->A storsge class is one ,which provides the following four informations about a variable:
Scope:
The scope of a variable determines the region of the program in which it is known. An identifier's "visibility" determines the portions of the
program in which it can be referenced—its "scope." An identifier is visible only in portions of a program encompassed by its "scope”, which
may be limited to the file, function or block in which it appears.
Lifetime: With lifetime we mean for what time period a variable is accessible(duration of time for which it is active foe a particular
module).Actually lifetime of a variable is the time difference between the time when it is created and when it is destroyed.

Default value: If user does not initialize any variable then any value automatically assign to it(known as default initial value) on the basis of
type of storage class. Default value of a variable can be either garbage or zero

Page 7
Storage class Scope Life time Default Storage area
value

Automatic Local to the block in till the control remains within the block in which defined Garbage Main memory
which defined

Static Local to the block in value of variable persists between different function calls Zero Main memory
which defined

Register Local to the block in till the control remains within the block in which defined Garbage CPU register
which defined

External Global As long as program execution does not Zero Main memory

UNIT-3

1.Explain all conditional statements and program loop with help of syntax, flowchart and an example,available in C programming.

There are three types of loop in C:


1. for loop
2. while loop
3. do-while loop
For loop:

Syntax: for(initialisation; condition; update expression)


{
Statement block or body of loop ;
}
Statement y;
When for loop is used ,the loop variable is initialized only once. With every iteration of the loop the value of the loop variable is updated and
the condition is checked. If the condition is true ,the statement block of the loop is executed and then update expression will be executed
otherwise the statements comprising the statement block of the for loop are skipped and the control jumps to the immediate statement
following the for loop body
Flow chart :
Initialization of variable

FALSE
Test
expression
ondition
TRUE

Statement block

Update the variable

Statement y

Page 8
Example : WAP of print the sum of Ist 10 natural no using for loop:

void main()
{
int i,s=0;
for(i=1;i<=10;i++)
{
s=s+i;
}
printf(“Sum of ist 10 natural no is s=%d”,s);
}

2. While Loop:

Syntax:

Initialization ;
while(Test expression)
{
Statement block or body of while;
Update statement;
}
Initialization of variable

Condition FALSE

TRUE

Statement block

Update the variable

Statement y

Example : // Write a program to print the sum of ist 10 natural no


void main()
{
int i,s=0;
i=0;//initialization
while(i<=10)
{
s=s+i;// statement
i++;
}
printf(“\n sum of ist 10 natural no=%d”,s);
}

Do –While():

Page 9
Syntax:

Initialization;
do
{
Statement block;
Update statement;
}while(test expression);

Flow chart :

Example: Write a program to print the sum of ist 10 natural no using do while loop
void main()
{
int I ,s=0;
i=1;
do
{
s=s+i;
i++;
} while(i<=10);
printf(“\n sum of ist 10 natural no=%d”,s);
}
Conditional statement:
Types:
1. Simple if statement 3.. If –else statement
2. Nested if statemet 4. Switch statement
Simple if statement:
General form:
if(condition)
{
Statement block;
}
Statement y;
Flow chart:

Page 10
Example:

void main()
{
if(printf(“hello”);

}
2 if –else:
Syntax:
if(condition)
{
Statement block x;

}
else
{
Statement block y;

}
Statement z;
Flow chart:

Page 11
3. Nested if:

The nested if-else statement's power comes from the fact that it is able to evaluate more than one condition at once, and/or use lots of
different conditions in one logical structure.

if(x == 0) {
// do this
} else if(y == 1) {
// do this
} else if(x == 1 && y == 0) {
// do this
}

Typically, nested if-else statements are used in the program's logic where there isn't only one condition to evaluate.

4. Switch statement :
A switch statement, on the other hand, evaluates only one variable and starts to work there. You can think of a switch statement as a
simplified (and stripped-down) version of an if-else block.
switch(x) {
case 1: // do this
case 2: // do this
case 3: // do this
// etc
}
When we talk about which one is better, its depends only on the requirement of the program. This depends very much on the specific case.
Preferably, I think one should use the switch over the if-else if there are many nested if-else.

2.What is the difference between break and continue statement, explain with programming example?

The break statement will exit the most immediately surrounding loop regardless of what the conditions of the loop are. Break is useful if
we want to exit a loop under special circumstances.
Syntax: break;
Example:
#include<stdio.h>
void main()
{
int i,j;
for(i=1;i<=3;i++)
{
for(j=1;j<=2;j++)
{
If(i==j)
{
break;
}
printf(“\n%d%d”,i,j);
}
}
}
Output:
21
31
32

Continue is another keyword that controls the flow of loops. If we are executing a loop and hit a continue , the loop will stop its current
iteration, update itself (in the case of for loops) and begin to execute again from the top. Essentially, the continue statement is saying
"this iteration of the loop is done; let's continue with the loop without executing whatever code comes after me.
syntax: continue;
Continue cannot be used with switch, like break.

Page 12
Example:

void main()
{
int i,j;
for(i=1;i<=3;i++)
{
for(j=1;j<=2;j++)
{
If(i==j)
{
continue;
}
printf(“\n%d%d”,i,j);
}
}
}
Output : 12
21
31
32
3.Write a program in C to calculate the sum of digits of a given number.
#include<stdio.h>
void main()
{
int num , rem ,s=0;
printf(“Enter a number of which user want to add digits\n”);
scanf(“%d”,&num);
While(num!=0)
{
rem=num%10;
s=s+rem;
num=num/10;
}
printf(“%d is the sum of digit of a number”,s);
}
4.Write a program in C to check whether a given number is palindrome or not.
#include<stdio.h>
void main()
{
int num , rem ,rev=0,b;
printf(“Enter a number of which user want to obtain reverse equivalent\n”);
scanf(“%d”,&num);
b=num;
While(num!=0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
if(b= =rev)
{
printf(“Number is palindrome\n”);
}
else
{
printf(“Number is not palindrome”);
}
}
5.Write a program in C to check whether a given number is prime or not.
#include<stdio.h>
void main()

Page 13
{
int num,i=1,c=0;
printf(“enter a number \n”);
scanf(“%d”,&num);
while(i<=num)
{
if(num%i==0)
{
c++;
}
}
if(c= =2)
{
printf(“Number is prime”);
}
else
{
printf(“Number is not prime”);
}
}
6.Write a program in C print Fibonacci series up to n terms using recursion
#include<stdio.h>
void main()
{
int n,i;
printf(“enter number of terms that user want to print in fibonacci series\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
printf(“%d”,fibo(i));
}
}
int fibo(int k)
{
if(k==1)
{
return 0;
}
else
if(k==2)
{
return 1;
}
else
{
return (fibo(k-1)+fibo(k-2));
}
}
7.Write a program to print the following patterns:
a) *
***
*****
*******
#include<stdio.h>
void main()
{
int line,i,j;
printf(“enter number of lines that user want to print\n”);
scanf(“%d”,&line);
for(i=1;i<=line;i++)
{
for(j=line-1;j>=i;j--)
{
printf(“ ”);
}

Page 14
for(j=1;j<=(2*i-1);j++)
{
printf(“*”);
}
printf(“\n”);
}
}
b)
1
23
456
7 8 9 10
#include<stdio.h>
void main()
{
int line,k=1,i,j;
printf(“enter number of line\n”);
scanf(“%d”,&line);
for(i=1;i<=line;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,k);
k=k+1;
}
printf(“\n”);
}
c)
A
AB
ABC
ABCD
ABCDE
#include<stdio.h>
void main()
{
int i,j;
for(i=’A’;i<=’E’;i++)
{
for(j=’A’;j<=i;j++)
{
printf(“%c”,j);
}
printf(“\n”);
}
}
8.what is the difference between call by value and call by reference ? Explain with programming example.
Or
In how many ways parameters can be passed to a function? Explain with programming example.
In function , we can pass parameter by using two methods :
1. Call by value
2. Call by reference
Call by value

It means sending the values of the arguments. The value of each of the actual arguments in the calling function is copied into
corresponding formal arguments of the called function. The changes made to the formal arguments have no effect on the values of
actual arguments in the calling function. This technique of passing arguments is called pass by value illustrated by the following
example.

Page 15
#include<stdio.h>
#include<conio.h>
void swap(int p,int q);
void main()
{
int a,b;
printf(“enter two integer number”);
scanf(“%d%d”,&a,&b);
swap(a,b); //here we pass value of variables a and b rather than their address
}

void swap(int p,int q)


{
int temp;
temp=p;
p=q;
q=temp;
printf(“values after swapping are %d %d”,p,q);
}

ii) Call by reference

it means sending the addresses of the arguments. the addresses of actual arguments in the calling function are copied into
formal arguments of the called function. Using these addresses we are actually working on actual argument so changes will be
reflected in the calling function. This technique of passing arguments is called pass by reference, illustrated by following example.

#include<stdio.h>
#include<conio.h>
void swap(int *p,int *q);
void main()
{
int a,b;
printf(“enter two integer number”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);//here we pass addresses of variables a and b rather than their values
}

void swap(int *p,int *q)


{
int temp;
temp=*p;
*p=*q;
*q=temp;
printf(“values after swapping are %d %d”,*p,*q);
}

9. What is recursion? Write a program to calculate factorial of an entered number using recursive function.
Ans. Recursion: - A recursion is defined as a function that calls itself to solve a smaller version of its task until a final call is made which does
not require a call to itself. Every recursion has two major cases:
Base Case: - in which the problem is simple enough to be solved directly without making any further calls to the same function.
Recursive Case: - in which first the problem at hand is divided into simpler sub-parts. Second the function call itself but with the sub parts of
problem obtained in the first step. Third, the result is obtained by combining the solutions of simpler sub parts.

#include<stdio.h>
#include<conio.h>
long int fact(int n);
void main()
{
int x;
long int f;
clrscr();
printf("enter an integer number");
scanf("%d",&x);
f=fact(x);
printf("factorial of given number is= %ld",f);

Page 16
getch();
}

long int fact(int n)


{
if(n==0)
{
return(1);
}
else
{
return(n*fact(n-1));
}
}

UNIT-4
1.Explain in detail about 1-dimensional and 2-dimensional array declaration, accessing elements,initialization with suitable examples
2-Write a C program to find out largest element in given list of elements.
#include<stdio.h>
void main()
{
int a[100],n,i,max;
printf(“enter number of elements \n”);
scanf(“%d”,&n);
printf(“enter elements in 1d array\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
max=a[0];
for(i=1;i<n;i++)
{
if(max<a[i])
{
max=a[i];
}
}
printf(“%d is the largest element”,max);
}
3-Write a C program to search a given element in a given list of elements using linear and binary search technique.
Searching means to find whether a particular value is present in the array or not. If the value is present in the array then searching is said to be
successful and the searching process gives the location of that value in the array. There are two popular methods for searching, one is linear
search and the second is binary search.
Linear search:-> Linear search works by comparing every element of the array one by one in sequence until a match is found. Linear search is
mostly used to search an unsorted list of elements.
Binary search:->Binary search works efficiently with a sorted list. In binary search, with each comparison, the size of the segment where search
has to be made is reduced to half. So for huge amount of data elements binary search is more efficient than linear search.

PROGRAM TO IMPLEMENT LINEAR SEARCH


#include<stdio.h>
#include<conio.h>
Void main()
{
int a[100] , n , i , item ,loc=-1;
printf(“Enter number of elements\n ”);
scanf(“%d”,&n);
printf(“Enter the numbers\n”);
for(i=0 ;i<n ;i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter item to be searched\n”);

Page 17
scanf(“%d”,&item);
for(i=0;i<n;i++)
{
if(item==a[i])
{
Loc=i;
break;
}
}
if(loc>=0)
printf(“\n %d is found in position %d item”,item,loc+1);
else
printf(“\n item does not exist\n”);
getch();
}

PROGRAM TO IMPLEMENT BINARY SEARCH


#include<stdio.h>

#include<conio.h>
Void main()
{
int a[100], n , i , item , beg , end ,mid;
printf(“Enter no of elements\n”);
scanf(“%d”,&n);
printf(“Enter numbers in ascending order\n”)
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter number to be searched\n”);
beg=0;
end=n-1;
mid=(beg+end)/2;

while(beg<=end&&item!=a[mid])

{
if(item>a[mid])

beg=mid+1;
else
end=mid-1;
mid=(beg+end)/2;
}
If(a[mid]==item)
printf(“%d is found in position %d”,item,mid+1);
else
printf(“item does not exist”);
getch();
}
4.Write a C program to sort a given list of elements(using bubble sort only).

Sorting is the process of putting a list or a group of items in a specific order. Some common sorting criteria are: alphabetical or numerical.
Sorting can be done in ascending order or descending order.

76, 89, 31, 11, -15, 17


No swap
76, 89, 31, 11, -15, 17
Swap
76, 31, 89, 11, -15, 17 Swap

76, 31, 11, 89, -15, 17


Swap
76, 31, 11, -15, 89, 17
swap
76, 31, 11, -15, 17, 89

Page 18
Here 1 pass is complete and last element is sorted, this process will repeat 5 times and all the elements of array will get sorted.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],temp;
int i,j,n;
clrscr();
printf("enter the size of array");
scanf(“%d”,&n)
for(i=0;i<n;i++)
{
scanf(" %d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\n Sorted array is \n");
for(i=0;i<n;i++)
{
printf("%d",a[i]);
}
getch();
}
5.Write a C program to multiply two matrices of which order is entered by user.
#include<stdio.h>
#include<conio.h>
Void main()
{
int a[100][100] , b[100][100] , c[100][100] , r1 , c1 , r2 , c2 , i ,j,k;
printf(“Enter order of first matrix\n”);
scanf(“%d %d”,&r1,&c1);
printf(“enter order of second matrix\n”);
scanf(“%d %d”,&r2,&c2);
if(c1!=r2)
{
printf(“Matrix multiplication not possible\n”);
}
else
{
printf(“Enter elements of first matrix\n”);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(“%d”, &a[i][j]);
}
}

printf(“Enter elements of second matrix\n”);


for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(“%d”, &b[i][j]);
}

Page 19
}

for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
printf(“\n resultant matrix after multiplication\n”);
for(i=0;i<r1;i++)
{
for(j=0;i<c2;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
getch();
}
6-What is structure in C? Declared a structure named book containing member b_name,b_id and price. Create an array of 30 such students
.Write a program to read and display the content of the array.
Structure-> A structure is similar to records. It stores related information about an entity. Structure is basically a user defined data type that
can stored related information (even of different data types ) together. The major difference between array and structure is that an array
contains related information of the same data type.
#include<stdio.h>
void main( )
{
struct book
{
char b_name[100];
int b_id;
int price;
};
struct book b1[30];
int i;
printf(“Input records of all books\n ”);
for(i=0;i<30;i++)
{
printf(“enter record of book %d\n”,i+1);
printf(“enter name of book\n”);
gets(b1[i].name);
printf(“enter id of book\n”);
scanf(“%d”,&b1[i].id);
printf(“enter price of book”)
scanf(“%d”,&b1[i].price)
}
printf(“Display records of all books\n”);
for(i=0;i<30;i++)
{
printf(“record of book %d\n”,i+1);
printf(“name of book is”);
puts(b1[i].name);
printf(“id of book is”);
printf(“%d”,b1[i].id);
printf(“price of book is”);

Page 20
printf(“%d”,b1[i].price);
}

}
7- What is the difference between structure and union? Explain with example.
Similar to structures , a union is a collection of variables of different data types. The only difference between structure and union is that in
case of unions, user can only store information in one field at any one time. In case of union ,the fields share the same memory space, so fresh
data replaces any existing data. In structure size of it is equal to the sum of size of individual field whereas in case of a union, size of it is equal
to the size of largest field.
#include<stdio.h>
{
struct point1
{
int x;
int y;
};
union point2
{
int x;
int y;
};
struct point1 p1;
union point2 p2;
p1.x=4;
p1.y=5;
p2.x=4;
p2.y=5;
printf(“\n component values of structure are x=%d,y=%d\n”,p1.x,p1.y);
printf(“\n component values of union are x=%d,y=%d\n”,p2.x,p2.y);
}
Output:
Component values of structure are x=4,y=5
Component values of union are x=5,y=5
UNIT-5
1.What are pointers? Why are they required? How do you declare and initialize them?
A pointer is a variable that contains the address of memory location of another variable.
Declaration:
A pointer provides access to a variable by using the address of that variable.
General syntax of declaring pointer variable:
Datatype * ptr_name;
Now. Let us declare an integer pointer variable and start using it in our code:
int x=10;
int *ptr; ptr x
ptr=&x; x1200
10
1200 1202

In the above statement, ptr is the name of pointer variable. The’*’ informs the compiler that ptr is a pointer variable and int specifies
that it will store address of integer variable.
Pointer as a Indirection or dereference operator:
User can dereference a pointer that is refer to value of variable to which it points by using unary “*”operator(also known as
indirection operator).
*(Address of any variable) is equal to Content or value stored inside that variable.
Example:->
Write a program to illustrate the concept of pointer.
#include<stdio.h>
void main()
{

Page 21
int x=10;
int *ptr;
ptr=&x;
printf(“\n value of x=%d\n”,*ptr);
}
Output-> value of x =10
2-What is file? Explain various file opening modes and various file handling functions in detail.
A file is a collection of data stored on a secondary storage device such as hard disk.
To use files in C, we must use the following steps:
->declare a file pointer variable
->open the file
->process the file
->close the file

File mode:
In C language different file opening modes are used during opening a file.

Mode Description
r Open a text file for reading .if the stream(file) does not exist, then an error will be reported.

w Open a text file for writing .if the stream(file) does not
Exist, then it is created,if the file already exist,then its contents would be deleted
a Append to text file. If the file does not exist ,then it is created .In this mode existing content in a file would not be
deleted and new data written by user append to a existing data

r+ Open a text file for both reading and writing .when user specify ‘r+’ ,indicate that user want to read the file
before write.Thus,the file must already exist.

w+ Open a text file for both reading and writing .The stream will be created if it does not exist
.
a+ Open a text file for both reading and writing. Existing data would not be deleted and new data append to it.if the
file does not exist then it is created

rb Open binary file for reading


wb Open binary file for writing
ab Open binary for writing ,but existing data would not be deleted and new data append to it.

File handling functions:


Function Meaning syntax: (FILE *fptr)
fopen() It is used to open a file and fptr=fopen(“file_name”,”mode”);
associate it with a stream.
fclose() It is used to close a open a fclose(fptr);
file.
fscanf() This is used to read fscanf(fptr,”%d”,&a);
formatted data from the file.
fgetc() This function returns the fgetc(fptr);
next character from stream,
and EOF if the end of the file
is reached
fgets() The function fgets() stands
for file get string. This fgets(str,80,fptr)
function is used to get a where char str[80];
string from a file.
fprintf() This is used to write fprintf(fptr,”%d”,a);
formatted data to the file.

Page 22
fputc() This function is just opposite fputc(ch,fptr);
of fgetc() and is used to where char ch;
write a character to the file.
fputs() This function is used to write
a string to a file. fputs(str,fptr)
where char str[80];

3. What is C pre-processor? List all preprocessor directives and explain any two with suitable example
Ans: C Pre-processor:- C Pre-processor is a program that processes the source program before it is complied. It is collection of special
statement called C Pre-processor statements or C Pre-processor directives. These directives are executed before the C program passes
through the compiler.

Source program C Pre- processor Compiler object program

Pre-processor Directives: Pre-processor Directives normally begin with a # and they are placed before the function
main(). There will be no semicolon at the end of such stateemnts.
Frequently used Pre-processor Directives in C are:
1- #include
2- #define
3- #ifdef #else #endif
4- #ifndef #else #endif
5- #if #else #endif
1-#include:- if a function of another file is required in the current program, then that file can be include in the current program by “include”
statement. Then all functions in program written in the include file can be used in the current file. It is written as
#include<filename> or #include”file name”
For example: #include<stdio.h>
This statement includes “stdio.h” file in the program and all functions in this file can be accessed by the program in which it has been
included.
2-#define:- This directive is mainly used for two basic purposes ,macro substitution and macro definition .
Macro substitution: the #define directive defines an identifiers and a string/constant that is substituted in place of the identifier each time, it
is encountered in the file. This identifier is called macro name and the replacement process is known as macro substitution. For eg:->
#define FALSE 0
The compiler will actually substitute the constant 0 when the identifier FALSE is encountered .
We can also substitute string .For eg:
#define TEST “This is a test program”
Macro definition :
#include<stdio.h>
#define ENTER printf(“please enter a number”)
void main()
{
int n;
ENTER;
scanf(“%d”,&n);
printf(“the value of n is %d”,n);
}

Page 23
In above given program the macro that is ENTER is replaced by statement printf(“please enter a number”).
Macro definition with arguments :
#include<stdio.h>
#define AREA (l,b) l*b
void main()
{
int area,length,breadth;
printf(“enter length and breadth of rectangle\n”);
scanf(“%d%d”,&length,&breadth);
area=AREA(length,breadth);
printf(“%d is the area of rectangle”,area);
}

Page 24

You might also like