VOOZH about

URL: https://www.geeksforgeeks.org/cpp/c-cpp-tricky-programs/

⇱ C/C++ Tricky Programs - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C/C++ Tricky Programs

Last Updated : 14 Mar, 2024

We may come across various tricky programs in our day-to-day life. Maybe in technical interviews, coding tests, or C/C++ classrooms. 

Here is a list of such programs:- 

  • Print text within double quotes (" "). 
    This may seem easy, but beginners may get puzzled while printing text within double quotes.

Output
"geeksforgeeks"

Time Complexity: O(1)
Auxiliary Space: O(1)

  • To check if two numbers are equal without using arithmetic operators or comparison operators. 
    The simplest solution for this is using the Bitwise XOR operator (^). We know that for two equal numbers XOR operator returns 0. We will use the XOR operator to solve this problem.

Output
 x is equal to y 

Time Complexity: O(1)
Auxiliary Space: O(1)

  • Print all natural numbers up to N without using a semi-colon. 
    We use the idea of recursively calling the main function.

Output
1 2 3 4 5 6 7 8 9 10 

Time Complexity: O(1)
Auxiliary Space: O(1)

  • To Swap the values of two variables without using any extra variable.

Output
X : 70
Y : 10

Time Complexity: O(1)
Auxiliary Space: O(1)

  • Program to find the Maximum and minimum of two numbers without using any loop or condition. 
    The simplest trick is-

Output
max = 20
min = 15

Time Complexity: O(1)
Auxiliary Space: O(1)

  • Print the maximum value of an unsigned int using One's Complement (~) Operator in C. 
    Here is a trick to find the maximum value of an unsigned int using one's complement operator:

Output
Max value : 4294967295

Time Complexity: O(1)
Auxiliary Space: O(1)

  • To find the sum of two integers without using '+' operator. 
    This is a very easy mathematics trick. 
    We know that a + b = - (-a-b). So this will work as a trick for us.

Output
10

Time Complexity: O(1)
Auxiliary Space: O(1)

  • Program to verify the condition inside if block.

Output
geeksforgeeks 

Time Complexity: O(1)
Auxiliary Space: O(1)

  • Program to divide an integer by 4 without using '/' operator. 
    One of the most efficient ways to divide an integer by 4 is to use right shift operator (">>").

Output
1

Time Complexity: O(1)
Auxiliary Space: O(1)

  • Program to check endianness of the computer.

Output
LITTLE ENDIAN

Time Complexity: O(1)
Auxiliary Space: O(1)


 

Comment
Article Tags: