Find Output of Program
Practice and master this topic with our carefully crafted questions.
What will be the content of 'file.c' after executing the following program?
#include<stdio.h>
int main()
{
FILE *fp1, *fp2;
fp1 = fopen("file.c", "w");
fp2 = fopen("file.c", "w");
fputc('A', fp1);
fputc('B', fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
Correct Answer: A. B ✅
Consider the following C program:
#include<stdio.h>
int main()
{
FILE *fp1, *fp2;
fp1 = fopen("file.c", "w");
fp2 = fopen("file.c", "w");
fputc('A', fp1);
fputc('B', fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
The file "file.c" is opened twice in "w" (write) mode.
- Opening a file in
"w"mode creates the file if it does not exist, or truncates it (clears its contents) if it already exists. fp1andfp2are two separate streams referring to the same file.fputc('A', fp1);writes'A'at the beginning of the file.fputc('B', fp2);also writes at the beginning of the file becausefp2's file position is initially at the start of the file.- Thus,
'B'overwrites'A', and the final contents of the file are simplyB.
- A.
B✅
Correct. The second stream writes'B'at the beginning of the file, replacing the earlier character. - B.
AB❌
Incorrect. No newline is written, and the second write occurs at the beginning of the file. - C.
BB❌
Incorrect. Only one character is ultimately present in the file. - D. Error in opening file
'file1.c'❌
Incorrect. There is no file named"file1.c"in the program, and opening the same file twice is permitted.
Exam Fact:
Opening a file with "w" truncates the file and positions the file pointer at the beginning. If the same file is opened multiple times in write mode, each stream maintains its own file position, and writing through one stream can overwrite data written by another stream.
What will be the output of the program ?
#include<stdio.h>
int main()
{
int k = 1;
printf("%d == 1 is" "%s\n", k, k == 1 ? "TRUE" : "FALSE");
return 0;
}
Correct Answer: B. 1 == 1 is TRUE ✅
Consider the following C program:
#include<stdio.h>
int main()
{
int k = 1;
printf("%d == 1 is" "%s\n", k, k == 1 ? "TRUE" : "FALSE");
return 0;
}
The printf() statement contains two adjacent string literals:
"%d == 1 is"
"%s\n"
In C, adjacent string literals are automatically concatenated by the compiler. Therefore, the above is equivalent to:
"%d == 1 is%s\n"
Now evaluate the arguments:
kis initialized to1.%dprints the value ofk, which is1.- The expression
k == 1evaluates totrue. - The conditional operator
k == 1 ? "TRUE" : "FALSE"returns the string"TRUE".
Hence, the output is:
1 == 1 isTRUE
Since there is no space after is in the format string, the actual output is 1 == 1 isTRUE. However, competitive exams generally intend the output to be read as:
1 == 1 is TRUE
- A.
k == 1 is TRUE❌
Incorrect.%dprints the value ofk, not the variable name. - B.
1 == 1 is TRUE✅
Correct.khas the value1, and the conditional expression evaluates to"TRUE". - C.
1 == 1 is FALSE❌
Incorrect. Sincek == 1is true, the conditional operator returns"TRUE". - D.
K == 1 is FALSE❌
Incorrect. The variable name is not printed, and the condition evaluates to true.
Exam Fact:
In C, adjacent string literals are automatically concatenated at compile time. Also, the conditional operator condition ? expr1 : expr2 returns expr1 if the condition is true; otherwise, it returns expr2.
What will be the output of the program ?
#include<stdio.h>
char *str =
"char *str = %c%s%c; main(){ printf(str, 34, str, 34);}";
int main()
{
printf(str, 34, str, 34);
return 0;
}
Correct Answer: A. char *str = "char *str = %c%s%c; main(){ printf(str, 34, str, 34);}"; main(){ printf(str, 34, str, 34);} ✅
Consider the following C program:
#include<stdio.h>
char *str =
"char *str = %c%s%c; main(){ printf(str, 34, str, 34);}";
int main()
{
printf(str, 34, str, 34);
return 0;
}
This program is a classic example of a Quine—a program that prints its own source code without reading it from a file.
The format string stored in str contains:
%c– Prints the double quotation mark ("). The value34is the ASCII code for".%s– Prints the string stored instritself.- The final
%cprints another double quotation mark.
The call:
printf(str, 34, str, 34);
replaces:
- First
%c→" %s→ the complete contents ofstr- Second
%c→"
Thus, the output becomes the complete program text:
char *str = "char *str = %c%s%c; main(){ printf(str, 34, str, 34);}";
main(){ printf(str, 34, str, 34);}
This matches Option A (formatting may vary slightly depending on line breaks).
- A.
char *str = "char *str = %c%s%c; main(){ printf(str, 34, str, 34);}"; main(){ printf(str, 34, str, 34);}✅
Correct. The program prints its own source code. - B.
char *str = %c%s%c; main(){ printf(str, 34, str, 34);}❌
Incorrect. The quotation marks around the string are missing. - C.
No output❌
Incorrect. The program executes successfully and produces output. - D.
Error in program❌
Incorrect. The program is syntactically valid (though modern C prefersint main(void)).
Exam Fact:
A Quine is a self-replicating program that prints its own source code. In C, such programs are commonly implemented using a format string with %c and %s, where %s prints the format string itself and 34 represents the ASCII value of the double quotation mark (").
If the file 'source.txt' contains a line "Be my friend" which of the following will be the output of below program?
#include<stdio.h>
int main()
{
FILE *fs, *ft;
char c[10];
fs = fopen("source.txt", "r");
c[0] = getc(fs);
fseek(fs, 0, SEEK_END);
fseek(fs, -3L, SEEK_CUR);
fgets(c, 5, fs);
puts(c);
return 0;
}
Correct Answer: C. end ✅
Consider the following C program:
#include<stdio.h>
int main()
{
FILE *fs, *ft;
char c[10];
fs = fopen("source.txt", "r");
c[0] = getc(fs);
fseek(fs, 0, SEEK_END);
fseek(fs, -3L, SEEK_CUR);
fgets(c, 5, fs);
puts(c);
return 0;
}
Assume the file source.txt contains:
Be my friend
Let's trace the program step by step.
getc(fs)reads the first character'B'and stores it inc[0].fseek(fs, 0, SEEK_END);moves the file pointer to the end of the file.fseek(fs, -3L, SEEK_CUR);moves the file pointer 3 bytes backward from the end.
The file contents are:
B e m y f r i e n d
0 1 2 3 4 5 6 7 8 9 10 11
The end of the file is just after 'd' (position 12). Moving back 3 bytes places the file pointer at index 9, which is the character 'e'.
Now the statement:
fgets(c, 5, fs);
reads at most 4 characters from the current position. Since only three characters remain ("end"), it reads:
end
This overwrites the previous value stored in c, and puts(c) prints:
end
- A.
friend❌
Incorrect. The file pointer is positioned only three bytes before the end of the file. - B.
frien❌
Incorrect. Reading begins at'e', not at'f'. - C.
end✅
Correct.fgets()reads the remaining characters from the position reached afterfseek(). - D.
Error in fseek()❌
Incorrect. Bothfseek()calls are valid.
Exam Fact:
fseek(fp, -n, SEEK_CUR) moves the file pointer n bytes backward from its current position. Also, fgets(str, n, fp) reads at most n-1 characters and appends a null character ('\0').
What will be the output of the program ?
#include<stdio.h>
int main()
{
float a = 3.15529;
printf("%2.1f\n", a);
return 0;
}
Correct Answer: C. 3.2 ✅
Consider the following C program:
#include<stdio.h>
int main()
{
float a = 3.15529;
printf("%2.1f\n", a);
return 0;
}
The format specifier used is:
%2.1f
%fprints a floating-point number..1specifies that one digit should be printed after the decimal point.2specifies the minimum field width. If the output is wider than 2 characters, it is printed in full.
The value of a is:
3.15529
Printing with one digit after the decimal requires rounding:
- First digit after the decimal:
1 - Second digit after the decimal:
5 - Since the next digit is
5, the first decimal digit is rounded up.
Therefore, the output is:
3.2
- A.
3.00❌
Incorrect. The format specifies only one digit after the decimal point. - B.
3.15❌
Incorrect. This would require two digits after the decimal point (e.g.,%.2f). - C.
3.2✅
Correct. The value is rounded to one digit after the decimal point. - D.
3❌
Incorrect. The%fformat always prints the specified number of digits after the decimal point.
Exam Fact:
For the %w.pf format specifier, w is the minimum field width and p is the number of digits printed after the decimal point. The value is rounded to p decimal places before printing.
What will be the output of the program ?
#include<stdio.h>
int main()
{
printf("%c\n", ~('C' * -1));
return 0;
}
Correct Answer: B. B ✅
Consider the following C program:
#include<stdio.h>
int main()
{
printf("%c\n", ~('C' * -1));
return 0;
}
Let's evaluate the expression step by step.
- The character
'C'has the ASCII value67. - The expression:
evaluates to:'C' * -167 * -1 = -67 - Now apply the bitwise NOT operator:
Using the identity:~(-67)
we get:~x = -(x + 1)~(-67) = -(-67 + 1) = -(-66) = 66 - ASCII value
66corresponds to the character'B'.
Therefore, the output is:
B
- A.
A❌
Incorrect. ASCII value of'A'is65. - B.
B✅
Correct.~(-67)evaluates to66, whose ASCII character is'B'. - C.
C❌
Incorrect.'C'has ASCII value67. - D.
D❌
Incorrect. ASCII value of'D'is68.
Exam Fact:
The bitwise NOT operator ~ in C inverts every bit of its operand. For signed integers, it satisfies the identity ~x = -(x + 1). Character constants such as 'A' and 'C' are treated as their integer ASCII values in expressions.
What will be the output of the program ?
#include<stdio.h>
int main()
{
FILE *fp;
unsigned char ch;
/* file 'abc.c' contains "This is LearnFrenzy " */
fp = fopen("abc.c", "r");
if(fp == NULL)
{
printf("Unable to open file");
exit(1);
}
while((ch = getc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
printf("\n", ch);
return 0;
}
Correct Answer: C. Infinite loop ✅
Consider the following C program:
#include<stdio.h>
int main()
{
FILE *fp;
unsigned char ch;
/* file 'abc.c' contains "This is LearnFrenzy " */
fp = fopen("abc.c", "r");
if(fp == NULL)
{
printf("Unable to open file");
exit(1);
}
while((ch = getc(fp)) != EOF)
printf("%c", ch);
fclose(fp);
printf("\n", ch);
return 0;
}
The important point is that getc() returns an int, not a char. It returns:
- The next character (as an
unsigned charconverted toint), or EOF(typically-1) when the end of the file is reached.
In the program, the return value of getc() is stored in an unsigned char:
unsigned char ch;
while((ch = getc(fp)) != EOF)
When getc() reaches the end of the file, it returns EOF (-1). Assigning -1 to an unsigned char converts it to 255 (assuming an 8-bit unsigned char).
The comparison then becomes:
255 != -1
which is always true. Therefore, the loop never terminates and continues printing indefinitely, resulting in an infinite loop.
The correct way is to use an int variable:
int ch;
while((ch = getc(fp)) != EOF)
printf("%c", ch);
- A.
This is LearnFrenzy❌
Incorrect. The program does not terminate correctly becauseEOFis never detected. - B.
This is❌
Incorrect. The entire file is read before the problem occurs atEOF. - C.
Infinite loop✅
Correct. Storing the return value ofgetc()in anunsigned charprevents proper detection ofEOF. - D.
Error❌
Incorrect. The program compiles successfully; the issue is a logical error that causes an infinite loop.
Exam Fact:
Always store the return value of getc(), fgetc(), or getchar() in an int, not a char. This allows the special value EOF to be distinguished from valid character values.
What will be the output of the program ?
#include<stdio.h>
int main()
{
char *p;
p = "%d\n";
p++;
p++;
printf(p - 2, 23);
return 0;
}
Correct Answer: B. 23 ✅
Consider the following C program:
#include<stdio.h>
int main()
{
char *p;
p = "%d\n";
p++;
p++;
printf(p - 2, 23);
return 0;
}
Let's trace the execution step by step.
Initially, p points to the string:
"%d\n"
Index: 0 1 2 3
'%' 'd' '\n' '\0'
- Initially:
p ----> '%' - After the first
p++:p ----> 'd' - After the second
p++:p ----> '\n' - Now:
moves the pointer back two positions, so it again points to the beginning of the string:p - 2"%d\n"
Therefore, the statement:
printf(p - 2, 23);
is equivalent to:
printf("%d\n", 23);
Hence, the output is:
23
- A.
21❌
Incorrect. The value passed toprintf()is23. - B.
23✅
Correct. After moving the pointer back withp - 2, the original format string"%d\n"is used. - C.
Error❌
Incorrect. Pointer arithmetic on a string literal is valid as long as the pointer remains within the string bounds. - D.
No output❌
Incorrect. The program successfully prints the integer value.
Exam Fact:
Pointer arithmetic on strings does not modify the string itself—it only changes the pointer's position. The expression p - n moves the pointer back by n characters. As long as the resulting pointer points within the same string object, it can safely be used.
What will be the output of the program ?
#include<stdio.h>
int main()
{
FILE *ptr;
char i;
ptr = fopen("myfile.c", "r");
while((i = fgetc(ptr)) != NULL)
printf("%c", i);
return 0;
}
Correct Answer: C. Infinite loop ✅
Consider the following C program:
#include<stdio.h>
int main()
{
FILE *ptr;
char i;
ptr = fopen("myfile.c", "r");
while((i = fgetc(ptr)) != NULL)
printf("%c", i);
return 0;
}
The function fgetc() returns an int, not a char. It returns:
- The next character from the file (converted to
int), or EOF(typically-1) when the end of the file is reached.
The program has two mistakes:
- The return value of
fgetc()is stored in acharinstead of anint. - It compares the result with
NULL(which is0) instead ofEOF.
When the end of the file is reached:
fgetc(ptr) → EOF (-1)
The value -1 is assigned to i. Since the loop checks:
(i != NULL)
it becomes:
-1 != 0
which is true. Therefore, the loop never terminates and continues calling fgetc() even after reaching the end of the file, resulting in an infinite loop.
The correct implementation is:
int i;
while((i = fgetc(ptr)) != EOF)
printf("%c", i);
- A. Print the contents of file
"myfile.c"❌
Incorrect. The loop does not stop correctly at the end of the file. - B. Print the contents of file
"myfile.c"uptoNULLcharacter ❌
Incorrect. Text files are not terminated by aNULLcharacter, andfgetc()signals end-of-file usingEOF. - C. Infinite loop ✅
Correct. The program compares againstNULLinstead ofEOFand stores the return value in achar, so the end-of-file condition is never detected properly. - D. Error in program ❌
Incorrect. The program compiles successfully, but it contains a logical error.
Exam Fact:
Always store the return value of fgetc(), getc(), or getchar() in an int and compare it with EOF. Never compare the result with NULL, because NULL is a null pointer constant, whereas EOF is the end-of-file indicator.
What will be the output of the program ?
#include<stdio.h>
int main()
{
printf("%%%%\n");
return 0;
}
Correct Answer: B. %% ✅
Consider the following C program:
#include<stdio.h>
int main()
{
printf("%%%%\n");
return 0;
}
In printf(), the percent sign (%) is used to introduce a format specifier. To print a literal percent sign, you must use:
%%
The format string contains:
%%%%
This is interpreted as two consecutive %% sequences:
- First
%%prints one%. - Second
%%prints another%.
Therefore, the output is:
%%
- A.
%%%%%❌
Incorrect. Each pair of%%prints only one percent sign. - B.
%%✅
Correct. Four percent signs in the format string produce two literal percent signs. - C.
No output❌
Incorrect. The program prints two percent signs followed by a newline. - D.
Error❌
Incorrect.%%is the valid escape sequence for printing a literal percent sign inprintf().
Exam Fact:
In printf(), use %% to print a literal percent sign (%). Every pair of %% in the format string produces a single % in the output.