Complete C Programming Guide Employment
Complete C Programming Guide Employment
PU-CCC
Complete C Guide for Placement
Structure of C Program:
This is a simple C program that calculates the sum of two numbers and displays the result. C
programs can vary in complexity, but they all follow a similar structure with a main function
as the starting point for program execution.
Example:
#include <stdio.h> // This line is called as preprocessor directives which includes necessary libraries
int main()
{
// Declare and initialize variables
return 0;
}
Explanation:
1. The preprocessor command #include <stdio.h> instructs the C compiler to include the
standard input/output library. Functions like printf and scanf, which are necessary for input and
output operations in C, are included in this library.
2. int main() {
This marks the start of a C program's main function, which is its entry point. This is where the
program execution begins.
3. Declaration and Initialization of Variables:
The required variables are declared and initialised in this section. In this example, we initialise
num1 and num2 with the numbers 10 and 20 respectively, after declaring them to be integers.
In order to store the addition's result, we additionally declare the sum variable.
4. Operations:
In this example, we perform an addition operation, adding num1 and num2, and store the result
in the sum variable.
5. printf("The sum of %d and %d is %d\n", num1, num2, sum);
This line uses the printf function to display the result on the console. It prints the values of
num1, num2, and sum using format specifiers %d to represent integers.
6. return 0;
This line indicates the end of the main function. It returns an exit status of 0 to the operating
system, indicating that the program executed successfully.
Note: In C, a return value of 0 typically means success, while a non-zero value can indicate
an error or abnormal termination.
When the return statement is used in a C program with a value of 1, it usually means that
an error or other abnormal termination has occurred. Success is typically indicated by a
return value of 0, while failure or an error condition is typically signalled by a return
value of 1.
Example:
In this program, we attempt to perform division by zero, which is not allowed in mathematics.
Therefore, we check if num2 is equal to zero, and if it is, we print an error message and use
return 1; to indicate that an error has occurred. If num2 is not zero, the program continues to
calculate and display the result of the division. The return 0; at the end indicates that the
program executed successfully.
#include <stdio.h>
int main()
{
int num1 = 5;
int num2 = 0;
int result;
if (num2 == 0)
{
printf("Division by zero is not allowed.\n");
return 1; // Indicates an error condition
}
result = num1 / num2;
printf("The result of the division is: %d\n", result);
return 0; // Indicates success
}
When you run this program and provide num2 with the value of 0, it will output the error
message and return 1 to indicate an error condition. If you provide a non-zero value for num2,
it will calculate and display the result of the division and return 0 to indicate success.
Explanation:
void rohini(): This is the definition of a function named "rohini," which would be equivalent
to the main function due to the macro substitution. The function has a void return type, which
doesn't return any value.
The code effectively renames the main function to "rohini" using a preprocessor macro. When
this program is executed, it will run the "rohini" function, which behaves like the main function
and displays the "Welcome to Presidency University" message.
Example 2:
#include <stdio.h>
#define rename(a,b,c,d) a##b##c##d
#define rohini rename(m,a,i,n)
void rohini()
{
printf("Hello Everyone\n");
printf("Welcome");
}
The above code defines macros and creates a custom function name by concatenating macros
using the C preprocessor. Let's examine the code and elucidate its functions:
Explanation:
#include <stdio.h> // Include the standard input/output library.
// Define a macro 'rename' that concatenates its arguments.
#define rename(a,b,c,d) a##b##c##d
// Define a function 'rohini' using the 'rename' macro.
#define rohini rename(m,a,i,n)
Explanation:
1. #include :
This line includes the standard input/output library, which is necessary for input and output
operations in C programs.
2. #define x 2:
This line defines a preprocessor macro named 'x' with the value 2. This macro allows us to
replace the token 'x' with the value '2' throughout the program. So, anywhere 'x' is used, it is
effectively replaced with '2'.
3. int main():
This line defines the main function, which serves as the entry point of the program.
4. int i; :
This declares an integer variable 'i' without initializing it.
i = x * x * x; - This line calculates the cube of 'x' (2 * 2 * 2) and assigns the result (8) to the
variable 'i'.
5. printf("%d", i); :
This uses the printf function to print the value of 'i' (which is 8) to the console. The format
specifier %d is used to indicate that an integer is being printed.
6. return 0; :
This line returns the value 0 to indicate successful program execution to the operating system.
In C programming, a return value of 0 typically means that the program has executed without
errors.
Example 4:
#include <stdio.h> // Include the standard input/output library.
#define square(x) x*x // Define a preprocessor macro 'square' for squaring a number.
int main()
i = 64 / square(4); // Perform the operation 64 / square(4) and store the result in 'i'.
Explanation:
1. #include :
This line includes the standard input/output library, which is necessary for input and output
operations in C programs.
2. #define square(x) x*x:
This line defines a preprocessor macro named 'square' that calculates the square of a number.
However, this macro is defined without parentheses around 'x'.
3. int main():
This line defines the main function, which serves as the entry point of the program.
4. int i; :
This declares an integer variable 'i' without initializing it.
5. i = 64 / square(4); :
This line performs the operation 64 divided by the result of the 'square' macro with the
argument '4.' The 'square(4)' macro expands to '4 * 4', so it becomes 64 / 4 * 4, which is 16 *
4, resulting in 'i' being assigned the value 64.
6. printf("%d", i); :
This uses the printf function to print the value of 'i' (which is 64) to the console. The format
specifier %d is used to indicate that an integer is being printed.
7. return 0; : This line returns the value 0 to indicate successful program execution to the
operating system. In C programming, a return value of 0 typically means that the program has
executed without errors.
Example 5:
#include <stdio.h> // Include the standard input/output library.
#define square(x) (x*x) // Define a preprocessor macro 'square' for squaring a number.
int main()
{
int i; // Declare an integer variable 'i'.
i = 64 / square(4); // Perform the operation 64 / square(4) and store the result in 'i'.
Explanation:
1. #include :
This line includes the standard input/output library, which is necessary for input and output
operations in C programs.
This line defines a preprocessor macro named 'square' that calculates the square of a number.
However, this macro is defined with parentheses around 'x'.
3. int main():
This line defines the main function, which serves as the entry point of the program.
4. int i; :
This declares an integer variable 'i' without initializing it.
5. i = 64 / square(4); :
This line performs the operation 64 divided by the result of the 'square' macro with the
argument '4.' The 'square(4)' macro expands to '4 * 4', so it becomes 64 / 4 * 4, which is 64 /
16, resulting in 'i' being assigned the value 4.
6. printf("%d", i); :
This uses the printf function to print the value of 'i' (which is 4) to the console. The format
specifier %d is used to indicate that an integer is being printed.
7. return 0; : This line returns the value 0 to indicate successful program execution to the
operating system. In C programming, a return value of 0 typically means that the program has
executed without errors.
Example 6:
This C code is a little strange since it defines a preprocessor macro for the function clrscr() that
just expands to 100 instead of clearing the screen.
#include <stdio.h> // Include the standard input/output library.
#define clrscr() 100 // Define a preprocessor macro 'clrscr' that expands to 100.
int main()
{
clrscr(); // Calls the 'clrscr' macro, which expands to 100 but doesn't perform any screen clearing.
printf("%d\n", clrscr()); // Prints the value of the 'clrscr' macro, which is 100.
return 0; // Return 0 to indicate successful program execution.
}
Explanation:
1. #include :
This line includes the standard input/output library, which is necessary for input and output
operations in C programs.
2. #define clrscr() 100:
This line defines a preprocessor macro named 'clrscr' that doesn't perform any screen-clearing
action but expands to the constant value 100.
3. int main():
This line defines the main function, which serves as the entry point of the program.
4. clrscr(); :
This line "calls" the clrscr macro, but the macro itself doesn't execute any code. It merely
expands to the value 100, which is effectively ignored in this context.
5. printf("%d\n", clrscr()); :
This line uses the printf function to print the value of the clrscr macro (which is 100) to the
console.
6. return 0; :
This line returns the value 0 to indicate successful program execution to the operating system.
In C programming, a return value of 0 typically means that the program has executed without
errors.
Example 7:
The code you provided is not a valid C program, as it contains a statement 100; outside of any
function or block. In C, statements need to be inside functions or code blocks.
#include <stdio.h> // Include the standard input/output library.
100; // This statement doesn't belong to any function or code block.
int main()
{
printf("%d\n", 100); // Print the value 100.
return 0; // Return 0 to indicate successful program execution.
}
Explanation:
1. #include :
This line includes the standard input/output library, which is necessary for input and output
operations in C programs.
2. 100; :
The statement 100; appears outside of any function or code block. In C, statements like this
should be inside a function or code block. It doesn't have any meaningful purpose in the code
and will be ignored by the C compiler.
3. int main() { ... }:
This part defines the main function, which serves as the entry point of the program. Inside the
main function, it contains a printf statement to print the value 100 and a return statement to
indicate a successful program execution with a return value of 0.
Note: If you want to create a valid C program that prints the value 100, you should place the
100; statement within a function or code block, such as inside the main function. Here's an
example of a valid C program:
#include <stdio.h>
int main()
{
100; // A statement inside the main function (though it doesn't serve any meaningful purpose).
printf("%d\n", 100); // Print the value 100.
return 0; // Return 0 to indicate successful program execution.
}
Example 8:
The provided C code prints the memory address of the main function. Here's a breakdown of
the code and an explanation of what it does:
Explanation:
1. #include :
This line includes the standard input/output library, which is necessary for input and output
operations in C programs.
2. int main() { ... }:
This part defines the main function, which serves as the entry point of the program.
3. printf("%p", main); :
The printf function is used to print the memory address of the main function. The format
specifier %p is used to indicate that a pointer is being printed. In this case, the pointer being
printed is the memory address of the main function.
4. return 0; :
This line returns the value 0 to indicate successful program execution to the operating system.
In C programming, a return value of 0 typically means that the program has executed without
errors.
When we run this program, it will print the memory address of the main function in a
hexadecimal format. The exact memory address will vary depending on the system, but it will
be the address where the main function is loaded in memory.
Example 9:
This C code defines a preprocessor macro x and then attempts to print the value of x within the
main function. However, there is a subtle issue with the macro definition that can lead to
unexpected results. Let's break down the code and explain what it does:
Explanation:
1. #include :
This line includes the standard input/output library, which is necessary for input and output
operations in C programs.
2. #define x 10; :
This line defines a preprocessor macro named 'x' with the value 10;. Notice that a semicolon
(;) is included in the macro definition. This can lead to unexpected behaviour, as the semicolon
is not part of the numeric value.
3. int main():
This line defines the main function, which serves as the entry point of the program.
4. printf("%d", x); :
This line attempts to print the value of the x macro. However, due to the semicolon in the macro
definition, it effectively expands to 10;, which is not a valid integer.
5. return 0; :
This line returns the value 0 to indicate successful program execution to the operating system.
In C programming, a return value of 0 typically means that the program has executed without
errors.
When you run this program, it will produce an error or unexpected output because of the
semicolon in the macro definition. To fix this issue, you should define the x macro without the
semicolon like this:
Placement Questions:
1. Why is a preprocessor directive used in C, and what does it mean?
Preprocessor directives are commands in C that are carried out by the C preprocessor prior to
the start of the actual code compilation. In order to get the code ready for compilation, it is used
for preprocessing operations such as include header files, defining macros, and conditional
compilation.
2. What distinguishes #include "file.h" from #include <file.h> in C?
To include standard library header files, use the #include <file.h> directive; to include user-
defined or project-specific header files, use the #include "file.h" directive. System or library
headers are normally enclosed in angle brackets <>, and user-defined headers are enclosed in
double quotations " ".
3. What does C's #define directive serve as? Give an instance.
A macro is a symbolic name for a chunk of code in C that is created using the #define directive.
5. What does conditional compilation use the #ifdef, #ifndef, #else, and #endif
directives for?
#ifdef verifies whether a macro is defined.
#ifndef verifies whether a macro is defined.
In the event that the condition in #ifdef or #ifndef is not met, #else designates an other code
block.
A conditional block ends with the #endif symbol.
6. Describe how C uses the #pragma directive. Give an instance of when it might be
applied.
For directives that are particular to a compiler, use the #pragma directive. Disabling a particular
compiler warning is one example:
8. How can you include the contents of one file in another file using preprocessor
directives? Provide an example.
We can include the contents of one file in another using the #include directive. For example,
to include "file.h":
9. Discuss the significance of the #error and #warning directives in C. When and why
are they used?
#error is used to generate a compilation error message with a custom error message.
#warning is used to generate a compilation warning message. They are typically used for
conditional compilation or to provide important messages to the programmer.
11. Explain the concept of macro functions in C. How do you create and use them?
Macro functions are defined using macros and allow us to define code snippets that act like
functions. They are created using the #define directive and are typically used for simple code
substitutions. For example:
12. What are the advantages and disadvantages of using preprocessor directives in C
code?
Advantages: Preprocessor directives allow for code reuse, conditional compilation, and
abstraction using macros. They enable platform-independent code and configuration
management.
Disadvantages: Preprocessor macros can make code harder to read, lead to potential errors,
and may not provide type safety. They can also hinder code debugging and maintenance.
Here are some Graduate Aptitude Test in Engineering (GATE) questions related to
preprocessor directives in C. These questions are in a multiple-choice format, which is a
common format used in GATE exams. Please note that the answers are provided as well.
Question 1: Which of the following is true about preprocessor directives in C?
A. They are executed during runtime.
B. They are used for defining and invoking functions.
C. They are executed before the actual compilation of the code.
D. They are used for declaring variables.
Answer: C. They are executed before the actual compilation of the code.
A. 5
B. 25
C. 15
D. 11
Answer: D. 11
A. 10000
B. 100
C. 200
D. 10
Answer: A. 10000
Question 15: Which preprocessor directive is used to include the contents of a header file
in a C program?
A. #define
B. #include
C. #pragma
D. #ifdef
Answer: B. #include
Question 16: What is the significance of using #ifndef and #endif in conditional
compilation?
A. #ifndef marks the end of a conditional block.
B. #ifndef checks if a macro is not defined, and #endif marks the end of a conditional block.
C. #ifndef is used for defining macros, and #endif is used for including header files.
D. #ifndef is used for declaring variables, and #endif is used for conditional execution.
Answer: B. #ifndef checks if a macro is not defined, and #endif marks the end of a
conditional block.
A. 2
B. 4
C. 8
D. 16
Answer: D. 16
Question 18: In C, what is the purpose of the #elif directive in conditional compilation?
A. To generate a compilation error.
B. To define a new macro.
C. To specify an alternative code block if the condition in #ifdef is not met.
D. To check another condition if the previous condition is false.
Answer: D. To check another condition if the previous condition is false.
Question 19: In C programming, what is the role of the #elif directive in conditional
compilation? How does it differ from #if and #else?
Answer: The #elif directive allows you to specify an alternative condition if the previous #if
or #elif condition is false. It is used for chaining conditions in conditional compilation. The #if
directive checks a condition, and if it is true, the code block is included. If it is false, the #elif
directive is evaluated. If it is also false, the #else directive is used as a fallback.
Question 20: In C programming, when is the #error directive commonly used, and what
is its purpose?
Answer: The #error directive is typically used in debugging or to enforce specific constraints
during the compilation process. It generates a compilation error with a custom error message
when the condition specified is met. It ensures that certain conditions, such as a required macro
definition, are satisfied during compilation.
Question 22: How can preprocessor directives be used for code optimization and
performance improvement in C programs? Provide an example where preprocessor
directives are employed for optimization.
Answer: Preprocessor directives can be used to conditionally include optimized code sections,
depending on whether optimization is needed. For example, in a matrix multiplication routine,
a preprocessor directive may be used to choose between a straightforward implementation for
correctness during debugging and a highly optimized implementation for performance in the
final release.
Question 23: What are the best practices for using preprocessor directives in a large-scale
software project to ensure code maintainability and readability?
Answer: Best practices for using preprocessor directives in large-scale projects include:
• Limiting the use of preprocessor directives to situations where they are necessary.
• Providing clear and concise comments explaining the purpose of macros and
conditional compilation.
• Maintaining coding standards and conventions for consistent use of directives.
• Avoiding complex and nested conditionals that can reduce code readability.
• Using macros and directives for well-defined, non-trivial tasks that improve code
clarity or maintainability.
Question 24: How can conditional compilation and preprocessor directives be beneficial
when developing software that needs to accommodate different product versions with
varying features?
Answer: Conditional compilation allows for the inclusion or exclusion of specific code
sections based on the product version or feature set. By defining feature-related macros or
version macros, different product versions can be built from a single codebase. This approach
streamlines maintenance and minimizes code duplication.
Question 25: Explain the impact of incorrect usage of preprocessor directives on code
maintainability and debugging. Provide an example illustrating these consequences.
Answer: Incorrect usage of preprocessor directives can lead to code that is difficult to maintain
and debug. For example, excessive use of macros can obscure the meaning of the code, making
it hard to understand. Additionally, conditional compilation can result in code paths that are
challenging to test and debug. Clear documentation and sensible use of directives are essential
to mitigate these issues.
Question 27:
Consider the following C code:
Answer: C) 64 or 49 (ambiguous)
Explanation: The macro ADD(x, y) expands to x + y, and when used as ADD(a, b) * ADD(a,
b), it results in either (a + b) * (a + b), which is 64, or a + (b * a) + b, which is 49. The output
is ambiguous and depends on the order of evaluation chosen by the compiler.
Question 28:
Which of the following preprocessor directives can be used to create a string of a macro
argument?
A) #
B) ##
C) #if
D) #define
Answer: A) #
Explanation: The # operator is used for stringizing a macro argument, converting it into a
string.
Question 29:
Consider the following code snippet:
Question 30:
Which preprocessor directive is used to generate a compilation error with a custom error
message in C?
A) #if
B) #error
C) #ifdef
D) #define
Answer: B) #error
Explanation: The #error directive is used to generate a compilation error with a custom error
message when a certain condition is met.
Scenario 1:
You are developing a C program that needs to run on both Windows and Linux
platforms. However, there are certain platform-specific functions that you want to
include in the code. How would you use preprocessor directives to manage this situation?
Question: In the context of cross-platform development, describe how you would use
preprocessor directives to include platform-specific code or configurations in your C program.
Provide an example to illustrate your approach.
Explanation: In this scenario, you would use preprocessor directives such as #ifdef, #ifndef,
and #endif to conditionally include or exclude platform-specific code. For example, you might
use #ifdef to check if the code is being compiled on Windows and include Windows-specific
code, while the Linux version would include different code.
Scenario 2:
You are working on a large-scale software project with a team of developers. The project
involves several configuration options that need to be controlled using preprocessor
directives. How would you ensure that the use of preprocessor directives is consistent and
well-documented across the project?
Question: In a large-scale software project where multiple developers are working with
preprocessor directives to control configuration options, what strategies would you employ to
maintain consistency, readability, and documentation of these directives?
Explanation: In a team-based project, consistency and documentation are crucial. You might
use coding standards, code reviews, and documentation practices to ensure that preprocessor
directives are used consistently, commented properly, and that their purpose is well-
documented.
Scenario 3:
You are tasked with optimizing a performance-critical part of your C program, which
involves two different algorithms: one for debugging purposes and one for the final
release. You want to use preprocessor directives to select the appropriate algorithm at
compile time.
Question: How would you use preprocessor directives to conditionally include optimized code
in your C program, depending on whether it is a debug build or a release build? Provide an
example of how you would structure your code to achieve this.
Explanation: Preprocessor directives like #ifdef and #ifndef can be used to conditionally
include or exclude code sections based on whether it's a debug or release build. You can use
macros to control which code is compiled, making it possible to include debugging code during
development and optimized code in the final release.
Scenario 4:
You are tasked with developing a library that will be used by multiple clients. Your
library has several configurable features that can be enabled or disabled using
preprocessor directives. Clients may have different requirements for these features.
Question: Explain how you would design and document your library to allow clients to
configure features using preprocessor directives, accommodating different client needs while
maintaining the library's modularity and reusability.
Explanation: In this scenario, you would design your library to expose preprocessor macro-
options that clients can customize. Clear documentation would guide clients on how to
configure these options to meet their specific requirements while ensuring the library's
modularity and reusability.
26. typedef: Used to create custom data type names, which can make code more readable
and maintainable.
27. union: Similar to a struct, but it allows variables to share the same memory location.
28. unsigned: Specifies that a data type can hold only non-negative values.
29. void: A data type used to indicate that a function does not return a value or that a pointer
is not associated with a specific data type.
30. volatile: Suggests that a variable's value can change at any time, even without any
action in the code.
These keywords are an integral part of C's syntax and serve specific roles in the language's
structure. It's important to use them as intended and not for other purposes to avoid errors and
ensure proper code execution.
8. Consistency: Adhering to naming conventions and best practices in your code helps
improve code quality and collaboration. Keywords typically follow a convention of being in
uppercase, and you should do the same for consistency.
Example 1:
This program attempts to use a C keyword, "break," as a variable name. In C, keywords are
reserved words that have special meanings and predefined functionality, and they cannot be
used for other purposes, such as naming variables.
#include <stdio.h>
int main()
{
int break = 100;
printf("The value of BREAK = %d ",break);
return 0;
}
Explanation:
int break = 100; :
This line declares a variable named "break" of type int and initializes it with the value 100. The
problem with this line is that "break" is a reserved keyword in C, used to exit loops or switch
statements prematurely, and cannot be used as a variable name.
To fix this code and make it valid, you should choose a different variable name that is not a C
keyword or reserved word. Here's an example of a corrected version:
#include <stdio.h>
int main()
{
int BREAK = 100;
printf("The value of BREAK = %d ",BREAK);
return 0;
}
Explanation:
This code is a valid C code because it doesn't use lowercase "break" as an identifier. Instead, it
uses "BREAK," which is an acceptable variable name in C because C is case-sensitive, and
"BREAK" and "break" are treated as distinct identifiers. Here's an explanation of the code:
#include :
This line includes the standard input/output library, which provides functions like printf for
input and output operations.
int main():
This is the beginning of the main function, which is the entry point of a C program. It returns
an integer value, typically 0 for successful execution.
7. What does the "static" keyword do in C, and how is it different from global
variables?
The "static" keyword is used to limit the scope of a variable or function to the current file. It is
different from global variables, which are accessible from other files. "Static" variables retain
their values between function calls.
8. Explain the role of the "return" keyword in C functions.
The "return" keyword is used in functions to exit the function and return a value to the caller.
It can also be used to exit a function without returning a value when the function has a void
return type.
9. What is the purpose of the "break" keyword in C? Provide an example of how it
is used in a loop.
The "break" keyword is used to prematurely exit from a loop. It is often used in conditional
statements to terminate the loop when a certain condition is met. For example:
for (int i = 0; i < 10; i++)
{
if (i == 6) {
break; // Exit the loop when i equals 6
}
// ...
}
10. How does the "switch" statement work, and what role does the "case" keyword
play within it?
The "switch" statement is used for multi-branching in C. The "case" keyword is used to define
individual cases or branches within the "switch" statement. Each "case" represents a specific
value or condition, and the code associated with the matching "case" is executed.
11. What does the "volatile" keyword mean in C, and when is it typically used?
The "volatile" keyword is used to indicate that a variable's value can change at any time, even
without any action in the code. It is often used for variables that are modified by hardware or
external factors, such as memory-mapped I/O registers.
12. Describe the usage of the "enum" keyword in C and provide an example of how it
can be used to define constants.
The "enum" keyword is used to define an enumeration, which is a user-defined data type
consisting of named integer constants. For example:
enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
13. Explain the "typedef" keyword in C and its role in creating custom data type
names.
The "typedef" keyword is used to create custom data type names, making code more readable
and maintainable. It allows you to define an alias for an existing data type. For example:
14. Differentiate between "auto" and "register" keywords in C and their impact on
variable storage.
The "auto" keyword is a default storage class for local variables. It is typically unnecessary to
specify "auto" because local variables are automatically considered "auto."
The "register" keyword suggests that a variable should be stored in a CPU register for faster
access. However, it is a hint to the compiler and may not have a significant impact on modern
compilers.
15. What is the "void" keyword used for in C, and when is it commonly used in
function declarations?
The "void" keyword is used to indicate that a function does not return a value or that a pointer
is not associated with a specific data type. It is commonly used in function declarations when
a function does not return any value.
16. Define the "const" and "volatile" keywords and explain how they are different
from each other in C.
The "const" keyword is used to declare constants, indicating that a variable's value cannot
change after initialization.
The "volatile" keyword is used to specify that a variable's value can change at any time, even
without any action in the code. These two keywords are essentially opposites.
17. Discuss the usage of the "sizeof" operator and the "sizeof" keyword in C. How are
they different?
The "sizeof" operator is used to determine the size (in bytes) of a data type or an object. It is
used in expressions to calculate the size of data.
The "sizeof" keyword is not a recognized keyword in C; "sizeof" is an operator. It is used as
"sizeof(type)" to get the size of a type or an object of that type.
18. Explain the concept of scope in C and how the "extern" keyword is used in
managing variable scope.
Scope in C refers to the region of the code where a variable or function is accessible. The
"extern" keyword is used to declare a variable or function that is defined in another file,
allowing it to be used in the current file.
19. What is the role of the "default" keyword in a C "switch" statement, and when is
it executed?
The "default" keyword is used in a "switch" statement to specify the code that should be
executed when none of the "case" values match the value being switched. It acts as a default
branch and is executed when no other "case" matches the value.
20. Give an example of how the "union" keyword is used in C and explain its purpose
in data structure design.
The "union" keyword is used to define a user-defined data structure that allows multiple
variables to share the same memory location. It is often used when you need to store different
types of data in the same memory space. For example:
union MyUnion
{
int intValue;
float floatValue;
char stringValue[10];
};
In this example, the union "MyUnion" can hold either an integer, a floating-point value, or a
string, but only one at a time, sharing the same memory space.
----------------------------------------------------------------------------------------------------------------
6. Match the C keyword on the left with its description on the right.
Keywords:
2. while
3. break
4. return
5. float
Descriptions:
A. Used to exit a loop prematurely.
B. Used to specify the data type of a floating-point number.
C. Used to repeat a block of code as long as a condition is true.
D. Used to exit a function and return a value.
Correct Matching:
1-C, 2-A, 3-D, 4-B
----------------------------------------------------------------------------------------------------------------
7. Which keyword is used to define a macro in C?
A. define
B. macro
C. #define
D. defmacro
Correct Answer: C - #define
----------------------------------------------------------------------------------------------------------------
8. Identify the Error:
Identify the error in the following C code:
#include <stdio.h>
int main()
{
int for = 5;
printf("%d\n", for);
return 0;
}
A. The usage of for as a variable name is not allowed.
B. The printf function is incorrectly used.
C. There are missing parentheses in the printf statement.
D. There is no error in the code.
Correct Answer: A - The usage of for as a variable name is not allowed.
Data Types in C:
In C programming, data types are used to specify the type of data that a variable can hold.
Data types determine the size and format of values that can be stored in variables.
C provides several built-in data types, which can be categorized into the following primary
categories:
Basic Data Types:
int:
Used to declare integer variables. Typically, it's either 2 or 4 bytes in size, depending on the
system.
char:
Used to declare character variables. It's typically 1 byte in size.
float:
Used to declare floating-point variables (single-precision). It's typically 4 bytes in size.
double: Used to declare double-precision floating-point variables. It's typically 8 bytes in size.
Here are some common C data types along with their typical sizes and ranges, along with
examples to illustrate their usage:
1.
int Data Type:
Size: Typically 2 or 4 bytes (16 or 32 bits, respectively).
Range: -32,768 to 32,767 for a 16-bit int, and -2,147,483,648 to 2,147,483,647 for a 32-bit int.
2.
char Data Type:
Size: Typically 1 byte (8 bits).
Range: -128 to 127 for signed char or 0 to 255 for unsigned char.
3.
float Data Type:
Size: Typically 4 bytes (32 bits).
Range: Approximately ±3.4 x 10^38, with 6 decimal places of precision.
4.
double Data Type:
Size: Typically 8 bytes (64 bits).
Range: Approximately ±1.7 x 10^308, with 15 decimal places of precision.
5.
short Data Type:
Size: Typically 2 bytes (16 bits).
Range: -32,768 to 32,767.
6.
long Data Type:
Size: Typically 4 bytes (32 bits) or 8 bytes (64 bits, long long).
Range: -2,147,483,648 to 2,147,483,647 for a 32-bit long, or a much larger range for a 64-bit
long.
7.
unsigned Data Types:
unsigned can be used with int, char, short, and long to represent non-negative values only.
Format Specifiers:
Example 1:
This code is a simple C program that includes the necessary library, declares an integer
variable, prints a message containing the value of the integer variable, and then returns 0 to
signify a successful program execution.
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
int variable = 100; // Declare an integer variable named 'variable' and initialize it with the value 100.
// Use the printf function to print a message to the console. The format specifier %d is a placeholder for an integer value.
Example 2:
The provided C code is a simple program that demonstrates integer overflow and underflow
using the int data type, along with comments explaining each part of the code:
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
int max = 2147483647; // Declare an integer variable and initialize it with the maximum value an 'int' can hold.
int min = -2147483648; // Declare an integer variable and initialize it with the minimum value an 'int' can hold.
printf("Maximum int value: %d\n", max); // Print the maximum 'int' value.
printf("Minimum int value: %d\n", min); // Print the minimum 'int' value.
max = max + 1; // Attempt to exceed the maximum 'int' value, causing an overflow.
min = min - 1; // Attempt to exceed the minimum 'int' value, causing an underflow.
printf("Overflowed int value: %d\n", max); // Print the result of overflow.
printf("Underflowed int value: %d\n", min); // Print the result of underflow.
return 0; // Return 0 to indicate successful program execution.
}
Explanation:
• After attempting to exceed the int data type's range:
• max (previously set to 2147483647) is incremented by 1, causing an overflow. As a
result, it wraps around and becomes the minimum value that an int can represent, which
is -2147483648.
• min (previously set to -2147483648) is decremented by 1, causing an underflow. It
wraps around and becomes the maximum value that an int can represent, which is
2147483647.
• Explanation of Overflow and Underflow:
• In both cases, when the value exceeds the range defined by the int data type, it "wraps
around" due to the way binary representation and two's complement arithmetic work.
This behavior is a fundamental characteristic of fixed-size integer data types in most
programming languages, including C.
• So, the program demonstrates that when you attempt to store a value in an int that
exceeds its range, it causes an overflow (for larger values) or an underflow (for smaller
values). The values wrap around to the opposite end of the range.
• The output of the program reflects these concepts and shows the consequences of
integer overflow and underflow in C.
Example 3:
In C, the char data type represents a single character and has a smaller range compared to the
int data type. The range of a char is typically from -128 to 127 or 0 to 255, depending on
whether it's signed or unsigned. When a char exceeds this range, it will wrap around. Here's a
C program demonstrating this behavior:
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
char max = 127; // Declare a character variable and initialize it with the maximum value (signed).
char min = -128; // Declare a character variable and initialize it with the minimum value (signed).
printf("Maximum char value (signed): %d\n", max); // Print the maximum char value (signed).
printf("Minimum char value (signed): %d\n", min); // Print the minimum char value (signed).
max = max + 1; // Attempt to exceed the maximum char value, causing an overflow.
min = min - 1; // Attempt to exceed the minimum char value, causing an underflow.
printf("Overflowed char value (signed): %d\n", max); // Print the result of overflow.
printf("Underflowed char value (signed): %d\n", min); // Print the result of underflow.
maxUnsignedChar = maxUnsignedChar + 1;
// Attempt to exceed the maximum char value (unsigned), causing it to wrap around.
Example 4:
In C, the float data type represents floating-point numbers with limited precision and a finite
range. If you try to store a value that exceeds the representable range of a float, it may result in
an overflow or underflow. Here's a C program that demonstrates how this can happen, along
with comments explaining each part of the code:
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
float maxFloat = 3.402823466e38;
// Declare a float variable and initialize it with the maximum positive value a 'float' can hold.
printf("Maximum float value: %f\n", maxFloat); // Print the maximum 'float' value.
printf("Minimum float value: %f\n", minFloat); // Print the minimum 'float' value.
maxFloat = maxFloat +1; // Attempt to exceed the maximum 'float' value, causing an overflow.
minFloat = minFloat -1; // Attempt to exceed the minimum 'float' value, causing an underflow.
Example 5:
The program prints the value of b with 11 decimal places, as specified in the format string.
Note that the value displayed (8.98765432129) has more decimal places than the original value
(8.987654321).
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
float b = 8.987654321; // Declare a floating-point variable 'b' and initialize it with the value 8.987654321.
// Use the printf function to print a message to the console with specific formatting.
// The format specifier %0.11f is used to display 'b' as a floating-point number with 11 decimal places.
Example 6:
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
double b = 8.987654321;
// Declare a double-precision floating-point variable 'b' and initialize it with the value
8.987654321.
// Use the printf function to print a message to the console with specific formatting.
// The format specifier %lf is used to display 'b' as a double-precision floating-point number.
printf("The value of b = %lf", b);
return 0; // Return 0 to indicate successful program execution.
}
Explanation:
8.987654: The value of 'b' is displayed with six decimal places, which is typical for the %lf
format specifier. The value 8.987654321 is rounded to six decimal places in the output.
The output "The value of b = 8.987654" is the formatted representation of the 'b' variable, and
it reflects the value with the precision specified by the %lf format specifier.
Placement Questions:
1.
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
char n = '\021'; // Declare a character variable 'n' and initialize it with the octal value '\021'.
// Use the printf function to print the decimal value of 'n'.
printf("%d", n);
Explanation:
char n = '\021';
In this line, a character variable named 'n' is declared and initialized. The value '\021' is an octal
escape sequence, representing a character based on its octal ASCII code. In this case, '\021'
represents the character that corresponds to the decimal value 17 in ASCII, which is a non-
printable control character (Device Control 1, or DC1).
printf("%d", n);
This line uses the printf function to print the value of 'n' as a decimal integer. The format
specifier %d is used for decimal integers. The character 'n' is promoted to an integer for the
purpose of printing.
The output is the decimal representation of the character represented by the octal escape
sequence '\021', which is the decimal value 17 in ASCII.
2.
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
void n = 100; // Declare a variable 'n' with an incorrect data type 'void' and initialize it with the value 100.
// Attempt to use an incorrect format specifier '%v' in printf to display the value of 'n'.
printf("%v", n);
return 0; // Return 0 to indicate successful program execution.
}
a. Runtime error
b. Compilation error
c. 100
d. Garbage value
Answer: b(Compilation error)
Explanation:
void n = 100;
This line is problematic. We are declaring a variable named 'n' with the data type 'void'. In C,
'void' is a special data type used for indicating that a function doesn't return a value, and it
cannot be used to declare variables like this.
printf("%v", n);
Here, we are attempting to use the format specifier %v in the printf function. However, the
format specifier %v is not a standard format specifier in C. To display the value of a variable,
we should use the appropriate format specifier based on the variable's data type (e.g., %d for
integers, %f for floating-point numbers, %c for characters).
To fix the code and correctly display the value of 'n', you should declare 'n' with the appropriate
data type (e.g., int for an integer) and use the correct format specifier in printf. Here's a
corrected example:
#include <stdio.h>
int main()
{
int n = 100; // Declare an integer variable 'n' and initialize it with the value 100.
// Use the correct format specifier '%d' to display the value of 'n'.
printf("%d", n);
return 0;
}
3.
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
void *ptr; // Declare a pointer variable 'ptr' with a 'void' data type, which can point to any data type.
int n = 1000; // Declare an integer variable 'n' and initialize it with the value 1000.
ptr = &n; // Assign the memory address of 'n' to the pointer variable 'ptr'.
// Use the printf function to print the value of 'ptr' as a memory address (in hexadecimal).
printf("%p", ptr);
return 0; // Return 0 to indicate successful program execution.
}
a. 0
b. 1000
c. Compilation error
d. Address
Answer: d(Address)
Explanation:
void *ptr;
This line declares a pointer variable named 'ptr' with a data type of 'void *'. A 'void *' pointer
is a special type of pointer that can point to objects of any data type. In this case, 'ptr' is
uninitialized.
int n = 1000;
This line declares an integer variable 'n' and initializes it with the value 1000.
ptr = &n;
This line assigns the memory address of the 'n' variable to the 'ptr' pointer. Now, 'ptr' points to
the memory location where the 'n' variable is stored.
printf("%p", ptr);
Here, the printf function is used to print the value of 'ptr' as a memory address. The format
specifier %p is used to format and display the value of 'ptr' as a hexadecimal memory address.
When we run this program, it will display the memory address where the 'n' variable is stored
in hexadecimal format. This address may vary depending on your system, but it will be a
hexadecimal number representing the memory location where 'n' resides.
4.
#include <stdio.h>
int main()
{
printf("%d\t", sizeof(5.2)); // Size of a double (floating-point)
printf("%d\t", sizeof(100)); // Size of an int (integer)
printf("%d", sizeof('B')); // Size of a char (character)
return 0;
}
a. 8 4 4
b. 2 4 1
c. 8 4 1
d. 5.2 100 B
Answer : c(8 4 1)
Explanation:
Any undefined float data type will be assigned as double by the C compiler by default. 8 4 1 is
thus produced.
sizeof(5.2):
This calculates the size (in bytes) of a double data type. On most systems, a double occupies 8
bytes of memory because it provides higher precision for floating-point numbers.
sizeof(100):
This calculates the size (in bytes) of an int data type. An int typically occupies 4 bytes of
memory on many systems.
sizeof('B'):
This calculates the size (in bytes) of a char data type. A char typically occupies 1 byte of
memory. In this case, it's displaying the size of a single character.
5.
#include <stdio.h>
int main()
{
signed a; // Declare a signed integer variable 'a'.
unsigned b; // Declare an unsigned integer variable 'b'.
a = 7u + -17 + 17u + -7; // Calculate the value of 'a'.
b = a + 1; // Calculate the value of 'b' as 'a + 1'.
if (a == b)
{
printf("%d %d", a, b); // If 'a' is equal to 'b', print them as signed integers.
}
else
{
printf("%u %u", a, b); // If 'a' is not equal to 'b', print them as unsigned integers.
}
return 0; // Return 0 to indicate successful program execution.
}
a. 0 0
b. 1 0
c. 0 1
d. Compilation error
Answer : c (0 1)
Explanation:
• a = 7u + -17 + 17u + -7;:
7u is an unsigned integer with the value 7.
-17 is a signed integer with the value -17.
17u is an unsigned integer with the value 17.
-7 is a signed integer with the value -7.
The calculation is: 7 - 17 + 17 - 7 = 0.
• b = a + 1;
• b is calculated as 0 + 1, which equals 1.
• Now, we can determine the output based on the condition in the if statement:
• Since a is equal to 0 and b is equal to 1, the if condition (a == b) is not true. Therefore,
the program will execute the code inside the else block and print the values as unsigned
integers.
6.
Which of the following data type is right in C programming?
A. long long double
B. unsigned long long int
C. long double int
D. unsigned long double
Answer : B
Explanation:
A. long long double: There is no data type called "long long double" in C.
B. unsigned long long int: This is a valid data type in C, representing an unsigned integer with
an extended range.
C. long double int: There is no data type called "long double int" in C.
D. unsigned long double: There is no data type called "unsigned long double" in C.
So, option B is the correct choice for a valid data type in C programming.
7.
Which one of the following is incorrect?
A. enum fruits = { apple, banana }f;
B. enum fruits{ apple, banana }f ;
C. enum fruits{ apple, banana };
D. enum f{ apple, banana };
Answer : A
Explanation:
The incorrect statement among the options is:
A. enum fruits = { apple, banana }f;
In C, when declaring an enumeration, we don't assign values to the enumeration members using
the equal sign (=) as shown in option A. Instead, the correct syntax for defining an enumeration
is shown in options B, C, and D.
8.
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
float a = 4.25; // Declare a float variable 'a' and initialize it with the value 4.25.
double b = 4.25; // Declare a double variable 'b' and initialize it with the value 4.25.
if (a == b)
{
printf("I Love C Programming"); // If 'a' is equal to 'b', print "I Love C Programming."
}
else
{
printf("I hate C Programming"); // If 'a' is not equal to 'b', print "I hate C Programming."
}
return 0; // Return 0 to indicate successful program execution.
}
a. I hate C Programming
b. I Love C Programming
c. Compilation error
d. Runtime error
Answer : b (I Love C Programming)
Explanation:
In this code, 'a' and 'b' have different data types (float and double), but they are initialized
with the same value (4.25). The if statement compares 'a' and 'b' for equality. Since they
have different data types, this comparison demonstrates the potential issues with comparing
floating-point numbers for equality.
In this specific case, the code will print "I Love C Programming" because the values are
equal, but this is not guaranteed for all floating-point comparisons due to the inherent
precision limitations of floating-point numbers.
9.
#include<stdio.h>
int main()
{
extern int n;
n = 10;
printf("%d", n);
return 0;
}
a. Compilation error
b. Runtime error
c. 10
d. Linker error
Answer : a (Compilation error)
Explanation:
In this code there is an issue: the use of the extern keyword for declaring a variable n
without a prior declaration. In C, the extern keyword is used to indicate that a variable is
defined in another source file, and it must be declared in that source file before it's used as
extern in another source file.
However, in this code, there is no prior declaration of the variable n, which would lead to
a compilation error. To correct this issue, we should declare n in a separate source file and
then use the extern keyword in this code. Here's an updated version of the code with
comments to explain how to use extern correctly:
// Source File 1 (declaration.c)
#include <stdio.h>
int n; // Declare the variable 'n' here.
n = 10;
This assigns the value 10 to the variable n. It assumes that n has been defined in another
source file, and this assignment will affect the value of n declared in that source file.
printf("%d", n);
It prints the value of n using the %d format specifier, which is used for integers.
In this updated code, n should be declared in a separate source file, and the two source files
need to be compiled together to produce the desired output. The output, in this case, will
be 10 because n is assigned the value 10 in the main.c source file.
10.
What will be the output?
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
char *ptr; // Declare a pointer to a character named 'ptr'.
// Use the printf function to print the sizes of the pointed data and the pointer itself.
printf("%d %d", sizeof(*ptr), sizeof(ptr));
return 0; // Return 0 to indicate successful program execution.
}
a. 1 4
b. 1 8
c. 8 1
d. 2 4
Answer: b
Explanation:
sizeof(*ptr): This calculates the size (in bytes) of the data type that 'ptr' points to, which is
a character (char). A char typically occupies 1 byte.
sizeof(ptr): This calculates the size (in bytes) of the pointer variable 'ptr' itself. The size of
a pointer depends on the architecture but is usually 4 bytes on a 32-bit system and 8 bytes
on a 64-bit system.
The output of this program will depend on system's architecture, which determines the size
of a pointer:
• On a 32-bit system, the output will be "1 4" because the size of a char is 1 byte, and
the size of a pointer is typically 4 bytes.
• On a 64-bit system, the output will be "1 8" because the size of a char is still 1 byte,
but the size of a pointer is typically 8 bytes.
11.
What is the output?
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
int n = - -5; // Declare an integer variable 'n' and initialize it with the value of "- -5."
// Use the printf function to print the value of 'n.'
printf("num = %d", n);
return 0; // Return 0 to indicate successful program execution.
}
a. -5
b. 5
c. 0
d. 1
Answer : b
Explanation:
int n = - -5;
• In this line, an integer variable 'n' is declared and initialized. The expression - -
5 may appear confusing due to the double negation. However, it's parsed as
follows:
• The first minus sign represents the unary negation operator (negating the
number 5), so it evaluates to -5.
• The second minus sign is also a unary negation operator applied to the result of
the first minus sign, so it evaluates to 5.
Therefore, n is assigned the value 5.
12.
What is the Output?
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
char n = 127; // Declare a char variable 'n' and initialize it with the value 127.
n = n + 1; // Increment the value of 'n' by 1.
printf("%d", n); // Print the value of 'n' as an integer.
return 0; // Return 0 to indicate successful program execution.
}
a. 127
b. 128
c. -128
d. -127
Answer : c
Explanation:
char n = 127;
This line declares a character variable 'n' and initializes it with the value 127. In C, a char
can hold values from -128 to 127 for a signed char or from 0 to 255 for an unsigned char.
n = n + 1;
This line increments the value of 'n' by 1. Since 'n' is a char, adding 1 to it will wrap around
if it exceeds the range of a char.
The initial value of 'n' is 127.
• When we increment 'n' by 1 with n = n + 1, it wraps around because char has a
limited range. In this case, it wraps to the minimum value for a signed char, which
is -128.
• So, the final value of 'n' is -128, and it is printed as such using the %d format
specifier.
13.
What is the Output?
#include<stdio.h>
int main()
{
int size = sizeof(volatile) + sizeof(const);
printf("%d",++size);
return 0;
}
a. 3
b. 8
c. 9
d. 5
Answer : c
Explanation:
The C Keywords volatile and const each have a size of four bytes.
int size = sizeof(volatile) + sizeof(const);
This line calculates the size of the volatile and const qualifiers using the sizeof operator and
stores the sum in the integer variable 'size'.
Therefore, size = 4 + 4 =8
Finally ++size = 9 is the output.
14.
What is the output?
#include <stdio.h> // Include the standard input/output library for using printf.
int main()
{
static int num = 6; // Declare a static integer variable 'num' and initialize it with the value 6.
Explanation:
static int num = 6;
This line declares a static integer variable 'num' and initializes it with the value 6. The static
keyword means that the variable retains its value between function calls.
if (num) { main(); }
This is a recursive call to the main function. It checks if 'num' is not zero. If 'num' is not
zero, it calls main again, effectively starting the countdown from 5 and continuing until
'num' reaches 0.
Here's the step-by-step breakdown:
• The initial call to main prints 6 and decrements 'num' to 5.
• It then calls main again with 'num' at 5, which prints 5 and decrements 'num' to 4.
• This recursive process continues until 'num' reaches 1, and each time it prints the
value of 'num' before decrementing.
Explanation:
16.
What is the Output?
#include<stdio.h>
int main()
{
typedef int num;
num num1 = 5;
printf("%d", num1);
return 0;
}
a. -5
b. 0
c. 1
d. 5
Answer : d
Explanation:
Here the program creates a user defined type num and creates a variable num1 of type num.
Hence there is no problem with the output
Explanation: Among the given options, double typically has the highest storage size as it
represents double-precision floating-point numbers and, therefore, requires more storage than
the other data types mentioned.
3. What is the range of values that can be represented by an `unsigned char` data
type in C?
A. -128 to 127
B. 0 to 255
C. -32768 to 32767
D. 0 to 65535
The correct answer is: B. 0 to 255
Explanation: An unsigned char data type in C represents values from 0 to 255, inclusive. It
can't represent negative values, and it has a range of 256 different values
4. Which of the following data types in C is not guaranteed to have a specific size
across different platforms?
A. int
B. long int
C. char
D. float
The correct answer is: D. float
Explanation: In C, the float data type is not guaranteed to have a specific size across different
platforms. The size of int, long int, and char may vary depending on the platform, but float is
more likely to have variations in size due to differences in floating-point representation.
5. What is the size (in bytes) of a `double` data type in C on most modern 64-bit
platforms?
A. 2
B. 4
C. 8
D. 16
The correct answer is: C. 8
Explanation: On most modern 64-bit platforms, a double data type in C typically has a size of
8 bytes. It is used to represent double-precision floating-point numbers.
6. In C, what is the range of values that can be represented by an `int` data type on
most modern platforms?
A. -128 to 127
B. -32,768 to 32,767
C. -2,147,483,648 to 2,147,483,647
D. -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
The correct answer is: B. -32,768 to 32,767
Explanation: On most modern platforms, an int data type in C typically has a size of 4 bytes,
and it can represent values in the range from -32,768 to 32,767 for signed integers. The actual
range may vary slightly depending on the platform and compiler but is commonly within this
range.
8. What is the size (in bytes) of a `short int` data type in C on most modern
platforms?
A. 1
B. 2
C. 4
D. 8
The correct answer is: B. 2
Explanation: On most modern platforms, a short int data type in C typically has a size of 2
bytes. It is used to represent integers with a smaller range compared to int.
11. What is the range of values that can be represented by an `unsigned short int` data
type on most modern platforms?
A. 0 to 65535
B. -32,768 to 32,767
C. -2,147,483,648 to 2,147,483,647
D. -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
The correct answer is: A. 0 to 65535
Explanation: On most modern platforms, an unsigned short int data type in C typically has a
size of 2 bytes and can represent values in the range from 0 to 65535. It is an unsigned data
type, so it cannot represent negative values.
Identifiers:
• An identifier is a symbolic name or label used in computer programming to uniquely
represent a variable, function, class, or other program elements.
• Identifiers are typically composed of letters, digits, and underscores, and they play a
crucial role in making source code more human-readable and maintainable.
• They serve as references to access and manipulate data or execute specific operations
within a program, allowing programmers to work with these elements efficiently.
• Identifiers are subject to rules and conventions that vary among programming
languages, but they generally must follow specific naming conventions and avoid
reserved words or symbols that may cause conflicts or errors in the code.
Example 1:
Here's a C program with comments explaining the code and the use of identifiers:
#include <stdio.h>
int main()
{
int a = 125; // Declare an integer variable 'a' and initialize it with the value 125.
int A = 145; // Declare another integer variable 'A' and initialize it with the value 145.
// Print the value of the variable 'a'.
printf("The number is %d ", a);
// Print the value of the variable 'A'.
printf("\nThe Number is %d ", A);
return 0;
}
Explanation:
int a = 125;
declares an integer variable named 'a' and initializes it with the value 125.
int A = 145;
declares another integer variable named 'A' and initializes it with the value 145. Note that in C,
variable names are case-sensitive, so 'a' and 'A' are treated as different identifiers.
By following these rules, we can create clear and well-structured code that is more readable
and less prone to errors. Additionally, adhering to any language-specific conventions is
important to maintain consistency in your codebase.
Note: An identifier cannot be redeclared once it has been declared under any datatype,
not even by the datatype it is currently using.
In the provided C program, you have declared and redeclared the variable 'A,' which leads to
issues due to variable redeclaration. Here's the code with comments explaining the
redeclaration of variables:
Example 2:
#include <stdio.h>
int main()
{
int a = 125; // Declare an integer variable 'a' and initialize it with the value 125.
int A; // Declare another integer variable 'A' without initializing it.
// Attempt to redeclare variable 'A' and initialize it with a new value (142).
int A = 142; // This line is problematic due to redeclaration.
// Print the value of the variable 'a'.
printf("The value of a: %d ", a);
// Attempt to print the value of the redeclared variable 'A' (not possible).
printf("\nThe value of A: %d ", A); // This line may lead to errors.
return 0;
}
Explanation:
int a = 125;
This line declares an integer variable 'a' and initializes it with the value 125. This is a valid
declaration.
int A;
Here, we declare another integer variable 'A' without initializing it. This is also valid.
int A = 142;
This line attempts to redeclare 'A' and initialize it with a new value (142). Variable 'A' was
already declared in the same scope, so this redeclaration is not allowed and will result in a
compilation error.
printf("The value of a: %d ", a);
This line prints the value of 'a,' which is 125. This is valid and will display the value of 'a.'
printf("\nThe value of A: %d ", A);
This line attempts to print the value of the redeclared 'A.' However, since 'A' was redeclared in
the same scope, it may lead to compilation errors or undefined behavior. In C, you should avoid
redeclaring variables with the same name within the same scope.
Note:
In summary, redeclaration of variables with the same name within the same scope is not
allowed in C. Each variable should have a unique name within its scope. If we need to assign
a new value to 'A,' you can do so without redeclaration, like A = 142.
Placement Questions:
Question 1: What is an identifier in C?
Answer: An identifier in C is a name used to identify a variable, function, array, or any other
user-defined item in the program. It consists of letters, digits, and underscores, following
specific naming rules.
Variables
• Variables are like containers in computer programming. They allow you to store and
work with different types of information, such as numbers, text, and more. Think of
them as labeled boxes where you can put things, and those things can change over time.
• Each variable has a name, which you choose, and a specific type, which determines
what kind of data it can hold, like whole numbers (integers), decimal numbers (floating-
point), or text (strings). You can think of the variable's name as the label on the box,
telling you what's inside.
• For example, you might have a variable called "score" to keep track of a player's score
in a game. You can start with a value, like 0, and as the game progresses, you can update
the score by putting a new number in the "score" box.
• Variables are essential for programs because they let you work with and manipulate
data. You can perform calculations, make decisions, and display information based on
the values stored in variables. They give programs the ability to be dynamic and respond
to changing conditions, making them incredibly powerful tools in the world of
computer programming.
Rules for naming variables:
Variable naming rules are guidelines that dictate how you should name variables in your code
to make it more readable, maintainable, and less error-prone. These rules are essential in
programming because they help you and others understand the purpose and usage of each
variable. Here are some common variable naming rules with explanations:
Use Descriptive Names:
Variable names should reflect their purpose or content. This makes your code self-documenting
and easier to understand. For example, use customerName instead of cn for a variable that
stores a customer's name.
Follow a Consistent Style:
Stick to a naming convention and use it consistently throughout your codebase. Common
conventions include camelCase (e.g., myVariableName) and snake_case (e.g.,
my_variable_name). Choose one and apply it uniformly.
Avoid Reserved Words:
Don't use language-reserved words or keywords as variable names, as this can lead to conflicts
or confusion. For example, avoid naming a variable int or for.
Start with a Letter or Underscore:
Variable names should begin with a letter (A-Z or a-z) or an underscore (_). They can be
followed by letters, digits, or underscores.
Don't Begin with a Digit:
Variable names must not start with a digit (0-9). However, they can contain digits after the
initial character.
Be Case-Sensitive:
Most programming languages are case-sensitive, meaning myVariable and MyVariable are
treated as different variables. Ensure consistency in capitalization.
Use Meaningful Abbreviations:
If we use abbreviations as variable names, make sure they are widely recognized and
unambiguous. For example, numCusts for "number of customers" is a meaningful abbreviation.
Avoid Excessive Abbreviations:
While abbreviations can be helpful for brevity, don't overdo it. A variable name like custCnt
might be more cryptic than customerCount.
Consider the Scope:
Choose variable names that reflect their scope. Short-lived variables in a limited scope can
have shorter names (e.g., i for loop counters), while longer-lasting and wider-scoped variables
should have more descriptive names.
Use Plural for Collections:
When a variable stores a collection of items, use a plural name to indicate it. For instance, users
instead of user when storing multiple user records.
Avoid Confusing Characters:
Be cautious with characters that are easily confused, such as l (lowercase "L") and 1 (the digit
one), or O (uppercase "O") and 0 (the digit zero). Avoid using them interchangeably.
Don't Use Special Characters:
Most programming languages don't allow special characters like spaces, punctuation marks, or
symbols in variable names. Stick to letters, numbers, and underscores.
Localize Global Variables:
If you use global variables, differentiate them from local variables. Prefix global variables with
something like g_ to make their scope clear.
Be Mindful of the Language's Naming Conventions:
Different programming languages may have specific naming conventions and guidelines.
Familiarize yourself with the conventions of the language you are using.
Adhering to these variable naming rules will improve the readability and maintainability of our
code, making it easier to understand and work with the code in the long run.
Placement Questions:
1.
What will be the Output?
#include<stdio.h>
int main()
{
int 2_two = 100;
printf("%d",2_two);
return 0;
}
a. 100
b. 1000
c. Compilation error
d. No output
Answer: c
Explanation:
The variable name 2_two is not a valid identifier in C.
2.
What will be the Output?
#include <stdio.h>
int main()
{
int default = 50, a = 35;
if (a > 5)
printf("%d", default);
return 0;
}
a. Rutime error
b. Compilation error
c. 50
d. 35
Answer: b
Explanation:
The variable name default is problematic because it's a C keyword used to specify default
values in switch-case statements. Using it as a variable name is not allowed and will result in
a compilation error.
3.
What will be the Output?
#include<stdio.h>
int main()
{
int class;
int public = 15;
int private = 30;
int protected = 45;
class = public + private + protected;
printf("%d",class);
return 0;
}
a. Compilation error
b. Runtime error
c. Garbage value
d. 90
Answer : d
Explanation:
C programming don't have any access specifier. Thus it is possible to use class, Public,
Private and Protected as a variable name.
4.
What will be the Output?
#include<stdio.h>
int main()
{
int _int = 150;
printf("%d",_int);
return 0;
}
a. 150
b. Garbage value
c. Compilation error
d. Runtime error
Answer: a
Explanation:
Though int is a keyword, it is prefixed with underscore, this makes it possible to use _int
as a valid variable.
5.
What will be the Output?
#include<stdio.h>
int main()
{
int _ = 50;
int =50;
int =_+ ;
printf("%d", );
return 0;
}
a. 50
b. 100
c. Compilation error
d. Runtime error
Answer: b
Explanation:
Using underscore ( _ ) alone as a variable name is too possible & valid in C programming.
6.
What will be the Output?
#include<stdio.h>
static int num=5;
extern int num;
int main()
{
printf("%d",num);
return 0;
}
a. Compilation error
b. Runtime error
c. 5
d. 50
Answer: c
Explanation:
Two of the global variable can have same variable name.
7. What will be the Output?
#include<stdio.h>
static int num=5;
extern int num=10;
int main()
{
printf("%d",num);
return 0;
}
a. 5
b. 10
c. Compilation error
d. Runtime error
Answer: c
Explanation: Though global variables can have same name, but we can initialize only one of
them.
8.
What will be the Output?
#include<stdio.h>
int main()
{
int min-value = 10;
int max-value = 20;
int avg = max-value + min-value / 5;
printf("%d",avg);
return 0;
}
a. 6
b. 14
c. Compilation error
d. Runtime error
Answer: c
Explanation:
Special characters are not allowed in declaring a variable name. In this case the special
character is min-value.
9.
What will be the Output?
#include<stdio.h>
int main()
{
printf("%d",EOF);
return 0;
}
a. 1
b. 0
c. -1
d. NULL
Answer: c
Explanation:
In C, EOF - End of File which is a macro and its header file is stdio.h. In C, EOF is equal to -
1 by default. We can use EOF in some programs to check whether file pointer reaches the end
of the file.
10.
What will be the Output?
#include<stdio.h>
int main()
{
int scanf = 100;
printf("%d",scanf);
return 0;
}
a. Compilation error
b. Runtime error
c. 100
d. No output
Answer: c
Explanation:
scanf as a variable name is possible because we have not used it as function declaration (int
scanf()=100).
11.
What will be the Output?
#include<stdio.h>
int main()
{
int printf = 100;
int c = 10 + printf;
printf("%d",c);
return 0;
}
a. 100
b. 110
c. Runtime error
d. Compilation error
Answer: d
Explanation:
• What's wrong with printf here and what's right with previous question scanf. Here we
explain
• printf can be declared as a variable, when to outputted the value stored in the printf
variable, we use printf() inbuilt function.
• when we use printf() it will search for printf() function in our program, here we declared
printf as a variable and not as a function , thus it leads to compile time error.
12.
What will be the Output?
#include<stdio.h>
int main()
{
int EOF = 10;
printf("%d",EOF);
return 0;
}
a. 10
b. 1
c. -1
d. Compilation error
Answer: d
Explanation:
In C, EOF is a predefined macro constant. We do not have any permission even to declare EOF
as a variable name. Then for sure we cannot declare or increment any values to EOF- End Of
File
13.
What will be the Output?
#include<stdio.h>
int main()
{
int main = 100;
printf("%d",main);
return 0;
}
a. 100
b. -1
c. 0
d. Compilation error
Answer: a
Explanation:
main can be declared as a variable name, but not as a function name.
14.
What will be the Output?
#include<stdio.h>
int main()
{
int x = 50;
{
int x = 100;
}
printf("%d",x);
return 0;
}
a. 50
b. 100
c. 150
d. No output
Answer: a
Explanation:
int x = 50; is a global variable, and int x = 100 is a local variable, Here we are calling x outside
the scope of x = 100. Thus it outputted 50.
15.
What will be the Output?
#include<stdio.h>
int main()
{
int x = --2;
printf("%d",x);
return 0;
}
a. 2
b. -2
c. Compilation error
d. Runtime error
Answer : c
Explanation:
decrement or increment operator cannot be initialized to any values.
16.
What will be the Output?
#include<stdio.h>
#define n 20
int main()
{
#define n 100
printf("%d",n);
return 0;
}
a. 20
b. 100
c. Compilation error
d. Runtime error
Answer: b
Explanation:
The pre-processor directives in c programming can be redefined anywhere in the program. So
the most recently assigned value will be outputted.
90
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 9: (GATE 2017)
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int a = 5;
printf("%d", a);
return 0;
}
A) Compilation Error
B) 5
C) 0
D) No Output
Answer: B) 5
Question 10: (GATE 2017)
Which of the following is a valid C variable name?
A) int
B) $variable
C) _myVariable
D) double float
Answer: C) _myVariable
91
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 12: (GATE 2016)
What is the keyword used to declare a constant in C?
A) const
B) constant
C) var
D) final
Answer: A) const
92
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 16: (GATE 2014)
What is the scope of a global variable in C?
A) Local
B) Function
C) File
D) System
Answer: C) File
Question 17: (GATE 2013)
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = 10, y = 20, z;
z = x++ + y;
printf("%d %d %d", x, y, z);
return 0;
}
A) 10 20 20
B) 11 20 21
C) 11 20 30
D) 10 21 21
Answer: C) 11 20 30
Question 18: (GATE 2013)
What is the maximum number of characters that can be used in a C identifier?
A) 31
B) 63
C) 127
D) No limit
Answer: D) No limit
93
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 19: (GATE 2012)
In C, which of the following is a reserved keyword?
A) variable
B) define
C) function
D) const
Answer: D) const
94
Presidency University – SOCSE & IS
Complete C Guide for Placement
Constants:
A constant variable: what is it?
A constant variable's value remains constant while the program is running. A data value that a
programmer writes is called a constant.
Constants can belong to any form of data (char, float, or int). Four fundamental kinds of
constants exist. These are
• A constant in integers.
• Constant Floating Point.
• Qualitative Constant.
• Constant for String.
95
Presidency University – SOCSE & IS
Complete C Guide for Placement
Negative integers (with a minus sign):
• -5
• -1024
Decimal integer constants represent whole numbers, and they don't contain a decimal point or
any fractional part. These are commonly used in many programming languages to represent
integers, such as in C, C++, Java, and Python.
96
Presidency University – SOCSE & IS
Complete C Guide for Placement
97
Presidency University – SOCSE & IS
Complete C Guide for Placement
Unsigned & Long Integer Constants:
Unsigned and long integer constants are types of integer constants used in programming. They
are used to represent integer values, but with specific characteristics:
Unsigned Integer Constants:
• An unsigned integer constant represents a non-negative (zero or positive) integer value.
• In many programming languages, including C and C++, you can denote an unsigned
integer constant by appending a 'U' or 'u' to the end of the constant.
• If no sign or 'U'/'u' is specified, the integer constant is assumed to be signed (positive
or negative).
Examples of unsigned integer constants:
• 42U (Unsigned integer constant, value 42)
• 123u (Unsigned integer constant, value 123)
• 0U (Unsigned integer constant, value 0)
These suffixes (U/u for unsigned, and L/l for long) help in specifying the type of constant you
intend to use explicitly. However, the actual behavior may vary between programming
languages. For example, in C/C++, int and long constants depend on the platform and compiler,
while the 'U'/'u' and 'L'/'l' suffixes help to clarify and standardize the type.
98
Presidency University – SOCSE & IS
Complete C Guide for Placement
Floating Point Constants:
• Floating-point constants are numeric values that include a decimal point or are
expressed in scientific notation. They are used to represent real numbers, including both
integers and fractional values.
• In most programming languages, floating-point constants are typically of two types:
single precision (float) and double precision (double).
Here are some examples of floating-point constants:
Single Precision (float) Constants:
These constants are represented using the f or F suffix to indicate single precision.
Examples of single precision floating-point constants:
• 3.14159f (Represents the value of π)
• -0.5F (Represents -0.5)
• 123.456F (Represents 123.456)
Double Precision (double) Constants:
These constants are the default in many programming languages and do not require a suffix.
However, we can optionally add the d or D suffix to indicate double precision explicitly.
Examples of double precision floating-point constants:
• 2.71828 (Represents the mathematical constant 'e')
• -1.0 (Represents -1.0)
• 0.001D (Represents 0.001, explicitly as double precision)
Scientific Notation:
Floating-point constants can also be expressed in scientific notation, where a number is
represented as a coefficient multiplied by a power of 10.
Examples of floating-point constants in scientific notation:
• 6.022e23 (Represents Avogadro's number, 6.022 x 10^23)
• -1.23e-4 (Represents -0.000123)
Floating-point constants are used for representing real numbers that may have fractional parts.
It's important to be aware of potential precision issues when working with floating-point
numbers due to their finite representation in computers.
99
Presidency University – SOCSE & IS
Complete C Guide for Placement
Mantissa & Exponent:
In scientific notation and floating-point representation, a number is typically broken down into
two parts: the mantissa and the exponent.
Mantissa:
The mantissa, also known as the significand or coefficient, is the part of the number that
contains its significant digits, including both the integer and fractional parts. It represents the
actual value or magnitude of the number.
Exponent:
The exponent indicates the power to which a base (usually 10 in decimal or 2 in binary) is
raised to scale the mantissa. It determines the position of the decimal point or binary point and,
in essence, represents the order of magnitude of the number.
Here's an example to illustrate mantissa and exponent:
Number in Scientific Notation: 3.14 × 10^2
In this example:
• The mantissa is 3.14, which represents the significant digits of the number.
• The exponent is 2, indicating that we need to multiply the mantissa by 10 raised to the
power of 2 (i.e., 100) to obtain the actual value.
• The number 3.14 × 10^2 is equivalent to 314, which is the actual value.
Another example in the context of binary floating-point representation:
Number in Binary Scientific Notation: 1.101 × 2^3
In this example:
• The mantissa is 1.101, which represents the significant digits in binary.
• The exponent is 3, indicating that we need to multiply the mantissa by 2 raised to the
power of 3 (i.e., 8) to obtain the actual value.
• The number 1.101 × 2^3 is equivalent to 11.01 in binary, which is equivalent to 3.25 in
decimal.
Mantissa and exponent are crucial concepts in scientific notation and floating-point
representation, as they allow for the representation of a wide range of numbers with varying
magnitudes and precision.
100
Presidency University – SOCSE & IS
Complete C Guide for Placement
Character Constants:
Character constants, also known as character literals, are values that represent individual
characters in a programming language.
These constants are enclosed in single quotes (') to distinguish them from strings, which are
enclosed in double quotes (""). Character constants can represent alphanumeric characters,
escape sequences, and special characters.
Here are some examples of character constants:
Alphanumeric Characters:
• 'A' (Represents the character 'A')
• '7' (Represents the digit '7')
• 'c' (Represents the lowercase letter 'c')
Escape Sequences:
• '\n' (Represents a newline character)
• '\t' (Represents a tab character)
• '\\' (Represents a backslash character)
• '\'' (Represents a single quote character)
Special Characters:
• '\0' (Represents the null character, often used to terminate strings)
• '\b' (Represents a backspace character)
• '\r' (Represents a carriage return character)
Character constants are often used when working with individual characters, for tasks like input
validation, text processing, and character manipulation in programming languages like C, C++,
and Java.
101
Presidency University – SOCSE & IS
Complete C Guide for Placement
String Constants:
String constants, also known as string literals, are sequences of characters enclosed in double
quotes (") in programming languages. They are used to represent text or sequences of
characters. String constants can contain letters, digits, special characters, and escape sequences.
Here are some examples of string constants:
Alphanumeric Characters:
• "Hello, World" (Represents the string "Hello, World")
• "12345" (Represents the string "12345")
• "This is a string" (Represents the string "This is a string")
Escape Sequences:
• "Newline:\n" (Represents the string "Newline:" followed by a newline)
• "Tab:\t" (Represents the string "Tab:" followed by a tab character)
• "Backslash:\\\\" (Represents the string "Backslash:\")
Special Characters:
• "\"Quoted String\"" (Represents the string ""Quoted String"")
• "End of Line: \r\n" (Represents the string "End of Line:" followed by a carriage return
and newline)
String constants are used extensively in programming for working with textual data, including
output to the console, reading from files, and processing user input. They are fundamental for
working with text-based information in programming languages like C, C++, Python, Java, and
many others.
102
Presidency University – SOCSE & IS
Complete C Guide for Placement
Placement Questions:
Question 1:
What is the value of the following C expression?
Explanation:
The expression 1000 + 0100 + 0x10 combines integer values in decimal and hexadecimal
formats. Let's break it down step by step:
• 1000: This is a decimal integer constant, and its value is 1000 in base 10 (decimal).
• 0100: This is an octal integer constant because it starts with a leading zero. In octal, the
value 0100 is equivalent to 64 in decimal (8 * 8).
• 0x10: This is a hexadecimal integer constant because it starts with "0x" or "0X." In
hexadecimal, the value 0x10 is equivalent to 16 in decimal (1 * 16).
Now, let's add these values together:
1000 (decimal) + 64 (octal, converted to decimal) + 16 (hexadecimal, converted to decimal) =
1080 + 16 = 1096
So, the output of the expression 1000 + 0100 + 0x10 is 1096
Question 2:
Which of the following is an integer constant?
a) 3.14
b) 'A'
c) 1234L
d) "Hello"
Answer: c) 1234L
Explanation: An integer constant is a numeric value without a decimal point. The "L" suffix
indicates a long integer constant.
Question 3:
What is the maximum value of a 16-bit signed integer?
a) 65535
b) 32767
c) 2147483647
103
Presidency University – SOCSE & IS
Complete C Guide for Placement
d) 4294967295
Answer: b) 32767
Explanation: A 16-bit signed integer can represent values from -32768 to 32767.
Question 4:
What is the octal representation of the decimal number 23?
a) 23
b) 31
c) 27
d) 35
Answer: c)
Explanation:
The octal representation of the decimal number 23 is 27. In octal, each digit represents a group
of three binary bits, so the conversion is as follows:
Decimal 23 in binary: 10111
Grouping into octal: 0 010 111 (Adding leading zeros to complete groups of three)
Octal representation: 27
So, 23 in octal is 27.
Question 5:
What is the hexadecimal representation of the decimal number 255?
a) FF
b) 0xFF
c) 0xFF00
d) 256
Answer: a) FF
Explanation:
The hexadecimal representation of the decimal number 255 is FF. In hexadecimal, each digit
represents a group of four binary bits (a nibble), so the conversion is as follows:
Decimal 255 in binary: 11111111
Grouping into hexadecimal: 1111 1111
Hexadecimal representation: FF
104
Presidency University – SOCSE & IS
Complete C Guide for Placement
So, 255 in hexadecimal is FF.
Question 6:
What does the 'U' or 'u' suffix signify in an integer constant?
a) It represents an unsigned integer.
b) It represents a signed integer.
c) It represents a floating-point number.
d) It has no specific meaning.
Answer: a) It represents an unsigned integer.
Explanation: The 'U' or 'u' suffix indicates that an integer constant is unsigned.
Question 7:
What is the binary representation of the decimal number 10?
a) 1010
b) 1001
c) 1101
d) 101
Answer: a) 1010
Explanation:
The binary representation of the decimal number 10 is 1010. In binary, each digit represents a
power of 2, and the binary representation of 10 is as follows:
1010 in binary means 1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0 * 2^0, which simplifies to 8 + 0 + 2 + 0,
resulting in the decimal number 10.
Question 8:
In C, which of the following is not a valid integer constant?
a) 123
b) -45
c) 3.14
d) 0xFF
Answer: c) 3.14
Explanation: The value 3.14 is a floating-point constant, not an integer constant.
105
Presidency University – SOCSE & IS
Complete C Guide for Placement
GATE Exam Questions:
Question 1: (GATE 2021)
What is the output of the following C code?
int x = 0x0A;
printf("%d", x);
Answer: 10
106
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 6: (GATE 2019)
What is the value of the C expression 011 | 4?
Answer: 15
Answer: c) 057
Question 9: (GATE 2017)
What is the hexadecimal representation of the decimal number 255?
a) FF
b) 0xFF
c) 0xFF00
d) 256
Answer: a) FF
Question 10: (GATE 2017)
What is the binary representation of the decimal number 42?
a) 101010
b) 101011
c) 101100
d) 110101
Answer: a) 101010
107
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 11: (GATE 2016)
What is the value of the C expression 0x12 + 012?
Answer: 20
Question 12: (GATE 2016)
In C, which of the following is not a valid integer constant?
a) 123
b) -45
c) 3.14
d) 0xFF
Answer: c) 3.14
Question 13: (GATE 2015)
What is the maximum value of a 16-bit signed integer?
a) 65535
b) 32767
c) 2147483647
d) 4294967295
Answer: b) 32767
Question 14: (GATE 2015)
What is the octal representation of the decimal number 31?
a) 031
b) 0031
c) 0x31
d) 33
Answer: a) 031
108
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 15: (GATE 2014)
What is the binary representation of the decimal number 17?
a) 10001
b) 11111
c) 10101
d) 11011
Answer: a) 10001
Question 16: (GATE 2014)
In C, which of the following is not a valid integer constant?
a) 123
b) -45
c) 3.14
d) 0xFF
Answer: c) 3.14
Answer: d) 4294967295
Question 18: (GATE 2013)
What is the decimal equivalent of the octal number 120?
Answer: 80
109
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 19: (GATE 2012)
What is the hexadecimal representation of the decimal number 15?
a) F
b) 0xF
c) 0xF0
d) 0x15
Answer: a) F
Question 20: (GATE 2012)
What is the binary representation of the decimal number 18?
a) 10010
b) 11110
c) 10001
d) 11000
Answer: a) 10010
Question 21:
Which of the following is a valid string constant in C?
a) "Hello, World"
b) 'A'
c) 1234
d) 0xFF
Answer: a) "Hello, World"
Question 22:
What is the output of the following C code?
printf("%s", 'Hello');
Answer: Compilation error
Explanation:
The printf function is typically used to print formatted strings in C and C++. When you use the
%s format specifier, it expects a null-terminated string as an argument.
110
Presidency University – SOCSE & IS
Complete C Guide for Placement
You are passing a character constant ('Hello') instead of a string. This code will result in a
compilation error because '%s' is used for strings, and 'Hello' is not a string but a character
constant.
To print the string "Hello," you should use double quotes to create a string:
printf("%s", "Hello");
Question 23:
In C, how do you escape a double quote within a string constant?
a) "
b) '
c) \
d) /
Answer: a) "
Question 24:
What is the value of the string constant "New\nLine" after processing escape sequences
in C?
a) New
b) New\nLine
c) New
Line
d) New\nLine
Answer: c) New
Line
Question 25:
Which of the following is not a valid way to declare a string constant in C?
a) "This is a string"
b) 'A'
c) "1234"
d) "Escape sequence: \n"
Answer: b) 'A'
111
Presidency University – SOCSE & IS
Complete C Guide for Placement
Escape Sequences:
Escape sequences are special combinations of characters used in strings to represent characters
that are otherwise hard to include directly. In programming languages like C, C++, Java, and
others, escape sequences start with a backslash ('') followed by a character or code that
represents a special character. Here are some common escape sequences with examples:
1. \n - Newline:
Inserts a newline character.
Example:
printf("Hello,\nWorld!");
Output:
2. \t - Tab:
3. \b - Backspace:
4. \r - Carriage Return:
112
Presidency University – SOCSE & IS
Complete C Guide for Placement
Output:
7. \\ - Backslash:
8. \0 - Null Character:
113
Presidency University – SOCSE & IS
Complete C Guide for Placement
printf("%s", str);
Output:
9. \v - Vertical Tab:
114
Presidency University – SOCSE & IS
Complete C Guide for Placement
C Const & Volatile:
Constants
Things which are all unchangable are said to be constant whereas things which are all
changable are said to be volatile.
The following diagram clearly represents the relationship between constant and volatile. In the
following diagram sealed box contains a variable i which is initialized by 16 at the time of
declaration which indicates that one cannot change the value of variable i after initialization
whereas opened box contains a varibale j which is intialized by 16 at the time of declaration,
open box indicates the one can change the value of variable j at anytime.
Constant vs Volatile:
Example 1:
In the below C code, we are trying to modify the value of a constant integer, which is not
allowed. Here's the code with explanations and comments:
#include <stdio.h>
int main()
{
const int i = 16; // Declare a constant integer 'i' and initialize it with the value 16.
i = i + 1; // Attempt to modify the value of the constant 'i,' which is not allowed.
printf("The value of i = %d ", i); // This line attempts to print the modified value of 'i' (which won't happen).
115
Presidency University – SOCSE & IS
Complete C Guide for Placement
return 0;
}
Explanation:
const int i = 16;
This line declares a constant integer variable 'i' and initializes it with the value 16. The 'const'
keyword makes 'i' read-only, meaning its value cannot be changed after initialization.
i = i + 1;
This line attempts to increment the value of 'i' by 1, but it will result in a compilation error
because 'i' is declared as a constant, and constant variables cannot be modified.
printf("The value of i = %d ", i);
This line is meant to print the value of 'i' (which is 16), but due to the compilation error in the
previous line, this code will not execute.
Volatile:
Example 2:
In the provided C code, you are using the volatile keyword to declare a volatile integer i, and
then you attempt to modify its value. Here's the code with explanations and comments:
#include <stdio.h>
int main()
{
volatile int i = 16; // Declare a volatile integer 'i' and initialize it with the value 16.
i = i + 1; // Attempt to modify the value of 'i'.
printf("The value of i = %d ", i); // Print the modified value of 'i.'
return 0;
}
116
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
volatile int i = 16;
This line declares a volatile integer variable 'i' and initializes it with the value 16. The volatile
keyword is used to indicate to the compiler that the variable can be changed at any time by
external factors, and it should not optimize away reads and writes to the variable.
i = i + 1;
This line attempts to increment the value of 'i' by 1. While i is declared as volatile, you can still
modify its value. However, the volatile keyword ensures that the variable's value is not
optimized away by the compiler.
117
Presidency University – SOCSE & IS
Complete C Guide for Placement
118
Presidency University – SOCSE & IS
Complete C Guide for Placement
This line attempts to modify the value of 'x' through the pointer 'p.' However, this is not allowed
because 'p' is declared as a pointer to a constant integer. You cannot modify the value of a
constant integer through a pointer like this.
printf("%d\n", x);
This line attempts to print the value of 'x,' but the previous attempt to modify 'x' through 'p' will
result in a compilation error.
119
Presidency University – SOCSE & IS
Complete C Guide for Placement
Typecasting in C:
• Typecasting in C (Casting) is the process of converting one data type into another. It's
often necessary when you want to perform operations involving variables of different
data types or when you want to ensure that the result of an operation is of a specific
data type.
• In C, typecasting can be explicit, where you explicitly specify the desired type, or
implicit, where the compiler performs the conversion automatically.
Here are some examples of typecasting in C:
1. Implicit Typecasting (Type Promotion):
Implicit typecasting occurs when the compiler automatically promotes data types during
operations to avoid data loss.
For example, when you perform an operation on an integer and a floating-point number, the
result is promoted to the data type with higher precision (usually the floating-point type).
#include<stdio.h>
void main()
{
int a = 5;
float b = 3.14;
float result = a + b; // 'a' is implicitly typecast to float for the addition.
printf(“%f”,result);
}
2. Explicit Typecasting:
Explicit typecasting is done using casting operators like (type) to convert one type to another.
Casting to a Smaller Type:
You can explicitly cast a larger data type to a smaller data type, but this can lead to data loss.
double d = 3.14159;
int i = (int)d; // Explicitly casting a double to an int (data loss occurs).
120
Presidency University – SOCSE & IS
Complete C Guide for Placement
Casting to a Larger Type:
Explicit typecasting is often used to ensure that the result of an expression is of the desired
type.
int a = 5;
int b = 2;
double result = (double)a / (double)b; // Explicitly casting 'a' and 'b' to double.
Pointer Typecasting:
Typecasting is also used with pointers to change the type of data to which a pointer points.
int x = 42;
int *ptr = &x;
double *doublePtr = (double *)ptr; // Explicitly cast an int pointer to a double pointer.
121
Presidency University – SOCSE & IS
Complete C Guide for Placement
Operators in C:
• Operators in C are symbols used to perform operations on variables and values.
• They are fundamental building blocks in C programming and are used for tasks like
arithmetic, comparison, assignment, and more.
Here are some common categories of operators in C with examples:
In C, an operator is a symbol(+, -, *, /) which operates on a certain data type to perform
mathematical, logical, relational operations.
• An operator indicates an operation to be performed on data results into a value.
• An operand is a data item (variable or constant) on which operators can perform the
operations.
• An expression is a combination of variables, constants and operators.
In C, every expression results(evaluates) into a value of certain data type.
Example
Assume variable a = 2 and b = 4, these values substituted to the expression, a + (5 * b) = 22.
The expression can be defined as follow, a and b are variables, 5 is a constant and 22 is a result
value.
Operator Classifications:
1. Comma Operator:
The comma operator in C is used to separate expressions within a statement, and it allows you
to evaluate multiple expressions in a specific order.
The result of a comma operator expression is the value of the rightmost expression. The left
expressions are evaluated for their side effects. Here's how the comma operator works:
122
Presidency University – SOCSE & IS
Complete C Guide for Placement
Example 1:
#include <stdio.h> // Include the standard input-output library.
int main()
{
int a = 15, b = 20; // Declare and initialize two integer variables 'a' and 'b'.
if (a > b, a < b) // Use the comma operator to separate two expressions within the 'if' condition.
printf("a is less than b"); // This block will execute if the last expression 'a < b' is true.
else
printf("a is greater than b"); // This block will execute if the last expression is false.
return 0;
}
Explanation:
if (a > b, a < b): In this line, you are using the comma operator to separate two expressions
within the if condition. However, the comma operator only considers the value of the last
expression, which is a < b.
Note: if(15>20, 15<20) this condition is checked, the comma operator always considers the
last expression, i.e. it checks if(15<20), condition is true and enters if conditional statement.
Therefore, the condition is essentially checking if a < b. If this condition is true, the code inside
the if block will be executed; otherwise, the else block will be executed.
123
Presidency University – SOCSE & IS
Complete C Guide for Placement
Placement Questions on Comma Operator:
Question 1:
What does the comma operator do in C?
a) Separates function arguments
b) Separates expressions and evaluates all of them
c) Separates statements in a block
d) Separates elements in an array
Answer: b) Separates expressions and evaluates all of them
Question 2:
In the expression a = 5, b = 10, what will be the value of 'a' after evaluation?
a) 5
b) 10
c) 15
d) 20
Answer: a) 5
Question 3:
What is the output of the following code?
#include<stdio.h>
void main()
{
int x = 5, y = 10;
x = (x++, y++);
printf("%d", x);
}
124
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
int x = 5, y = 10;
Here, we declare two integer variables, x and y, and initialize them with the values 5 and 10,
respectively.
x = (x++, y++);
This line contains the interesting part. It uses the comma operator to update the value of x. Let's
break it down step by step:
x++:
This is the post-increment operator. It means that the current value of x is used in the
expression, and then x is incremented by 1. So, at this point, x is incremented from 5 to 6, but
the value used in the expression is still 5.
y++:
This is also the post-increment operator for the variable y. It means the current value of y is
used in the expression, and then y is incremented by 1. After this, y is incremented from 10 to
11, but the value used in the expression is still 10.
(x++, y++) à evaluates to the value of the last expression, which is the value of y++, so it's
10.
Finally, the value of 10 is assigned back to x, replacing its previous value of 5.
Question 4:
Which of the following operators is NOT used as a separator in C?
a) Comma operator (,)
b) Semicolon (;)
c) Colon (:)
d) Period (.)
Answer: d) Period (.)
125
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 5:
What is the value of y in the following code?
#include <stdio.h>
void main()
{
int x = 5, y;
y = x++, x++, x++;
printf("%d", y);
}
Output : 5
Explanation:
int x = 5, y;
we declare two integer variables, x and y. x is initialized with the value 5, and y is declared but
not initialized.
126
Presidency University – SOCSE & IS
Complete C Guide for Placement
This line prints the value of y after the assignment. Since y has been assigned the value of 5,
the correct output is "5."
Question 6:
What is the value of y in the following code?
#include<stdio.h>
void main()
{
int x = 5, y;
y = (x++,x++,x++);
printf("%d", y);
}
Output:7
Explanation:
Initially, x is set to 5, and y is declared but not initialized.
y=(x++, x++, x++):
The first x++ evaluates to the current value of x, which is 5, and then increments x to 6.
The second x++ evaluates to the current value of x, which is now 6, and then increments x to
7.
The third x++ evaluates to the current value of x, which is 7, and then increments x to 8.
The result of the entire expression (x++, x++, x++) is the value of the last expression,
which is 7 (the value of x after the third increment).
The value 7 is assigned to the variable y.
printf("%d", y); prints the value of y, which is 7.
127
Presidency University – SOCSE & IS
Complete C Guide for Placement
GATE Exam Questions on comma operator:
Question 1:
What is the primary purpose of the comma operator in C?
a) To separate function arguments
b) To separate expressions and evaluate all of them
c) To separate statements within a block
d) To separate elements in an array
Answer: b) To separate expressions and evaluate all of them
Question 2:
In the expression a = 5, b = 10, what is the value of 'a' after evaluation?
a) 5
b) 10
c) 15
d) 20
Answer: a) 5
Question 3:
What is the associativity of the comma operator in C?
a) Left to right
b) Right to left
c) It depends on the usage
d) It has no associativity
Answer: a) Left to right
128
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 4:
What is the result of the expression 3, 4, 5?
a) 3
b) 4
c) 5
d) 12
Answer: c) 5
Question 5:
In the code a = (x++, y++, z++);, which expression is evaluated first?
a) x++
b) y++
c) z++
d) All are evaluated simultaneously
Answer: a) x++
Question 6:
What is the output of the following code?
#include <stdio.h>
int main()
{
int x = 5, y = 10;
int z = (x > y, x, y);
printf("%d",z);
return 0;
}
a) 5
b) 10
c) 15
d) 0 Answer: b) 10
129
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 7:
Which of the following is NOT a valid use of the comma operator in C?
a) for loop initializer
b) Function argument separator
c) Array subscript separator
d) Logical OR operator
Question 8:
What is the value of y in the following code?
#include <stdio.h>
int main()
{
int x = 5, y;
y = x++, x++, x++;
printf("%d",y);
return 0;
}
a) 5
b) 6
c) 7
d) 8
Answer: a) 5
130
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 9:
What is the output of the following code?
#include <stdio.h>
int main()
{
int a = 5, b = 10;
int c = (a = b, b = a + 1, a + b);
printf("%d",c);
return 0;
}
a) 15
b) 20
c) 25
d) 21
Answer: c) 21
Question 10:
Which of the following statements about the comma operator is true?
131
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 11:
What is the output of the following code?
#include <stdio.h>
int main()
{
int x = 5, y = 10;
int z = (x > y) ? x++ : y++;
printf("%d",z);
return 0;
}
a) 5
b) 10
c) 11
d) 6
Answer: c) 10
Question 12:
What is the value of x after the following code is executed?
#include <stdio.h>
int main()
{
int x = 5;
x = (x++, x++, x++);
printf("%d",x);
return 0;
}
a) 3
b) 7
c) 5
132
Presidency University – SOCSE & IS
Complete C Guide for Placement
d) 6
Answer: b) 7
Question 13:
In the code a = (x, y, z);, what is the value assigned to 'a'?
a) x
b) y
c) z
d) The value of 'z'
Question 14:
What is the output of the following code?
#include <stdio.h>
int main()
{
int x = 5, y = 10, z = 15;
int result = (x++, y++, z++, x + y + z);
printf("%d",result);
return 0;
}
a) 5
b) 33
c) 30
d) 31
Answer: b) 33
133
Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 15:
In the code a = (x++, y++, z++);, which expression is evaluated first?
a) x
b) y
c) z
d) All are evaluated simultaneously
Answer: a) x
Question 16:
What is the output of the following code?
#include <stdio.h>
int main()
{
int x = 5, y = 10, z;
z = x++ + y, x++;
printf("%d",z);
return 0;
}
a) 20
b) 25
c) 15
d) 16
Answer: c) 15
134
Presidency University – SOCSE & IS
Complete C Guide for Placement
Arithmetic Operators:
What is Arithmetic Operators?
Arithmetic operators can be used to perform arithmetic operations such as Addition,
Subtraction, Multiplication and Division.
Arithmetic operators are most commonly used operators in computer programming languages.
The operands involved in arithmetic operations must represent numerical value. Thus, the
operands can be an integer type, floating point types, double and char.
In C, characters represent numerical value according to ASCII table. Arithmetic operators can
be divided into 3 types, they are:
• Unary Operator
• Binary Operator
• Ternary Operator
Unary Operators in C:
Unary operators are act upon a single operand to produce a new value.
135
Presidency University – SOCSE & IS
Complete C Guide for Placement
Example 1: Unary Minus
#include <stdio.h> // Include the standard input-output library
int main() // Main function
{
int x = -5; // Declare and initialize an integer variable x with the value -5.
int y = -x; // Declare and initialize an integer variable y with the negative value of x.
136
Presidency University – SOCSE & IS
Complete C Guide for Placement
137
Presidency University – SOCSE & IS
Complete C Guide for Placement
// It first assigns the current value of 'a' to 'a' (which is 2) and then decrements 'a' by 1.
// So, after this line, 'a' remains 2.
// Use the '&' operator to get the address of 'n' (memory location where 'n' is stored)
printf("\nAddress of n = %u ", &n); // Print the address of 'n'
138
Presidency University – SOCSE & IS
Complete C Guide for Placement
// Use the 'sizeof' operator to determine the size (in bytes) of 'x' and 'y' and print the results
printf("sizeof(x) = %d\nsizeof(y) = %d", sizeof(x), sizeof(y));
Explanation:
We use the sizeof operator to determine and print the size (in bytes) of both x and y. The sizeof
operator is used with the variables as its argument. It returns the size of the specified data type
or variable in bytes. In this case, it returns the size of an int for x and the size of a float for y.
The output of this code will display the size of x and y in bytes. The actual size might vary
depending on your platform and compiler, but typical sizes for intare 4 bytes, and forfloat`, it's
4 bytes as well on most systems.
139
Presidency University – SOCSE & IS
Complete C Guide for Placement
Binary Operator:
Binary operators are act upon two operands to produce a new value.
140
Presidency University – SOCSE & IS
Complete C Guide for Placement
return 0;
}
141
Presidency University – SOCSE & IS
Complete C Guide for Placement
Program without Conditional Operator
Here we are to find the least age and store it in a variable younger_age without using
Conditional operator.
#include <stdio.h> //header file section
int main() //main section
{
int son = 18;
int father = 40;
int younger_age;
if(son < father)
younger_age = son;
else
younger_age = father;
printf("%d is the younger age", younger_age);
return 0;
}
142
Presidency University – SOCSE & IS
Complete C Guide for Placement
return 0;
}
C Relational Operators
What Is Relational Operator?
Relational operators are used to compare arithmetic, logical and character expressions.
If the condition is "true" it returns 1, otherwise, it returns 0.
Relational operator Types
C Programming provides 6 relational operators for comparing numeric quantities.
143
Presidency University – SOCSE & IS
Complete C Guide for Placement
return 0;
}
Note:
Here true condition returns 1 and false condition returns 0.
144
Presidency University – SOCSE & IS
Complete C Guide for Placement
145
Presidency University – SOCSE & IS
Complete C Guide for Placement
C Logical Operators
Why Logical Operator?
By learning relational operator, we should have a general idea on how to use conditions in if
statements by now, but imagine if we want to check two condition to execute certain sets of
statement. Then we have two options:
Option A
Using nested if statement( 2 if statements one after another) to evaluate two condition.
Option B
Make use of Logical Operators
Answer:
Though option A looks classic it fails in either or condition. In such case we are insisted to
make use of Logical Operators with no choices.
Logical Operator in C
• Logical operators are used to check (or) compare the logical relations between the
expressions.
• Logical operator, returns 1 if given condition is true, 0 if given condition is false.
Logical Operator Flow:
C provides 3 logical operator for comparing numeric quantities.
146
Presidency University – SOCSE & IS
Complete C Guide for Placement
Logical AND Operator
Let us write a C program to demonstrate logical AND operator
Example 1:
#include <stdio.h> // Include the standard input/output library
int main() // The main function where the program starts
{
int a = 20; // Declare an integer variable 'a' and assign the value 20 to it
int b = 10; // Declare an integer variable 'b' and assign the value 10 to it
int c = 15; // Declare an integer variable 'c' and assign the value 15 to it
printf("C is the greatest number of all"); // If the condition is true, print this message
}
else
{
printf("C is not the greatest number of all"); // If the condition is false, print this message
}
return 0; // Return 0 to indicate successful execution of the program
}
147
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
In this code:
• We have three integer variables: a, b, and c with the values 20, 10, and 15, respectively.
• The condition inside the if statement consists of two parts separated by &&:
o a < b: This is the first part of the condition, which checks if 'a' is less than 'b'. In
your case, 20 is not less than 10, so this part is false.
o b < c: This is the second part of the condition, which checks if 'b' is less than 'c'.
In your case, 10 is less than 15, so this part is true.
• The logical AND operator (&&) requires that both parts of the condition must be true
for the overall condition to be true. If either part is false, the overall condition is false.
• In this specific case, the first part (a < b) is false, and the second part (b < c) is true.
Since both parts of the condition are not true, the overall condition is false.
• Since the overall condition is false, the code within the else block is executed, and it
prints "C is not the greatest number of all."
In summary, the logical AND (&&) operator is used to combine two or more conditions, and
it returns true if and only if all the individual conditions are true. In this code, it checks whether
'a' is less than 'b' and 'b' is less than 'c'. If both conditions are true, the code within the if block
is executed; otherwise, the code within the else block is executed.
148
Presidency University – SOCSE & IS
Complete C Guide for Placement
Logical OR Operator
Let us write a C program to demonstrate logical OR operator.
Example 1:
#include <stdio.h> // Include the standard input/output library
int main() // The main function where the program starts
{
int a = 20; // Declare an integer variable 'a' and assign the value 20 to it
int b = 10; // Declare an integer variable 'b' and assign the value 10 to it
int c = 15; // Declare an integer variable 'c' and assign the value 15 to it
// Use an if statement to compare the values of 'a', 'b', and 'c' using the logical OR operator
if (c > a || c > b)
{
// Check if 'c' is greater than 'a' OR 'c' is greater than 'b'. If either condition is true, enter the if statement.
printf("C is not the smallest and may not be the biggest of all");
// If the condition is true, print this message
}
else
{
printf("C is the smallest of all"); // If the condition is false, print this message
}
return 0; // Return 0 to indicate successful execution of the program
}
Explanation:
• We declare three integer variables: a, b, and c, and assign them the values 20, 10, and
15, respectively, using int a = 20;, int b = 10;, and int c = 15;.
• We use an if statement to check a condition. In this case, the condition is c > a || c > b,
which checks if 'c' is greater than 'a' OR 'c' is greater than 'b'. If either condition is true,
the code within the if block is executed.
• The logical OR operator (||) is used here. It returns true if at least one of the conditions
is true.
149
Presidency University – SOCSE & IS
Complete C Guide for Placement
• In this specific case, 'c' is 15, 'a' is 20, and 'b' is 10. The condition c > a is false because
15 is not greater than 20. However, the condition c > b is true because 15 is greater than
10. Since at least one part of the condition is true, the overall condition is true.
• Because the overall condition is true, the code within the if block is executed, and it
prints "C is not the smallest and may not be the biggest of all."
In summary, the logical OR (||) operator is used to combine two or more conditions, and it
returns true if at least one of the individual conditions is true. In this code, it checks whether 'c'
is greater than 'a' or 'c' is greater than 'b'. If either condition is true, the code within the if block
is executed; otherwise, the code within the else block is executed.
Note:
Here printf statement next to if conditional statement will execute even either condition
is true.
Logical NOT Operator
Let us write a C program to demonstrate logical NOT operator
Example 1:
#include <stdio.h> // Include the standard input/output library
int main() // The main function where the program starts
{
int a = 20; // Declare an integer variable 'a' and assign the value 20 to it
int b = 10; // Declare an integer variable 'b' and assign the value 10 to it
// Use an if statement to compare the values of 'a' and 'b' using the logical NOT operator
if (a != b)
{
// Check if 'a' is NOT equal to 'b' (i.e., if they are not equal), enter the if statement.
printf("a is not equal to b"); // If the condition is true, print this message
} else
{
printf("a is equal to b"); // If the condition is false, print this message
}
150
Presidency University – SOCSE & IS
Complete C Guide for Placement
return 0; // Return 0 to indicate successful execution of the program
}
Explanation:
if (a != b) :
• The if statement is used to control the flow of a program based on a condition enclosed
within parentheses.
• In this specific case, the condition being checked is a != b, which translates to "a is not
equal to b."
• To evaluate this condition, the program checks whether the value of a (which is 20) is
not equal to the value of b (which is 10). This is done by comparing 20 != 10.
• When the program evaluates 20 != 10, it's a logical expression. This expression checks
if 20 is not equal to 10.
• In this scenario, the expression 20 != 10 is indeed true because 20 is equal to 10.
• When a condition is True in C, it is represented by the value 1. Therefore, the return
value of the expression 20 != 10 is 1.
• Now, the if statement has the condition if(1) because the expression 20 != 10 evaluated
to 1, which means it's considered true.
• The compiler checks the if(1) condition, and since the condition is 1 (which is true), the
code inside the if block is executed.
• In summary, the if statement initially evaluates the condition a != b, which results in a
true condition (1), and as a result, the code inside the if block is executed.
151
Presidency University – SOCSE & IS
Complete C Guide for Placement
Bitwise Operators:
Bitwise operators in C are used to manipulate individual bits in integer values. There are six
main bitwise operators in C:
• AND (&)
• OR (|)
• XOR (^)
• NOT (~)
• left shift (<<) and
• right shift (>>).
Bitwise AND (&):
The bitwise AND operator & compares each pair of corresponding bits and returns 1 if both
bits are 1, otherwise 0.
The bitwise AND operator (&) is a binary operator that performs a bit-by-bit logical AND
operation on its two operands. This means that it compares the corresponding bits of the two
operands and returns a 1 if both bits are 1, and a 0 otherwise.
Example 1:
#include <stdio.h>
int main()
{
int a = 10; // Binary: 1010
int b = 7; // Binary: 0111
return 0;
}
152
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
We have two integer variables:
• a is assigned the decimal value 10, which is represented in binary as 1010.
• b is assigned the decimal value 7, which is represented in binary as 0111.
We then perform a bitwise AND operation between a and b using the & operator:
• Bitwise AND is a binary operation that takes two numbers and performs the AND
operation on each pair of corresponding bits.
• In this case, for each bit position, if both a and b have a 1 in that position, the result will
have a 1; otherwise, it will have a 0.
The binary representation of the values is:
a (10) = 1010
b (7) = 0111
Performing the bitwise AND operation:
1 0 1 0 (a)
& 0 1 1 1 (b)
= 0010
The result of the bitwise AND operation is 0010 in binary, which corresponds to the decimal
value 2.
We then use the printf function to print the result to the console with the format specifier %d,
so the output will be:
"a & b = 2"
So, the output of the program is: "a & b = 2."
In summary, the program correctly demonstrates how to use the bitwise AND operator to
perform a bitwise operation on two integers, and it prints the result, which is the decimal value
2 or 0010 in binary.
Note:
Bitwise operations, including the bitwise AND operation, are typically performed from the
least significant bit (LSB) to the most significant bit (MSB). In other words, the operation is
carried out on the individual bits in each position, starting from the rightmost bit and moving
towards the leftmost bit.
153
Presidency University – SOCSE & IS
Complete C Guide for Placement
In the above C program:
int result = a & b; // Bitwise AND
The operation is performed on each pair of bits in the binary representations of a and b, starting
from the rightmost bit (LSB) and moving towards the leftmost bit (MSB). This means that the
LSB of a is ANDed with the LSB of b, the second least significant bit is ANDed with the
second least significant bit, and so on, until the MSB of both numbers is processed.
So, in the case of a = 10 (binary: 1010) and b = 7 (binary: 0111), the operation proceeds like
this:
• 0 (LSB of a) & 1 (LSB of b) = 0
• 1 (2nd least significant bit of a) & 1 (2nd least significant bit of b) = 1
• 0 (3rd least significant bit of a) & 1 (3rd least significant bit of b) = 0
• 1 (MSB of a) & 0 (MSB of b) = 0
The result is 0010, where each bit in the result is calculated from LSB to MSB.
Bitwise OR operator:
The bitwise OR operator, represented by the | symbol in C and many other programming
languages, is a binary operator used to perform a bitwise OR operation on individual bits of
two integers. It operates on the binary representations of these integers, comparing the
corresponding bits and producing a result where each bit is set to 1 if at least one of the
corresponding bits in the operands is 1.
Here's how the bitwise OR operator works:
Bitwise OR Operation: For each pair of corresponding bits in the two integers:
• If at least one of the bits is 1, the result bit will be set to 1.
• If both bits are 0, the result bit will be 0.
• Result: The result of the bitwise OR operation will be an integer with bits set to 1
wherever there was at least one 1 in the corresponding positions of the operands.
Example:
#include <stdio.h>
int main()
{
int a = 10; // Binary: 1010
int b = 7; // Binary: 0111
int result = a | b; // Bitwise OR
printf("a | b = %d\n", result);
return 0;
}
154
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
The program is similar to the previous one, but it uses the bitwise OR operator (|) to perform a
bitwise OR operation on integers a and b.
Here's the explanation of the bitwise OR operation:
We have two integer variables:
• a is assigned the decimal value 10, which is represented in binary as 1010.
• b is assigned the decimal value 7, which is represented in binary as 0111.
We then perform a bitwise OR operation between a and b using the | operator:
• Bitwise OR is a binary operation that takes two numbers and performs the OR operation
on each pair of corresponding bits.
• In this case, for each bit position, if either a or b has a 1 in that position (or both), the
result will have a 1; otherwise, it will have a 0.
| 0 1 1 1 (b)
=1 111
The result of the bitwise OR operation is 1111 in binary, which corresponds to the decimal
value 15.
155
Presidency University – SOCSE & IS
Complete C Guide for Placement
We then use the printf function to print the result to the console with the format specifier %d,
so the output will be:
"a | b = 15"
So, the output of the program is: "a | b = 15."
In summary, the program demonstrates how to use the bitwise OR operator to perform a bitwise
operation on two integers, and it prints the result, which is the decimal value 15 or 1111 in
binary. The operation is also performed from LSB to MSB, just like the bitwise AND operation.
Bitwise XOR(^) :
The bitwise XOR (exclusive OR) operator, represented by the ^ symbol in C and many other
programming languages, is a binary operator used to perform a bitwise XOR operation on
individual bits of two integers.
It operates on the binary representations of these integers, comparing the corresponding bits
and producing a result where each bit is set to 1 if the corresponding bits in the operands are
different (one is 1 and the other is 0).
Here's how the bitwise XOR operator works:
• Bitwise XOR Operation: For each pair of corresponding bits in the two integers:
• If the bits are different (one is 1 and the other is 0), the result bit will be set to 1.
• If the bits are the same (both 1 or both 0), the result bit will be 0.
• Result: The result of the bitwise XOR operation will be an integer with bits set to 1
wherever there was a difference in the corresponding positions of the operands.
Example:
#include <stdio.h>
int main()
{
int a = 10; // Binary: 1010
int b = 7; // Binary: 0111
int result = a ^ b; // Bitwise XOR
printf("a ^ b = %d\n", result);
return 0;
}
156
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
let's explain the C program that uses the bitwise XOR operator and its output:
We have two integer variables:
• a is assigned the decimal value 10, which is represented in binary as 1010.
• b is assigned the decimal value 7, which is represented in binary as 0111.
We then perform a bitwise XOR operation between a and b using the ^ operator:
Bitwise XOR is a binary operation that takes two numbers and performs the XOR operation on
each pair of corresponding bits.
In this case, for each bit position, if the bits are different (one is 1 and the other is 0), the result
will have a 1; if the bits are the same, the result will be 0.
The binary representation of the values is:
a (10) = 1010
b (7) = 0111
Performing the bitwise XOR operation:
1 0 1 0 (a)
^ 0 1 1 1 (b)
= 1 1 0 1
The result of the bitwise XOR operation is 1101 in binary, which corresponds to the decimal
value 13.
We then use the printf function to print the result to the console with the format specifier %d,
so the output will be:
"a ^ b = 13"
So, the output of the program is: "a ^ b = 13."
In summary, the program demonstrates how to use the bitwise XOR operator to perform a
bitwise operation on two integers, and it prints the result, which is the decimal value 13 or 1101
in binary. The operation is also performed from LSB to MSB, similar to other bitwise operators.
157
Presidency University – SOCSE & IS
Complete C Guide for Placement
Bitwise NOT operator(~):
The bitwise NOT operator, represented by the ~ symbol in C and many other programming
languages, is a unary operator used to perform a bitwise NOT operation on individual bits of
an integer. It inverts each bit in the binary representation of the integer, changing 0s to 1s and
1s to 0s.
Here's how the bitwise NOT operator works:
• Bitwise NOT Operation: For each bit in the binary representation, invert the bit (change
0 to 1 and 1 to 0).
• Result: The result of the bitwise NOT operation is an integer with all its bits inverted.
Example:
#include <stdio.h>
int main()
{
int a = 10; // Binary: 1010
int result = ~a; // Bitwise NOT
printf("~a = %d\n", result);
return 0;
}
Explanation:
let's break down the output of the program step by step and provide a clearer explanation:
• We have an integer variable a assigned the decimal value 10, which is represented in
binary as 1010.
• The program performs a bitwise NOT operation on a using the ~ operator. This
operation inverts each bit in the binary representation of a.
• Original binary representation of a (10): 1010
• Bitwise NOT operation inverts each bit:
158
Presidency University – SOCSE & IS
Complete C Guide for Placement
1 becomes 0
0 becomes 1
Resulting binary representation after bitwise NOT operation: 0101
• The binary representation 0101 corresponds to the decimal value 5. So, the result of the
bitwise NOT operation is 5.
• However, the output is displayed as "~a = -11". This apparent discrepancy arises from
the interpretation of the result in two's complement form:
• In two's complement representation:
• The leftmost (most significant) bit is the sign bit.
• If the leftmost bit is 0, it represents a positive number.
• If the leftmost bit is 1, it represents a negative number.
• The binary representation 0101 starts with a 0, which typically signifies a positive
number.
• To display the result as "-11," it seems the program is interpreting the binary result
(0101) as if it were in two's complement form. In this interpretation, the leftmost 0 is
taken as a sign bit, indicating a positive number, and the rest of the bits are interpreted
as positive values. When converted to decimal, it's represented as 11.
• To clarify, the bitwise NOT operation indeed inverts the bits in a, resulting in 0101 in
binary, which correctly corresponds to the decimal value 5. However, the interpretation
of the result as "-11" in decimal appears to be an unusual or erroneous conversion, given
the binary representation of the result. Normally, the result should be "5" in decimal
when considering standard binary-to-decimal conversion rules.
159
Presidency University – SOCSE & IS
Complete C Guide for Placement
Here's an example using a C program:
Example:
#include <stdio.h>
int main()
{
int a = 5; // Binary: 0101
int result = a << 2; // Left shift by 2 positions
printf("a << 2 = %d\n", result);
return 0;
}
Explanation:
a << 2 = 20
This output means that the left shift operation on a by 2 positions shifted the bits to the left,
and it's effectively equivalent to multiplying the original value by 2^2.
5 x 2^2 = 5 x 4 = 20, which results in 20. In binary, the result is 10100, corresponding to the
decimal value 20.
160
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
a >> 16 = 4
This output means that the right shift operation on a by 2 positions shifted the bits to the right,
and it's effectively equivalent to dividing the original value by 2^2.
16 / 2^2 = 16 x 4 = 4, which results in 4. In binary, the result is 00100, corresponding to the
decimal value 4.
C Operator Precedence:
Why Operator Precedence?
Every Operator have their own precedence because without operator precedence a complier
will conflict with data when performing mathematical calculations.
Example:
Consider the following expression 6 - 4 + 8 without operator precedence compiler is helpless
to choose which operator needs to execute first. Thu, Operator Precedence helps compiler out
there.
The following table lists all C operators and their precedence from higher priority to lower
priority.
161
Presidency University – SOCSE & IS
Complete C Guide for Placement
162
Presidency University – SOCSE & IS
Complete C Guide for Placement
Placement Questions on Operators:
1.
What is the output?
#include<stdio.h>
int main()
{
int num = 8;
printf ("%d %d", num << 1, num >> 1);
return 0;
}
a. 7 6
b. 4 16
c. 9 7
d. 16 4
Answer: d (16 4)
Explanation:
#include <stdio.h>
int main()
{
int num = 8; // Define an integer variable 'num' and initialize it with the value 8.
// Use the left shift operator (<<) to double the value of 'num' (multiply by 2).
// This effectively shifts the bits of 'num' one position to the left.
int left_shift_result = num << 1; // The result will be 16 (8 * 21).
// Use the right shift operator (>>) to halve the value of 'num' (divide by 2).
// This effectively shifts the bits of 'num' one position to the right.
int right_shift_result = num >> 1; // The result will be 4 (8 / 21).
// Print the results of the left shift and right shift operations.
163
Presidency University – SOCSE & IS
Complete C Guide for Placement
printf("%d %d", left_shift_result, right_shift_result);
return 0;
}
164
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
How 16 comes instead of 15. Let's explain it
Step 1: a = 7 + ++i
Step 2: a = 7 + 8
Step 3: a = 8 + 8
Final Answer = 16
Note that even if you have n number of operands with pre increment operator(++). the
above discussed effect will take place only between first and second operand. Please check
next quiz to clear it 100%.
3.
What will the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = ++i + ++i + ++i;
printf("%d",a);
return 0;
}
a. 15
b. 22
c. 21
d. 20
Answer : b (22)
165
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
a = ++i + ++i + ++i;
a = 6 + ++i + ++i
a = 6 + 7 + ++i
a = 7 + 7 + ++i
a=7+7+8
a=7+7+8
Finally a = 22.
4.
What will be the output?
#include<stdio.h>
int main()
{
int i = 5;
int a = ++i + ++i + ++i + ++i;
printf("%d",a);
return 0;
}
a. 20
b. 21
c. 25
d. 31
Answer : d (31)
166
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
a = ++i + ++i + ++i + ++i;
a = 6 + ++i + ++i + ++i;
a = 6 + 7 + ++i + ++i
a = 7 + 7 + ++i + ++i
a = 7 + 7 + 8 + ++i
a=7+7+8+9
Finally a = 31.
5.
What is the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = --i + ++i;
printf("%d",a);
return 0;
}
a. 9
b. 10
c. 11
d. 8
Answer: 10
167
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
a = --i + ++i
a = 4 + ++i
a = 4+ 5
a=5+5
a=10
6.
What will be the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = --i + i++;
printf("%d",a);
return 0;
}
a. 10
b. 11
c. 8
d. 9
Answer: d (9)
Explanation:
a = --i + i++
a = 4 + i++
a = 4 + 4 (after this expression, i becomes 5)
a = 5 + 4 (first operand takes the current value of i)
a= 9
168
Presidency University – SOCSE & IS
Complete C Guide for Placement
169
.
What will be the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = --i + i++ + i++;
printf("%d",a);
return 0;
}
a. 12
b. 13
c. 14
d. 15
Answer: c (14)
Explanation:
a = --i + i++ + i++
a = 4 + i++ + i++
a = 4 + 4 + i++
a = 5 + 4 + i++
a= 5+ 4+ 5
a =14
169
Presidency University – SOCSE & IS
Complete C Guide for Placement
170
.
What will be Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = --i + --i;
printf("%d",a);
return 0;
}
a. 5
b. 6
c. 7
d. 8
Answer: 6
Explanation:
a = --i + --i
a = 4 + --i
a=4+ 3
a=3 + 3
a=6
170
Presidency University – SOCSE & IS
Complete C Guide for Placement
9.
What will be the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = --i + --i + i++;
printf("%d",a);
return 0;
}
a. 9
b. 10
c. 8
d. 11
Answer: a (9)
Explanation:
a = --i + --i + i++
a = 4 + --i + i++
a = 4 + 3 + i++
a = 3 + 3 + i++
a=3+ 3+ 3
a=9
171
Presidency University – SOCSE & IS
Complete C Guide for Placement
10.
What will be the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = --i + --i + ++i;
printf("%d",a);
return 0;
}
a. 9
b. 10
c. 11
d. 8
Answer: 10
Explanation:
a = --i + --i + ++i
a = 4 + --i + ++i
a = 4 + 3 + ++i
a = 3 + 3 + ++i
a=3+3+4
a=10
172
Presidency University – SOCSE & IS
Complete C Guide for Placement
11. What will be the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = i++ + i++ + i++;
printf("%d",a);
return 0;
}
a. 19
b. 18
c. 17
d. 20
Answer: b(18)
Explanation:
a = i++ + i++ + i++
a = 5 + i++ + i++
a = 5 + 6 + i++
a=5+ 6+7
a= 18
173
Presidency University – SOCSE & IS
Complete C Guide for Placement
12. What will be the Output?
#include<stdio.h>
int main()
{
int i = 5;
int a = i++ + i++ + ++i;
printf("%d",a);
return 0;
}
a. 19
b. 18
c. 17
d. 20
Answer: a(19)
Explanation:
a = i++ + i++ + ++i
a = 5 + i++ + ++i
a = 5 + 6 + ++i
a=5+ 6+8
a= 19
174
Presidency University – SOCSE & IS
Complete C Guide for Placement
175 What will be the Output?
.
#include<stdio.h>
int main()
{
int i = 5;
int a = --i + ++i - i-- + --i;
printf("%d",a);
return 0;
}
a. 6
b. 7
c. 8
d. 9
Answer: c (8)
Explanation:
a = --i + ++i - i-- + --i
a = 4 + ++i - i-- + --i
a = 4 + 5 - i-- + --i
a = 5 + 5 - 5 + --i
a=5+5-5+3
Finally a = 8.
175
Presidency University – SOCSE & IS
Complete C Guide for Placement
176 What will be the Output?
.
#include<stdio.h>
int main()
{
int a = 2, b = 2, c = 0, d = 2, m;
m = a++ && b++ && c++ || d++;
printf("%d %d %d %d %d",a, b, c, d, m);
return 0;
}
a. Compilation error
b. 33131
c. 33130
d. some garbage value
Answer: b
Explanation:
As operator enjoys priority && have more priority than ||.
m = a++ && b++ && c++ || d++;
m = 1 && c++ || d++;
m = 1 || d++;
m = 1 || 0;
m = 1;
176
Presidency University – SOCSE & IS
Complete C Guide for Placement
15. What will be the Output?
#include<stdio.h>
int main()
{
int a = 5;
a = 1, 2, 3;
printf("%d", a);
return 0;
}
a. 3
b. 2
c. 1
d. 0
Answer: c
Explanation:
Priority for the values assigned to any variable is given from left to right.
177
Presidency University – SOCSE & IS
Complete C Guide for Placement
a. 1
b. 2
c. 3
d. 0
Answer: c
Explanation:
Priority for the values inside a brackets () assigned to any variable is given from right to left.
178
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
• ~ is a One's Complement bitwise operator.
• The function of ~ is a One's Complement is to inverse all value only after converting a
decimal value to binary 0's and 1's
• Here int num = -4;
• Which is num = -100 (in binary 0's and 1's)
• ~num = +011 (in binary 0's and 1's)
• ~num = 3
Explanation:
As & is a unary operator we have to assume all decimal values to binary(0's and 1's)
int x = 2 (in decimal)
x = 00000010( in decimal 0's and 1's)
Now we go for condition (00000010 & 00000001)
Clearly, condition false as it leads to 0 when multiplied.
179
Presidency University – SOCSE & IS
Complete C Guide for Placement
19. What will be the Output?
#include<stdio.h>
int main()
{
int a = 4, b = 2;
printf("a^b = %d", a^b);
return 0;
}
a. 5
b. 6
c. 7
d. 8
Answer: b
Explanation:
^ represent XOR otherwise called as exclusive OR.
Bitwise EX OR operator returns 1 if and only if either of the operands is 1
Bitwise EX OR operator returns 0 for similar inputs
Here a = 4 which is a = 0100
and b = 2 which is b = 0010
0100 ^ 0010
0 1 0 0
0 0 1 0
0 1 1 0=6
Thus output is 0110 i.e) 6
180
Presidency University – SOCSE & IS
Complete C Guide for Placement
20. What will be the Output?
#include<stdio.h>
int main()
{
int a = 4, b = 2;
printf("a|b = %d\n", a|b);
return 0;
}
a. 4
b. 5
c. 6
d. 0
Answer: c
Explanation:
Bitwise OR operator returns 1 either or both of the operands are 1 .
Here a = 4 which is a = 0100
and b = 2 which is b = 0010
0100 | 0010 = 0110
Thus output is 0110 i.e) 6
21. What will be the Output?
#include<stdio.h>
int main()
{
int a = 7, b = 4, c = 2;
printf("a|b&c = %d\n", a|b&c);
return 0;
}
181
Presidency University – SOCSE & IS
Complete C Guide for Placement
a. 5
b. 6
c. 7
d. 10
Answer: c
Explanation:
As operator enjoys priority, & has higher priority over |.
a = 7 which is 0111
b = 4 which is 0100
c = 2 which is 0010
Now a|b&c which is 0111|0100& 0010.
0111|0000.
0111 which is 7 and then outputted.
182
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
2-- stands meaningless
Explanation:
i++ alone store the result in variable i
183
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
= is defined in proprocessor with the name of x. Thus no problem with a normal compilation
flow.
184
Presidency University – SOCSE & IS
Complete C Guide for Placement
GATE Exam Questions:
1. GATE 2021: What will be the output of the following C code?
int main()
{
int a = 5, b = 3;
printf("%d", a++ - b--);
return 0;
}
Answer: The output is 2.
3. GATE 2019: Given the following C code, what is the value of x after the code
execution?
int x = 4;
x = x << 2;
Answer : 4 x 22 = 4 x 4 = 16
4. GATE 2018: If x is an integer variable in C, what does the expression x = x << 1
do?
Answer: It shifts the bits of x to the left by 1 position, effectively doubling the value of x.
185
Presidency University – SOCSE & IS
Complete C Guide for Placement
8. GATE 2014: In C, what is the value of x after the operation: x = 5 && 6?
Answer: The value of x is 1, which represents "true" in C.
10. GATE 2012: Given the following code, what is the output of the printf statement?
int a = 6, b = 3, c;
c = a = b;
printf("%d %d %d", a, b, c);
Answer: The output is 3 3 3.
12. GATE 2010: What is the output of the C code snippet below?
int a = 5, b = 6, c = 7;
a = b = c;
printf("%d %d %d", a, b, c);
Answer: The output is 7 7 7.
14. GATE 2008: If x is an integer variable in C, what does the expression x = x >> 1
do?
Answer: It shifts the bits of x to the right by 1 position, effectively dividing the value of x by
2.
186
Presidency University – SOCSE & IS
Complete C Guide for Placement
15. GATE 2007: What is the value of x after the operation: x = 4 & 6 in C?
Answer: The value of x is 4.
16. GATE 2006: In C, what is the output of the expression (5 || 0) && (3 || 0)?
Answer: The output is 1, which represents "true" in C.
17. GATE 2005: Given the C code snippet below, what is the output of the printf
statement?
int a = 1, b = 1;
if (a == 1)
if (b == 1)
printf("Hello");
else
printf("Hi");
Answer: The output is Hello.
20. GATE 2002: What is the output of the C code snippet below?
int x = 10;
int y = x++;
printf("%d %d", x, y);
Answer: The output is 11 10.
187
Presidency University – SOCSE & IS
Complete C Guide for Placement
21. GATE 2021: What is the value of a after the following C code is executed?
int a = 2;
a = a << 3;
Answer: The value of a is 16.
22. GATE 2020: In C, what is the result of the expression (5 >> 2)?
Answer: The result is 1.
23. GATE 2019: Given the following C code, what is the value of x after the code
execution?
int x = 8;
x = x >> 2;
Answer: The value of x is 2.
24. GATE 2018: If x is an integer variable in C, what does the expression x = x >> 1
do?
Answer: It shifts the bits of x to the right by 1 position, effectively dividing the value of x by
2.
188
Presidency University – SOCSE & IS
Complete C Guide for Placement
29. GATE 2013: Given the following code, what is the value of x after the code
execution?
int x = 3;
x = x & ~2;
Answer: The value of x is 1.
30. GATE 2012: What is the output of the C code snippet below?
Answer: The output is 6 6.
31. GATE 2011: In C, what is the value of x after the operation: x = 6 & 3?
Answer: The value of x is 2.
32. GATE 2010: What is the output of the C code snippet below?
int a = 5, b = 6;
a = a++;
b = ++b;
printf("%d %d", a, b);
Answer: The output is 5 7.
34. GATE 2008: If x is an integer variable in C, what does the expression x = 5 | 3 do?
Answer: It performs a bitwise OR operation between 5 and 3, setting bits in x where either of
the two numbers has a corresponding bit set. The value of x is 7.
35. GATE 2007: What is the value of x after the operation: x = 4 && 6 in C?
Answer: The value of x is 1, which represents "true" in C.
189
Presidency University – SOCSE & IS
Complete C Guide for Placement
36. GATE 2006: In C, what is the output of the expression (0 && 1) || (1 && 0)?
Answer: The output is 0, which represents "false" in C.
37. GATE 2005: Given the C code snippet below, what is the output of the printf
statement?
int a = 1, b = 1;
if (a == 0)
{
if (b == 1)
printf("Hello");
}
else
printf("Hi");
Answer: The output is nothing because neither of the conditions is satisfied, so nothing is
printed.
40. GATE 2002: What is the output of the C code snippet below?
int x = 10;
int y = x--;
printf("%d %d", x, y);
Answer: The output is 9 10.
190
Presidency University – SOCSE & IS
Complete C Guide for Placement
C Input and Output:
Reading data from a file or from input devices is known as input in programming. Results are
displayed on the screen as output. Numerous input and output functions are offered by C.
The corresponding header files for these input and output functions include predefined
definitions. Stdio.h is the header file for standard input and output functions. These are
preceded with the #include statement and included into the programme.
Functions for input and output are divided into two groups. Declaratives of decision-making
(or) Control statements are used to verify conditions; if they are met, a block of statements is
executed.
• C formatted I/O functions are a set of functions in the C programming language that
allow you to perform input and output operations with formatted data.
• These functions are part of the C Standard Library and are primarily used for reading
data from and writing data to files, standard input (keyboard), and standard output
(screen). The most commonly used C formatted I/O functions are printf, scanf, fprintf,
and fscanf.
1. `printf`:
• `printf` is used for formatted output to the standard output (usually the console or
terminal).
• It allows you to display data with specified formats, such as integers, floating-point
numbers, strings, and more.
• The format specifier is used to specify the type of data you want to print, and the data
to be printed is provided as arguments.
Example:
It is a simple C program that uses the `printf` function to display a message containing the
value of an integer variable. Here's the explanation of each part of the code with comments:
191
Presidency University – SOCSE & IS
Complete C Guide for Placement
#include <stdio.h> // This line includes the standard input/output library, allowing you to use
the printf function.
int main()
{
int number = 100; // Declares an integer variable named 'number' and initializes it with the value 100.
printf("The value of number is %d\n", number);
// Uses the printf function to display a message with the value of 'number'.
return 0;
// Indicates the end of the main function and returns 0, which typically means the program executed successfully.
192
Presidency University – SOCSE & IS
Complete C Guide for Placement
4. `return 0;`:
This line marks the end of the `main` function and returns 0, which is a common convention in
C to indicate that the program has executed successfully. A return value of 0 typically signifies
that no errors occurred during the program's execution.
After executing the code, it will display the message "The value of number is 100" on the
console, and the program will return 0, indicating successful execution.
The `printf` statement is a fundamental way to print formatted messages in C, making it a
valuable tool for outputting information to the user.
2. `scanf`:
• `scanf` is used for formatted input from the standard input (usually the keyboard).
• It allows you to read data from the user with specified formats, just like `printf`.
• Format specifiers are used to specify the type of data you want to read, and the data
read is stored in the specified variables.
Example:
The is a simple C program that prompts the user to enter a number, reads the number using the
`scanf` function, and then displays the entered number using `printf`.
Here's the code with comments explaining each part:
#include <stdio.h> // Include the standard input/output library.
int main()
{
int number; // Declare an integer variable named 'number' to store the user's input.
printf("Enter a number: "); // Prompt the user to enter a number.
scanf("%d", &number); // Use scanf to read an integer from the user and store it in 'number'.
printf("The value of number: %d", number); // Display the value of 'number'.
return 0; // Return 0 to indicate successful program execution.
}
193
Presidency University – SOCSE & IS
Complete C Guide for Placement
Here's how the code works:
1. `#include <stdio.h>`:
This line includes the standard input/output library, which provides functions like `printf` and
`scanf` for input and output operations.
2. `int number;`:
This line declares an integer variable named 'number' without initializing it. This variable will
be used to store the integer value entered by the user.
3. `printf("Enter a number: ");`:
This line uses the `printf` function to display the message "Enter a number: " on the console,
prompting the user to input a number.
4. `scanf("%d", &number);`:
This line uses the `scanf` function to read an integer from the user. Let's break it down:
• `" %d"`: This is a format specifier within the `scanf` function. It specifies that the input
should be an integer. The `%d` format specifier is used for reading integers.
• `&number`: The `&` operator is used to pass the memory address of the 'number'
variable to `scanf`. `scanf` needs the address of the variable where it will store the value
it reads. By using `&number`, we provide `scanf` with the address of the 'number'
variable so it can store the entered value there.
5. `printf("The value of number: %d", number);`:
After reading the integer using `scanf`, this line uses the `printf` function to display the value
of 'number' with the message "The value of number: ".
6. `return 0;`:
This line marks the end of the `main` function and returns 0, which is a common convention in
C to indicate successful program execution.
When we run this code, it will work as follows:
1. It will prompt the user to enter a number.
2. The user enters a number (e.g., 42) and presses the "Enter" key.
3. The `scanf` function reads the entered integer (42) and stores it in the 'number' variable.
4. The program then uses `printf` to display "The value of number: 42" on the console.
194
Presidency University – SOCSE & IS
Complete C Guide for Placement
Example on Width Specifier:
#include <stdio.h> // Include the standard input/output library for printf.
int main()
{
// Define the main function, the entry point of the program.
// Print the first 2 characters of the string "Rohini" with a field width of 2.
printf("\n%.2s", "Rohini");
// Print the first 3 characters of the string "Rohini" with a field width of 3.
printf("\n%.3s", "Rohini");
// Print the first 4 characters of the string "Rohini" with a field width of 4.
printf("\n%.4s", "Rohini");
// Print the first 5 characters of the string "Rohini" with a field width of 5.
printf("\n%.5s", "Rohini");
// Print the entire string "Rohini" with a field width of 6.
// Since the string is shorter, it will be padded with spaces to match the width.
printf("\n%.6s", "Rohini");
return 0; // Return 0 to indicate successful program execution.
}
195
Presidency University – SOCSE & IS
Complete C Guide for Placement
• In the last printf statement, the field width is set to 6, but since "Rohini" is shorter than
6 characters, it will be padded with spaces to fill the field width.
The output demonstrates how the %.<n>s format specifier controls the number of characters
printed from the string, and how padding is added to reach the specified field width when the
string is shorter.
Various Format specifiers in C Language:
In C programming, format specifiers are used with functions like `printf` and `scanf` to specify
the data type and format of the data that is being input or output.
Here are some common format specifiers in C along with explanations:
196
Presidency University – SOCSE & IS
Complete C Guide for Placement
Explanation:
• #include : This line includes the standard input/output library in your C program, which
is required for using functions like printf for output.
• int number = 100;: This line declares an integer variable named number and initializes
it with the decimal value 100.
%i: The %i specifier is also used for formatting and printing integers. It behaves like %d for
decimal integers. However, it has a more versatile role. It can be used to interpret integers in
different bases, such as octal (base 8) and hexadecimal (base 16), if the input value is formatted
accordingly.
197
Presidency University – SOCSE & IS
Complete C Guide for Placement
198
Presidency University – SOCSE & IS
Complete C Guide for Placement
These format specifiers are used with `printf` for output and `scanf` for input. For example,
when using `printf`, you specify the format specifier, followed by the variable you want to
print. When using `scanf`, you specify the format specifier and provide a pointer to the variable
where the input should be stored. For example:
```c
int num = 42;
printf("The value of num is %d\n", num);
```
In this example, `%d` is the format specifier for an integer, and it is replaced with the value of
the `num` variable in the output.
3. `fprintf`:
- `fprintf` is used for formatted output to a file instead of the standard output.
- It works similarly to `printf`, but you specify the file to which the data is written as the first
argument.
199
Presidency University – SOCSE & IS
Complete C Guide for Placement
Example:
```c
FILE *file = fopen("output.txt", "w");
fprintf(file, "This is written to the file.\n");
fclose(file);
```
4. `fscanf`:
- `fscanf` is used for formatted input from a file instead of the standard input.
- It works similarly to `scanf`, but you specify the file from which data is read as the first
argument.
Example:
```c
FILE *file = fopen("input.txt", "r");
int num;
fscanf(file, "%d", &num);
fclose(file);
```
In all of these functions, format specifiers like `%d`, `%f`, `%s`, etc., are used to specify the
data type and format for input or output. They also allow you to control the precision, width,
alignment, and other formatting options for the data. C formatted I/O functions provide a
powerful and flexible way to interact with data in a structured manner, making them an
essential part of C programming for handling input and output operations.
scanf() Function:
• scanf function reads all types of data value from input devices (or) from a file. The
address operator '&' is to indicate the memory location of the variable. This memory
location is used to store the data which is read through keyboard.
• scanf is used for formatted input from the standard input (usually the keyboard).
• It allows you to read data from the user with specified formats, just like printf.
• Format specifiers are used to specify the type of data you want to read, and the data
read is stored in the specified variables.
200
Presidency University – SOCSE & IS
Complete C Guide for Placement
Example:
int num;
printf("Enter a number: ");
scanf("%d", &num);
201