Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
We were taught about if goto loops in school. The program given by instructor doesnt work. By doesnt work I mean that it gets compiled, but when i execute it, the output is nothing :
#include <iostream>
using namespace std;
int main() {
int i = 0;
prev: i++; // prev label
cout << "a ";
if(i < 20) { goto prev; }
return 0;
}
The actual loop to be implemented in was equivalent to this for loop:
for(int i = 0; i < 20; i++) {
cout << "a ";
}
Thank you!
Depending on how fast you are, you may not notice the programs output, because it does not wait for the user. It just closes. You should make it wait for you to observe it's runtime behavior:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
prev: // prev label
i++;
cout << "a ";
if(i < 20)
{
goto prev;
}
// wait for the user to press [enter]
cin.get();
return 0;
}
The problem with the given program is that the value of i is incremented at the beginning of the loop, and the check is performed at the end; thus, it will increment before the first iteration, and always execute at least one iteration. The following would more accurately reflect the given for loop:
int main() {
int i = 0;
next: if(!(i < 20)) goto end;
cout << "a ";
i++;
goto next;
end: return 0;
}
For the most part, labels and gotos are rarely used - they result in harder to follow code, are only ways to make while/for/if blocks (such as here) about 99% of the time, and are most useful to know in order to better understand the compiler's job and how your code relates to the machine code it generates.
THanks to everyone very much. I was using WIndoes 8 with g++.
The problem was that I was using the filename to execute the application. When I used filename.exe to execute, it executed succesfully and showed the output. THanks to everyone!
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have simplified the code to get rid of unrelated objects. This is my code:
#include <iostream>
#include <fstream>
using namespace std;
fstream asdf;
int input;
void import_image(){
asdf.seekg(0);
char character;
for(int k = 0; k < 40; k++){
asdf.get(character);
input = (unsigned int)(unsigned char)character;
}
}
void print_hello_world(){
for(int rows; rows <= 27; rows++){
cout << "hello world" << endl;
}
cout << "goodbye.";
}
int main(){
asdf.open("abc.txt", ios::binary | ios::in);
cout << asdf.is_open() << endl;
import_image();
//cout << endl;
print_hello_world();
return 0;
}
Running this code results only in
1
goodbye.
--------------------------------
Process exited after 0.1511 seconds with return value 0
however removing double slash (simply adding cout << endl;) fixes everything. I have no idea why it happens and would like to now why is it so. I know that variable "rows" has no value, but why does printing a new line fix everything?
The new "endl"
is a great sign
that what you see,
is called "UB".
Your program has Undefined Behavior (UB) because your int rows that you use for the loop iterations is uninitialized.
By UB definition anything may happen. Activate all (sane) compiler warnings to find errors like this earlier in your development process.
Undefined behavior yield working programs by completely random changes (for example the addition of std::endl) but in the end it's undefined behavior.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am learning C++ and I have a problem with my program. It should print out following if n=11:
*---------*
-*-------*-
--*-----*--
---*---*---
----*-*----
-----*-----
----*-*----
---*---*---
--*-----*--
-*-------*-
*---------*
This is my code, which works correctly with n=5, but not with greater numbers:
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter size (n x n): " << endl;
cin >> n;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i%n==j%n) cout << '*';
else if (i%(n-i)==j%(n-j)) cout << '*';
else cout << '-';
}
cout << endl;
}
return 0;
}
This is being printed out if n=11:
*---------*
-*----*--*-
--*-----*--
---*---*---
----*------
-----*-----
-*----*--*-
---*---*---
--*-----*--
-*----*--*-
*---------*
I see that I have successfully wrote how to print out one of '*' diagnoles. But something isn't working with other one, which is going backwards.
Unfortunately, I am not being able to resolve this problem and need your advice. What am I doing wrong? How to debug such problems?
This problem is really simple to debug.
Take a look at the first erroneous *. It appears at the position with i=1, j=6. With n=11, your condition i%(n-i)==j%(n-j) becomes 1%(11-1) == 6%(11-6) which is effectively true because the expression evaluates to 1 on both sides.
What is behind this expression? Why do you use this kind of if to determine whether the cell belongs to the second diagonal? Try to write down each pair i, j which should be printed on the second diagonal, and you should notice a more simple pattern.
P.S. In the expression if (i%n==j%n) you don't have to take operands modulo n, because both of them are less than n, so it is redundant and may be rewritten simply as if (i == j).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Solving my homework for Informatics at University, I always find different ways to solve the same problem.
One way is the fastest(execution time) but the longest and more complex.
And the other is way easier to realize, falls short in execution time, it's easy to understand and so on.
As an mini-example is that we have have to create a program in C++, which outputs a line of N elements where each element has same adjacent elements different of that in the middle.
Ex.
6 Elements: *_*_*_
7 Elements: *_*_*_*
First solution is the easiest:
#include <iostream>
using namespace std;
int main(void){
int a;
cin >> a;
for (int i=1; i<=a; i++)
{
if (i%2 != 0)
{
cout << "*";
}
else
{
cout << " ";
}
}
return 0;
}
And the second one is a little bit harder to implement but faster to execute(less conditionals checks):
#include <iostream>
using namespace std;
int main(void){
int a;
cin >> a;
if (a%2 == 1)
{
for (int i=1; i<=a; i=i+2)
{
cout << "*";
cout << " ";
}
}
else
{
for (int i=1; i<a; i=i+2)
{
cout << "*";
cout << " ";
}
cout << " ";
}
return 0;
}
My question is what should I focus on? Clean code, easy to implement/deploy and better readability or best algorithm, faster to execute and strong logic, or just try as best as possible to mix all these 2, because there is always a discrepancy between these 2 ways of solving problems?
You should try to write readable, easy to debug code for an ease of understanding.
Whenever you encounter portions of code where it can be heavily optimized in order to get much higher performance (either by modifying the code's architecture or/and by implementing assembly in your code), you can add in a commented section the better performance alternative of it. Even if you choose the better performance alternative, you'll always have the other one which can back up you up, in order to understand it.
Also, stick to better performance alternatives when you can see huge gains by doing it so, not every time.
Keep in mind that these improvements are better to be only implemented in the case of performance bottlenecks or in systems where power efficiency is crucial.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
As soon as I enter the string and press enter the compiler shows debug error and says abort() was encountered.
What is actually wrong?
#include<iostream>
#include<string>
using namespace std;
int main()
{
std::string str;
std::string rev;
std::cout << "Enter the string\n";
std::getline(std::cin, str);
int len = str.size();
for (int i = len; i > 0; i--)
{
std::string temp;
temp= str.at(i);
int j = 1;
rev.insert(j, temp);
j++;
}
std::cout << "The reversed string is\n";
std::cout << rev;
cout << "Thank You";
cin.get();
}
for (int i = len; i > 0; i--)
Should be
for (size_t i = len - 1; i >= 0; i--)
// ^^^ ^
The statement
temp= str.at(i);
will be out of bounds for the first iteration otherwise.
Indices in c++ are in the [0 ... (size - 1)]range.
The earlier answer points out the problems with str.at (i). There's another: on the first iteration it calls rev.insert (1, ...). Since rev has, at that point, a length of zero, that is an out-of-bound access, which will cause an out_of_range exception to be thrown, terminating your program.
Also, move the declaration of j out of the loop. Now it gets recreated with value 1 each time through.
Using an entire string object for tmp seems overkill. Indeed, rev += str.at(i); could replace the entire loop body.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am a beginner and still learning C++ I was playing with vectors to see what will happen.whenever I start it gives me a debug error.
here is the code
int main()
{
vector<int> num;
int i = 0;
while (i != 1000)
{
++i;
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
}
}
Problem lies in the order of operations inside while() loop:
while (i != 1000)
{
++i;
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
}
i starts from 0. In each iteration, you push_back an element and then print it using counter i - after its incrementation. So, num[i] refers to a non-yet-existing element.
Change your code to:
while (i < 1000)
{
num.push_back(i + 1);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
++i;
}
The index of a vector starts from zero. In your code you were always accessing 1 index ahead of what you were updating(or pushing).
When I incremented i after the two statements it worked fine.
I dont know how but it worked fine.
Thanks everyone.
int main()
{
vector<int> num;
int i = 0;
while (i != 1000)
{
num.push_back(i);
cout <<num[i]<<"\t"<< sqrt(num[i]) << "\n";
++i;
}
}
Make sure that you are using
#include<vector>
#include<iostream>
using namespace std;