Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
117 views

Complete C Programming Guide Employment

Complete C Programming Guide Employment

Uploaded by

Rohini Aravindan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
117 views

Complete C Programming Guide Employment

Complete C Programming Guide Employment

Uploaded by

Rohini Aravindan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 201

Presidency University – PSCS & PSIS

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

int num1 = 10;


int num2 = 20;
int sum;

// Perform some operations

sum = num1 + num2;

// Display the result

printf("The sum of %d and %d is %d\n", num1, num2, sum);

// Return an exit status to the operating system

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.

Ms. Rohini A, AP/PSCS 1 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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;

Ms. Rohini A, AP/PSCS 2 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Concepts on Preprocessor Directives:


Example 1:
#include<stdio.h>
#define rohini main
void rohini()
{
printf("Welcome to Presidency University");
}

Ms. Rohini A, AP/PSCS 3 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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)

Ms. Rohini A, AP/PSCS 4 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

// Define the 'rohini' function.


void rohini()
{
printf("Hello Everyone\n");
printf("Welcome");
}
1. #define rename(a,b,c,d) a##b##c##d:
This line defines a preprocessor macro named rename that uses the ## operator to concatenate
its four arguments (a, b, c, and d) into a single identifier. This macro allows us to create custom
identifiers by concatenating the provided arguments.
2. #define rohini rename(m,a,i,n):
This line defines a preprocessor macro rohini that uses the rename macro to create an identifier
"main." This effectively renames the function main to "rohini."
3. void rohini():
This defines the rohini function. The function name is a result of macro substitution, and it has
a void return type, which doesn't return any value.
Inside the rohini function, there are two printf statements that display the messages "Hello
Everyone" and "Welcome" to the console.
When we run this program, it behaves as if the main function is named "rohini." The rohini
function is executed, and it prints the two messages to the console.
Example 3:
This is a basic C program that does some simple arithmetic operations and makes use of a
preprocessor macro. Let's examine the code.
#include <stdio.h> // Include the standard input/output library.
#define x 2 // Define a preprocessor macro 'x' with the value 2.
int main()
{
int i; // Declare an integer variable 'i'.
i = x * x * x; // Calculate the cube of 'x' and store it in 'i'.
printf("%d", i); // Print the value of 'i'.
return 0; // Return 0 to indicate successful program execution.
}

Ms. Rohini A, AP/PSCS 5 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 6 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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()

int i; // Declare an integer variable 'i'.

i = 64 / square(4); // Perform the operation 64 / square(4) and store the result in 'i'.

printf("%d", i); // Print the value of 'i'.

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 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); :

Ms. Rohini A, AP/PSCS 7 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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'.

printf("%d", i); // Print the value of 'i'.

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 square(x) x*x:

Ms. Rohini A, AP/PSCS 8 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.
}

Ms. Rohini A, AP/PSCS 9 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.
}

Ms. Rohini A, AP/PSCS 10 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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:

Ms. Rohini A, AP/PSCS 11 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

#include <stdio.h> // Include the standard input/output library.


int main()
{
printf("%p", main); // Print the memory address of the 'main' function.
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. 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:

Ms. Rohini A, AP/PSCS 12 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

#include <stdio.h> // Include the standard input/output library.


#define x 10; // Define a preprocessor macro 'x' with the value 10 and a semicolon.
int main()
{
printf("%d", x); // Print the value of 'x'.
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 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; :

Ms. Rohini A, AP/PSCS 13 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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:

#include <stdio.h> // Include the standard input/output library.


#define x 10 // Define a preprocessor macro 'x' with the value 10 and a semicolon.
int main()
{
printf("%d", x); // Print the value of 'x'.
return 0; // Return 0 to indicate successful program execution.
}

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

Ms. Rohini A, AP/PSCS 14 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

4. How may preprocessor directives be used in C to enable conditional compilation?


Give a usage example for it.
It is possible to accomplish conditional compilation by utilising the #ifdef, #ifndef, #else, and
#endif directives. For instance:

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:

Ms. Rohini A, AP/PSCS 15 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

7. What is the purpose of the #undef directive in C? How is it used?


The #undef directive is used to undefine a previously defined macro. For 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.

10. What is the purpose of the # operator and ## operator in C preprocessor


directives? Provide examples of their usage.
# is the stringizing operator and converts a macro argument into a string.
## is the token-pasting operator and concatenates two tokens into a single token.
For example:

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:

Ms. Rohini A, AP/PSCS 16 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Question 2: What is the primary purpose of the #define directive in C preprocessor?


A. Defining macros and constants.
B. Declaring variables.
C. Including header files.
D. Writing comments.
Answer: A. Defining macros and constants.

Question 3: Given the following code snippet:

What will be the value of result?

Ms. Rohini A, AP/PSCS 17 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

A. 5
B. 25
C. 15
D. 11
Answer: D. 11

Question 4: Which preprocessor directive is used to include a system or library header


file in a C program?
A. #import
B. #define
C. #include
D. #pragma
Answer: C. #include

Question 5: In conditional compilation, which directive is used to check if a macro is not


defined?
A. #ifndef
B. #elif
C. #else
D. #endif
Answer: A. #ifndef

Question 6: Which of the following preprocessor directives is used for compiler-specific


instructions or optimizations?
A. #ifdef
B. #pragma
C. #undef
D. #include
Answer: B. #pragma

Question 7: What is the purpose of the #undef directive in C preprocessor?

Ms. Rohini A, AP/PSCS 18 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

A. To define a new macro.


B. To undefine a previously defined macro.
C. To include a header file.
D. To generate a compilation error.
Answer: B. To undefine a previously defined macro.

Question 8: In C, what is the result of the token-pasting operator (##)?


A. It generates a compilation warning.
B. It converts a macro argument into a string.
C. It concatenates two tokens into a single token.
D. It expands a macro definition.
Answer: C. It concatenates two tokens into a single token.

Question 9: What is the purpose of the #error directive in C preprocessor?


A. To generate a compilation warning.
B. To generate a compilation error with a custom error message.
C. To include a header file.
D. To define a new macro.
Answer: B. To generate a compilation error with a custom error message.

Question 10: What is the output of the following code?

A. 10000
B. 100
C. 200
D. 10
Answer: A. 10000

Ms. Rohini A, AP/PSCS 19 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

Question 11: What is the purpose of the # operator in C preprocessor directives?


A. It is used for stringizing a macro argument.
B. It concatenates two tokens into a single token.
C. It defines macros.
D. It includes header files.
Answer: A. It is used for stringizing a macro argument.

Question 12: Given the following code:

What will be the value of result?


A. 1020
B. 30
C. 10
D. 20
Answer: A. 1020

Question 13: In conditional compilation, which preprocessor directive is used to check if


a macro is defined?
A. #ifdef
B. #ifndef
C. #if
D. #else
Answer: A. #ifdef

Question 14: What is the primary advantage of using preprocessor directives in C?


A. Improved runtime performance.
B. Enhanced code readability.
C. Easier debugging.

Ms. Rohini A, AP/PSCS 20 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

D. Platform-independent code and configuration management.


Answer: D. Platform-independent code and configuration management.

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.

Question 17: What is the output of the following code?

A. 2
B. 4
C. 8
D. 16
Answer: D. 16

Ms. Rohini A, AP/PSCS 21 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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 21: Describe the use of preprocessor directives in cross-platform development.


How can preprocessor directives help manage platform-specific code or configurations?
Answer: Preprocessor directives are vital in cross-platform development to handle platform-
specific code or configurations. By using conditionals like #ifdef, #ifndef, and #elif combined
with platform-specific macros, developers can include or exclude sections of code based on the
target platform. For instance, they can manage code differences between Windows and Linux
or between 32-bit and 64-bit systems.

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

Ms. Rohini A, AP/PSCS 22 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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 26: Consider the following C code:

Ms. Rohini A, AP/PSCS 23 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

What will be the output of this code?


A) 16
B) 12
C) 9
D) 7
Answer: D) 7
Explanation: The macro SQUARE(x) is not defined with proper parentheses around x, which
leads to unexpected behavior due to operator precedence. The expression SQUARE(y + 1)
expands to y + 1 * y + 1, which evaluates to 3 + 1 * 3 + 1, resulting in 7.

Question 27:
Consider the following C code:

What will be the output of this code?


A) 64
B) 49
C) 64 or 49 (ambiguous)
D) Compiler error

Ms. Rohini A, AP/PSCS 24 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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:

What will the value of result be?


A) 4
B) 5
C) 9
D) 16
Answer: B) 5

Explanation: The macro SQUARE(x) expands to x * x. When a + 1 is substituted for x, it


becomes 2 + 1 * 2 + 1, which results in 5.

Ms. Rohini A, AP/PSCS 25 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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 Based Questions on Preprocessor Directives:


Scenario-based questions on preprocessor directives help assess your practical understanding
of how these directives are used in real-world programming situations. Here are some scenario-
based questions along with explanations:

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:

Ms. Rohini A, AP/PSCS 26 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 27 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

These scenario-based questions explore practical applications of preprocessor directives in


various programming situations, including cross-platform development, large-scale projects,
optimization, and library design.

Ms. Rohini A, AP/PSCS 28 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement
Keywords:
Keywords in the C programming language are reserved words with special meanings and
predefined functionality. These words are part of the language's syntax and cannot be used for
other purposes such as naming variables or functions. Here are some common C keywords:
1. auto: It is used to declare automatic variables, which are local variables that have a
limited scope within a block or function.
2. break: Used to exit from loops or switch statements prematurely.
3. case: Part of the switch statement, used to define individual cases.
4. char: A data type used to declare character variables.
5. const: It is used to declare constants, values that cannot be modified after initialization.
6. continue: Used to skip the current iteration of a loop and move to the next iteration.
7. default: Part of the switch statement, executed if no matching case is found.
8. do: Starts a do-while loop, which executes a block of code at least once before checking
the loop condition.
9. double: A data type used to declare double-precision floating-point variables.
10. else: Used in conditional statements to specify an alternative block of code to execute.
11. enum: Used to define an enumeration, a set of named integer constants.
12. extern: Declares a variable or function as existing in another file.
13. float: A data type for single-precision floating-point variables.
14. for: Begins a for loop, which is used for iterative control flow.
15. if: Starts a conditional statement to execute code based on a condition.
16. int: A data type for integer variables.
17. long: A data type for longer integer variables.
18. register: Suggests that a variable should be stored in a CPU register for faster access.
19. return: Used to exit a function and return a value to the calling code.
20. short: A data type for shorter integer variables.
21. signed: Specifies that a data type can hold positive and negative values.
22. sizeof: A unary operator used to determine the size (in bytes) of a data type or object.
23. static: Declares variables and functions as having a static scope, limiting their visibility
to the current file.
24. struct: Used to define user-defined data structures, combining multiple variables of
different data types.
25. switch: Begins a switch statement, allowing you to choose one of several code paths
based on a value.
Ms. Rohini A, AP/PSCS 29 Dr. Blessed Prince P, HoD/PSCS
Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Rules for naming Keywords:


Here are some rules for naming keywords in C:
Case Sensitivity: Keywords are case-sensitive, which means that uppercase and lowercase
letters are treated differently. For example, "if" and "IF" are not the same keyword.
1. All Uppercase: While C doesn't require keywords to be written in all uppercase letters,
it is a common convention to write them in uppercase for clarity. For instance, "if" and "IF"
both work, but "IF" is often preferred for consistency.
2. Don't Use Keywords as Identifiers: It's crucial not to use keywords as variable names,
function names, or any other identifiers in your C code. Doing so will result in compilation
errors.
3. Reserved Meanings: Keywords have predefined meanings and are an integral part of
the C language's syntax. Attempting to redefine or repurpose a keyword is not allowed.
4. Stay Informed: Keep yourself updated with the list of keywords for the version of C
you are using. While most of the keywords are consistent across different C standards, some
may change or be introduced in newer versions.
5. Avoid Confusing Similar Identifiers: Be cautious when naming your variables or
functions to avoid names that resemble keywords. This helps maintain code readability and
reduces the chance of accidental conflicts.
6. Use Descriptive Identifiers: Choose meaningful and descriptive names for your
variables and functions. This practice enhances the clarity and maintainability of your code.
7. Compiler Warnings: Most C compilers will issue a warning or error if you attempt to
use a keyword as an identifier. Pay attention to these warnings and resolve any issues before
compiling your code.

Ms. Rohini A, AP/PSCS 30 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

printf("The value of BREAK = %d ", break); :


This line is an attempt to print the value of the "break" variable using printf. However, as
mentioned earlier, "break" is not a valid variable name in C, so this code is incorrect.

Ms. Rohini A, AP/PSCS 31 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

int BREAK = 100; :


This line declares a variable named "BREAK" of type int and initializes it with the value 100.
The use of uppercase for "BREAK" makes it a valid identifier in C because C is case-sensitive,
and "BREAK" and "break" are treated as different.

Ms. Rohini A, AP/PSCS 32 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

printf("The value of BREAK = %d ", BREAK); :


This line uses the printf function to display the value of the "BREAK" variable. It will print the
message "The value of BREAK = 100" if executed.
return 0; :
This line signifies the end of the main function and returns an exit status of 0, indicating
successful program execution.
Placement Questions:
1. What are keywords in C programming, and why are they important?
Keywords in C programming are reserved words with special meanings and predefined
functionality. They are crucial because they form the foundation of the language's syntax and
are used to define control structures, data types, and various other language constructs.
Attempting to use keywords for other purposes may lead to compilation errors and unexpected
behavior.
2. Give examples of some C keywords and their purposes.
Examples of C keywords include "if," "for," "int," "switch," "return," and "while." Each
keyword has a specific role: "if" is used for conditional branching, "int" is a data type for
integers, "for" is used for loops, "switch" is used for multi-branching, "return" exits a function,
and "while" is used for looping.
3. Explain the importance of case sensitivity when dealing with C keywords.
C is a case-sensitive language, meaning that uppercase and lowercase letters are treated
differently. This impacts the usage of keywords. For example, "if" and "IF" are considered
distinct. Therefore, it's important to use keywords in the correct case to avoid errors.
4. Why is it a bad practice to use C keywords as variable names?
Using C keywords as variable names is discouraged because it can lead to confusion and errors.
Keywords have predefined meanings in the language, and repurposing them for variable names
can make the code less readable and maintainable.
5. Can you use C keywords as part of user-defined identifiers (variable or function
names)? If so, under what conditions?
In C, you can technically use C keywords as part of user-defined identifiers if they are not used
in isolation. For example, "myif" is a valid identifier because "if" is not a standalone keyword.
However, it is best practice to avoid using keywords in this manner to enhance code readability.
6. What is the significance of the "const" keyword in C, and how is it used?
The "const" keyword is used to declare constants, which are values that cannot be modified
after initialization. It is often applied to variables to indicate that their values should not change
throughout their lifetime.

Ms. Rohini A, AP/PSCS 33 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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 };

Ms. Rohini A, AP/PSCS 34 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 35 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

GATE Exam questions:


1. Which of the following is a valid C keyword?
A) print
B) real
C) constant
D) case
E) string
Answer:
D) case

2. What is the primary purpose of the "const" keyword in C?


A) To declare a constant variable.
B) To define a character data type.
C) To indicate a loop condition.
D) To define a structure.
E) To specify a case label.
Answer:
A) To declare a constant variable.

Ms. Rohini A, AP/PSCS 36 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

3. In C, what does the "volatile" keyword indicate about a variable?


A) It is a global variable.
B) It is a constant.
C) It can be modified by external factors.
D) It is a floating-point number.
E) It is a type qualifier.
Answer:
C) It can be modified by external factors.

4. What is the purpose of the "register" keyword in C?


A) It defines a function.
B) It suggests that a variable should be stored in a CPU register for faster access.
C) It indicates a global variable.
D) It is used in defining arrays.
E) It is a type qualifier.
Answer:
B) It suggests that a variable should be stored in a CPU register for faster access.

5. Which keyword is used in a "switch" statement to specify the default case?


A) default
B) continue
C) case
D) else
E) break
Answer:
A) default

----------------------------------------------------------------------------------------------------------------

Ms. Rohini A, AP/PSCS 37 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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;

Ms. Rohini A, AP/PSCS 38 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

}
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.

Ms. Rohini A, AP/PSCS 39 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Derived Data Types:


Array: A collection of elements of the same data type.
Pointer: A variable that stores the memory address of another variable.
Structure (struct): A composite data type that groups multiple variables under a single name.
Union: Similar to a structure but shares the same memory location for all its members. It's
typically used for efficient memory utilization.
Enum (Enumeration): A user-defined data type that consists of a set of named integer
constants.

Void Data Type:


void: This data type is used when there is no value available or when the function does not
return any value. It's often used for function return types.
Qualifiers:
const: Used to declare variables that cannot be modified.
volatile: Informs the compiler that the variable's value can change at any time, typically due to
external factors.
_Atomic: Introduced in C11, it's used for atomic operations in multi-threaded environments.

Ms. Rohini A, AP/PSCS 40 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 41 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

// The value of 'variable' is inserted into the placeholder.


printf("The value of integer variable = %d ", variable);
return 0; // Return 0 to indicate successful program execution.
}

Ms. Rohini A, AP/PSCS 42 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 43 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

• 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.

unsigned char maxUnsignedChar = 255;


// Declare an unsigned character variable and initialize it with the maximum value (unsigned).

printf("Maximum char value (unsigned): %u\n", maxUnsignedChar);


// Print the maximum char value (unsigned).

Ms. Rohini A, AP/PSCS 44 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

maxUnsignedChar = maxUnsignedChar + 1;
// Attempt to exceed the maximum char value (unsigned), causing it to wrap around.

printf("Wrapped around char value (unsigned): %u\n", maxUnsignedChar);


// Print the wrapped-around value.

return 0; // Return 0 to indicate successful program execution.


}

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.

float minFloat = -3.402823466e38;


// Declare a float variable and initialize it with the maximum negative 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.

Ms. Rohini A, AP/PSCS 45 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

printf("Overflowed float value: %f\n", maxFloat); // Print the result of overflow.


printf("Underflowed float value: %f\n", minFloat); // Print the result of underflow.

return 0; // Return 0 to indicate successful program execution.


}

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.

printf("The value of b = %0.11f", b);


return 0; // Return 0 to indicate successful program execution.
}

Ms. Rohini A, AP/PSCS 46 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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);

Ms. Rohini A, AP/PSCS 47 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

return 0; // Return 0 to indicate successful program execution.


}
a. 08
b. 010
c. 17
d. 21
Answer: c(17)

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.

Ms. Rohini A, AP/PSCS 48 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

}
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);

Ms. Rohini A, AP/PSCS 49 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 50 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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):

Ms. Rohini A, AP/PSCS 51 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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)

Ms. Rohini A, AP/PSCS 52 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 53 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

Ms. Rohini A, AP/PSCS 54 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 55 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

// Source File 2 (main.c)


#include <stdio.h>
extern int n; // Declare 'n' as an external variable.
int main()
{
n = 10; // Assign a value to 'n'.
printf("%d", n); // Print the value of 'n'.
return 0;
}
Explanation:
extern int n;
In the main.c source file, we declare the variable n as an external variable using the extern
keyword. This indicates that the variable n is defined in another source file and should be
linked at compile time.

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.

Ms. Rohini A, AP/PSCS 56 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 57 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 58 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 59 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 60 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

printf("%d ", num--); // Print the value of 'num' and decrement it by 1.


if (num)
{
main(); // If 'num' is not zero, call the main function recursively.
}
return 0; // Return 0 to indicate successful program execution.
}
a. 5 4 3 2 1
b. 6 5 4 3 2 1
c. Compilation error
d. Runtime error
Answer b.

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.

printf("%d ", num--);


This line prints the value of 'num' using the %d format specifier and then post-decrements
'num' by 1. The value of 'num' is printed before the decrement operation.

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.

Ms. Rohini A, AP/PSCS 61 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

• The last call prints 1, and 'num' is decremented to 0.


• After reaching 0, no further recursive calls are made, and the program terminates.
15.
What is the Output?
#include<stdio.h>
int main()
{
if (sizeof(char) > -12)
printf("yes");
else
printf("No");
return 0;
}
a. Yes
b. No
c. Compilation error
d. None of the above
Answer : b

Explanation:

By default, all integer literals such as


-12
-56
23
are assigned as unsigned integer by C compiler. So, if negative integers are given it will
loop through its range 0 to 65,535. i.e) -12 is equal to 65524.

Ms. Rohini A, AP/PSCS 62 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

GATE Exam Questions:


1. Which of the following data types in C has the highest storage size?
A. int
B. long int
C. float
D. double
The correct answer is: D. double

Ms. Rohini A, AP/PSCS 63 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

2. In C, what is the result of dividing an `int` by `0`?


A. Compile-time error
B. Run-time error
C. Infinity
D. Zero
The correct answer is: B. Run-time error
Explanation: When you divide an integer by zero in C, it results in a run-time error, causing
undefined behavior. This error is not caught at compile time but rather at run time.

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.

Ms. Rohini A, AP/PSCS 64 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

7. Which data type in C is used to represent a single character?


A. char
B. int
C. float
D. double
The correct answer is: A. char
Explanation: The char data type in C is used to represent a single character, such as a letter or
symbol. It typically occupies 1 byte of memory.

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

Ms. Rohini A, AP/PSCS 65 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

9. What is the size (in bytes) of a pointer on a 32-bit platform?


A. 1
B. 2
C. 4
D. 8
The correct answer is: C. 4
Explanation: On a 32-bit platform, a pointer typically has a size of 4 bytes. It can vary
depending on the platform and compiler, but this is a common size for 32-bit systems.

10. Which data type in C is used to represent a true or false value?


A. int
B. char
C. bool
D. float
The correct answer is: A. int
Explanation: In C, boolean values are often represented using an int, where 0 typically
represents "false," and any non-zero value represents "true." The C language itself does not
have a dedicated bool data type, but it can be emulated using 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.

Ms. Rohini A, AP/PSCS 66 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 67 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

printf("The number is %d ", a);


prints the value of the 'a' variable to the standard output.
printf("\nThe Number is %d ", A);
prints the value of the 'A' variable to the standard output, starting on a new line.
This program demonstrates the use of identifiers 'a' and 'A' to represent two different variables,
showcasing that C is a case-sensitive language, and 'a' and 'A' are distinct identifiers.

Identifier rules for Declaration


Identifiers are used in programming languages to name variables, functions, classes, and other
elements within your code. When declaring identifiers, we need to follow certain rules to
ensure that our code is syntactically correct and readable.
1. Case Sensitivity: In many programming languages, identifiers are case-sensitive. This
means that myVariable, MyVariable, and myvariable would be considered as three
different identifiers.
2. Start with a Letter or Underscore: Typically, an identifier must start with a letter (a-
z or A-Z) or an underscore (_). It should not start with a digit.
3. Subsequent Characters: After the first character, you can use letters, digits, or
underscores in an identifier. Avoid using special characters like spaces, punctuation, or
symbols.
4. Reserved Words: Avoid using reserved words or keywords of the programming
language as identifiers, as they have special meanings. For example, in C, you shouldn't
use int, for, or if as identifiers.
5. Length Limit: Some programming languages impose a maximum length for
identifiers. While it can vary, it's typically a reasonable length to maintain code
readability.
6. Meaningful Names: Choose meaningful and descriptive names for your identifiers.
This makes your code more understandable to yourself and others.
7. CamelCase or Underscore Naming Conventions: While not a strict rule, many
programming languages have naming conventions. For instance, in Java, it's common
to use CamelCase (e.g., myVariableName). In Python, underscores are often used (e.g.,
my_variable_name).
8. Consistency: Be consistent in your naming style throughout your code. If you start
with CamelCase, continue to use it for all identifiers. The same applies to underscore-
based naming conventions.
9. Numbers in Identifiers: You can use numbers in identifiers, but they are usually not
recommended to start with. For example, value1 is acceptable, but 1value might be
confusing.
10. Context: Consider the context in which the identifier is used. Variables that represent
names, like 'userName', should be named differently from those representing numbers,
like 'userCount'.

Ms. Rohini A, AP/PSCS 68 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 69 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Question 2: Which of the following is a valid identifier in C?


a) 2nd_variable
b) _myIdentifier
c) main-function
d) my variable
Answer: b) _myIdentifier
Question 3: Can a C identifier start with a digit?
Answer: No, a C identifier cannot start with a digit.
Question 4: Is the following a valid C identifier?
myVariable@2023
Answer: No, the @ symbol is not allowed in C identifiers, so myVariable@2023 is not valid.

Ms. Rohini A, AP/PSCS 70 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

Question 5: What is the maximum length of an identifier in C?


Answer: C does not specify a maximum length for identifiers, but most C compilers support
identifiers of at least 31 characters.

Question 6: Are C identifiers case-sensitive?


Answer: Yes, C identifiers are case-sensitive. myVariable and MyVariable are treated as two
different identifiers.

Question 7: Which of the following is not a valid way to declare a C identifier?


a) int variableName;
b) double 2nd_variable;
c) char MyVar;
d) float my_var;
Answer: b) double 2nd_variable;
Question 8: Which header file must be included to use the printf and scanf functions in
C?
Answer: To use printf and scanf functions, you must include the header file.

Question 9: Is it a good practice to use keywords as identifiers in C?


Answer: No, it is not a good practice to use keywords as identifiers in C. Keywords are reserved
for specific language constructs and cannot be used as identifiers.

Question 9: Which of the following is a valid identifier in C?


a) total_sales$
b) 123_identifier
c) user-name
d) myVariableName
Answer: d) myVariableName

Ms. Rohini A, AP/PSCS 71 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

GATE Exam Questions:


Question 1: (GATE 2019)
Which of the following is true for identifiers in C?
A) Identifiers can be a combination of letters, digits, and underscores.
B) Identifiers must start with a digit.
C) Identifiers can include special characters like @, #, and $.
D) Identifiers cannot be longer than 6 characters.
Answer: A) Identifiers can be a combination of letters, digits, and underscores.

Question 2: (GATE 2018)


In C, which of the following is NOT a valid identifier?
A) total_sales$
B) My_Name
C) 123_identifier
D) int
Answer: D) int
Question 3: (GATE 2017)
Which of the following is a valid identifier in C?
A) main-function
B) break
C) int
D) _for
Answer: D) _for

Question 4: (GATE 2016)


Which of the following is true about identifiers in C?
A) Identifiers cannot have more than 31 characters.
B) Identifiers are not case-sensitive.
C) Identifiers cannot start with an underscore.
D) Identifiers cannot be the same as C keywords.
Answer: D) Identifiers cannot be the same as C keywords.

Ms. Rohini A, AP/PSCS 72 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

Question 5: (GATE 2015)


In C, if you declare a variable as "int double," is it a valid identifier?
A) Yes
B) No
C) It depends on the compiler.
Answer: B) No
Question 6: (GATE 2014)
Which of the following is a valid identifier in C?
A) 1_variable
B) _underscore
C) double float
D) long int
Answer: B) _underscore

Question 7: (GATE 2013)


What is the maximum length of an identifier in C?
A) 31 characters
B) 63 characters
C) 127 characters
D) There is no specified maximum length.
Answer: D) There is no specified maximum length.

Question 8: (GATE 2012)


Identify the valid and invalid identifiers among the following:
i) $identifier
ii) _2ndValue
iii) while
iv) my-variable
A) i) and ii) are valid; iii) and iv) are invalid.
B) ii) and iii) are valid; i) and iv) are invalid.
C) i) and iii) are valid; ii) and iv) are invalid.

Ms. Rohini A, AP/PSCS 73 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

D) i), ii), and iii) are valid; iv) is invalid.


Answer: A) i) and ii) are valid; iii) and iv) are invalid.

Question 9: (GATE 2011)


Which of the following is not a valid identifier in C?
A) _abc
B) 23abc
C) if
D) double
Answer: C) if
Question 10: (GATE 2010)
Which of the following is a valid identifier in C?
A) 1x
B) _abc
C) #define
D) int
Answer: B) _abc

Ms. Rohini A, AP/PSCS 74 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 75 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 76 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

Ms. Rohini A, AP/PSCS 77 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

Ms. Rohini A, AP/PSCS 78 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 79 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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;

Ms. Rohini A, AP/PSCS 80 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

}
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

Ms. Rohini A, AP/PSCS 81 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 82 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

Ms. Rohini A, AP/PSCS 83 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

Ms. Rohini A, AP/PSCS 84 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

Ms. Rohini A, AP/PSCS 85 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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);

Ms. Rohini A, AP/PSCS 86 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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

Ms. Rohini A, AP/PSCS 87 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

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.

Ms. Rohini A, AP/PSCS 88 Dr. Blessed Prince P, HoD/PSCS


Presidency University – PSCS & PSIS
PU-CCC
Complete C Guide for Placement

GATE Exam Questions:


Question 1: (GATE 2021)
Which of the following is a valid variable name in C?
A) 123abc
B) _abc123
C) float
D) break
Answer: B) _abc123

Question 2: (GATE 2021)


What is the maximum length of an identifier in C?
A) 31 characters
B) 63 characters
C) 127 characters
D) There is no specified maximum length.
Answer: D) There is no specified maximum length.

Question 3: (GATE 2020)


Which of the following is a valid C variable name?
A) 2variable
B) _variable
C) float
D) main_function
Answer: B) _variable
Question 4: (GATE 2020)
In C, are variable names case-sensitive?
A) Yes
B) No
C) It depends on the compiler.
Answer: A) Yes

Ms. Rohini A, AP/PSCS 89 Dr. Blessed Prince P, HoD/PSCS


Presidency University – SOCSE & IS
Complete C Guide for Placement
Question 5: (GATE 2019)
Which of the following is NOT a valid variable name in C?
A) myVariable
B) totalSales$
C) char
D) num_123
Answer: C) char

Question 6: (GATE 2019)


What is the scope of a local variable in C?
A) Global
B) File
C) Function
D) System
Answer: C) Function

Question 7: (GATE 2018)


In C, can a variable name start with a digit?
A) Yes
B) No
C) It depends on the compiler.
Answer: B) No
Question 8: (GATE 2018)
Which of the following is a reserved keyword in C?
A) variable
B) int
C) double
D) 123abc
Answer: B) int

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

Question 11: (GATE 2016)


In C, are variable names with leading underscores reserved?
A) Yes
B) No
C) It depends on the compiler.
Answer: A) Yes

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

Question 13: (GATE 2015)


Which data type is used to represent a single character in C?
A) char
B) character
C) single
D) int
Answer: A) char
Question 14: (GATE 2015)
What is the default value of an uninitialized variable in C?
A) 0
B) 1
C) It depends on the variable type.
D) Undefined
Answer: D) Undefined

Question 15: (GATE 2014)


In C, which of the following is a valid variable declaration?
A) int 2ndValue;
B) double float;
C) long int;
D) _underscore;
Answer: D) _underscore;

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

Question 20: (GATE 2012)


What is the keyword used in C to declare a function?
A) func
B) function
C) fn
D) void
Answer: D) void

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.

Decimal Constants (Integer Constants):


• An integer constant is made up of the integer values 0 through 9.
• An integer constant cannot contain decimal points, black spaces, or commas.
• An integer constant has three possible values: zero, positive, and negative.
• If there is no sign, the number is presumed to be positive.
There are three categories for integer constants.
1. Decimal integer constants are what they are.
2. Constants for Octal Integers.
3. Constants for Hexadecimal Integers.
In programming, decimal integer constants are numeric values expressed in base 10, which is
the standard decimal numeral system. They consist of a sequence of digits (0-9) without any
prefix or suffix. Decimal integer constants can be both positive and negative.
Here are some examples of decimal integer constants:
Positive integers:
• 42
• 123
• 7890

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.

Octal Integer Constants:


Octal integer constants are numeric values expressed in base 8, which means they consist of
digits from 0 to 7. In most programming languages, including C and C++, you can represent
octal integers by prefixing the number with a leading '0' (zero).
Octal constants are less common in modern programming, but they can still be used for specific
purposes.
Here are some examples of octal integer constants:
• 012 (Represents the decimal value 10)
• 077 (Represents the decimal value 63)
• 0377 (Represents the decimal value 255)
• 045 (Represents the decimal value 37)
• 01000 (Represents the decimal value 512)
In octal notation, each digit represents three bits (binary digits). For example, the octal number
012 is equivalent to the binary number 001010 and the decimal number 10.
In many programming languages, if we use the leading '0' before a sequence of digits, the
compiler or interpreter interprets them as octal. So, it's important to be aware of this when
working with numeric literals in our code.

96
Presidency University – SOCSE & IS
Complete C Guide for Placement

Hexadecimal Integer Constants:


Hexadecimal integer constants are numeric values expressed in base 16. They consist of digits
0-9 and the letters A-F (or a-f) to represent values 10 to 15.
Hexadecimal notation is commonly used in programming for several purposes, such as
representing memory addresses, colors in web design, and bitwise operations.
In most programming languages, hexadecimal integer constants are prefixed with "0x" or "0X"
to indicate that they are in hexadecimal form. For example, the hexadecimal value for the
decimal number 15 is 0xF.
Here are some examples:
• 0x1F (Represents the decimal value 31)
• 0xA5 (Represents the decimal value 165)
• 0xFF (Represents the decimal value 255)
• 0x10 (Represents the decimal value 16)
Each hexadecimal digit represents four bits (a nibble) in binary. For instance, the hexadecimal
number 0xA5 is equivalent to the binary number 10100101 and the decimal number 165.
Hexadecimal notation is particularly useful in low-level programming, such as dealing with
memory addresses or manipulating bits and flags within registers. It is also common in web
development when specifying colors using the RGB color model.

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)

Long Integer Constants:


• A long integer constant represents an integer value that requires more memory storage
than a regular integer.
• In many programming languages, including C and C++, you can denote a long integer
constant by appending an 'L' or 'l' to the end of the constant.
Examples of long integer constants:
• 1000L (Long integer constant, value 1000)
• 1234567890L (Long integer constant, value 1234567890)
• 0x1FFFFFFFFL (Long integer constant in hexadecimal, value 8589934591)

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?

Answer: 1096(in decimal)

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

Question 2: (GATE 2021)


Which of the following represents the decimal number 23 in octal?
a) 23
b) 33
c) 43
d) 53
Answer: b) 33
Question 3: (GATE 2020)
What is the value of the C expression 0xFF - 037?
Answer: 240

Question 4: (GATE 2020)


What is the maximum value of a 32-bit signed integer?
a) 32767
b) 2147483647
c) 65535
d) 4294967295
Answer: b) 2147483647
Question 5: (GATE 2019)
What is the binary representation of the decimal number 15?
a) 1010
b) 1101
c) 1111
d) 10000
Answer: c) 1111

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

Question 7: (GATE 2018)


What is the decimal equivalent of the octal number 64?
Answer: 52

Question 8: (GATE 2018)


In C, which of the following is an octal integer constant?
a) 123
b) 0xA0
c) 057
d) 0x123

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

Question 17: (GATE 2013)


What is the maximum value of a 32-bit unsigned integer?
a) 65535
b) 32767
c) 2147483647
d) 4294967295

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:

Inserts a tab character.


Example:
printf("Name:\tJohn");
Output:

3. \b - Backspace:

Moves the cursor back one position.


Example:
printf("Hello\bWorld");
Output:

4. \r - Carriage Return:

Moves the cursor to the beginning of the line.


Example:
printf("One\rTwo");

112
Presidency University – SOCSE & IS
Complete C Guide for Placement
Output:

5. \' - Single Quote:

Inserts a single quote character.


Example:
printf("It\'s raining.");
Output:

6. \" - Double Quote:

Inserts a double quote character.


Example:
printf("She said, \"Hello!\"");
Output:

7. \\ - Backslash:

Inserts a backslash character.


Example:
printf("Path: C:\\Programs\\Folder");
Output:

8. \0 - Null Character:

Represents the null character (ASCII code 0).


Example:
char str[] = "Hello\0World";

113
Presidency University – SOCSE & IS
Complete C Guide for Placement
printf("%s", str);
Output:

9. \v - Vertical Tab:

Inserts a vertical tab character.


Example:
printf("Line1\vLine2");
Output:

10. \a - Alert (Bell):


Produces an alert or sound (e.g., system beep).
Example:
printf("Beep!\a");
11. \? – Question mark
Will print Question mark.
Example:
printf(“How are you\?”);
Output:

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.

printf("The value of i = %d ", i);


This line prints the modified value of 'i' (which is 17 after incrementing).
The code will compile and execute successfully. The use of volatile is appropriate when we
want to ensure that the variable's value is always read from memory and not cached or
optimized away by the compiler, which is particularly important when dealing with hardware
registers or shared data in multi-threaded environments.
GATE Exam Questions:
Question 1 (GATE 2019):
What is the role of the const qualifier in C?
a) It makes a variable constant, and its value cannot be changed after initialization.
b) It makes a variable volatile, allowing it to be changed by external factors.
c) It specifies that a variable should be stored in non-volatile memory.
d) It specifies that a variable should not be optimized by the compiler.
Answer: a) It makes a variable constant, and its value cannot be changed after
initialization.
Question 2 (GATE 2020):
What is the primary purpose of the volatile qualifier in C?
a) To indicate that a variable can be optimized by the compiler.
b) To prevent the variable from being modified.
c) To indicate that a variable can be modified by external factors not controlled by the program.
d) To make a variable constant.
Answer: c) To indicate that a variable can be modified by external factors not controlled
by the program.

117
Presidency University – SOCSE & IS
Complete C Guide for Placement

Question 3 (GATE 2017):


Which of the following declarations is valid if pi is a pointer to a constant integer?
a) int const * pi;
b) const int * pi;
c) int * const pi;
d) const * int pi;
Answer: b) const int * pi;
Question 4 (GATE 2018):
In C, what is the output of the following code?
#include <stdio.h>
int main()
{
int x = 5;
const int *p = &x;
*p = 10;
printf("%d\n", x);
return 0;
}
a) 10
b) 5
c) Compiler error
d) Undefined behavior
Answer: c) Compiler error
Explanation:
const int *p = &x;
This line declares a pointer to a constant integer 'p' and assigns the address of 'x' to it. The use
of const means that 'p' is a pointer to an integer that cannot be modified through 'p.'
*p = 10;

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.

Question 5 (GATE 2016):


What does the volatile qualifier indicate in C?
a) It indicates that the variable's value cannot be changed.
b) It indicates that the variable should be stored in non-volatile memory.
c) It indicates that the variable can be changed by external factors not controlled by the
program.
d) It indicates that the variable is a constant.
Answer: c) It indicates that the variable can be changed by external factors not controlled
by the program.

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.

3. Typecasting and Constants:


You can also use typecasting to change the type of constants.
int x = (int)3.14; // Explicitly cast a double constant to an int.
Note: Typecasting should be used with care as it may lead to data loss, especially when
converting to a smaller type. It's essential to understand the potential side effects and use
typecasting when it's necessary for our specific programming requirements.

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.

y = x++, x++, x++;


In this line, we use the post-increment operator (x++) to update the value of x and assign the
result to y.
Let's break it down step by step:
x++: This is the post-increment operator. It means the current value of x (which is 5) is used
in the expression, and then x is incremented by 1. So, at this point, x is incremented to 6, but
the value used in the expression is still 5.
The second x++ and third x++ work in the same way. The current values of x (6 and 7,
respectively) are used in the expressions, and then x is incremented by 1 for each of them.
The important point to note here is that in the expression y = x++, x++, x++, the value
assigned to y is the value of x before the first post-increment, which is 5.
printf("%d", y);

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

Answer: 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?

a) It has higher precedence than the assignment operator.


b) It can be overloaded in C.
c) It always evaluates all of its operands.
d) It is right-associative.

Answer: c) It always evaluates all of its operands

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'

Answer: 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.

// Print the values of x and y using printf.


printf("The value of x = %d\nThe value of y = %d", x, y);
return 0; // Return 0 to indicate successful program execution.
}

Example 2: Increment Operator(post & pre increment)


#include <stdio.h> // Include the standard input-output library
int main() // Main function
{
int a = 2; // Declare an integer variable a and initialize it with the value 2.
// Print the initial value of a using printf.
printf("The value of a = %d", a);
// Post-increment operator a++
a = a++; // This statement uses the post-increment operator a++ on the variable a. It has a unique behavior:
// 1. The current value of a (which is 2) is used in the expression.
// 2. After the expression is evaluated, a is incremented by 1.
// However, in this case, the result of a++ is ignored because it is assigned back to 'a,'
effectively canceling the increment.
// So, 'a' remains 2.

136
Presidency University – SOCSE & IS
Complete C Guide for Placement

// Print the value of a after a++ using printf.


printf("\nThe value of a = %d", a); // The value of 'a' is still 2.

// Pre-increment operator ++a


a = ++a; // This statement uses the pre-increment operator ++a on the variable a.
// 1. 'a' is incremented by 1 first, so it becomes 3.
// 2. The result (3) is then assigned back to 'a.'

// Print the value of a after ++a using printf.


printf("\nThe value of a = %d", a); // The value of 'a' is now 3.

return 0; // Return 0 to indicate successful program execution.


}

Example 3: Decrement(Post & Pre decrement)

#include <stdio.h> // Include the standard input/output library


int main() // The main function where the program starts
{
int a = 2; // Declare an integer variable 'a' and assign the value 2 to it
printf("The value of a = %d ", a); // Print the value of 'a' (2)

// Post-decrement operator (a--):


a = a--; // This line is somewhat tricky due to post-decrement.

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.

printf("\nThe value of a = %d ", a); // Print the value of 'a' (2)

// Pre-decrement operator (--a):


a = --a; // Now, 'a' is decremented by 1 before the assignment, so 'a' becomes 1.
printf("\nThe value of a = %d ", a); // Print the value of 'a' (1)

return 0; // Return 0 to indicate successful execution of the program


}

Example 4: Address (&) operator


#include <stdio.h> // Include the standard input/output library
int main() // The main function where the program starts
{
int n = 10; // Declare an integer variable 'n' and assign the value 10 to it
printf("The value of n = %d ", n); // Print the value of 'n' (10)

// 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'

return 0; // Return 0 to indicate successful execution of the program


}

138
Presidency University – SOCSE & IS
Complete C Guide for Placement

Example 5: sizeof() operator


The sizeof operator in C and C++ is used to determine the size, in bytes, of a data type, variable,
or expression.
It is often employed when working with memory allocation, memory management, and
understanding the memory layout of data structures.

#include <stdio.h> // Include the standard input/output library


int main() // The main function where the program starts
{
int x = 5; // Declare an integer variable 'x' and assign the value 5 to it
float y = 10; // Declare a floating-point variable 'y' and assign the value 10 to it

// 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));

return 0; // Return 0 to indicate successful execution of the program


}

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.

Binary Operators - C Program


In this program, we make use of several Binary Operators.
+ is a binary operator, which is used to sum two operands to yield a resultant value.
- is a binary operator, which is used to subtract two operands to yield a resultant value.
* is a binary operator, which is used to multiply two operands to yield a resultant value.
/ is a binary operator, which is used to divide two operands to yield a resultant value.
% is a binary operator, which is used to find the remainder of two operands when divided.
Example 1:
#include <stdio.h> //header file section
int main() //main section
{
int a = 5;
int b = 2;
int l = a + b;
int m = a - b;
int n = a * b;
int o = a / b;
int p = a % b;
printf("Addition of a and b = %d ", l);
printf("\nSubtraction of a and b = %d ", m);
printf("\nMultiplication of a and b = %d ", n);
printf("\nDivision of a and b = %d ", o);
printf("\nRemainder of a and b = %d ", p);

140
Presidency University – SOCSE & IS
Complete C Guide for Placement
return 0;
}

C Conditional or Ternary Operator:


The conditional operator is sometimes called a ternary operator because it involves three
operands. It is best understood by considering the following example
younger = son < father ? 18 : 40;
In the above example, son's age is 18 whereas father's age is 40.

Syntax of Conditional Operator in C:


The conditional operator contains a condition followed by two statements or values.
(If the condition is true the first statement is executed, otherwise the second statement or value.)

condition ? (value 1) : (value 2)

How Conditional Operator Works?


Conditional operator performs nothing more special. It is the abstraction of if else statement.
Consider the following example how Condtional Operator works
younger = true ? 18 : 40;
If the logical expression resulted true, 18 will be stored in a variable younger.
younger = false ? 18 : 40;
If the logical expression resulted true, 40 will be stored in a variable younger.

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;
}

Program Using Conditional Operator


Here we are to find the least age and store it in a variable younger_age using Conditional
operator.
#include <stdio.h> //header file section
int main() //main section
{
int son = 18;
int father = 40;
int younger_age;
younger_age = son < father ? son : father;
printf("%d is the younger age", younger_age);

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.

Relational Operator Program


Let us write a C program to demonstrate
#include <stdio.h>
int main()
{
printf("\nCond.\t Return"); //Cond. stands for Condition
printf("\n5 > 3 :\t %d",5 > 3);
printf("\n5 < 3 :\t %d",5 < 3);
printf("\n5 <= 5 :\t %d",5 >=5);
printf("\n6 >= 5 :\t %d",6 >=5);
printf("\n5 == 3 :\t %d",5 == 3);
printf("\n3 != 3 :\t %d",3 != 3);

143
Presidency University – SOCSE & IS
Complete C Guide for Placement
return 0;
}

Note:
Here true condition returns 1 and false condition returns 0.

Relational Operator in Conditional Statement:


#include <stdio.h>
int main()
{
int a = 5;
int b = 10;
if(a < b)
/* if(5<10), condition fails then if(5<10) will be replaced by if(0), because the return value
after the evaluation of expression 5<10 is false*/
//Note: if(cond) is true, return value is 1 i.e. if(1) which enters the if conditional statement.
//Note: if(cond) is false, return value is 0 i.e. if(0) which enters the else part
printf("a is the smallest number");
else
printf("b is the smallest number");
return 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

// Use an if statement to compare the values of 'a', 'b', and 'c'


if (a < b && b < c)
{
// Check if 'a' is less than 'b' AND 'b' is less than 'c', if both the conditions are true then enters if statement

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 if statement is used to evaluate a condition, which is a combination of two


conditions joined by the logical AND operator (&&).

• 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

int result = a & b; // Bitwise AND

printf("a & b = %d\n", result);

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.

The binary representation of the values is:


a (10) = 1010
b (7) = 0111
Performing the bitwise OR operation:
1 0 1 0 (a)

| 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.

Bitwise Left Shift operator(<<):


let's explain the left shift operation and provide an example using a C program:
• The left shift operator (<< in C and many other programming languages) is used to shift
the bits of an integer to the left by a specified number of positions.
• This operation effectively multiplies the integer by 2 raised to the power of the number
of positions shifted.
• Each shift to the left moves the bits one position to the left and fills in the vacant position
on the right with zeros.
Here's how the left shift operator works:
• Left Shift Operation: Shift all the bits to the left by a specified number of positions. The
vacant positions on the right are filled with zeros.
• Result: The result of the left shift operation is an integer with its bits shifted to the left,
effectively multiplying the original integer by 2 raised to the power of the number of
positions shifted.

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.

Bitwise Right Shift operator(>>):


Example:
#include <stdio.h>
int main()
{
int a = 16; // Integer to be divided (binary: 10000)
int result = a >> 2; // Right shift by 2 positions (effectively dividing by 2^2 = 4)
printf("a >> 2 = %d\n", result);
return 0;
}

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;
}

Here's what the program does step by step:


• It defines an integer variable num and initializes it with the value 8.
• It uses the left shift operator (<<) to double the value of num. This is done by shifting
the bits of num one position to the left, which is equivalent to multiplying it by 2
(i.e 8 x 21=16). The result is stored in the variable left_shift_result, which will be 16.
• It uses the right shift operator (>>) to halve the value of num. This is done by shifting
the bits of num one position to the right, which is equivalent to dividing it by 2
(i.e 8 / 21= 8 / 2 = 4). The result is stored in the variable right_shift_result, which will
be 4.
• It prints the results of the left shift and right shift operations using printf. The output
will be "16 4" because those are the values stored in left_shift_result and
right_shift_result, respectively.
2.
What will be the Output?
#include<stdio.h>
int main()
{
int i = 6;
int a = ++i + ++i;
printf("%d",a);
return 0;
}
a. 12
b. 13
c. 14
d. 16
Answer: d (16)

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.

16. What will be the Output?


#include<stdio.h>
int main()
{
int a;
a = (1, 2, 3);
printf("%d", a);
return 0;
}

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.

17. What will be the Output?


#include<stdio.h>
int main()
{
unsigned int num = -4;
printf("%d", ~num);
return 0;
}
a. 3
b. 4
c. 2
d. 0
Answer: a

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

18. What will be the Output?


#include<stdio.h>
int main()
{
int x = 2;
(x & 1) ? printf("true") : printf("false");
return 0;
}
a. True
b. False
c. Compilation error
d. Runtime error
Answer: b

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.

22. What will be the Output?


#include<stdio.h>
int main()
{
printf("%d",3 * 2--);
}
a. 6
b. 3
c. Runtime error
d. Compilation error
Answer: d

182
Presidency University – SOCSE & IS
Complete C Guide for Placement

Explanation:
2-- stands meaningless

23. What will be the Output?


#include<stdio.h>
int main()
{
int i = 10;
i++;
i * i;
printf("%d\n",i);
return 0;
}
a. 121
b. 100
c. 10
d. 11
Answer: d

Explanation:
i++ alone store the result in variable i

183
Presidency University – SOCSE & IS
Complete C Guide for Placement

24. What will be the Output?


#include<stdio.h>
#define x =
int main()
{
int a;
a x 5;
printf("%d",a);
return 0;
}
a. 4
b. 5
c. 10
d. 15
Answer: b

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.

2. GATE 2020: What is the result of the expression (3^4) in C?


Answer: The result is 7.

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.

5. GATE 2017: In C, what is the output of the expression 5 & 9?


Answer: The output is 1.

6. GATE 2016: What is the result of the expression 5 + 4 * 3 % 7 in C?


Answer: The result is 8.

7. GATE 2015: If x is an integer variable in C, what is the value of x after the


following operation: x = x | (1 << 2)?
Answer: The value of x is x | 4, which sets the 3rd bit of x to 1.

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.

9. GATE 2013: What is the result of the expression sizeof(3.14) in C?


Answer: The result is the size in bytes required to store a double value, which is typically 8
bytes on most systems.

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.

11. GATE 2011: In C, what is the value of x after the operation: x = 6 | 3?


Answer: The value of x is 7.

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.

13. GATE 2009: What is the output of the expression 3 * 4 / 2 in C?


Answer: The result is 6.

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.

18. GATE 2004: What is the value of x after the operation: x = 6 ^ 3 in C?


Answer: The value of x is 5.

19. GATE 2003: In C, what is the output of the expression 3 && 0?


Answer: The output is 0, which represents "false" in C.

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.

25. GATE 2017: What is the output of the expression 7 | 3 in C?


Answer: The output is 7.

26. GATE 2016: What is the result of the expression 6 / 3 * 2 in C?


Answer: The result is 4.

27. GATE 2015: In C, what is the value of x after the operation: x = 5 || 0?


Answer: The value of x is 1, which represents "true" in C.

28. GATE 2014: What is the output of the expression sizeof('a') in C?


Answer: The result is the size in bytes required to store a character, which is typically 1 byte
on most systems.

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.

33. GATE 2009: What is the output of the expression sizeof(3) in C?


Answer: The result is the size in bytes required to store an integer, which depends on the
system but is typically 4 bytes on many systems.

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.

38. GATE 2004: What is the value of x after the operation: x = 6 | 5 in C?


Answer: The value of x is 7.

39. GATE 2003: In C, what is the output of the expression 0 || 0?


Answer: The output is 0, which represents "false" in C.

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:

• 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.

Here's a step-by-step explanation of how the code works:


1. `#include <stdio.h>`:
This line includes the standard input/output library, `stdio.h`, which is required for using the
`printf` function. This library provides functions for input and output operations.
2. `int number = 100;`:
This line declares an integer variable named 'number' and initializes it with the value 100. The
variable 'number' now holds the value 100.
3. `printf("The value of number is %d\n", number);`:
This is the `printf` statement, and it has two important components:
- `"The value of number is %d\n"`: This is the format string or message that will be
displayed. It contains a format specifier `%d`, which is a placeholder for an integer value.
- `number`: This is the actual value that will replace the `%d` placeholder in the format
string. In this case, it's the value of the 'number' variable, which is 100.
The `printf` function takes the format string and any additional arguments (in this case,
'number'), and it prints the formatted message to the standard output (usually the console). So,
the output will be "The value of number is 100" followed by a newline character (`\n`).

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.
}

Here's what the code does:


• It includes the standard input/output library (s format specifier, where represents the
field width. This format specifier is used to print a string with a specified field width.
• The code prints the first 2, 3, 4, 5, and 6 characters of the string "Rohini" with different
field widths. The field width limits the number of characters to be printed from the
string.

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:

1. %d, %i: specifies Integer


- `%d` and `%i` are used to format and print integers. They can be used interchangeably.
The provided C code demonstrates the use of the %d and %i format specifiers to print integers,
as well as the conversion from an octal number to its equivalent decimal representation. Here's
an explanation of the code:
#include <stdio.h>
int main()
{
int number = 100;
// Using %d specifier to print the integer
printf("Using %%d: The number is %d\n", number);
// Using %i specifier to print the integer
printf("Using %%i: The number is %i\n", number);
int octalNumber = 075; // In octal notation
printf("The equivalent decimal number for the given Octal is: %i\n", octalNumber);
return 0;
}

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.

Printing number with %d and %i specifiers:


The first printf statement uses the %d specifier to print the value of number as a decimal integer.
The second printf statement uses the %i specifier to print the same number as a decimal integer.
As mentioned earlier, for decimal integers, %d and %i are interchangeable.

int octalNumber = 075;:


This line declares another integer variable named octalNumber and initializes it with the octal
value 075. In C, leading zeros in an integer constant indicate octal notation. So, 075 is treated
as an octal number, which is equivalent to the decimal number 61.

Printing the equivalent decimal number for the given octal:


The third printf statement uses the %i specifier to print the octalNumber. In this case, %i
interprets the value as an octal number and prints its equivalent decimal representation, which
is 61.
Difference between %d & %i:
%d: This specifier is used to format and print integers in decimal notation. It expects the
argument to be an integer, and it will format and print it as a decimal number.

%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.

2. %f: specifies Floating-Point


- `%f` is used to format and print floating-point numbers (e.g., decimals).

3. %c: specifies Character


- `%c` is used to format and print a single character.

197
Presidency University – SOCSE & IS
Complete C Guide for Placement

4. %s: specifies String


- `%s` is used to format and print strings (arrays of characters).

5. %x, %X: specifies Hexadecimal


- `%x` and `%X` are used to format and print integers in hexadecimal (base-16) format. `%x`
produces lowercase letters, and `%X` produces uppercase letters.

6. %o: specifies Octal


- `%o` is used to format and print integers in octal (base-8) format.

7. %u: specifies Unsigned Integer


- `%u` is used to format and print unsigned integers.

8. %e, %E: specifies Scientific Notation


- `%e` and `%E` are used to format and print floating-point numbers in scientific notation
(e.g., 1.23e+05).

9. %g, %G: specifies Auto


- `%g` and `%G` are used to format and print floating-point numbers in either standard or
scientific notation, depending on the value.

10. %p: specifies Pointer


- `%p` is used to format and print pointers. It displays the memory address in hexadecimal.

11. %ld, %li: specifies Long Integer


- `%ld` and `%li` are used for formatting and printing long integers.

12. %lu: specifies Unsigned Long Integer


- `%lu` is used to format and print unsigned long integers.

198
Presidency University – SOCSE & IS
Complete C Guide for Placement

13. %lld, %lli: specifies Long Long Integer


- `%lld` and `%lli` are used for formatting and printing long long integers.

14. %llu: specifies Unsigned Long Long Integer


- `%llu` is used to format and print unsigned long long integers.

15. %hd, %hi: specifies Short Integer


- `%hd` and `%hi` are used for formatting and printing short integers.

16. %hu: specifies Unsigned Short Integer


- `%hu` is used to format and print unsigned short integers.
17. %%: specifies Percentage
- `%%` is used to print a literal percentage symbol ("%"). It does not take any additional
arguments.

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

You might also like