C++ Program to check joke programming code is generating output or not


Suppose we have a string S with n characters. In a joke programming language, there are only 4 instructions.

  • "H" to print "Hello World"
  • "Q" to print its source code
  • "9" to print "99 bottles of juice"
  • "+" to increment the value stored in accumulator

Instructions "H" and "Q" are case-sensitive and they must be in uppercase. The characters except these four are ignored. We have a program written in this language. You have to check whether executing this program will produce any output or not.

Problem Category

Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first, and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can be used. This problem can be solved by some basic logic or a brute-force approach. Follow the following contents to understand the approach better.

So, if the input of our problem is like S = "H+995jkl", then the output will be True, because H, + and 9 are valid instructions.

Steps

To solve this, we will follow these steps −

for initialize i := 0, when i < size of S, update (increase i by 1), do:
   c := S[i]
   if c is same as 'H' or c is same as 'Q' or c is same as '9', then:
      return true
return false

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool solve(string S){
   for (int i = 0; i < S.size(); i++){
      char c = S[i];
      if (c == 'H' || c == 'Q' || c == '9'){
         return true;
      }
   }
   return false;
}
int main(){
   string S = "H+995jkl";
   cout << solve(S) << endl;
}

Input

"H+995jkl"

Output

1

Updated on: 08-Apr-2022

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements