PSP July2019 QP Solution
PSP July2019 QP Solution
Ans:
Input unit: The input unit that links the external environment to input data & tasks with the computer
system to execute. Data are entered in different forms through different input devices. Keyboard is
used for characters input. Mouse is used in GUI (Graphic User Interface). Internally data is processed in
machine readable form.
Output Unit: Output/result is displayed, printed & transmitted to outside world. There are many
output devices: monitor, printer/plotters, display boards, speaker etc.
Storage unit: The data and instructions that are entered into the computer system through input units
have to be stored inside the computer before the actual processing starts. Similarly, the results
produced by the computer after processing must also be kept somewhere inside the computer system
before being passed on to the output units. The storage unit is Primary Memory (RAM) & Secondary
(permanent storage devices: disks, tapes)
CPU (Central processing Unit): It is the main unit which controls all events within computer. The CPU
has 3 internal units: CU, ALU & Registers:
CU(Control unit): By selecting, interpreting, and seeing to the execution of the program instructions,
the control unit is able to maintain order and directs the operation of the entire system. the control
unit acts as a central nervous system for the other components of the computer. It manages and
coordinates the entire computer system. It obtains instructions from the program stored in main
memory, interprets the instructions, and issues signals that cause other units of the system to execute
them.
ALU (Arithmatic & Logic Unit): The arithmetic and logic unit (ALU) is the part where actual
computations take place. It consists of circuits that perform arithmetic operations (e.g. addition,
subtraction, multiplication, division over data received from memory and capable to compare numbers
(less than, equal to, or greater than).
MU (Memory Unit/Registers): Registers are built-in memory with CPU having less storage space in bits.
Registers are a group of cells used for memory addressing, data manipulation and processing.
Instruction Registers, Address registers, Program Counters, Accumulators are example of registers. ALU
takes data from here inside the CPU.
RAM(Random Access Memory): RAM is the memory - primary storage where our data & programs are
stored temporarily. It is volatile in nature. After switching off the system everything will be vanished
from RAM.
ROM(Read Only Memory): ROM is storage medium/”firmware” where some code of manufacturer is
permanently hardwired in chip which always executes automatically when we start the system. The
process is known as POST(Power on Self test). Booting preceeds POST.
Ans:
1c. Define the terms Network, LAN, WAN, MAN and Network Topology 5M
Ans:
Network: Collection of devices/computers connected together is called a Network.
LAN(Local Area Network): A group of computers & devices connected together, usually within the same
building or in same campus is LAN.
MAN(Metropolitan Area Network): MAN is a larger network that usually spans several buildings in the
same city or town. The Dish TV network is an example of a MAN.
WAN(Wide Area Network): A WAN (wide area network), in comparison to a MAN, is not restricted to a
geographical location, although it might be confined within the bounds of a state or country. A WAN
connects several LANs, and may be limited to an enterprise (a corporation or an organization) or
accessible to the public. The technology is high speed and relatively expensive.
Network Topology: Network topology is topological structure of a network where nodes may be
connected in different ways. Examples of Network Topologies are : Bus Topology, Ring Topology, Star
Topology & Mesh topology.
2a. Write the basic structure of a C Program. Explain each section briefly with suitable examples. 9M
Ans:
Structure of a C program
• Documentation Section: This section is used to write Problem, file name, developer, date etc in comment lines within
/*….*/ or separate line comments may start with // . Compiler ignores this section. Documentation enhances the
readability of a program.
• Link section : To include header and library files whose in-built functions are to be used. Linker also required these files
to build a program executable. Files are included with directive # include
• Definition section: To define macros and symbolic constants by preprocessor directive #define
• Global section: to declare global variables – to be accessed by all functions
• main() is the user defined function which is recognized by the compiler first. So, all C program must have user defined
function main() { ............ }. It should have declaration part first then executable part.
• Sub program section: There may be other user defined functions to perform specific task when called.
2c. State whether following are valid identifiers or not: integer, float. I am,
123_AbC
Ans:
A valid identifier may contain a-z, A-Z, 0-9 & _ (underscore). It must not start with a digit and it should
nt be a keyword.
integer: Valid
float: In-valid (It is a keyword)
I am Invalid(contains space/blank)
123_AbC Invalid(starts with a digit)
3a. Define and write classification of input and output statements in C. Write a Program that prints the
following output:
“ I am
an” ‘Engineering
Student’ 6M
Ans:
Input Statements of C Output Statements of C
Formatted Input stmts Unformatted Input stmts Formatted Output stmts Unformatted Output stmts
scanf( ) gets( ) printf( ) puts( )
fscanf( ) getchar( ) fprintf( ) putchar( )
sscanf( ) fgetc( ) sprint( ) fputc( )
Formatted input/output statements provides certain features that can be effectively exploited to control the
alignment, spacing & width specification.
Unformatted input/output statements are limited with their built-in features only.
Formatted Input statements:
scanf(): to read values from keyboard (by default) as formatted input:
Syntax:
scanf (“control string”, &arg1, &arg2, ......... , &argn);
The control string specifies the field format in which the data is to be entered and the arguments
arg1,arg2 .... ,argn specify the address of locations where the data is stored. Actually arguments are pointers which
indicate where the data items are stored in computer’s memory.
Control string contains field specification which direct the interpretation of input data. It may include:
o Field (or format) specification, consisting of the conversion character %, a data type character
(or type specifier, and an optional number, specifying the width (Maximum width
Specification).
o Blanks, tabs, or new lines.
o The arguments are written as variables or arrays, whose type match the corresponding
character groups in the control string. Each variable name must be preceded by an ampersand
(&). Array names should not begin with an ampersand.
Examples:
scanf(“ %d%s%d”, &roll, name, &marks);
scanf(“%2d%2d%2d”,&marks1, &marks2, &marks3); /* only 2 digits will be scanned */
fscanf( ) : Fromatted data from files/standard input, one more argument for file pointer/standard input
fscanf (fp, “control string”, &arg1, &arg2, ......... , &argn);
sscanf( ) : Formatted data from a string, one more argument as pointer to string
fscanf (char *ptr, “control string”, &arg1, &arg2,.......... , &argn);
Q 3c.
Evaluate:i=1;
L: if(i>2)
{
printf(“Saturday”);
i=i+1;
goto L;
}
printf(“Sunday”);
Explain your result briefly. 4M
Ans:
It will print Sunday.
L is a label followed by a colon for goto statement.
i=1; so if(i>2) is false & it will not go inside of if statement
Finally it will print Sunday (which is followed by if statement)
Q 4a. State the drawback of ladder if-else. Explain how do you resolve with suitable example. 8M
Ans:
if any of the condition1, condition2 & condition3 is evaluated true then corresponding statements are
executed and the control comes out entire of the ladder if-else statement. If all conditions are false
then last statement will be executed.
/* Example of switch */
#include <stdio.h>
int main()
{
int salary,bonus;
char grade:
printf(“Enter grade : “);
scanf(“%c”, &grade);
printf(“Enter salary : “);
scanf(“%d”, &salary);
switch (grade)
{
case ‘a’:
case ‘A’: bonus=salary;
break;
case ‘b’:
case ‘B’:
case ‘c’:
case ‘C’: bonus=salary+5000;
break;
case ‘d’:
case ‘D’: bonus=salary+10000;
break;
default : bonus=salary+15000; /*lower grade-more bonus*/
}
print(“Bonus = %d\n”, bonus);
return (0);
}
return (0);
}
Expected O/p:
Enter a number (>1) : 17
Yes, 17 is a prime number.
Q 5a. Define an array. Explain with suitable example how do you declare & initialize 1D array.
10 M
Ans:
An array is an identifier that refers to the collection of data items which all have the same name. The
individual data items are represented by their corresponding array elements. Address of an element
(subscript) ranges from 0 to n-1, where n is total number of elements.
Q 5b. Write a C program to search an element using linear & binary techniques. 10 M
Ans:
int main()
{
int a[1000],x, y,temp,N, first, last, mid, skey, found;
printf("Enter number of elements : ");
scanf("%d", &N);
for(x=0;x<N;x++)
{
printf("Enter element %d : ", x+1);
scanf("%d",&a[x]);
}
printf("\nEnter search key integer for linear search : ");
scanf("%d",&skey);
for(x=0;x<N;x++)
if(a[x] == skey)
printf("Found at %dth Position\n",x+1);
return (0);
}
Expected Ouput:
Q 6a. Define a string. Explain any 4 string library functions with syntax & example. (10 marks)
Ans:
A string is array of characters terminated with NULL ‘\0’ character.
When a string is entered by default one NULL character is added at the end.
String declaration and initialization:
Declaration:
char str[size];
example:
char str[50];
Initialization
char name[ ]=’SINGH’;
char name[5]={‘S’,’I’,’N’,’G’,H’,’\0’};
Q 6b. Write a C program to copy a string (combination of digits & alphabets) to another string (only alphabet)
10 M
Ans:
/* copy string only alphabets (not numbers) */
#include <stdio.h>
int main()
{
char str1[50], str2[50];
int x,y;
printf("Enter alphanumeric string : ");
gets(str1);
y=0;
for(x=0;str1[x]!=NULL;x++)
if( !(str1[x]>='0' && str1[x] <= '9')) /* non-numeric */
{
str2[y]=str1[x];
y++;
}
str2[y]=NULL; /* last character of copied string */
printf("Copied string(only alphabets) %s\n",str2);
return (0);
}
Expected O/P 1:
Enter alphanumeric string : Pay me 465 rupees
Copied string(only alphabets) Pay me rupees
Expected O/P 2:
Enter alphanumeric string : 1CR18CS001
Copied string(only alphabets) CRCS
Q 7a. Define a function. List & explain the categories of user defined functions. 10 M
Ans:
return (hra);
}
Q 7b. Write a C program evaluating the Binomial coefficient using a function Factorial(n). 10 M
Ans:
/* Binomial coefficient using factorial */
#include<stdio.h>
int main()
{
int n,r;
printf("Enter n and k : ");
scanf("%d%d",&n,&r);
printf("Binomial coefficient of %d & %d = %ld\n",
n,r,fact(n)/(fact(r)*fact(n-r)));
return 0;
}
Output:
Enter n & k : 8 4
Binomial coefficient of 8 & 4 = 70
Q 8a. Define a recursion. Write a C recursive function for multiplying two integers where a function call
ispassed with two integers m &n. 10 M
Ans:
Recursion is a process where a function calls itself directly or indirectly. The simplest example of
recursion is finding factorial of a number. The corresponding function is called as recursive function.
factorial of n = n * factorial of (n-1)
Using recursive algorithm, certain problems can be solved quite easily.
int main()
{
int m,n;
printf("Enter value of m & n : ");
scanf("%d%d",&m,&n);
printf("%d",multiply(m,n));
return (0);
}
Q 8b. Differentiate (i) user defined & built in function (ii) Recursion & iteration 10 M
Ans:
A function is a method to perform a given task. Functions are of 2 types: built-in function (library
function) & user defined function
A recursive function must comprise of at There are loops with a control variable that
least one base case i.e. a condition need to be initialized, incremented or
for termination of execution. decremented and a conditional control
statement that continuously gets checked for
the termination of execution.
The function keeps on converging to the The value of the control variable
defined base case as it continuously calls continuously approaches the value in
itself. the conditional statement.
Stack memory is used to store the current A control variable stores the value, which is
state of the function. then updated, monitored, and compared with
the conditional statement.
If there is no base case defined, recursion Infinite loops keep utilizing CPU cycles until we
causes a stack overflow error. stop their execution manually.
The execution of recursion is The execution of iteration is
comparatively slower. comparatively faster.
A statement in the function’s body calls the Allows the execution of a sequential set of
function itself. statements repetitively using conditional loops.
A recursive function must comprise of at There are loops with a control variablethat
least one base case i.e. a condition need to be initialized, incremented or
for termination of execution. decremented and a conditional control
statement that continuously gets checked for
the termination of execution.
long int factorial(int n) /* A recursive /* A program using loop to for factorial */
function to find factorial*/ int main()
{ {
If(n==0 || n==1) long int fact = 1;
return (1); int x, n;
else printf(“Enter number : “);
return (n*factorial(n-1)) scanf(“%d”, n);
} for(x=n;x>1;x--)
fact=fact*x;
printf(“Factorial = %ld\n”, fact);
return (0);
}
Q 9a. Define structures. Explain how do you declare, initialize & represent the memory for structure variable.
10 M
Ans:
Structure is a data structure whose individual elements can differ in type. It may contain integer elements,
character elements, pointers, arrays and even other structures can also be included as elements within a
structure. struct is keyword to define a structure.
Syntax:
struct tag
{
type member1;
type member2;
type member3;
......;
type member n;
};
Expected Output:
size of s1=24
Address of s1=980
Address of roll=980, Size of roll=2 bytes
Address of name=982, Size of name=20 bytes
Address of marks=1002, Size of marks=2 bytes
Q 9b. Write a C program that accepts a structure variable as a parameter to a function from a function call. 10
MAns:
Structure variable can be passed as copy of the structure or address of the structure variable. If address is
passed then called function may corrupt/modify the value of members of the structure.
/* program to structure variable as argument */
#include <stdio.h>
struct student
{
int roll;
char name[20];
int marks;
}s1={111,"paras",76};
int main()
{
struct student *sp;
sp=&s1;
printf("roll = %d name = %s marks= %d\n",s1.roll,s1.name,s1.marks);
displaystruct(s1);
printf("roll = %d name = %s marks= %d\n",s1.roll,s1.name,s1.marks);
printstruct(sp); /* passing address */
printf("roll = %d name = %s marks= %d\n",s1.roll,s1.name,s1.marks);
return (0);
}
Output:
roll = 111 name = paras marks= 76
roll = 111 name = paras marks= 76
roll = 111 name = paras marks= 76
roll = 111 name = paras marks= 76
roll = 111 name = paras marks= 95
Q 10a. Define Pointers. Explain pass by value and pass by reference with C statements and an example. 10 M
Ans:
A pointer keeps address of data. A pointer is variable that represents the location ( rather than the value) of a
data item, such as a variable or an array element.
Pointers is an important feature of C and frequently used in C. They have a number of useful applications.
Pointer operator is asterisk ( * ).
To declare a pointer: datatype *pointervariable;
To initialize: pointervariable = &data;
& is address of operator.
Example1:
int n;
int *p; /* here p is pointer variable & can be used to keep address */
p=&n; /* here p keeps address of n */
Example2:
int a[5] = { 10,20.30,40,50};
int *p;
p = a; /* It is equivalent to p = &a[0]; Here it keeps address of first element */
Pass by value: A function is called passing value. Value of the variable of the calling function will not change
Pass by reference: A function is called passing reference (address of a variable) and received as pointer. The
value of the variables of the calling function may be changed by the called function.
/*Pass by value – Function is called by passing value. It will not effect the value of calling function */
int area( int l, int w) { return (l*w);
int main()
{
int len, wid;
printf(“Enter length and width of rectangle : “);
scanf(“%d%d”,&len,&wid);
printf(“Area of rectangle = %d square unit\n”, area(len,wid));
return (0);
}
/*Pass by reference When a function is called by passing address then called function may change value of
the variable because it receives address. Thus value of the variable of calling function will change also */
Q 10b. Define Pre-processor directives. Write C program that finds addition of two squared by defining macro
forSquare(x). 10 M
Ans:
A pre-processor represents pre-compilation process. These directives are preceded with # ( and there is no
semicolon at the end).
C has the special feature of pre-processor directives. The pre-processor processes the C source code before it
passes to the compiler. Pre-processor directives are executed before the C source code passes through the
compiler.
Pre-processor directives can be categorized in 2 groups:
• General Directives : These are written in header section of the program and there will not be control of
compiler over it. They are processed before compilation of program starts.
Examples: #include, #define, #undef, #pragma
• Compiler control directives: These are conditional directives and may be written within program also. For
example whether a macro is defined or not we can check it within program and redefine (general directives
also) if required. Mostly #if family directives are of this category.
Examples: #if, #endif, #else, #ifdef, #ifndef
int main()
{
int a,b,sumsq;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
sumsq=Square(a)+Square(b);
printf("Sum of squares = %d\n",sumsq);
return (0);
}
Output:
Enter two numbers : 5 7
Sum of squares = 74