100% found this document useful (1 vote)
54 views27 pages

Sol-Model Answer-VTU Exam-Aug 2022

Uploaded by

reshma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
54 views27 pages

Sol-Model Answer-VTU Exam-Aug 2022

Uploaded by

reshma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

VTU-PSP-21PSP23-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)

Out of the given program Reason


7 && 0 = 0 with && both expressions are not 1 so, 0
7 || 0 = 1 with || one expression is true (7 i.e. 1) So, 1
!0 = 1 With ! negation of false is true so !0 is 1

c. Discuss basic data types supported in ‘C’. [5 Marks]

Solution:

A data type is a classification of data, which can store a specific type of


information.
Basic data types are primary, fundamental or predefined types of data, which are
supported by the programming language.
In C basic/fundamental/primitive data types with their sizes as per ANSI-C
standard:
Type Size
char 1 Byte
int 2 Bytes (Now 4 bytes)
float 4 bytes
double 8 Bytes

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:

 while is a pre-tested (entry-controlled) loop. Condition is checked before


entering in the loop.
 do-while is a post-tested (exit-controlled) loop. Condition is checked after
execution of the statements within the loop.
 The main difference is that do-while loop must execute once (because
condition is checked at the end.)

while statement syntax:


while (condition)
{
statement1;
statement2;
......
}
/*working example – to display squares of numbers from 1 to 20 */
#include <stdio.h>
int main()
{
int x;
x=1;
while(x<=20)
{
printf(“%d %d\n”, x, x*x);
x++;
}
return (0);
}
do…while statement syntax: (It is a post tested loop & must executes at least once)
do
{
statement1;
statement2;
......
} while (condition);

/*working example – to display squares of numbers from 1 to 20 */


#include <stdio.h>
int main()
{
int x;
x=1;
do
{
printf(“%d %d\n”, x, x*x); /* if x > 20 also it will print once */
x++;
}while(x<=20);
return (0);
}

b. Write a C program to print whether a given integer number is palindrome or


not. (7 Marks)

Solution:

/* To check number whether it is palindrome */


#include <stdio.h>
int main()
{
long int num,temp,rem,rev=0;
printf("Enter number : ");
scanf("%ld",&num);
temp=num;
while(temp!=0)
{
rem=temp%10;
rev=rev*10+rem;
temp/=10;
}
printf("Reverse of number is %ld\n",rev);
if(rev==num)
printf("Yes, %ld is palindrome\n",num);
else
printf("No, %ld is not palindrome\n",num);
return (0);
}

Expected output: (Test case 1)


Enter number: 12321
Reverse of number is 12321
Yes, 12321 is palindrome

Expected output: (Test case 2)


Enter number: 34034
Reverse of number is 43043
No, 43043 is not palindrome

c. Discuss break and continue statement with suitable examples. (7 Marks)

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.

//Example program to check a number whether it is prime


#include<stdio.h>
int main()
{
int n,d,prime=1;
printf(“Enter a number : “);
scanf(“%d”, &n);
for (d=2;d<n/2;d++)
{
if (n%d==0) {
prime=0;
break; /* there is no need to check further */
}
if (prime)
printf(“Yes %d is a prime number.\n”, n);
else
printf(“No, %d is not a prime number.\n”, n);
return (0);
}
continue statement
The continue statement is used in loops to skip the following statements in the loop
and to continue with the beginning of the iteration.

//Example program to enter marks (0-100) in 6 subjects for sum


#include<stdio.h>
int main()
{
int marks,sum=0, x;
for (x=1;x<=6;x++)
{
printf("Enter marks %d : ", x);
scanf(“%d”, &marks);
if(marks <0 || marks > 100)
{
printf("Invalid marks!!!\n"); x=x-1;
continue; /* again read marks for same paper */
}
sum+=marks;
}
printf("sum of marks = %d.\n", sum);
return (0);
}

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.

Declaration of one-dimensional array:


One dimensional array:
Syntax to declare 1D array:
type array_name[size];

Examples:
float height[50];
int batch[10];
char name[20];

Initialization of one-dimensional array:


Examples:
int marks[5] = {76,45,67,87,92};
static int count[ ] = {1,2,3,4,5};
static char name[5] = {‘S’, ‘I’, ‘N’, ‘G’, ‘H’, ‘\0’};
If an array is initialized with single element, all rest of the elements will be initialized
to zero.
int arr1[5] = { 0 }; /* Here first element is initialized with zero and rest of the
elements are initialized with 0. */
int arr1[5] = { 5 }; /* Here first element is initialized with 5 and rest of the elements
are initialized with 0. */

Individual elements of array can be initialized by its index (subscript).


arr1[3] = 20;
Loops can be used in a program to initialize array elements by values given by the
user.
int main() {
int a[5], int x;
for(x=0;x<5;x++) {
printf(“Enter element : “);
scanf(“%d”, &a[x]);
/* rest of the code */
return (0);
}

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

Tracing in each pass:


The array: 22 3 44 5 13
After 1st pass : 3 22 44 5 13
After 2nd pass: 3 5 44 22 13
After 3rd Pass: 3 5 13 22 44
After 4th pass: 3 5 13 22 44

6.
a. Define strings and explain how they are declared and initialized. (6 Marks)

Solution:

A string is array of characters terminated with a NULL (‘\0’) character.


Syntax to declare:
datatype str_name[size_numberof characters];

Example:
char name[30];
To Initialize:
By Individual characters:

char name[6] = {‘P’,’a’,’r’,’a’,’s’,’\0’};

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

c. Explain any 6 string manipulation functions with example. (6 Marks)

Solution:
String manipulating Functions: (Header file: string.h)

Now explaining:
i. strlen (str) – returns Length of string
Example:
printf(“%d”, (“Dr. Singh”));
Output: 9

ii. strcpy(strvar, strval); copies strval to strvar


Example:
char name[11];
strcpy(name, “Ritambhara”);
Ritambhara is copied to name

iii. strrev(str) : reverses the string in its place.


char name[] = “Paras”;
strrev(name);
printf(“Reveres of name = %s”, name);
Output:
saraP

iv. strcat(str1, str2) – Concatenates(appends) str2 to str1 at the end.


Syntax:
char* strcat (char* strg1, const char* strg2);
Example:
If two strings are:
char name[]=”Roma”;
char surname[]=”Ritambhara”;
Then to append “Ritambhara” with name “Roma”
strcat(name,surname);
printf(“%s”, name);
Output: Roma Ritambhara

v. strcmp( str1, str2) – Compares two string and returns:


0 if both strings are identical
else returns difference based on ASCII value of first mismatch.
Syntax:
int strcmp (const char* str1, const char* str2);
Example:
printf(“%d”, strcmp(“SINGH”, “SINHA”);
output: - 1

vi. strncat(destination, source, number_of_characters);


concatenates numbe of characters from beginning of source to destination.
#include <stdio.h>
#include <string.h>
int main() {
char *name = "Dr. Paras";
char *surname= "Nath Singh";
strncat(name,surname,4); /*
printf("%s",name);
return (0);
}
Output: Dr.ParasNath

Module 4:

7.
a. What is user defined function? Discuss different categories of user defined
functions with appropriate example for each. (10 Marks)

Solution:

 A function is a self-contained block of statements that performs a coherent


task of some kind.
 Mathematical definition of a function is like that “A function f(x) returns
value for the argument x.”
 Functions are classified of two types – In-built function and
User/Programmer defined functions.
 A function name is followed by a pair of ( ).
 A function may or may not have arguments. Arguments are written within
parentheses separating by , (comma).
 An user defined function is defined by user as per task is to be performed by
function. Now a days user defined functions are also called method as a
function is a method to perform a task.
 Yes, main( ) is a user defined function which is specially recognised function
in C. Every program must have a function main( ) to indicate where the
program has to begin its execution.

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.

Function based on argument:


A function may or may not send back any value to the calling function. The data type
void says that the function will not return any value and suppresses the warning
message that “Function should return a value.” If any function returns any value, it is
done through the return statement.
return; or return (expression);
Function without parameter:
void gao()
{
printf(“Kudi Punjaban dil chura ke lay gai – Sona Sona, Dil Mera Sona);
}
int main()
{
gao(); /* calling function */
return (0);
}
A function may have arguments. Formal declaration of the data type of arguments
to be passed with function should be done also.

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 */
{ ...... }

A function may be nested also:


int max2(int a, int b) { return (a>b?a:b); }
int main( )
{
int x,y,z;
printf(“Enter 3 numbers : “);
scanf(“%d%d%d”,&x,&y,&z);
printf(“Maximum = %d\n”. max2(max2(x,y),z)); /* Nesting of function if more
arguments */
return (0);
}

Arguments are passed as i. Pass/call by value ii. Pass/call by reference


/*i. Examples of call 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);
}
/*ii. Pass/Call 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 */
int swap(int *a, int *b) { int temp=*a; *a=*b; *b=temp; }
int main()
{
int a=20, b=30;
printf(a=%d b=%d\n”,a,b); /* a=20 b=30 */
swap(&a,&b); /* pass/call by reference */
printf(a=%d b=%d\n”,a,b); /*a=30 b=20 */
return (0);
}

b. Write a recursive function to find factorial of a number. (6 Marks)

Solution:

/*Recursive function to find factorial of a number */


long int factorial ( int n) {
if (n==0 || n==1)
return (1);
else
return (n*factorial(n-1)); /* recursion */
}

For example for value of n 5 it will return 5*4*3*2*1 = 120

c. Discuss storage class specifiers. (4 Marks)

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

b. Write a program to find GCD and LCM of two numbers. (8 marks)

Solution:

/* GCD using recursion */


#include <stdio.h>
int gcd(int a,int b) {
int rem=a%b;
if(rem==0)
return (b);
else
return (gcd(b,rem));
}
int main() {
int x,y,hcf;
printf("Enter two numbers : ");
scanf("%d%d",&x,&y);
hcf=gcd(x,y);
printf("GCD = %d\n",hcf);
/* LCM = product of numbers/hcf of numbers */
printf("LCM = %d\n",x*y/hcf);
return (0);
}
Expected output:
Enter two numbers : 45 10
GCD = 5
LCM = 90

c. What are advantages of writing user defined functions? (4 Marks)

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:

 Hence, a large project can be divided among many programmers.


 The program will be easier to understand, maintain and debug.
 Reusable codes that can be used in other programs
 It is modular approach of software development.
 Faulty functions can isolated for further investigation

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:

Syntax of union is similar to structure

union tagname {
data_type member1;
data_type member2;
data_type member3;
……..
data_type membern;
}

Example to declare and initialize:


union student { int roll; char name[20]; int marks; };
Only one block of largest sized data will be in memory:

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>

int swap(int *a, int *b)


{
int temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int a=20, b=30;
printf(a=%d b=%d\n”,a,b); /* a=20 b=30 */
swap(&a,&b); /* pass/call by reference */
printf(a=%d b=%d\n”,a,b); /*a=30 b=20 */
return (0);
}

When a function is called by passing address then called function receiving in


pointers may change value of the variable because it receives address. Thus value
of the variable of calling function will change also.

So, Advantages of call by reference over call by value:


I. The function can change the value of arguments at its address.
II. It does not create duplicate data and saving memory space.
III. No copy of arguments get made so, processing will be faster.
IV. It avoids changes which occur by mistake.
V. Person who reads the code is not aware directly that value can be modified
by the function.

c. List any 5 pre-processor directives in C. (5 Marks)

Solution:

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.

Examples of pre-processor directives:


i) #include
This pre-processor is used to include another file. File name is written in angle
brackets or within double quotes.
#include <stdio.h>

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:

/* Structure Complex for adding complex numbers – Using pointer to structure */


#include <stdio.h>
typedef struct Complex {
float real;
float imag;
} complex; /* here complex is for struct Complex as defined by typedef */
void addNumbers(complex c1, complex c2, complex *result)
/* result is pointer to structure */
{
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
int main() {
complex c1, c2, result;
printf("For first number,\n");
printf("Enter real part: "); scanf("%f", &c1.real);
printf("Enter imaginary part: "); scanf("%f", &c1.imag);
printf("For second number, \n");
printf("Enter real part: "); scanf("%f", &c2.real);
printf("Enter imaginary part: "); scanf("%f", &c2.imag);
addNumbers(c1, c2, &result);
printf("\nresult.real = %.3f\n", result.real);
printf("result.imag = %.3f", result.imag);
return 0;
}

Comments are written as explanation


Expected output:
For first number,
Enter real part: 2
Enter imaginary part: .876
For second number,
Enter real part: 4
Enter imaginary part: .543

result.real = 6.000
result.imag = 1.419

b. Write a C program to compute sum, mean and standard deviation of all


elements stored in an array using pointers. (10 Marks)

Solution:

/* Sum, mean and Standard deviation */


#include <stdio.h>
#include <math.h>
#define size 5
int main()
{
int x[size],*p,sum=0,i,diff,summd;
float mean,variance,stdev;
p=x;
for(i=0;i<5;i++) {
printf("Enter Number %d : ",i+1);
scanf("%d", p+i); /* we can write &*(p+i) */
sum+= *(p+i);
}
mean= (float)sum/size;
summd=0;
for(i=0;i<5;i++) {
diff=mean- *(p+i); /*mean - x[i] */
summd+= (diff*diff);
}
variance=(float)summd/(size-1);
stdev=sqrt(variance);
printf("Sum = %d Mean = %.2f Standard Deviation = %.2f\n",
sum,mean,stdev);

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

c. What are pointers? Discuss pointer arithmetic with examples. (4 Marks)

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 */

“************Think like a person of action. Act like a Person of thought.*********”

You might also like