PPS Important Question's Solutions21-22
PPS Important Question's Solutions21-22
PPS Important Question's Solutions21-22
Noida
PPS IMPORTANT QUESTIONS
SOLUTION
Programming for Problem Solving (BCS-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.
Output unit
CPU
CU
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.
Page 1
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.
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:
(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.
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:
Page 2
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 .
CPU Main
Memory
Cache
memory
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,
Page 3
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 or
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.
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:
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.Explain the need of type conversion and typecasting in any expression by giving suitable example and also
tell the difference between both with example.
Ans: Converting one data type into another is known as type casting or, type-conversion. For example, if you want to
store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from one type
to another explicitly using the cast operator as follows –
(type_name) expression
Page 4
Consider the following example where the cast operator causes the division of one integer variable by another to be
performed as a floating-point operation –
#include <stdio.h>
main() {
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
}
When the above code is compiled and executed, it produces the following result −
Value of mean : 3.400000
Here, It should be noted here that the cast operator has precedence over division, so the value of sum is first converted
to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly
through the use of the cast operator. It is considered good programming practice to use the cast operator whenever
type conversions are necessary.
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either
to int or unsigned int. Consider an example of adding a character with an integer −
#include <stdio.h>
void main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following result −
Value of sum : 116
Here, the value of sum is 116 because the compiler is doing integer promotion and converting the value of 'c' to ASCII
before performing the actual addition operation.
3. int a = 5; 3. int a = 5;
int b = 25.5;
int c = a + b int b = 25.5;
Page 5
5.Differentiate between the following:
(a)Difficult to use;>It is difficult to understand and develop a program using machine language.
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.
are also known as terminal symbols. These symbols are always the first and last symbol in the flowchart .
2.Arrow;
Page 6
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.
are represented using parallelogram and are used to get Input from users or display results to them
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.
Page 7
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 -
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 operators to be used in expressions .These operators 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.
Logical Operators:-C language supports three logical operators logical AND(&&), 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
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 (||)
Page 8
A B A||b
0 0 0
0 1 0
1 0 0
1 1 1
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
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
Page 9
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 ;
Operator Precedence : It determines the priority of operators when more than one operators are present in an
expression. Hence, it gives the order in which operators should be evaluated.
Operator Associativity : It determines the direction of evaluation of expression when there are operators of same
precedence present in an expression. It is either left to right or right to left.
X = 12*3+5-9%2/4
Applying the rules of precedence and associativity, this expression can be written as :
X = ( (12*3) + 5 – ( ( 9%2 ) / 4) )
Hence X = 41 after evaluation.
#include <stdio.h>
int main() {
double n1, n2, n3;
printf("Enter three numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
// outer if statement
if (n1 >= n2) {
// inner if...else
if (n1 >= n3)
printf("%.2lf is the largest number.", n1);
else
printf("%.2lf is the largest number.", n3);
}
// outer else statement
else {
// inner if...else
if (n2 >= n3)
printf("%.2lf is the largest number.", n2);
else
printf("%.2lf is the largest number.", n3);
}
return 0; }
Ans.Storage class->A storage class is one, which provides the following four information 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
Page 10
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
Automatic Local to the till the control remains within the block in which Garbage Main
block in which defined memory
defined
Static Local to the value of variable persists between different function Zero Main
block in which calls memory
defined
Register Local to the till the control remains within the block in which Garbage CPU
block in which defined register
defined
UNIT-3
1.Explain all conditional statements and program loop with help of syntax, flowchart and an example, available
in C programming.
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 11
Example:
void main()
{
if(printf(“hello”);
}
2 if –else:
Syntax:
if(condition)
{
Statement block x;
}
else
{
Statement block y;
}
Statement z;
Flow chart:
Page 12
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.
Examle Write a program in C to input any character and check whether it is uppercase or lower case or any
digit or any special character and also draw a flowchart.
Answer-
#include <stdio.h>
int main() {
char ch; /* Input character from user */
printf("Enter any character: ");
scanf("%c", &ch);
Page 13
if(ch >= 'A' && ch <= 'Z') {
printf("'%c' is uppercase alphabet.", ch); }
else if(ch >= 'a' && ch <= 'z') {
printf("'%c' is lowercase alphabet.", ch); }
else if(ch >= '0' && ch <= '9') {
printf("'%c' is a digit.", ch); }
else {
printf("'%c' is a Special symbol.", ch); }
return 0; }
Output-Enter any character a
a is lowercase alphabet
b)Define switch case and describe limitations for using it in a program. Write a program in C to perform basic
function of calculator using switch case.
switch statement: switch statement takes a variable of type integer or character and matches it against constant values.
If the match is found, statement block corresponding to that matched case is executed
Syntax of switch case:
switch(variable) {
case constant_1: statement block 1
break;
case constant_2: statement block 2
break;
……..
…….
…….
case constant _n:
statement block n
break;
default: default statement block
}
Limitations of switch statements:
• float constant cannot be used in the switch as well as in the case.
• You cannot use the variable expression in case.
• You cannot use the same constant in two different cases.
• We cannot use the relational expression in case
Page 14
break; case '/':
result = a/b;
break; case '%':
result = a%b;
break;
default:
printf("Invalid operator");
flag = 0;
}
if(flag==1)
printf("The result of operation is %d", result);
getch();
return 0;
}
LOOP-
There are three types of loop in C:
1. for loop
2. while loop
3. do-while loop
For loop:
Flow chart:
Initialization of variable
Test FALSE
expression
ondition
Page 15
TRUE
Statement block
Statement y
Example: WAP of print the sum of 1st 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
Page 16
TRUE
Statement block
Statement y
Do –While():
Syntax:
Initialization;
do
{
Statement block;
Update statement;
}while(test expression);
Flow chart :
Page 17
Example 2: Write a program to print the sum of 1st 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);
}
2.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);
}
3.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;
Page 18
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”);
}
}
4.Write a program in C to check whether a given number is prime or not.
#include<stdio.h>
void main()
{
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”);
}
}
5.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)
{
Page 19
return 0;
}
else
if(k==2)
{
return 1;
}
else
{
return (fibo(k-1)+fibo(k-2));
}
}
6.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(“ ”);
}
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;
}
Page 20
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”);
}
}
7.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.
Page 21
syntax: continue;
Continue cannot be used with switch, like break.
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 : 1 2
21
31
32
8. Explain in detail about 1-dimensional, 2-dimensional and multi-dimensional array declaration, accessing
elements, initialization with suitable examples
1-Dimensional Array- An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the primitive type of data such
as int, char, double, float, etc.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't
grow the size dynamically like Linked List.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Now, let us see the example to declare the array. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array (compile time)
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Page 22
Example -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]); //Runtime Initialization of array
}
max=a[0];
for(i=1;i<n;i++)
{
if(max<a[i])
{
max=a[i];
}
}
printf(“%d is the largest element”,max);
}
2-Dimensional Array-
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be
represented as the collection of rows and columns.
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array in C
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
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++)
{
Page 23
for(j=0;j<c1;j++)
{
scanf(“%d”, &a[i][j]);
}
}
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();
}
Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general form of a multidimensional array
declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];
We can initialize a three-dimensional array in a similar way to a two-dimensional array. Here's an example,
int test[2][3][4] = {{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Three-dimensional array
// C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
Page 24
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
9.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 ”);
Page 25
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”);
printf(“%d”,b1[i].price);
}
}
10. 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
Page 26
Component values of union are x=5,y=5
As union members are sharing same memory location so latest initialisation of member will get memory.
UNIT-4
1. 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);
getch();
}
Page 27
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”);
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();
}
#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”);
Page 28
getch();
}
3.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.
4. What is the difference between call by value and call by reference? Explain with programming
example.
Or
Page 29
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.
#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
}
It means sending 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
}
Page 30
}
UNIT-5
1.What are pointers? Why are they required? How do you declare and initialize them?
Also explain applications of pointer.
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; 1200 x
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()
{
int x=10;
int *ptr;
ptr=&x;
printf(“\n value of x=%d\n”,*ptr);
}
Output-> value of x =10
Application of pointers:
1. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to
memory location.
2. Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well. Hence
it can be said the Memory of pointers is dynamically allocated.
3. Pointers are used with data structures. They are useful for representing two-dimensional and multi-
dimensional arrays.
4. An array, of any type, can be accessed with the help of pointers, without considering its subscript range.
5. Pointers are used for file handling.
6. Pointers are used to allocate memory dynamically..
Drawbacks of Pointers:
1. If pointers are pointed to some incorrect location then it may end up reading a wrong value.
2. Erroneous input always leads to an erroneous output
Page 31
3. Segmentation fault can occur due to uninitialized pointer.
4. Pointers are slower than normal variable
5. It requires one additional dereferences step
6. If we forgot to deallocate a memory then it will lead to a memory leak.
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.
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent
storage of data. It is a readymade structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
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
Page 32
fscanf() This is used to read fscanf(fptr,”%d”,&a);
formatted data from the
file.
fgetc() This function returns fgetc(fptr);
the next character from
stream, and EOF if the
end of the file is
reached
fgets() The function fgets()
stands for file get fgets(str,80,fptr)
string. This function is where char str[80];
used to get a string
from a file.
fprintf() This is used to write fprintf(fptr,”%d”,a);
formatted data to the
file.
fputc() This function is just fputc(ch,fptr);
opposite of fgetc() and where char ch;
is used to 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];
Page 33
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\n Contents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
5. 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.
Page 34
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);
}
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;
Page 35
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);
}
6.Explain the concept of dynamic memory allocation in C and its pre define functionwith suitable
example.
C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is
changed during the runtime.C provides some functions to achieve these tasks. There are 4 library functions provided
by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory
with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t
initialize memory at execution time so that it has initialized each block with the default garbage value initially.
Syntax: ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address
of the first byte in the allocated memory. If space is insufficient, allocation fails and returns a NULL pointer.
C calloc() method
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of
memory of the specified type. it is very much similar to malloc() but has two different points and these are:It
initializes each block with a default value ‘0’. It has two parameters or arguments as compare to malloc().
Syntax: ptr = (cast-type*)calloc(n, element-size);
Here, n is the no. of elements and element-size is the size of each element.
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the float. If space is
insufficient, allocation fails and returns a NULL pointer.
C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc()
and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory
allocation takes place. It helps to reduce wastage of memory by freeing it.
Syntax: free(ptr);
C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously
allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient,
realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value
and new blocks will be initialized with the default garbage value.
Syntax: ptr = realloc(ptr, newSize);
Page 36
where ptr is reallocated with new size 'newSize'.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
Page 37
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Page 38
2. Circular Linked List:
Circular linked list is a singly linked list in which the pointer field of the last node contains the address
of the first node.
It does not contain NULL pointer like singly linked list.
We can traverse only in one direction that is forward direction.
It has the biggest advantage of time saving when we want to go from last node to first node, it directly
points to first node.
Page 39
Circular doubly linked list is like a doubly linked list where the previous pointer fields of the first node contains
the address of last node and the next pointer field of the last node contains an address of first node.
Page 40