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;
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
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.
Improve this question
I've been given an assignment to build the following function template "list primeFactors(unsigned long int n)". The function returns a list of integers of the prime factorization of a natural number. I've created a program that can prime factorization but I'm having issues using a list.
#include <list>
#include <numeric>
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
list<unsigned long int> primeFactors(unsigned long int n)
{
list<unsigned long int> list;
for (unsigned long int i=2; i <=n; i++)
{
while(n % i == 0)
{
n /= i;
//cout << i << " ";
list.push_back(i);
}
return list;
}
}
int main()
{
unsigned long int n;
list<unsigned long int> plist;
cout << "Enter num: " <<endl;
cin>>n;
plist = primeFactors(n);
for(list<unsigned long int>::iterator it=plist.begin(); it != plist.end(); ++it)
{
cout << ' ' << *it;
cout << '\n ';
}
return 0;
}
My program is no longer returning the correct numbers of the factorization and I'm unsure what the issue is.
Any help is appreciated
This likely has nothing to do with returning the list. The problem is you always return it before finishing your iterations:
for (unsigned long int i=2; i <=n; i++)
{
while(n % i == 0)
{
n /= i;
//cout << i << " ";
list.push_back(i);
}
return list; // I think you meant to put this outside the for loop
}
// Probably here is better for the return.
Try using a debugger next time, you will see this issue much more quickly then posting here.
Just return the list outside the for loop
Line return list; is too early. Move it beyond the curly brace.
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 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!
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 writing a code to subtract the adjacent elements of a vector and enter the answer into a new vector. However, my code isn't working. What exactly is wrong with it?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int length;
vector<int>values;
vector<int>values2;
cout << "Enter the length of the vector";
cin >> length;
values[0]=1; values[1]=2; values[2]=3; values[3]=4; values[4]=5;
for(int i=0; i<length; i++)
{
cout<<"Enter the " << i <<"th element of the vector";
cin >> values[i];
}
for (int i=0; i<length-1; i++)
{
values2[i]=values[i+1]-values[0];
}
return 0;
}
You need to size the vectors accordingly before accessing elements. You can do that on construction, or using resize.
vector<int>values(5/*pre-size for 5 elements*/); and similar for values2 would fix your problem.
Currently your program behaviour is undefined.
If you want to subtract adjacent elements, then shouldn't you have values2[i]=values[i+1]-values[i];?
The line of code:
values2[i]=values[i+1]-values[0];
will take the looked-at element away from the first element each time.
Did you mean:
values2[i]=values[i+1]-values[i];
?
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 have to make a program in C++ that will read numbers and then arrange them in ascending order. The numbers can be infinite, so the program should read numbers until any particular value is entered to terminate the reading process. I have written below code but is not working and showing undesired output. I will be so thankful if someone will help me.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *p,*q,i=1,j,k,temp;
p=(int*)malloc(sizeof(int));
cin>>*p;
while((*p)!=-1) //read until -1 is entered
{
i++;
p=(int*)realloc(p,sizeof(int)*i);
q=p;
p=p+(i-1); //going to next address to read
cin>>*p;
}
p=q;
for(j=1;j<i;++j)
{
for(k=0;k<i-j-1;++k)
{
if((*(p+k))>(*(p+k+1)))
{
temp=*(p+k);
*(p+k)=*(p+k+1);
*(p+k+1)=temp;
}
}
}
cout<<"\n";
for(j=0;j<i-1;++j)
{
cout<<*(p+j)<<" ";
}
}
Expanding on my comment, here is what an actual C++ solution might look like:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers;
int number = -1;
std::cin >> number;
while (number != -1)
{
numbers.push_back(number);
number = -1;
std::cin >> number;
}
std::sort(numbers.begin(), numbers.end());
for (int x : numbers)
{
std::cout << x << ' ';
}
std::cout << '\n';
}
After
p=p+(i-1);
p is no longer a pointer that is valid to realloc.
Replace
p=p+(i-1);
cin>>*p;
with
cin >> p[i-1];
and get rid of q.
(You can use cin >> *(p + i - 1); if you insist on obfuscation.)
Your sorting routine also becomes much more readable if you replace the pointer arithmetic with indexing.