Here's the link for the flowchart:
http://i1146.photobucket.com/albums/o530/HTHVampire/C%20plus%20plus/Capture_zps5a6c3acf.jpg
Here's the code for the flowchart as shown, just ignore the ambiguous statement in the flowchart.
#include <iostream>
using namespace std;
int main()
{
//declare and initialize a variable
int a = 0;
//prompt user for a value
cout << "please enter a value" << endl;
cin >> a;
again1:
//enter a decision block
if(a > 10)
{
if(a < 10)
{
again2:
if(a < 100)
{
a = a - 3;
goto again2;
}
else goto again1;
}
else
{
a = a - 7;
goto again1;
}
}
else cout << "the output is " << a << endl;
return 0;
}
May I know that can I play this code with if-else statement together with while statement? instead of goto statement.
Thanks for your guides!
This structure should do the core logic according to the flowchart:
while (a > 10) {
if (a < 10) {
while (a < 100) {
a += 3;
}
} else {
a -= 7;
}
}
Note that the if test is absurd. However, I didn't draw the flowchart; I just reproduced it in code.
Nothing wrong with goto so long as you restrict use to state machines.
Many teachers erroneously ban use of it for lack of understanding.
For simple state machines like yours, and protocol decoding, it produces extremely readable code. I ruined years of embedded C routines because I was afraid to use goto.
I started using goto and my finger paintings turned into Van Gogh.
Related
I just recently created a code in C++ where I have to display the occurrence of numbers from a text file that I made using this code:
using namespace std;
int main()
{
bool isCovered[99] = {};
int number;
// Read each number and mark its corresponding element covered
while (cin.good())
{
cin >> number;
if (number == 0)
{
break;
}
if ((number >= 1) && (number <= 99))
{
isCovered[number - 1] = true;
}
}
// Check if all covered
bool allCovered = true; // Assumes all covered initially
for (int i = 0; i < 99; i++)
if (!isCovered[i])
{
allCovered = false; //Finds one number not covered
break;
}
// Display result
if (allCovered)
cout << "The tickets cover all numbers" << endl;
else
cout << "The tickets don't cover all numbers" << endl;
return 0;
}
It's not displaying a result, is the program too complex, or is it something that I'm missing?
EDIT: Thanks #selbie for the edit to my code, i was able to figure out that it was a user input but when i put in a zero for the final input. It displays the messages "The tickets don't cover all numbers", why is that?
The bug, if any, is here:
cin >> number;
while (number != 0)
{
isCovered[number - 1] = true;
cin >> number;
}
Two possible issues:
If reading from a redirected file, there's no detection of an end-of-file condition. Such would be the case if the program was invoked as program.exe < input.txt and the input.txt did not contain a 0. Without checking for eof, the program will hang when reading from an input file redirection.
Further, there's nothing to guard against bad input. i.e. numbers outside the range of [1..99]. Without guarding against out of range numbers, undefined behavior will get introduced. Or more likely, the stack will get trashed as a result of inserting into a memory address out of range.
The easy fix is this:
while (cin.good())
{
cin >> number;
if (number == 0)
{
break;
}
if ((number >= 1) && (number <= 99))
{
isCovered[number - 1] = true;
}
}
So I am trying to code a game using C++. I am using this online compiler so I can also work on it at school. This program was just a simple clicker game that I starting making. When I tested it to see if the code worked so far, nothing showed up, which is strange considering I have print statements in the code that give the directions for the player.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int SCORE = 0;
int LEVEL = 1;
int COST = 50;
int ADDSCORE = 10;
char KEYINPUT;
bool GAMEON = true;
printf("Press space bar to gain points to your score.\n");
printf("Press z key to upgrade your score multiplyer.\n");
printf("Press the escape key (esc) to quit.\n");
printf("Upgrade score multiplyer = %d.\n", COST);
printf("Score multiplyer = LV%d.\n", LEVEL);
printf("Score = %d.\n", SCORE);
while (GAMEON == true) {
if (KEYINPUT == 32) {
SCORE += ADDSCORE;
}
if (KEYINPUT == 122) {
ADDSCORE += 10;
SCORE -= COST;
COST *= 2;
LEVEL += 1;
}
if (KEYINPUT == 27) {
GAMEON = false;
}
}
printf("Game has ended. You may now close out of the game");
return 0;
}
I am not sure if it is my code or if it is the online compiler, but I executed on a different compiler and got the same result. Nothing. Not exactly sure why this is happening, but if someone can spot what is wrong can you let me know.
I tried a bit around and on my system with a local compiler the text also does not print. Now in the first place if you want to code in C++ you need to use C++. printf is actually a C function. You are not using any C++ specific code in your example. If you want to use C in your C++ application though, use the C++ equivalents of the C libraries which wourld be <cstdio> in your case. Now to the problem itself: i am using MSYS shell on windows and i assume you use something similar. There seems to be a problem with the output buffer when you use printf. Normally the output buffer is flushed with the \n newline character at the end of the input. Apparently this does not seem to work in some cases. Adding an fflush(stdout) at the end of the output worked in my case and the text was printed from the buffer and also calling it directly from windows command line, without flushing the buffer, did the trick. So i think it is a problem how your shell handles the buffers. Now to the solutions. Either you flush the output buffer everytime you want to print or you start to use C++ IO. Also as mentioned you need to initialize and change the value from KEYINPUT while your program is running.
#include <iostream>
using namespace std;
int main()
{
int SCORE = 0;
int LEVEL = 1;
int COST = 50;
int ADDSCORE = 10;
char KEYINPUT;
bool GAMEON = true;
/* Use cout instead of printf for output operations */
cout << "Press space bar to gain points to your score." << endl
<< "Press z key to upgrade your score multiplyer." << endl
<< "Press the escape key (esc) to quit" << endl
<< "Upgrade score multiplyer = " << COST << endl
<< "Score multiplyer = LV" << LEVEL << endl
<< "Score = " << SCORE << endl;
while (GAMEON == true) {
KEYINPUT = cin.get(); /* You need to initialize the value before using and change it in the loop */
if (KEYINPUT == 32) {
SCORE += ADDSCORE;
}
if (KEYINPUT == 122) {
ADDSCORE += 10;
SCORE -= COST;
COST *= 2;
LEVEL += 1;
}
if (KEYINPUT == 27) {
GAMEON = false;
}
}
cout << "Game has ended. You may now close out of the game" << endl;
return 0;
}
A little note at the end: Since i tried to do similar little games as i started, you will need to use a platform dependent library to capture those keystrokes like ESC or other keys which not directly get put into the input buffer. i know conio for windows and otherwise the winapi is well documented and relatively easy to use. There are also many examples of how to use the winapi to capture keystrokes from the command line window which can easily be found on google.
Just started C++ at university so I've decided to try and do a classic 'shop project' using C++.
I'm just wandering if there is any way to repeat an if statement from the else. For example in the code I'm asking the user if the would like help browsing the shop and if they reply yes then it shows them the options, if they reply no then it continues with the code, however if it isn't yes or no then the code tells the user it can't understand the user.
What I am asking is can I get the user to input the value again and it re-run the if statement without using a loop, or do I have to use a loop?
Here's the bit of code:
cin >> help;
if (help == "Yes" || help == "yes")
{
cout << "These are out current sections that you are able to browse:" << endl;
cout << "-Offers and Deals (1) \n-Computing (2) \n-Console (3) \n-Audio (4) \n-Electronic Displays (5) \n-Cabling (6) \n-General Accessories (7)" << endl;
}
else if (help == "No" || help == "no")
{
cout << "You have chosen not to look at our browsing list." << endl;
}
else
{
cout << "Sorry the system does not understand what you have entered. \n Please use full English (Yes/No)." << endl;
}
If anyone could help me with this, that would be great.
I know its simple code and probably a lot more efficient ways of doing it, just using the ways ive currently been taught at university so far.
Thank in advance.
without using a loop, or do I have to use a loop?
There are ways of achieving this without using a loop, but a loop is exactly the construct that allows you to repeat a block of code while a condition is true.
This explicitly expresses your intent and achieves the result you desire.
void menu()
{
while (true)
{
int i; std::cin >> i;
if (i == 0) { action0(); }
else if (i == 1) { action1(); }
else if (i == 2) { break; /* Return to caller */ }
else { /* Invalid selection, retry */ }
}
}
Another reasonable solution uses recursion. Example:
void menu()
{
int i; std::cin >> i;
if (i == 0) { action0(); }
else if (i == 1) { action1(); }
else if (i == 2) { return; /* Return to caller */ }
else { menu(); /* Invalid selection, retry */ }
}
However, this can have several drawbacks compared to a loop. Quoting François Andrieux from the comments:
Recursion is a reasonable alternative if loops can't be used, but it's worth mentioning the drawbacks. For example, there may be a limit to the number of times you can recur if tail call optimization doesn't come into play. If it does, then you essentially have a hidden loop. It's also worth mentioning that you can't do this with main. It's a mistake many beginners make when they first discover recursion.
As I'm sure the question makes clear, I'm new and learning and I'm sure many will wonder why ask.....cause I get the rest of it, just not this. I am using C++ and am trying to make a self guessing program, that uses an algorithim given to me. I have played with this section of code multiple ways and so far the one thing I have narrowed down, is what its not doing, and I want to both understand why and how to fix it because nothing I have tried is working. The basic version of the code I have been playing with is this:
// test_room.cpp : This file contains the 'main' function. Program execution
//begins and ends there. This is where
//I am going to test some code to understand my mistakes and how to fix
//them.
//
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include<ctime>
using namespace std;
int main()
{
char play = 'y';
while (play == 'y')
{
int bad = 27;
int a = 50;
int b = 1;
int good = ((a - b) / 2);
int s = 0;
cout << "\nBegin?";
cin >> play;
do
{
++s;
if (good > bad)
{
cout <<"\n" <<good;
cout <<"\n" << s;
--a;
}
else if (good < bad)
{
cout << "\n"<<good;
cout <<"\n" << s;
++b;
}
else
{
cout << "good job";
}
} while (s < 50);
}
cout << "\nOK\n";
return 0;
}
What my question is I have tried moving the variables, I have fixed brace issues, I have tried using cin>>good>>a or b(depending on >< ) and so far I can not manipulate variables a or b to get it to try to guess or figure out the number 27, all it does is repeat 24 50 times. What do I need to do to change the values of a and b based on the algorithim?
Good and bad are never changed in the loop, I don't really understand the purpose of you algorithm(it looks like a binary search, but not really), but if you aren't changing any values that the if conditions evaluate in the loop, then none of the other conditions will ever be evaluated.
I am new in programming and now I'm learning from a book written by Bjarne Stroustrup ("2014 Programming Principles And Practice Using C++"). Anyway, the problem I am encountering is about the fact that when I define a string, the program stop working properly. This is the code:
#include <iostream>
using namespace std;
int main() {
double i;
double c = 0;
double bsf;
double ssf;
while (cin >> i) {
if (c == 0) {
bsf = i;
cout <<"The largest so far: " << i<<endl;
}
if (c == 1 && i > bsf) {
ssf = bsf;
bsf = i;
cout << "The largest so far: " << i<<endl;
} else if (c > 0 && i > bsf) {
bsf = i;
cout <<"The largest so far: " << i<<endl;
} else if (c > 0 && i < bsf) {
if (i < ssf) {
ssf = i;
cout <<"The smallest so far: " << i <<endl;
}
}
c++;
}
}
In CodeBlocks, this program works properly (I want the program to let me insert as many numbers as I want and to specify me when I write the biggest number and, also, the smallest number (you can make a better idea from the code). The problem appears when I try to define, as I said earlier, a string:
string um;
If I am doing this, the program doesn't recognize the smallest number written. If I write, for example, firstly, the number 220, it will be printed "The largest so far: 220", but if I write after that 45, it will not be printed "The smallest so far: 45".
If you guys can offer me some advices, it would be great.
Thank you!
The Answer is not undefined behavior as far as I can see. But the total lack of an if clause that caters to the OP's requirement.When the second no is entered, c is equal to 1 and in the if clauses there is no code for i <= bsf. So the code must be rewritten as
#include <iostream>
using namespace std;
int main() {
double i;
double c = 0;
double bsf;
double ssf;
while (cin >> i) {
if (c == 0) {
bsf = i;
cout <<"The largest so far: " << i <<endl;
}
if (c == 1 && i > bsf) {
ssf = bsf;
bsf = i;
cout <<"The largest so far: " << i <<endl;
} else if(c == 1 && i <= bsf) {
ssf = i;
cout <<"The smallest so far: " << i <<endl;
} else if (c > 0 && i > bsf) {
bsf = i;
cout <<"The largest so far: " <<i <<endl;
} else if (c > 0 && i < bsf) {
if (i < ssf) {
ssf = i;
cout << "The smallest so far: " << i <<endl;
}
}
c++;
}
}
This will also curb the UB in #Ron 's answer
EDIT : Thank you #drescherjm i forgot to add <=, that has been corrected
In your program you are trying to use local variables:
double bsf; // uninitialized local variable
double ssf; // uninitialized local variable
without initializing them thus causing undefined behaviour. Initialize your (local) variables prior to using them:
double bsf = 0;
double ssf = 0;
The actual culprit is on line 26:
if (i < ssf) // UB access to uninitialized variable `ssf`
Here is a screenshot from Visual Studio with the important info underlined:
Here is a GCC version on Coliru.
There is no std::string variable in your program. If there was one you would need to include the <string> header.
Think in terms of initial values; this code becomes much simpler if you initialize bsf to DBL_MIN and initialize ssf to DBL_MAX. Then as you go through the loop you just have to check the new value against bsf and ssf without all that confusion involving c.