0% found this document useful (0 votes)
60 views8 pages

CS151 Sem2 ISA2Afternoon Solns

The document is the question paper for the subject "Problem Solving with C" for the second semester B.Tech students of PES University, Bengaluru. It contains 4 questions related to C programming. Question 1 has two parts related to reading data from a file and compiling C code with gcc options. Question 2 contains problems on finding product of array elements and understanding gdb commands. Question 3 deals with implementing priority queue operations. Question 4 asks to write a program to copy only alphabets from lines of a file to another file.

Uploaded by

KB SCOUTS
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
0% found this document useful (0 votes)
60 views8 pages

CS151 Sem2 ISA2Afternoon Solns

The document is the question paper for the subject "Problem Solving with C" for the second semester B.Tech students of PES University, Bengaluru. It contains 4 questions related to C programming. Question 1 has two parts related to reading data from a file and compiling C code with gcc options. Question 2 contains problems on finding product of array elements and understanding gdb commands. Question 3 deals with implementing priority queue operations. Question 4 asks to write a program to copy only alphabets from lines of a file to another file.

Uploaded by

KB SCOUTS
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/ 8

SRN

PES University, Bengaluru UE20CS151


(Established under Karnataka Act No. 16 of 2013)

JULY 2021: IN SEMESTER ASSESSMENT B.TECH II SEMESTER


TEST – 2
UE20CS151 – PROBLEM SOLVING WITH C

Time: 2 Hrs Scheme and Solution Max Marks: 70

Q1 a) Consider the data file having the sale details of 15 Mobiles in the month of June(Model_id, 6M
Price per piece and the Number of units sold). All these are separated by a comma in the
data file in a separate line. Write a C code to display the model_id and the total value of that
model if the number of units sold is more than 1000.
Total value = Price per unit * Number of quantities.
Use redirection operator to provide data file as an input to the executable.
4,9990,999
7,19990,9999
8,36990,3699
9,36990,3699
2,25990,2599
15,19990,1999
13,26990,2699
1,6499,650
6,7999,800
3,8999,900
10,11990,1199
5.10990,1099
14,9999,1000
11,41999,4200
12,16999,1700
Solution:
#include<stdio.h>
int main()
{
int i = 0;
int id;
int price; // variable declarations, 1 mark
int num_quant;
printf("reading from the data file\n");
while(i<15)
{
scanf("%d,%d,%d",&id,&price,&num_quant);
// 2 marks. If comma missing, give 1 mark
if(num_quant > 1000) // 1 mark
{
printf("Model id is %d and ",id);
printf("total value is %d\n",num_quant*price); // 1 mark
}
i++; // 1 mark
SRN
}
return 0;
}
b) Describe the usage of gcc with various options to preprocess, compile and execute the C code. 4M
Solution: Any four commands with description – 4 marks
gcc -E first.c // To see the output of preprocessing stage on the terminal
gcc -c first.c // To pre-process and compile. Output of this command is object file. first.o
gcc first.o // linking with itself and with other files. Output of this command is loadable image or
executable. a.exe in windows and a.out in ubuntu
a.exe or ./a.out and press enter to execute the code. This results in output of the code
gcc first.o -o FIRST // this is to rename the executable to FIRST
Q2 a) Write a function to find the product of all the integers in an array. Test this function in the client 6M
code and check whether the product has the digit 1 in it. Display appropriate message.
Solution:
int find_product(int *a, int n);
#include<stdio.h>
int main()
{
int ints[] = {2,5,1,6,2};
int n = sizeof(ints)/sizeof(*ints);
int product = find_product(ints,n);
printf("product of elements in the array is %d\n",product);
int rem;
int status = 0;
while(product != 0) // 1 mark
{
rem = product % 10; // 1 mark
if(rem==1) // 1 mark
status = 1;
product = product /10; // 1 mark
}
if(status == 1)
printf("product has the digit 1 in it\n");
else
printf("Digit 1 is not available in the product\n");
return 0;
}
int find_product(int *a, int n) // finding the product 2 marks.
{
int i;
int product = 1; // 1 mark
for(i = 0;i<n; i++)
product = product * a[i]; // 1 mark
return product;
}
b) i) Differentiate between next and step command in gdb 4M
ii) What is the output of below code snippet?
char s[] = {'D', 'A', '\0', 'T', 'A',};
printf("%lu\n",sizeof(s));
printf("%d\n",strlen(s));
Solution:
i) 2 points 2 marks
SRN
Next command doesn’t dive into the function. n is the shorthand
Step command dives into the function. s is the shorthand used
ii) 1 marks each
5
2
Q3 a) Fill the implementation of Enque and Display functions to perform Ascending Priority Queue. 6M
Client code is given to understand the interface of these functions
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct component
{ char details[20]; int priority; };
typedef struct component compo_t;
struct node
{ compo_t c; struct node *link; };
typedef struct node node_t;
struct priority_queue
{ struct node *head; };
typedef struct priority_queue prio_t;
void init_queue(prio_t* pq); void enqueue(prio_t* pq,compo_t* c);
void dequeue(prio_t* pq); void display(const prio_t* pq);
int main()
{ prio_t q; init_queue(&q);
compo_t c; int choice,ele;
printf("enter ua choice\n1.insert 2.delete 3.display 4 exit\n");
scanf("%d",&choice);
do
{
switch(choice)
{ case 1: printf("enter the detail and priority\n");
scanf("%s %d",c.details, &(c.priority));
enqueue(&q,&c); break;
case 2: dequeue(&q); break;
case 3: display(&q); break;
}
printf("enter ua choice\n1.insert 2.delete 3.display 4 exit\n");
scanf("%d",&choice);
}while(choice<4);
return 0;
}
void init_queue(prio_t* pq)
{ pq->head = NULL; }
void enqueue(prio_t* pq,compo_t* c)
{ // Fill this implementation }
void dequeue(prio_t* pq)
{ // code to find delete and display the node with highest priority is available here }
void display(const prio_t* pq)
{ // Fill this implementation }
Solution:
void enqueue(prio_t* pq,compo_t* c)
{
node_t* temp = (node_t*)malloc(sizeof(node_t)); // 1 mark
SRN
strcpy(temp->c.details,c->details); // making the component as a node 1 mark
temp->c.priority = c->priority;
temp->link = pq->head; // changing the links 1 mark
pq->head = temp;
}
void display(const prio_t* pq)
{
node_t *p = pq->head;
if(p==NULL) printf("No elements to display\n"); // 1 mark
else
{
while(p != NULL) // 1 mark
{
printf("%s %d\n",(p->c).details, (p->c).priority);
p = p->link; // traversal 1 mark
}
}
}
b) Detect and correct the errors in the below code to get the expected output. 4M
Expected output: 3 ABC
#include<stdio.h>
#include<stdlib.h>
struct PLAYER
{ int id; char name[100]; };
int main()
{ struct PLAYER *p = (struct PLAYER)calloc(sizeof(struct PLAYER));
p.id = 3; p->name = "ABC"; printf("%d\t%s\n",p->id,p->name);return 0;
}
Solution:
i) calloc takes two parameters
ii) struct PLAYER* while type casting
iii) p->id must be used as p is a pointer
iv) arrays are assignment incompatible. So must use strcpy(p->name,”ABC”);
Q4 a) Write a C program to copy only the alphabets of each line to another file. Sample input and 6M
output files are as below.
Sample input file:
Digital image processing is the use of a digital computer
to process digital images through an algorithm. It has many advantages
over analog image processing
The generation and development of digital image processing are mainly affected by three
factors
1. The development of computers
2. The development of mathematics
3. The demand for a wide range of applications in environment,agriculture, military, industry and
medical science
Sample output file:
Digitalimageprocessingistheuseofadigitalcomputer
toprocessdigitalimagesthroughanalgorithmIthasmanyadvantages
overanalogimageprocessing
Thegenerationanddevelopmentofdigitalimageprocessingaremainlyaffectedbythreefactors
Thedevelopmentofcomputers
Thedevelopmentofmathematics
Thedemandforawiderangeofapplicationsinenvironmentagriculturemilitaryindustryandmedicalscie
SRN
nce
Solution:
#include<stdio.h>
int main()
{
FILE *fpr = fopen("data.txt","r"); // 1 mark
FILE *fpw = fopen("data_out.txt","w"); // 1 mark
char ch;
while((ch = fgetc(fpr)) != EOF) // 1 mark
{
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '\n' ) // 2 marks
fputc(ch,fpw); // 1 mark
}
fclose(fpr);
fclose(fpw);
return 0;
}
b) What is the output of below code execution? 4M
#include<stdio.h>
int f1(int);
int fun(int n, int (*f)(int));
int f2();
int main()
{ printf("in fun:"); int res = fun(10,f1) + fun(100,f2);
printf("%d",res);
return 0;
}
int f1(int n)
{ printf("in f1:"); return n+1; }
int f2(int n)
{ printf("in f2:"); return n+2; }
int fun(int n, int (*f)(int n))
{ return f(n); }
Solution: // 1 mark each . If mentioned in different lines, give partial 2 marks
in fun:in f1:in f2:113
Q5 a) Mobile.txt contains the below data as per the column headers given. All these data are 5M
separated by a tab.
Brand Models Color PRICE
COOLPAD COOL_3_PLUS SILVER 6499
COOLPAD COOL_5 BLUE 7999
LG W10 PURPLE 8999
OPPO A5_2020 WHITE 11990
OPPO A5S GOLD 10990
OPPO A5S RED 9990
OPPO F11_PRO BLACK 19990
OPPO RENO_2 BLUE 36990
OPPO RENO_2F GREEN 25990
Write a C code to read the contents of Mobile.txt and write the details of only OPPO branded
mobiles to another file.
Solution:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fpr = fopen("Mobile.txt","r");
FILE *fpw = fopen("Mobile_out.txt","w"); // 1 mark for fopen
char data[1000];
while(fgets(data,500,fpr) != NULL) // 1 mark
{
SRN
char d[1000];
strcpy(d,data); // 1 mark
strtok(data,"\t"); // 1 mark
if(!strcmp(data,"OPPO")) // 1 mark
fputs(d,fpw);

}
fclose(fpr);
fclose(fpw);
return 0;
}
b) The client code is given in which the price of each mobile is stored in the array and the array of 5M
pointers is initialized. Implementation of swap function is also mentioned. Fill the implementation
of sort function using selection sort without changing the client code.
#include<stdio.h>
void sort(int *a[],int n);
void swap(int **x,int **y);
int main()
{
int price[] = {11990, 10990, 9990,19990,36990, 36990, 25990, 29990};
int *p_price[100];
int i;
int n = sizeof(price)/sizeof(*price);
for(i = 0; i < n ; i++)
p_price[i] = &price[i];
printf("before sorting\n");
for(i = 0; i < n ; i++)
printf("%d\t",*p_price[i]);
sort(p_price,n);
printf("\nafter sorting\n");
for(i = 0; i < n ; i++)
printf("%d\t",*p_price[i]);
return 0;
}
void swap(int **x,int **y)
{ int *temp; temp = *x; *x = *y; *y = temp; }
void sort(int *a[ ],int n)
{ // Fill this implementation }
Solution:
void sort(int *a[],int n)
{
int i,pos,j;
for(i = 0;i<n-1;i++) // 2 loop 2 marks
{
pos = i;
for(j = i+1;j<n;j++)
{
if(*a[pos] > *a[j]) // 1 mark. If * not there do not award any marks
pos = j;
}
if(pos != i) // 1 mark
swap(&a[pos],&a[i]); // 1 mark
}
}
SRN
Q6 a) If the size of integer is 4 bytes, what is the output of below code? Provide brief explanation. 5M
#include<stdio.h>
struct DATA
{ unsigned int data1:21; unsigned int data2:6; };
int main()
{ printf("Size of structure is %lu\n",sizeof(struct DATA));
struct DATA d; d.data2 = -8;
printf("%d",d.data2); return 0;
}
Solution: 1 marks for each output
4
56
Brief explanation: 3 marks with binary representation
00001000 – 8
11110111 -- 1st complement
11111000 – 2s complement
Only 6 bits for data2 for8+16+32 = 56
b) i) List three differences between union and struct. 3+2
ii) Find the output of below code M
#define DATA 10
#include<stdio.h>
int main()
{ const int DATA = 10; printf("%d",DATA); return 0; }
Solution:
i) Any three differences, 3 marks
In structures, Each member hasunique storage area location. In unions, memory allocated is
shared by individual members.
Keyword struct is used. Keyword union is used
Size of structure is at least equal to the sum of the sizes of the data members. Size of union
is at least equal to the size of the largest member.
ii) 2 marks
Compiletime Error
Q7 a) What is the output of below codes? 5M
i) #include<stdio.h>
int main()
{ char c = 'q'; char d = 'p'; const char* cp = &c; cp = &d;
printf("%c",*cp); return 0;
}
ii) union A
{ int x; char y; float z; };
#include<stddef.h>
int main()
{ printf("%lu\n",offsetof(union A,y)); return 0; }
iii) #include<stdio.h>
int main()
{ printf("%d",sizeof(short) <= sizeof(int)); return 0; }
iv) #include<stdio.h>
void fun_static();
int main()
{ fun_static(); fun_static(); return 0; }
void fun_static()
{ static int a; auto int b = 1; a = a+b; printf("%d\t",a); }
SRN
Solution: first three 1 mark each. Last one 2 marks
i) p ii) 0 iii) 1 iv) 1 2
b) i) Mention the code snippet to print all the environment variables using environ global variable 3+2
available in stdlib.h M
ii) Program is executed using a.exe "help us". What is the output of below statement if argv is
an array of character pointers?
printf("%d",strlen(argv[0]));
Solution:
i) char **p = environ; // 1 mark
while(*p != NULL) // 1 mark
{ printf("%s\n", *p); // 1 mark
p++;
}
ii) 5 // 2 marks

You might also like