Sol-Model Answer-VTU Exam-Aug 2022
Sol-Model Answer-VTU Exam-Aug 2022
Model Answer
Dr. P. N. Singh, Professor(CSE), President, ICT-CS, Indian Science Congress 2021-23
Module 1:
1.
a. Discuss various generations computers, high lighting features of each one. (10
Marks)
Solution:
b. Write the basic structure of a C program and explain with an example. (10
Marks)
Solution:
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.
/* Example: a program to find area of a circle – area.c
- Documentation Section*/
#include <stdio.h> /* - Link/Header Section */
#define PI 3.14 /* definition/global section*/
int main() /* main function section */
{
float r, area; /* declaration part */
printf(“Enter radius of the circle : “); /* Execution part*/
scanf(“%f”, &r);
area=PI*r*r; /* using symbolic constant PI */
printf(“Area of circle = %0.3f square unit\n”, area);
return (0);
}
2.
a. Differentiate primary memory and secondary memory. (5 Marks)
Solution:
⚫ Primary memory is also called internal memory whereas Secondary memory is
also known as a Backup memory or Auxiliary memory.
⚫ Primary memory data is directly accessed by the processing unit
whereas Secondary memory data cannot be accessed directly by the processor
b. List and explain logical operators and analyze the following code and write the
output with proper reasoning
#include <stdio.h>
void main()
{
printf( "7 && 0 = %d\n", 7 && 0);
printf("7 || 0 = %d\n", 7 || 0);
printf("!0 = %d\n", !0);
} [10 Marks]
Solution:
Logical operators of C :
&& (AND where both of the conditions must be satisfied to give output 1 (true))
|| (OR where either of the condition should be satisfied to give output true(1))
! (NOT – Negation of true is false and vice-versa)
Solution:
Programmers can use these data types when creating variables in their
programs. For example, a programmer may create a variable called marks and
define it as a int data type type.
Examples:
int marks;
double num = 0.00;
char c;
float sum;
Module 2:
3.
a. Write a C Program to find roots of a quadratic equation. (10 marks)
Solution:
/* C program to find roots of a quadratic equation */
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, d, r1, r2, real, imag;
printf("\nEnter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
d = b*b-4*a*c; /* discriminant */
if (d == 0)
{
r1 = r2 = -b/(2*a);
printf("Roots are real : root1 = root2 = %.2lf;", r1);
}
else
if (d > 0)
{
r1 = (-b+sqrt(d))/(2*a);
r2 = (-b-sqrt(d))/(2*a);
printf("Roots are distinct: root1 = .2lf root2 = %.2lf\n",r1, r2);
}
else
{
real = -b/(2*a);
imag = sqrt(-d)/(2*a);
printf("Roots are imaginary:\n");
printf("root1 = %.2lf+%.2lfi and root2 = %.2lf-%.2lfi", real, imag, real,
imag);
}
return (0);
}
Expected Output:
Enter coefficients a, b and c:
Enter coefficients a, b and c: 2 4 2
Roots are real : root1 = root2 = -1.00;
b. Write syntax of switch statement and explain with suitable examples (10
Marks)
Solution:
switch statement:
C has a built-in multiway decision statement known as a switch. It tests the value of
a given variable (or expression) against a list of case values and when a match is
found, a block of statements associated with the case is executed. The break
statement at the end of each block signals the end of a particular case and causes
an exit from the switch statement, transferring the control to the next statement
following the switch ( where branch ends with } ). The default is an optional case.
When present, it will be executed if the value of the expression does not match with
any of the case values.
switch statement syntax:
switch (expression)
{
case condition1 :
statement1;
statement2;
......
break;
case condition2 :
statement1;
statement2;
.......
break;
.....
default:
statement1;
statement2;
.......
}
/* 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’: bonus=salary+5000;
break;
default : bonus=salary+10000; /*lower grade-more bonus*/
}
print(“Bonus = %d\n”, bonus);
return (0);
}
4.
a. Write the syntax of while and do while statements. Also list differences
between them with example. [6 Marks]
Solution:
Solution:
Solution:
break statement would only exit from the loop containing it. The inner most loop
containing the break will only be terminated. With switch statement the break
comes out from the switch and does not check other cases.
Module 3:
5.
a. Define arrays and discuss various ways of initializing 1-D array with examples.
(10 Marks)
Solution:
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.
Examples:
float height[50];
int batch[10];
char name[20];
b. Write a C program to sort given integers in ascending order using selection sort
and trace by taking 5 integers. (10 Marks)
Solution:
Logic: selecting minimum in each pass and replacing with its correct postion.
#include <stdio.h>
int main()
{
int a[1000], n, i, j, pos, temp;
printf("Enter number of elements : ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter element %d : ", i);
scanf("%d", &a[i]);
}
/* Now sorting */
for(i = 0; i < n - 1; i++) {
pos=i;
for(j = i + 1; j < n; j++)
if(a[j] < a[pos]) pos=j; /* finding pos of next minimum */
if(pos != i) { temp=a[i]; a[i]=a[pos]; a[pos]=temp; }
}
printf("Sorted Array:\n");
for(i = 0; i < n; i++)
printf(" %d", a[i]);
return (0);
}
Expected output:
Enter number of elements: 5
Enter element 1: 22
Enter element 2: 3
Enter element 3: 44
Enter element 4: 5
Enter element 5: 13
Sorted Array:
3 5 13 22 44
6.
a. Define strings and explain how they are declared and initialized. (6 Marks)
Solution:
Example:
char name[30];
To Initialize:
By Individual characters:
or without restricting the size so last character will be NULL by the compiler.
char name[]=”Paras”;
or using pointer
char *name=”Paras”;
Here both the above initializations are correct but arrays are not pointers.
b. Write a C program to search for a given number in an array using Binary Search
technique. (8Marks)
Solution:
/* Binary search in given array of N elements */
#include <stdio.h>
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]);
}
/* now sorting - because Binary search requires sorted elements */
for(x=0;x<N;x++)
for(y=0;y<N-x-1;y++)
if(a[y] > a[y+1])
{
temp=a[y];
a[y]=a[y+1];
a[y+1]=temp;
}
printf("The sorted array:\n");
for(x=0;x<N;x++)
printf(" %d",a[x]);
printf("\nEnter search key integer : ");
scanf("%d",&skey);
first=0;
last=N-1;
found=0;
while(first <= last && ! found)
{
mid=(first+last)/2; /* integer value of mid */
if(a[mid] > skey)
last=mid-1;
else if (a[mid] < skey)
first=mid+1;
else
found=1;
}
if(found)
printf("Found at %dth position\n",mid+1);
else
printf("Not found\n");
return (0);
}
Expected Ouput:
Enter number of elements : 11
Enter element 1 : 22
Enter element 2 : 3
Enter element 3 : 44
Enter element 4 : 5
Enter element 5 : 66
Enter element 6 : 7
Enter element 7 : 88
Enter element 8 : 9
Enter element 9 : 111
Enter element 10 : 23
Enter element 11 : 54
The sorted array:
3 5 7 9 22 23 44 54 66 88 111
Enter search key integer : 88
Found at 10th position
Solution:
String manipulating Functions: (Header file: string.h)
Now explaining:
i. strlen (str) – returns Length of string
Example:
printf(“%d”, (“Dr. Singh”));
Output: 9
Module 4:
7.
a. What is user defined function? Discuss different categories of user defined
functions with appropriate example for each. (10 Marks)
Solution:
Function prototyping : Formal declaration of a function with data type like variables,
arrays prior to its use is known as function prototyping. Without it most of the
compilers displays an error message “abcd function should have a prototype.” Called
function should receive the same data type as declared.
In the called function arguments are received as parameters declaring their type:
int mul( int a, int b)
{
......
}
or int mul(a,b)
int a,b; /* T & R classical style */
{ ...... }
Solution:
Solution:
In C there are 4 storage class specifiers:
i. auto (Automatic variables) :
Scope is local to the function only in which they are defined. All the variables defined
within the function are by default of auto storage class.
ii. extern (External variables) Scope is global to all the functions
Variables defined outside of the function are by default of extern storage class.
iii. register : (Register variables) : Registers are special storage area within a
computer’s central processing unit (In-built memory with CPU). The actual
arithmetic and logical operations that comprise a program are carried out within this
registers. The execution time can be reduced considerably if certain values can be
stored within these registers rather than in computer’s memory.
The register variables are local to the function in which they are declared. The
address of operator cannot ‘&’ cannot be applied to register variables.
register int x, y, z;
static (Static variable): Static variables have the same scope as automatic variables,
i.e. they are local to the functions in which they are defined. Unlike automatic
variables, however, static variables retain their values throughout the life of the
program. As a result, if a function is called again, the static variables defined in the
called function will retain their former values (They will not be reinitialized again.
They are confined at the first initialization).
#include <stdio.h>
int func()
{
static int k = 0; /* by default also zero */
k++;
return (k);
}
int main()
{
int x, sum=0;
for(x=1;x<=5;x++)
sum+=func();
print(“sum = %d\n”, sum);
return (0);
}
8.
a. Define recursion. Write a recursive program to find n th Fibonacci number. (08
Marks)
Solution:
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.
/* Fibonacci series up to nth terms using recursion */
#include <stdio.h>
int fibo(int n)
{
if (n==1)
return (0);
if (n==2)
return (1);
else
return (fibo(n-1)+fibo(n-2));
}
int main()
{
int n;
printf("Enter nth term for Fibonacci series : ");
scanf("%d",&n);
printf(" %dth Fibonacci number is %d\n",fibo(n));
return (0);
}
Output:
Enter nth term for Fibonacci series : 10
The 10th Fibonacci number is 34
Solution:
Solution:
A large program can be divided into smaller meaningful segments. These segments
are known as modules, sub-modules, routines. Sub-routines, methods. User defined
functions are building blocks of a program. Advantages of writing user defined
functions are:
Module 5:
9.
a. Differentiate structures and unions with syntax and examples. (6 Marks)
Solution:
The important difference between structures and unions is that in structures each
member has it's separate memory locations but for union is declared the compiler
allocates only one memory sufficient to hold the largest member of the union.
Members of the union can be accessed one by one only and only one value will be
there.
Syntax of structure:
struct tagname {
data_type member1;
data_type member2;
data_type member3;
……..
data_type membern;
}
Example:
struct student { int roll; char name[20]; int marks; };
Memory is allocated separately for each member:
union tagname {
data_type member1;
data_type member2;
data_type member3;
……..
data_type membern;
}
And one by one we can access. Only last data in memory will be available.
union student s1 = {56};
Here firsr member of the union i.e. s1.roll is initialized. We can use it and then we
can access others one by one.
b. Write a C program to swap 2 numbers and use the same to explain advantage
of call by reference over call by value.
Solution:
/* C Program to swap two numbers – Call by reference */
#include <stdio.h>
Solution:
ii) #define
#define directive is used to define the symbolic constant or macro name with macro
expression.
#define symconstant value
#define macroname macroexpression
Example
#define PI 3.141
Here the C pre-processor searches for the symbolic constant PI the source code and
substitutes 3.141 each time it is encountered.
iii) #ifdef
#ifdef preprocessor directives checks whether a macro is defined by #define. If yes,
it executes the code:
Example:
#ifdef PI
Printf(“PI symbolic constant is already defined\n”);
#endif
iv) #ifndef
#ifndef preprocessor directives checks whether a macro is not defined by #define. If
yes, it executes the code:
Example:
#ifndef PI
#define PI 3.14
#endif
v) #pragma
#pragma preprocessor directives schedules the execution of function before and
after main() function by clauses startup and exit:
Example:
#pragma startup func2
#pragma exit func1
Here func2() function will execute before main() function and func1() function will
execute after main() function. There is no need to call these function from main()
10.
a. Write a C program to add 2 complex numbers using structures. (6 Marks)
Solution:
result.real = 6.000
result.imag = 1.419
Solution:
return (0);
}
Expected output:
Enter Number 1 : 3
Enter Number 2 : 4
Enter Number 3 : 5
Enter Number 4 : 6
Enter Number 5 : 7
Sum = 25 Mean = 5.00 Standard Deviation = 1.58
Solution:
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 */
Pointer’s Arithmetic
Pointers variables can be added or subtracted (but can not be multiplied or divided)
int *p;
(p represents address and *p represents value stored at that address)
p=p+1;
p++;
++p; /* They add size of data according to type to address and not 1 */
Similarly p=p-1 or p-- or --p will subtract size of data and not 1
*p=*p+1; /* will add add 1 to value store on that location */
(*p)++; /* do */
*(p++) /* represents the current value and increment pointer to next address
adding size of data */