
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
A C Puzzle in C Programming?
C programming puzzles are small but tricky coding problems, which are designed to challenge and to understand the C programming language in a better way.
Problem Statement
We are given two numbers, and our task is to combine them in such a way that the second integer is placed before the first integer, resulting in a single combined integer. But here, we are not allowed to use any logical, arithmetic, string-related operations, or any pre-defined functions.
Consider the following input/output scenarios to understand the puzzle statement better:
Scenario 1
Input: 12, 54 Output: 5412 Explanation: Here, the second integer 54 is placed before the first integer 12, resulting in the output as a single combined integer 5412.
Scenario 2
Input: 48, 96 Output: 9648 Explanation: Here, the second integer 96 is placed before the first integer 48, resulting in the output as a single combined integer 9648.
Puzzle Solution Using Token-pasting Operator
To solve this puzzle in C, we will use the Token-pasting operator (##). The Token Pasting operator (##) is a preprocessor operator in C and C++ that is used with a macro to concatenate (or combine) two tokens into a single token.
A macro is a name(string) that is defined using the #define preprocessor directive. It is used to define constant values or pieces of code, which can be reused in a program.
Here, we will define a macro and will use the '##' token-pasting operator inside the macro to merge (concatenate) tokens. This operator will take two tokens as input and combine them according to the given problem by placing the second integer before the first.
Algorithm
Here is the following algorithm for combining two tokens using the Token-pasting operator (##).
- First, define a macro named merge using #define and pass two tokens, a and b.
- Use the token-pasting operator (##) inside the macro to combine the two tokens by placing token b before a.
- In main() function, call the macro and pass the required integers, and then print the result.
C Code for Puzzle Solution
Here is the following example code for solving a C puzzle using the Token-pasting operator.
#include <stdio.h> #define merge(a, b) b##a int main(void) { printf("%d ", merge(432 ,23)); return 0; }
The output of the above code is:
23432
Conclusion
The token-pasting operator (##) gives direct access to combine two integer tokens effectively without using any logical, arithmetic, string operations, or built-in functions. It is like a shortcut method, which merges tokens during compile-time; therefore, it reduces the runtime processing and generates values early.