Practice 03 C Programming Constructs
Practice 03 C Programming Constructs
The loop invariant condition at the end of the ith iteration is:
(a) n = D1D2.Dm-i and rev = DmDm-1Dm-i+1
(b) n = Dm-i+1Dm-1Dm and rev = Dm-1.D2D1
(c) n != rev
(d) n = D1D2.Dm and rev = DmDm-1D2D1
Page|1
n = n - m;
}
print f ("% d", n);
}
int main ()
{
int a = 2048, sum = 0;
foo (a, sum);
printf ("%d\n", sum);
getchar();
}
Page|2
Identify the compiler's response about this line while creating the object-module
(a) No compilation error
(b) Only a lexical error
(c) Only syntactic errors
(d) Both lexical and syntactic errors
7. Consider the following code fragment:
if (fork() == 0)
{ a = a + 5; printf(%d,%d\n, a, &a); }
else { a = a 5; printf(%d, %d\n, a, &a); }
Let u, v be the values printed by the parent process, and x, y be the values printed by the child
process. Which one of the following is TRUE?
(a) u = x + 10 and v = y
(b) u = x + 10 and v != y
(c) u + 10 = x and v = y
(b) u + 10 = x and v != y
8. Consider the following C code segment.
for (i = 0, i<n; i++)
{
for (j=0; j<n; j++)
{
if (i%2)
{
x += (4*j + 5*i);
y += (7 + 4*j);
}
}
}
Page|3
(a) No choice
(b) Choice A
(c) Choice B
(d) Program gives no output as it is erroneous
10. Consider the following C program:
# include <stdio.h>
int main( )
{
int i, j, k = 0;
j = 2 * 3 / 4 + 2.0 / 5 + 8 / 5;
k -= --j;
for (i = 0; i < 5; i++)
{
switch(i + k)
{
case 1:
case 2: printf("\n%d", i + k);
case 3: printf("\n%d", i + k);
default: printf("\n%d", i + k);
}
}
return 0;
}
Page|4
13. Answer the following questions:
a. What does the following function return in terms of the argument n?
unsigned int f ( unsigned int n )
f unsigned int s = 0, t = 0;
while (n > 0) f s = s + n;
t = t + n * n * n;
n = n - 1;
return (t - s * s);
(a) 0
(b) 1
(c)
(d) 1 3 2
b. Consider the following program:
#include <stdio.h>
main ()
int m, n;
printf("Supply two integers: ");
scanf("%d%d",&m,&n);
m = m - n;
n = m + n;
m = n - m;
printf("%d %d\n", m,n);
Describe, in terms of the scanned integers m and n, what integer values are printed at
the end of the above program.
14. The following program computes the sum of the digits in the decimal representation of
a non-negative integer. For example, the sum of the digits of 320127 is 3+ 2 +0 + 1 +2
+ 7 = 15. Fill in the blanks with appropriate C constructs.
#include <stdio.h>
int main ()
{
unsigned int n, d, sum;
/* Read the unsigned integer n*/
scanf("%u", );
/* Initialize sum to zero */
/* Loop as long as n is not reduced to zero*/
while ( ) {
/* Store in d the least significant digit of n*/
d=;
/* Add this least significant digit to sum*/
sum = ;
/* Remove this digit from n */
n=;
}
/* Print the sum of digits of the input integer*/
printf("The sum of digits is \n", );
}
15. Let i, j be integer variables. What is the value printed after the following loop?
Page|5
Page|6
count = printf("\nn:%d\n",n);
20. What will be the contents of the variables a and b after the execution of the following
code on the input I do not know ?
char a, b;
scanf("%c do not %c", &a, &b);
21. Write an iterative function that reads positive integers a0, a1, . . . , an1 (not necessarily
in that order). The function computes and prints the value of ha0, a1, . . . , an1i as a
rational number in the form p/q and also its floating-point value. The number of terms,
that is, n is supplied to the function as an argument. Make clear in your code in which
order you are reading and processing a0, a1, . . . , an1. There is no need to use an
array.
void cfracitr ( int n )
{
int num, den; /* Numerator and denominator */
/* Declare other int variables, if necessary */
Page|7
Page|8
___________________________________
/* Include a header file for I/O operation. (1) */
main()
{
float x,y;
int z;
printf(Read x and y \n);
scanf(_______,__,__); /* Read x and y in appropriate format. (1)*/
z= ______(int)____(x+y); /* Type-cast. (1) */
if (z ____ 0) /* Check equality with zero. (1) */
printf(x=_ __, y=__ ___\n,____, ___); /* Print values of x, and y. (1) */
29. Write a C-program to print the first ten multiples of 5 using a while loop.
[Sample Output : 5 10 15 20 25 30 35 40 45 50]
Ans.
#include<stdio.h>
main(){
int i=5;
while(i<=50){
printf(%d\t,i);
i=i+5;}
printf(\n);}
30. Consider the following code:
int main(){
int a = 0, b = 100;
if (a)
if (b) printf("abc\n");
else printf("bcd\n");
}
a. What will be the output generated by the above code? Also explain your reasoning
in one sentence.
b.What will be the output generated by the above code when a = -100 and b = 100?
Also explain your reasoning in one sentence.
31. Consider the following C-code which intends to compute simple interest on an amount
of Rs. 2000/- for a period of four years at simple interest rate of 10.5% per annum.
# include <stdio.h>
int main (){
int amount = 2000;
int time = 4 ;
float rate = 10.5;
float simInt;
simInt = time/100 * amount * rate;
printf(Interest on Rs %d at %f per annum for %d y = %d\n,
amount, rate, time, simInt);
return 0;
}
a. What will be the output given generated by the above code? Write the reason(s) in
one sentence.
Page|9
b. Modify the above code so that you get the correct output. Explain your answer in
one sentence.
32. In the following code snippet , replace the while loop by a for loop. Your program
should produce identical output after you replace the statements commented "Replace
With a for loop".
int i;
int j=5;
int sum=0;
while(sum<10000){ /* Replace */
sum=sum+i*j; /* With a */
i++; /* for */
} /* loop */
printf("%d %d \n",sum,i,j);
33. What would be the output of the following program? In one sentence justify your
answer.
main(){
printf("Expression values = %d %d\n", 5/2*2, 2+5/2*3-1);
}
34. What will be printed when the following program is executed with 75 and 35 as the keyboard
inputs? What does the program compute?
#include <stdio.h>
main(){
int x, int y ;
printf(Enter two numbers: ) ;
scanf(%d%d, &x, &y);
while(x!=y){
if(x>y) x-=y;
else y-=x;
printf(x=%d y=%d\n,x,y);
}
printf("%d\n",x);
35. How many times will the print statement be executed?
for(i=0;i<=99;i++)
for(j=i;j<100;j++)
printf(Class Test 1\n);
36. How many times will the following while loop execute? Explain your answer.
char a='a';
while(a > 'a' && a <= 'z') a++;
37. What is the value of x after the execution of the following program segment? Explain
your answer.
x=-5; y=10;
if(x>y)x=1;
else if(y<0) x=(x) * (-1);
else x=2*x;
38. What will be printed by the following code segment? Explain your answer.
Page|10
46. What is the output of the following code?
do {
while (0) printf ("0\n");
printf ("1\n");
} while (0);
47. Given below is a program to find the second largest of TOTAL (_ 2) integers. You are
required to fill up theparts of the code that are left blank so that the overall code has
the required functionality.
#include <stdio.h>
#define TOTAL 1000
int main () {
int i, num, max1 /* largest */, max2 /* second largest */;
scanf ("%d%d", &max1, &max2); // read first two numbers
if (max2 > max1) { // interchange these (in three steps)
___________
______________
____________
}
for (i = 3 ; i <= TOTAL; i++) {
scanf ("%d", &num); // read next number
// make necessary updates to max1 and max2
___________
__________
if (num > max1) {
} else if (num > max2 && num < max1)
_____________
} // end-for
printf ("Second largest integer: %d\n", max2);
return 0;
}
48. Divisibility of a number by 9 is defined recursively as follows: 0 and 9 are divisible by
9, any other number is divisible by 9 if and only if the sum of its digits is divisible by
9. Write a code to test whether the given number is divisible by 9.
49. Let n, i and sum be int variables. The user enters a positive value of n. Which of the
following program segments prints the largest value of sum?
(a) sum = 0; i = 1; while (++i < n) sum += i; printf("%d", sum);
(b) sum = 0; i = 1; while (i++ < n) sum += i; printf("%d", sum);
(c) for (sum = 0, i = 1; i < n; i++) sum += i; printf("%d", sum);
(d) for (sum = 0, i = 1; i <= n; ++i) sum += i; printf("%d", sum);
50. What is printed by the following program?
main ()
{
int x = 0, y = 10, z = 20;
while (1) {
x++;
Page|12
if (y > z) break;
y += 4*x; z += 2*x;
}
printf("x = %d, y = %d, z = %d", x, y, z);
}
51. What is printed by the following program?
main() {
int x = 1, y = 0, z = 1, t;
for (t = 0; t < 10; ++t) {
y += (x) ? z : -z;
z++; x = !x;
}
printf("y = %d", y);
}
52. What is printed by the following program?
main ()
{
int x = 0;
if (x = 0) printf("Case (a): %d", x);
else if (x -= 7) printf("Case (b): %d", x);
else printf("Case (c): %d", x);
}
53. A positive integer is called square-free if it is not divisible by the square of any prime
number. For example, 98 = 272, 99 = 32 11,100 = 22 52 are not square-free,
whereas 101 (a prime) and 102 = 2317 are square-free. Your task is to find the
divisor m of a positive integer n supplied by the user, such that m is square-free and as
large as possible. Indeed, m is the product of all the distinct prime factors of n, each
taken only once. For example, for n = 98,99,100,101,102, the values of m will be 14 =
27,33 = 311,10 = 25,101,102 = 2317, respectively. Complete the following
program to solve this problem.
main ()
{
int n, m, d;
scanf("%d", &n); /* Assume that a positive integer is entered as n */
d = 2; m = 1; /* Initialize d (potential divisors of n) and m (the output) */
while ( ) { /* Supply a condition on n */
if ( ) { /* if n is divisible by d */
/* If the above condition is true, then d is prime (see the note below) */
m = ; /* Record this prime factor of n in m */
/* Write a loop to remove all factors of the prime d from n */
}
d++; /* Check the next potential divisor in the next iteration */
}
printf("The desired square-free divisor is %d\n", m);
}
54. In this exercise, your task is to evaluate a polynomial a0 + a1x + a2x2 + + adxd
with floating-point coefficients ai at a floating-point value of x. The user supplies the
Page|13
degree d, the value of x, and then the coefficients a0,a1, . . . ,ad. In the following
program, the variable sum accumulates the desired output value, and the variable
xpower stores the value of xi in the i-th iteration. Complete the program.
main ()
{
int i, d;
float x, a, sum, xpower;
scanf( ); /* Read both d and x from the user */
xpower = ; sum = ; /* Initialize */
/* Loop for reading the coefficients and updating sum and xpower */
for ( ; ; ) {
scanf( ); /* Read ai to a */
/* Update sum */
/* Update xpower for next iteration */
}
printf("The polynomial evaluates to %f\n", sum);
}
55. What is the output of the following program?
main()
{
int s = 0;
while (s++ < 10) {
if ((s < 4) && (s < 9)) continue;
printf("%d,", s);
}
}
56. You write a program which runs a loop for the user to enter a sequence of zeros and
ones. Entering an integer other than 0;1 terminates the loop. Your task is to count how
many times the user enters the sequence 1010. For example, if the user enters
1;0;0;1;0;1;0;1;0;0;1;0;1;0;1;1; 2, then the sequence 1010 occurs thrice:
1001010100101011
In order to solve this problem, you maintain a progress indicator preflen to remember
the length of the longest prefix of 1010, that you have read in the last preflen iterations
(including the current one). For example, at the beginning of the loop, or after reading
two consecutive zeros, preflen is zero (indicating that we cannot be somewhere inside
a match of 1010 at this point of time). On the other hand, if you read two consecutive
ones, preflen should be one, because if the user enters 0;1;0 in the next three iterations,
then you locate one occurrence of the pattern 1010. For the user input in the example
above, preflen changes as follows. The preflen value after processing each scanned
integer is shown below.
Input 1 0 0 1 0 1 0 1 0 0 1 0 1 0 1 1
preflen 1 2 0 1 2 3 2 3 2 0 1 2 3 2 3 1
Here, preflen starts with the value 0 before any user input. After the first input (1),
match occurs with the first symbol of 1010, so preflen becomes 1. After the second
input (0), the length of the matched prefix increases to two. The third input (0) destroys
the partial match, so preflen reduces to zero.
57. Which of the following nested if statements are logically equivalent to the flow chart
below?
Page|14
Page|15
Page|16
Page|17
sum = sum + i;
(d) for (int i = 2; i < 5; i++)
sum = sum + i;
(e) for (int i = 1; i < 6; i++)
sum = sum + i;
68. What is the output of the program segment:
int x=0;
for(int i=0; i<3; i++) {
for( int j=i; j<3; j++) {
x = x + j;
}
}
printf(%d,x);
69. What is the output of the following program segment:
int num = 1, x = 10;
do
{
x += 10;
num ++;
}
while (num == 2);
printf("Num = %d, x = %d", num, x);
70. Rewrite the following statement using a switch statement.
if( letter == 'X' )
sum = 0;
else if ( letter == 'Z' )
valid_flag = 1;
else if( letter == 'A' )
sum = 1;
else
printf("Unknown letter -->%c\n", letter );
1. Read the symbol of a binary arithmetic operator (such as +, -, *, /) and its two operands from the
keyboard and perform the operation on those two operands depending upon the operator entered by the
user. Print the result accordingly.
Page|18
3. A point in a plane can be represented by its X and Y coordinates. Write C programs to do the
following.
i) Read the coordinates of a pair of points and find the distance between these two points and
print the result.
ii) Read the coordinates of three points and then check whether they can constitute a triangle. If
so, find the area and perimeter of the triangle and check whether it is a scalene, isosceles or a
equilateral triangle.
4. Read a sequence of integer numbers (terminated by 0) and find the maximum, minimum and average
value of the numbers (excluding 0) that have been entered.
5. Read a sequence of characters (terminated by new line character \n) and count the number of vowels
entered.
6. A number is called a perfect number, if the number is equal to the sum of all its positive divisors except
the number itself. For example, (6 = 1 + 2 + 3, 28 = 1 + 2+ 4 + 7 + 14). Find and print all the perfect
numbers less than or equal to 1000.
8. Write a program that reads three integers representing time of a day. The integers are SS, MM, HH,
representing seconds, minutes and hours. Write a program to print valid time if the integers
represent a valid time of the day.
9. Write a program to read three integers and print the largest among them.
10. Write a program to compute and print the taxi fare based on the following chart. Total number of
Kilometers traveled will be input by the user as a floating point number.
11. Read n integers and print the third largest among them. n is input by user. Dont use any array.
12. Read any 4 digit number and print the sum of its digits.
13. Find the sum of the first n terms of the following series.
1 + x + x2/2! + x3/3! + .
Page|19
[Hint: Value of x and n is input by user. Do not use the factorial or power functions available in math.h]
14. A number is called a perfect number, if the number is equal to the sum of all its positive
divisors except the number itself. For example, 6 = 1 + 2 + 3, 28 = 1 + 2+ 4 + 7 + 14 are the
two perfect numbers. Find and print all the perfect numbers less than or equal to 1000.
15. Read a sequence of integer numbers (terminated by 0) and find the maximum, minimum
and average value of the numbers (excluding 0) that have been entered.
--*--
Page|20