0% found this document useful (0 votes)
45 views23 pages

C Questions

Uploaded by

dhakshanms06
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)
45 views23 pages

C Questions

Uploaded by

dhakshanms06
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/ 23

1.

a)

i)
Write the function definition for the following function:

void sumdif(int x, int y, int *sum, int *dif);

// put the sum of x and y into *sum and the difference (x-y) into *dif

Show how the function sumdif declared would be called.

ii)
Why is it necessary to give the size of an array in an array definition? When is it optional? Analyze the following code
segment:

void main() {

int xxx[10] = {5}, yyy[10];

printf("%d %d", xxx[1], xxx[9]);

yyy = xxx;

printf("%d %d", yyy[1], yyy[9]);

b)

How can structure elements be accessed through:


• a structure variable
• a pointer to a structure?

What is the difference between structure and union?

Consider the following code segment.


Find the size and draw the memory layout of the variable X in each case:

union Ex {

int a;

float f;

char c;

} X;

struct Ex {

int a;

float f;

char c;

} X;

c)
What is an Array in C? Why do we need the concept of array?

Explain how to define 1D and 2D arrays in C and also draw a memory map.

Consider the following scenario:


A company has records for the hours worked by each employee per week. Each employee's record consists of the
hourly rate of pay and seven numbers, representing the hours worked by the employee on the seven days of the
week. For example, a typical entry could be the following:

13.25 1.3 7 80 4.700

Write a program that:

1. Reads a number specifying the number of employees.

2. Reads in the specified data.

3. For each employee, finds the total number of hours worked for the week.

4. For each employee, finds the weekly pay by multiplying the hours worked by the rate per hour.

5. Finds the number of employees absent on each day of the week. An employee is considered absent on a
given day if the hours worked are less than 1.

6. Finds which day has the most absentees.

2.a)

i)
A program uses a function named convert() in addition to its main function.

 The function main() defines the variable x within its body.

 The function convert() defines two variables y and z within its body; z is made static.

 A fourth variable m is defined ahead (i.e., at the top) of both the functions.

State the visibility and lifetime of each of these variables.

ii)
What is random access in a text file?
How do you perform random access from a text file in C?
Write a sample code segment.

b)

Consider the following C functions.


Draw the activation record tree and find the return value if the function fun2 is called with 5 from the main function.

int fun1(int n) {

static int i = 0;

if (n > 0) {

++i;

fun1(n - 1);

return(i);

int fun2(int n) {
static int i = 0;

if (n > 0) {

i = i + fun1(n);

fun2(n - 1);

return(i);

c)

Write a C program that reads the name of a text file.


The program should open that file and copy its contents to stdout, except that any input line that contains more than
40 characters should be truncated to 40 characters (not counting the \n newline at the end of the line).

Example:
If the input file alice.txt contains:

"Who are YOU?" said the Caterpillar.

This was not an encouraging opening for a conversation.

Alice replied, rather shyly, "I-I hardly know, sir, ...

Then the output of the program should be (truncated to 40 characters):

"Who are YOU?" said the Caterpillar.

This was not an encouraging opening for

Alice replied, rather shyly, "I-I hardly

Constraints:

 You must read input lines by calling a function to read each complete line, not by reading one character at a
time.

 The file contains only ASCII text and each line has a \n at the end.

 No line contains more than 500 characters, including any \n or \0 at the end.

 It’s fine to use standard C library routines for file I/O and string handling.
1. a)

i)
What is a cyclic property of data type in C?
How is it related to data overflow and data underflow?
Justify with an example.

ii)
Consider the given while loop below:

i = 1;

while (i <= 10) {

printf("hello\n");

i = i + 2;

Rewrite the code above using:


a) for loop
b) do-while loop

1. b)

i)

Find the number of iterations in the following program.


What does this program do, and what will be the final value of a and b?

int a = 6;

int b = 0;

while (a < 10) {

a = a / 12 + 1;

a += b;

printf("%d", a);

ii)
What is the minimum number of bits which can be used to encode the following numbers?
A = 1023
B = 1024
C = -1025
D = -1024

Justify your answer, then convert the values into their equivalent binary.

1. c)
Construct an algorithm and flow chart for solving the following problem.
Convert the algorithm to corresponding C language code.

In the computer representation of colours, colours are often specified by an RGB triple, three floating point numbers
between 0.0 and 1.0.
A different specification, which takes account of the different responses of the human eye to red, blue and green
light, is the XYZ system.

An RGB specification (r, g, b) is converted to an XYZ specification (x, y, z) by the following rules:

x = 0.412453*r + 0.357580*g + 0.180423*b

y = 0.212671*r + 0.715160*g + 0.072169*b

z = 0.019334*r + 0.119193*g + 0.950227*b

Write a program which:

 Reads three floating point numbers from the user

 Treats them as RGB specifications

 Prints the corresponding XYZ specification as three floating point numbers rounded to 4 decimal places
separated by spaces

Example run:

Input r g b values: 0.5 0.5 0.5

x y z are:

0.4752 0.5000 0.5444

2. a)

i)
If the value of x = 8, y = 5, z = 5, w = 2, n = 4 and m = 5, is the value of each of the following expressions 21?
Justify your reasoning.

1)++(n * m);

2)p = x * w + y * z = 1;

3) s = ((5, (x = 3)), x = 21);

ii) Compute the values of the following C expressions assuming:

int b = 1, s = 3, e = 5, m = 4, k = 10, a = 6, c = 5;

float z = 2.0, t = 5.5;

Expressions:

1)z = b + k * z / m % e - 1;

2)(b < s) % s + 1;

3)++b && s--;

4)a += b *= c = 5;
2. c)

What do you mean by flow control?


Explain the branching and looping styles of flow control available in C.

The following code segment is intended to compute the sum of odd numbers between 1 and 1000 (i.e., 1 + 3 + 5 + ...
+ 999), but the source code generates a wrong result.

What is wrong and why is it wrong?


How can you change the code to make it correct?

int main() {

int i = 1;

int sum = 0;

while (i <= 1000) {

if ((i % 2) = 1)

sum += i;

else

continue;

++i;

printf("%d\n", sum);

}
1. a)

i) Define, initialize and print sum:

 Write C statements that define and initialize two variables with the values (2B)₁₆ and (235).

 Print the sum of these values in Hexadecimal using a single printf statement.

ii) l-value and r-value:

 What do you mean by l-value and r-value?

 Comment on the following:

o An operator that requires l-value as operand and yet yields r-value.

o An operator that accepts r-value as operand and gives l-value.

 Give examples for each.

1. b)

i) Underflow and Overflow:

 Define underflow and overflow of data.

 Does the compiler provide any warning/indication of overflow?

 A system uses 5 bits for signed integers in 2's complement:

o A = 01010

o B = 11010

o Which arithmetic operation between A and B causes overflow or underflow?

ii) Type and Sign Modifiers:

 Why do we need type and sign modifiers in C?

1. c)

i) Compilation Block Diagram:

 Draw a block diagram to describe the process of compiling and running a C program.

ii) ABC Company Bonus Problem:

 Flowchart to calculate employee bonus:

o 6% bonus if salary ≥ Rs. 6000

o Rs. 250 bonus otherwise

 Algorithm

 C program equivalent

2. a)

i) Control Structures:
Fill in the table below:

Control Task/Process | Category | C Example | Reason |

As long as age is less than 50, print Happy Birthday

If a guess is too high/low, ask again

Print a message based on grade

ii) Operator Precedence and Associativity:

 Operators: +, -, *, /

 Given precedence table

 Evaluate:
3+1+5*2/7+2-4-7-6/2

o Show order of execution and value.

2. b)

Function: enough

 Write a function named enough(int goal)

o Returns the smallest positive integer n such that 1 + 2 + 3 + ... + n >= goal

 Examples:

o enough(9) → 4

o enough(21) → 6

o enough(-7) → 1

o enough(1) → 1

2. c)

i) Use of switch...case over if...else

ii) Formats of if statement in C with flowcharts.

iii) Behavior of conditionals:

Initial value of x = 1. Determine final value for each:

1.

if (x >= 0)

x = x + 1;

else if (x >= 1)

x = x + 2;

2.

if (x >= 0)
x = x + 1;

if (x >= 1)

x = x + 2;

3.

if(x >= 0)

if(x >= 1)

x = x + 2;

else

printf("x is negative");

iv) Simplify nested if:

float income;

printf("Enter your monthly income: ");

scanf("%f", &income);

if (income < 0.0)

printf("You are going farther into debt every month.");

else if (income < 12000.00)

printf("You are living below the poverty line.");

else if (income < 25000.00)

printf("You are living in moderate comfort.");

else

printf("You are well off.");

3. a)

i) String Length Function:

int fX(char *a){

char * b = a;

while(*b) b++;

return b-a;

 What is the value returned?

 Justify.

ii) Value Tracking in Loop:

int main(){

int a = 6;
int b = 0;

while (a < 10){

a = a / 12 + 1;

a += b;

printf("%d", a);

return 0;

 Show how variable values change using diagrams.

3. b)

Pointers, Arrays and Strings:

 How are they related in C? Give example.

number_of_matches function:

 Compares two strings, returns the count of matching characters from the start.

 e.g., boast and boat → 3

3. c)

Significance of Arrays

Memory Map:

 Draw and explain for:

o 1D array

o 2D array

 Address calculations in both

Program Output:

int a[10] = {1, 20, 3}, i;

int *p = &a[3];

int q = p + 2;

for(i = 3; i < 10; i++) a[i] = a[i - 2] + 1;

*(++q) = *(++p); q++; *(q++) = *(p++);

printf("%d %d %d\n", *a, *q - *p, q - p, *p - *q);

for (i = 4; i < 8; i++) printf("%d", a[i]);

 Justify output with diagrams.


4. a)

i) Pointer Types:

Differentiate with examples:

 Constant Pointer

 Pointer to a Constant

 Constant Pointer to a Constant

ii) Function: sumdif

void sumdif(int x, int y, int *sum, int *dif);

// Computes: *sum = x + y; *dif = x - y

 Show how to call this function.

4. b)

Stack Frame / Activation Record:

 What is it?

 Information it stores

Program:

int main() {

f1();

f2(2);

f3();

return 0;

int f1(){

return 1;

int f2(int X) {

f3();

if (X == 1) return f1();

else return (X * f2(X - 1));

int f3() {

return 5;

Activation Tree:
 Draw for above program

4. c)

Scope, Lifetime, Visibility:

 Define and explain

 Role of storage classes

Program Output:

int funcp(){

static int x = 1;

x++;

return x;

int main(){

int x, y;

x = funcp();

y = funcp() + x;

printf("%d\n", (x + y));

return 0;

 Justify output.

5. a)

i) Macro vs Variable:

 What is a macro?

 Differences from variable names

Given Macro:

#define root(a, b) sqrt((a)(a) + (b)(b))

 Expand: root(a++, b++)

ii) Random Access in Text File:

 What is it?

 Sample code

5. b)

Structure Members:
Access via:

1. Structure variable

2. Pointer to structure

Structure vs Union:

Memory layout and size for:

union Ex {

int a;

float f;

char c;

} X;

struct Ex {

int a;

float f;

char c;

} X;

5. c)

File Opening Modes in C:

 List and explain with syntax

File Handling Functions:

 Opening a file

 Reading a character

 Writing a character

 Closing a file

Program:

 Takes a file name as command-line argument

 Output:

o File name

o Number of lines

o Contents of last line

Output Format Example:

test1.txt lines 921

Hey! I finished writing C exam. Bye!!


 Handle error for 0 or >1 arguments

 Check if file exists


1. a)

i) Predict the output of the following program. Give reason.

#include <stdio.h>

int main()

int a = 3, b = 5, c;

a = (a > 3) + (b < 5);

b = (a = 3) + ((b - 2) >= 3);

c = (b != 1);

printf("%d %d %d\n", a, b, c);

return 0;

ii) What is a cyclic property of data type in C? How is it related to data overflow and data underflow? Predict the
output of the following:

main()

x = 32769;

printf("%d", x);

1. b)

i) Write the difference between = and ==. What will be the output of the program?

#include<stdio.h>

int main()

unsigned int x = -1;

int y = ~0;

if (x == y)

printf("same");

else

printf("not same");

return 0;

ii) A library charges a fine for every book returned late.


 For first 5 days, fine = 1 rupee/day.

 For 6–10 days, fine = 2 rupees/day.

 For more than 10 days, fine = 15 rupees/day.

 If the book is returned after 30 days, the membership is cancelled.

1. Write an algorithm for the above case.

2. Write a program that accepts the number of days the member is late and displays the fine or appropriate
message.

1. c)

Construct an algorithm and flow chart for the following problem. Convert the algorithm to C code using switch case
with functions.

WELCOME TO QUIZ

Questions:

1. Who is the founder of C language?

2. How many binary digits will a byte have?

3. Which is predefined and reserved that has special meaning to the compiler?

Each correct answer = 1 mark.


Wrong answers show correct answer.
At the end, print message based on score.

Score Message

3 Very Good

2 Good, but improve

1 Not bad, should improve much

0 Very bad, should work hard

2. a)

i) Which of the following loops will never exit? Why?

int i = 0;

do {

i++;

printf("%d", i);

} while (i < 10);

int i = 10;

while(i <= 10) {


i--;

printf("%d", i);

int i = 10;

do {

i--;

printf("%d", i);

if (i == 0)

break;

} while (1);

ii) Can we use a goto statement to take control from one function to another? Justify:

CopyEdit

int main()

goto here;

return 0;

other_function() {

here: printf("The label is in other function");

2. b)

i) Define dangling else problem. What is the output of the following program? Justify.

#include <stdio.h>

int main(void)

int i = 30;

if(i=!20) // instead of !=

printf("One\n");

else

printf("Two\n");

printf("%d\n", i);
return 0;

ii) Compare break, continue, and goto keywords in C.

2. c)

i) Write a program that characterizes earthquakes based on Richter scale number:

Richter Number (n) Characterization

n < 5.0 Little or no damage

5.0 ≤ n < 5.5 Some damage

5.5 ≤ n < 6.5 Serious damage

6.5 ≤ n < 7.5 Disaster: Houses and Buildings may collapse

n ≥ 7.5 Catastrophe: most buildings destroyed

ii) Write a program for the following output using switch and loop:

MENU CARD
++++++++++

1. COFFEE Rs:15

2. TEA Rs:10

3. COLD COFFEE Rs:25

Sample Input/Output:

Enter Your choice: 2

You have selected Tea

Enter the quantity: 5

Total amount: Rs. 50.00

Do you want order again? No

*****Thanks for shopping*****

3. a)

i) What will be the output of the following C code? Why?

#include <stdio.h>

void main()

int a[2][3] = {1, 2, 3,, 4, 5};

int i = 0, j = 0;

for(i = 0; i < 2 ; i++)


for(j = 0; j < 3; j++)

printf("%d", a[i][j]);

ii) What is the output of the following program?

#include <stdio.h>

int main(void)

int *ptr1, *ptr2, *ptr3, i = 10, j = 20, k = 30;

ptr1 = &i;

i = 100;

ptr2 = &j;

j = *ptr2 + *ptr1;

ptr3 = &k;

k = *ptr3 + *ptr2;

printf("%d %d %d\n", *ptr1, *ptr2, *ptr3);

return 0;

3. b)

i) What is the output of the following program?

#include <stdio.h>

int main(void)

int *ptr, i = 0;

for(ptr = &i; *ptr < 5; i++) {

(*ptr)++;

++*ptr;

printf("%d ", i);

return 0;

ii) Write a function that removes duplicates and sorts elements in descending order.

Input: 1 4 9 16 97 49 11
Expected Output: 97 49 16 11 9 4 1
3. c)

Write a menu-driven C program that performs the following for an array of integers:

1. Replace all even elements with 0.

2. Return second-largest and second-smallest element.

3. Remove duplicate elements.

4. Swap first and last elements.

4. a)

i) Consider the following structure:

struct employee_detail {

short emp_no[5];

union {

float Salary;

long address;

} u;

} t;

Assume:

 short = 2 bytes

 float = 4 bytes

 long = 8 bytes

What is the memory requirement for variable t? Justify.

ii) How is enumeration useful in C? What will be the output of the following:

#include<stdio.h>

int main() {

enum day {sunday=1, monday, tuesday=5, wednesday, thursday=10, friday, saturday};

printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday, friday, saturday);

return 0;

4. b)

Differentiate between call by value and call by address parameter passing mechanism by giving an example.

4. c)
Declare a structure SHOP with members: item_no, item_name, stock, price, and total_amount.

Write a menu-driven program to:

1. Calculate and display the total amount (stock × price).

2. Read an item number and check availability. If available, display details. Else, print "not available".

5. a)

i) What does the fseek() function do? Identify the file pointer position in:

1. fseek(ptr, 21, SEEK_SET);

2. fseek(ptr, 10, SEEK_CUR);

3. fseek(ptr, -7, SEEK_END);

ii) What does the following program do?

#include<stdio.h>

int main(void) {

FILE *fp;

char ch;

if((fp = fopen("test.txt", "r")) == NULL) {

while((ch = getc(fp)) != EOF)

putc(ch, stdout);

fclose(fp);

return 0;

5. b)

List and explain file opening methods in C. With syntax, describe file handling functions for:

1. Opening a file

2. Reading a character

3. Writing a character

4. Closing a file

5. c)

i) Create a structure item_in_store with fields: item_code, qty_in_stock, and price. Create an inventory file and write
a program to compute total value.

Sample Input:
ITEM_CODE | QTY_IN_STOCK | PRICE

101 | 200 | 15.50

145 | 100 | 20

Expected Output:

ITEM_CODE | QTY_IN_STOCK | PRICE | VALUE

101 | 200 | 15.50 | 3100.00

145 | 100 | 20 | 2000.00

Total Value: 5100.00

(OR)

Write statements that accomplish the following. Assume:

struct product {

int id;

char name[20];

int quantity;

int cost;

};

Assume file productinfo has 5 records.

1. Append new records to the file.

2. Update existing product info.

3. Display the contents of the file.

1.a)ii)

Consider the following C function. What is the value returned by this function for any string that is passed as
argument? Why?

int fX (char *a) {

char * b = a

while(*b)

b++;

return b - a;}

b)i)
What is Pointer? Differentiate constant pointer, pointer to a constant and constant pointer to a constant by giving
example for each. Consider the following program, what is the output of the following program? Include diagrams
that justify your answer.

int a[10]= (1, 20, 3), i;

int * p = &a[3];

int *q = p + 2;

for (i = 3; i < 10; i++) a[i] = a[i - 2] + 1;

*(++q) = * (++p); q++; *(q ++)=*(p++);

printf("%d %d %d\n", *a * *q - *p, q-p, *p-*q ) ;

for (i = 4; i < 8 ; i ++) printf("%d", a[i]);

You might also like