Tricky C++ programs

By | December 13, 2022

Programming has never been easier. Even though you may have mastered a particular programming language, there might still be some concepts that may make you dizzy on reading it. This article contains some set of tricky questions which may make you go dizzy.

1. Take a look at this terminated int main ();

#include<iostream>

int main ();

int main ()
{
	std::cout<<"Hello World";

    return 0;
}

What will this program do?

  • (A) Compile Error
  • (B) Runtime Error
  • (C) “Hello World”
  • (D) Nothing will print

The correct answer is option (C). This program will print “Hello World” simply because it will jump to int main() and execute the code normally.

2. Multiple prototypes are defined for the same function.

#include<iostream>

void add();
void add()
{
	std::cout<<"Inside Add function";
}
int main ()
{
	add();
} 

What will this program do?

  • (A) Compile Error
  • (B) Runtime Error
  • (C) “Inside Add function”
  • (D) Nothing will print

The correct answer is option (C). This is because no matter how many times a prototype for the same function is defined, the program will continue to execute normally.

3. How many variables does it take to add n numbers? We would say just 2 elements of an array.

Take a look at this code below:

#include<iostream>

int main ()
{
	int ar[2]={0,0};
	char ch='y';
	while(ch=='y' || ch=='Y')
	{
		std::cout<<"\n Enter a number: ";
		std::cin>>ar[0];
		ar[1]+=ar[0];
		std::cout<<"\n"<<ar[1];
		std::cout<<"\n\nContinue ? (y/n)";
		std::cin>>ch;
	}
}  

Arrays execute faster because they save data in sequential order. Hence, no matter how many values have to be added, simply input the value in one element and add it to the other element, and update values in both elements to make the code optimized. This will definitely save memory space.

Please write comments below if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.