Count possible ways to construct buildings

Here n number of sections are given, in each section, there are two sides on the road to constructing buildings. If there is one empty space between two houses are needed, then how many possible ways to construct buildings in the plot.

There are four possibilities to construct buildings

  •  One side of the road
  •  Another side of the road
  •  No building can be constructed
  •  Both sides of the road

Input and Output

It takes the number of sections to construct buildings. Say the input is 3.
Enter Number of sections: 3
Buildings can be constructed in 25 different ways.



Input: There are n number of section.

Output − Number of possible ways.

   if n = 1, then
      return 4
   countEnd := 1
   countEndSpace := 1

   for i := 2 to n, do
      prevCountEnd := countEnd
      prevCountEndSpace := countEndSpace
      countEndSpace := countEnd + prevCountEndSpace
      countEnd := prevCountEndSpace

   answer := countEndSpace + countEnd
   return answer^2


using namespace std;

int constructionWays(int n) {
   if (n == 1)        //if there is one section
      return 4;       //4 possible ways to construct building in that section

   //set counting values for place at the end and end with space
   int countEnd=1, countEndSpace=1, prevCountEnd, prevCountEndSpace;

   for (int i=2; i<=n; i++) {       //fot the second section to nth section
      prevCountEnd = countEnd;
      prevCountEndSpace = countEndSpace;

      countEndSpace = countEnd + prevCountEndSpace;
      countEnd = prevCountEndSpace;

   //possible ways to end with space and building at the end
   int answer = countEndSpace + countEnd;

   return (answer*answer);     //for two sides the answer will be squared

int main() {
   int n;
   cout << "Enter Number of sections: ";
   cin >> n;
   cout << "Buildings can be constructed in " << constructionWays(n) <<" different ways." ;


Enter Number of sections: 3
Buildings can be constructed in 25 different ways.