Assignment Solution 4 Jan 2020
Assignment Solution 4 Jan 2020
2. What is the purpose of the given program? n is the input number given by the user.
#include <stdio.h>
int main()
{
int n, x = 0, y;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0)
{
y = n % 10;
x = x * 10 + y;
n = n/10;
}
printf("Output is = %d", x);
return 0;
}
a) Sum of the digits of a number
b) Sum of the factorial of individual digits in a number
c) Reverse of a number
d) The same number is printed
Solution: (c) Reverse of a number. Please take a number and follow the operation step-by-
step. You will be able to find the reversed number as output.
3. What is the output of the following C code?
#include <stdio.h>
int main()
{
int a = 1;
if (a--)
printf("True\n");
if (++a)
printf("False\n");
return 0;
}
WEEK 4 ASSIGNMENT SOLUTION
a) True
b) False
c) Both ‘True’ and ‘False’ will be printed
d) Compilation error
Solution: (c) ‘a--’ post-increment the value of a. Thus, the if statement is executed as the
value of a is considered as 1 which is true. ‘++a’ pre-increment the value of a. Thus, the
decremented value of a (which is 0) is incremented first and then assigned. So, both the if
statements are executed ad correspondingly both True and False will be printed.
a) NPTEL
b) PROGRAMMING
c) No output
d) Compilation error as A and a are not declared as character variable
Solution: (a)
ASCII value of ‘A’ is 65, which is lesser than the ASCII value of ‘a’ (i.e., 97). Therefore, if
condition is true and NPTEL is printed.
c) 1400.000000
d) Compilation error
Solution: (b) si is declared as integer variable, but printed as float. So it will print 0.000000
6. In the following example, tell which statement is correct
if( (condition1==1) && (condition2)==1))
printf(“SUCESS”);
Solution: (c) Condition1 will be evaluated first; condition2 will be evaluated only if
condition1 is TRUE. This is called the Short-circuited evaluation of the operators
var2++;
}
printf("%d %d", var1, var2++);
return 0;
}
a) 10 6
b) 10 8
c) 57
d) 58
Solution: (c)
Firstly, var1=5 is an assignment operation that results always TRUE. Therefore, the if
condition is executed.
Secondly, var2++ increases the value of var2 by one. i.e., var2=7.
Finally, inside the printf statement, var1=5 and var2++=7 will be printed. Remember,
var2++ is a post-increment operation, so for the printf statement, its value is not
incremented to 8.
a) False statement
b) Infinite loop
c) Terminating the loop
d) Never executed loop
Solution: (b) while(1) is used to create infinite loop.
a) 0
12
b) 1
WEEK 4 ASSIGNMENT SOLUTION
11
c) 0
00
d) 0
11
Solution: (d)
Inside the first printf statement, i++ results in 0 (due to post increment operation). As the
left operand of && operator is zero, the compiler will not evaluate the right operand (i.e.,
++j). So, j is not incremented after the first printf statement. Finally, the result is i=1 and
j=1.