Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 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
int main()
{
vector<int>numbers;
int numb = 0;
int i = 0;
int j = i - 1;
while (cin >> numb)
{
if (numb == numbers[j]) HERE IS THE PROBLEM!*
{
cout << "Numbers repeated\n";
}
numbers.push_back(numb);
cout << "numbers[" << i << "] = " << numbers[i] << endl;
++i;
}
/*** I don't understand why a exception, run time error, break or whatever it names.....................................................
On the first iteration through the loop, j is -1. Accessing numbers[-1] is undefined behavior because the index is outside the bounds of the vector.
Indeed, accessing any index is out of bounds until you put something in the vector, so you cannot index numbers at all until you have called push_back on it at least once.
This code will display the message if the user enters a number already in the vector:
while (cin >> numb) {
vector<int>::iterator found = std::find(numbers.begin(), numbers.end(), numb);
if (found == numbers.end()) {
cout << "Numbers repeated" << endl;
}
// If you don't want duplicate numbers in the vector, move this statement
// into an "else" block on the last "if" block.
numbers.push_back(numb);
}
This code on the other hand will only display the message when a number was the same as the last number entered, that is, if sequential numbers are the same:
while (cin >> numb) {
if (!numbers.empty() && numb == numbers.back()) {
cout << "Numbers repeated" << endl;
}
numbers.push_back(numb);
}
You need to initialize your numbers vector with initial data, or check to make sure j is withing in vector size. A vector is essentially an array, and like any array, you cannot go out of bounds.
if (j < numbers.size() && numb == numbers[j]) HERE IS THE PROBLEM!*
{
cout << "Numbers repeated\n";
}
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 8 months ago.
Improve this question
I am a beginner, and I am trying to learn C++.
For now, all I am trying to do is input 3 numbers, and print them back.
#include <iostream>
using namespace std;
int main(){
int n[2];
cout << "Enter three numbers" << endl;
for (int j = 0; j <= 2; j++){
cin >> n[j];
}
cout << "Debug " << n[2] << endl;
cout << endl;
for (int i = 0; i <= 2; i++){
cout << n[i] << "\t" << i << endl;
}
return 0;
}
Every time I print them, the last value of the array is modified, and I cannot figure out why! For a test input 6,7,8, the output is in the image below.
This for
for (int j=0;j<=2;j++){
cin>>n[j];
}
expects that the array has at least three elements with indices in the range [0, 2].
However you declared an array with two elements
int n[2];
If you are going to input three elements then the array should be defined as
int n[3];
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'm new to programming and i have problem with some items
i would appreciate any help
first i started initializing the vector as followed but i couldn't end the loop with Ctrl+Z
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector <double> temps;
double temp;
cout << "Enter a sequence of tempreatures : " << "\n" ;
while (cin >> temp){
temps.push_back(temp);
}
double sum = 0;
for (int i = 0; i< temps.size(); ++i)
sum += temps[i];
cout << "Mean temprature : " << sum / temps.size() << "\n";
sort(temps.begin(), temps.end());
cout << "Median temprature : " << temps[temps.size() / 2];
then i changed the while into this format :
cout << "ENter a sequence of tempreatures ending in 1500 : " << "\n" ;
while (cin >> temp){
if (temp == 1500)
break;
temps.push_back(temp);
}
now i have this error
"vector subscript out of range"
apparently break does not work properly here
what should i do?
Your issue is in the check condition of for loop.
for (int i = 0; i, temps.size(); ++i)
sum += temps[i];
It should be
for (int i = 0; i < temps.size(); ++i)
i, temps.size() will evaluate and then ignore the part before , and are left with temps.size() as check condition which will always be greater than 0 if you push_back at least one element and your loop will never end.You might want to read how ,(comma) works.
If you switch to std::getline into a string instead of std::cin into a double, you can check whether the input is empty:
std::string input;
std::getline(std::cin, input);
while (!input.empty()){
temps.push_back(atof(input.c_str()));
std::getline(std::cin, input);
}
If you also fix the for-loop as mentioned by Gaurav Sehgal, it works fine (Enter all numbers then hit enter without any input).
If you are on windows then you have to do
CTRL + Z
If you are on Unix based(Linux/Mac) then you have to do
CTRL + D
This will give the end of file signal and you will be able to break the loop
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 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
#include <iostream>
using namespace std;
int main()
{
int i,t,x[20], even, odd, prime;
cout << "Enter 20 integer numbers from 0 to 99: "<<endl;
for (i=1;i<=20;i++)
{
cout << "Input " << i <<":";
cin >> x[i];
}
cout << "\nPrime numbers are: " << endl ;
prime=1;
for (i=2; i<=20 ; i++)
{
for(t=2;t<x[i];t++)
{
if(x[i]%t==0)
{
prime=0;
}
}
if(prime==1)
{
cout << x[i] << endl;
}
prime=1;
}
for(i=1; i<=20; i++) // this is where i have problem.
{
if(x[i]% 2 == 0)
{
even++;
}
else
{
odd++;
}
}
cout << "Number of odd numbers: " << odd << "\n";
cout << "Number of even numbers: " << even << "\n";
return 0 ;
}
When i compile it shows even (40) and odd (10) for input of 0 till 19. Where it should show even 10(including the 0) and odd (10). Im not sure where am i doing it wrongly. I hope someone can help me improve the code.
Variables even and odd are never set to a known value, so you are not formally allowed to read from them. Doing so invokes that most infamous Standardese concept: undefined behaviour. So the values of these variables could be right or could be wrong; the variables and all code trying to read them could be optimised entirely out of your program; or anything can happen. You cannot rely on these variables doing anything right. All attempts to read them make your program ill-formed, so now it can do anything, including things you would never have imagined.
You should search for the abundant background info about these concepts, but I like to think I made a fairly decent summary here: https://stackoverflow.com/a/38150162/2757035
Also, as Thomas points out in the comments, you appear not to understand how array indexing works: Indexes are 0-based. So, int i[20] declares 20 elements numbered from 0 to 19. You try to access index 20, which is not part of the array and hence is more undefined behaviour.
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
[EDIT] - Nevermind, this is a really dumb question
I'm currently trying to create a program that will basically tell me when insertion sort takes a longer time than merge sort for given a, b and n (in this case, successive powers of 2). This is what I have so far:
int comparisonSort()
{
//prompt user for values of a and b
int a = 0;
int b = 0;
cout << "Enter the value for a" << endl;
cin >> a;
cout << "Enter a value for b" << endl;
cin >> b;
double insertionSortTime = 0;
double mergeSortTime = 0;
double n = 2;
cout << outside while loop" << endl; //check
while (insertionSortTime < mergeSortTime)
{
cout << "inside while loop" << endl; //check
//compute the insertion and merge sort execution times
insertionSortTime = a*n*n;
mergeSortTime = b*n*log2(n);
cout << "is = " << insertionSortTime << " ms = " << mergeSortTime << endl;
n = pow(n, 2); // n^2
}
cout << "value of n that insertion sort beat merge sort is: " << n << endl;
return 0;
}
when I run this, I get:
Enter the value for a
8
Enter a value for b
64
outside while loop
value of n that insertion sort beat merge sort is: 2
I have no idea why the while loop isn't getting executed... Sorry if this seems like a really simple question, but I'm new to C++ and any help would be greatly appreciated, thank you!!
The conditional in
while (insertionSortTime < mergeSortTime)
is false in the first iteration when both insertionSortTime and mergeSortTime are set to zero. That explains why the loop never got executed.
Perhaps you meant to use:
while (insertionSortTime <= mergeSortTime)
Its because you have insertionSortTime = 0 and mergeSortTime = 0 and the condition for your loop is insertionSortTime < mergeSortTime.
Of course 0 is not < 0 so it never enters the loop.
Change it to <=.
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 8 years ago.
Improve this question
I'm almost positive it's something simple, but i cannot for the life of me figure it out. This whole code is to print a menu which asks users for the and array size, then fills it with random numbers, sorts it ascending and descending, printing the array, as well as letting the user use a binary search or a sequential search. I know a linear search is much more efficient for what we're supposed to do, but the instructor insists on a binary search. I have the Binary search working, and it prints out the correct result, but with a 1 on the end of it(i.e position 14 comes out as 141). here's the switch case that calls the function:
case 7:
int num, result;
cout << "Please enter an int to search for" << endl;
cin >> num;
result = binarySearch(Array1, num, 0, size);
cout << num << "was found at position " << result;
break;
}
}
here is the function:
int binarySearch(int arr[], int key, int first, int last)
{
while (first <= last)
{
int mid = (last + first) / 2;
if (key < arr[mid])
{
last = mid - 1;
}
else if (key > arr[mid])
{
first = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
Just tried the code on my machine - I am not getting an extra 1 appended to the output. So, I would think the 1 is being printed out somewhere else.
First, add in the space (or endl at the end of cout. This will confirm that the result you're getting is correct and also that the 1 is being printed elsewhere. Then, you can try looking for the extra 1 being printed in your code (after the switch() probably).
cout << num << "was found at position " << result << " ";
Update the rest of the code if you need further help.