In: Computer Science
in c++ codeblocks
Convert the following code into a switch structure. Make the switch structure as short as possible (do not repeat code). if (i == 3 || i == 5) { n++; tryagain = 0; } else if (i == 4) || i == 10) { n = 5; } else if (i == 6) { n = 6; } else { n = 0; tryagain = 1; }
Write an if statement that will give 5 extra credit points to students who answer Question A correctly, and 10 extra points if they answer Question A and Question B correctly. Name the variable intBonus.
So, here we want to convert a nested loop to switch:
Steps to follow:
Please refer to the comments of the program for more clarity.
// Starting of the switch block
switch(i)
{
case 3: // For (i == 3 || i == 5)
case 5:
{
n++; tryagain = 0;
break;
}
case 4: // For (i == 4 || i == 10)
case 10:
{
n = 5;
break;
}
case 6: // For (i == 6)
{
n = 6;
break;
}
default: // For others
{
n = 0; tryagain = 1;
break;
}
} // End of the switch block
CodeBlock Screenshot:
Now, as asked lets see an example of if statement, using variable, intBonus:
In the below code, we care finding the intBonus using the if-statements,
I have applied if conditions on variable "workExperience" and calculated intBonus. You can interchange the variables according to your requirement.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int intBonus = 0; // Initializing intBonus as 0
int workExperience = 0; // Initializing workExperience as 0
cout << "Enter your work experience: ";
cin >> workExperience; // Taking input
// calculating the bonus using the if statements
if(workExperience >= 2 && workExperience < 5)
{
intBonus = 1000;
}
else if(workExperience >= 5)
{
intBonus = 5000;
}
else
{
intBonus = 500;
}
cout << "\n\nYour Bonus: " << intBonus << endl; // Printing the output
return 0;
}
Code-run/Input-Output:
CodeBlock Screenshot:
Please let me know in the comments in case of any confusion. Also, please upvote if you like.