Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 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 working on a hangman game for a college asignment and i aleady have most of the work done but for some reason this part here is not working. Is there a problem with my logic? It seems to be incredibly simple.
bool second_check(char user_input) {
char u[3]={'a','r','i'};
for (int i = 0; i <= 3; i++) {
if (user_input==u[i]){
return true;
};
};
return false;
}
int main(){
char o;
cout<<"enter"<<endl;
cin>>o;
if (second_check(o)==true) {
cout << "Correct!" << endl;
}
else
cout << "Wrong! \n Strike one!" << endl;
return 0;
}
The for loop will loop 4 times even though you have 3 elements, causing it to try and access an undefined location in memory, to fix this replace the 'i <=3' with 'i<3'
so the for loop should like this in the end:
for (int i = 0; i < 3; i++) {
if (user_input==u[i]){
return true;
};
};
Answer
Since char u[3]={'a','r','i'}; contains only 3 characters, your for loop will be:
for (int i = 0; i <= 2; i++) or
for (int i = 0; i < 3; i++).
Explanation
This is because, in C/C++ and most of the programming language, the array count starts from 0. Therefore the first element will be array[0] and last will array[n-1] where n is the size of the array used at initialization. (Above, n=3)
So it would be helpful to the community if you state clearly what the problem is (i.e expected vs. actual output).
That said, a couple problems I can see...
for (int i = 0; i <= 3; i++)
if (user_input==u[i]){
Since u is of size 3 (char user[3]), you need to change your for loop to be i < 3 since arrays are 0 based, valid indices are 0,1,2 and you will go out of bounds of the array. I.e. user[3] is not a valid index.
You are not comparing an index of user_input which I suspect you want to. i.e. user_input[i].
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 3 years ago.
Improve this question
I am new to the C++ language and trying to complete a very simple code challenge to sum up all the numbers in an array. The test environment doesn't show an error message it only gives me an exit code 139. Upon some research this means my code is producing undefined behavior (also maybe memory fragmentation?). Is it just something with the syntax or is there something I'm missing about C++?
#include <vector>
int sum(std::vector<int> nums) {
int runningSum = 0;
for (int i=0; i <= nums.size(); i++) {
runningSum = runningSum + nums[i];
}
std::cout << "The total sum for nums: " << runningSum;
}
Your function is supposed to return. You don’t, so you have undefined behavior there.
Your loop goes one beyond the last element of the vector, that has another UB.
Here is the fixed version:
int sum(std::vector<int> nums) {
int runningSum = 0;
for (int i=0; i < nums.size(); i++) {
// ^^^^
runningSum = runningSum + nums[i];
}
std::cout << "The total sum for nums: " << runningSum;
return runningSum;
// ^^^^
}
Please note that std::accumulate can do the same for you.
And as #gast128 suggested, your function signature can be changed to avoid copying the vector:
int sum(const std::vector<int>& nums)
Sorry ya'll yes I just had to return the result. I also had to remove the <= and replace with < but leaving <= gave me an exit code 139.
I'd also like to add a quick note on the use of std::vector<>::operator[].
From the documentation here, you can read that it returns the reference of the element in the vector. But unlike std::vector<>::at, using the operator[] with a number n >= vector.size() causes undefined behavior.
If you had used std::vector<>::at instead, it would have thrown an out_of_range exception, which is more talkative.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 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 was solving a problem https://codeforces.com/contest/489/problem/B
Its a simple brute force approach,In my terminal when i am giving input
#include<bits/stdc++.h>
using namespace std;
vector <int> b;
vector <int> g;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
b.push_back(a);
}
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int a;
cin >> a;
g.push_back(a);
}
sort(b.begin(), b.end());
sort(g.begin(), g.end());
int ans = 0;
bool visited[10000];
memset(visited, sizeof(visited), false);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(!visited[j])
if (abs(b[i] - g[j]) <= 1) {
visited[j] = true;
ans++;
break;
}
}
}
cout << ans;
}
4
1 4 6 2
5
5 1 5 7 9
I am getting correct output as 3 , This is the very first test case on codeforces also and codeforces showing output as 2 and as showing as wrong answer.
Please see here Proof ,I never faced such kind of problem in competitive
programming .
accepted solution solution
There was also announcement related to this ques read below here
This is a case of undefined behavior: if(!visited[j]) is undefined. visited is not initialized because the call memset(visited, sizeof(visited), false); is wrong. You are reading uninitialized variables.
The declaration of memset is
void *memset( void *dest, int ch, size_t count );
You are writting 0 times the value 10000 into visited. On your machine this memory was filled with zeros. But on other machines there can be different values.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
So, I need to get the sum of the first 5 even numbers from my array, this is the code that I've got so far, have no clue what to do next. It runs, but the result is incorrect
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int niz[10];
cout << "Unesi 10 brojeva:";
for (int i = 0; i < 10; i++) {
cin >> niz[i];
}
int suma = 0;
int parni[5];
int j = 0;
for (int i = 0; i < 10; i++) {
if (niz[i] % 2 == 0) {
niz[i] == parni[j];
j++;
if (j == 5) {
break;
}
}
}
for (int i = 0; i < 5; i++) {
suma = parni[i] + suma;
}
cout << suma;
system("PAUSE");
return 0;
}
This line:
niz[i] == parni[j];
does nothing. (It tests if niz[i] happens to be equal to the current, uninitialized value of parni[j], and throws away the result of the comparison.)
You want to store niz[i] in parni[j], so do this:
parni[j] = niz[i];
Incidentally, there is a problem if there are fewer than 5 even numbers in the niz array. In that case, you still sum up all five entries of the parni array, using uninitialized values, which is Bad. One way to avoid this is to just sum up the even entries as you find them, without using a secondary array.
IE, do suma += niz[i] at the line in question, and get rid of parni altogether.
Unless you're really required to use arrays here, vectors will work much more nicely.
You can also use a couple of standard algorithms to make your life easier (especially std::copy_if and std::accumulate).
// for the moment I'll ignore the code to read the input from the user:
auto input = read_input();
auto pos = std::remove_if(input.begin(), input.end(),
[](int i) { return i % 2 != 0; });
// assume that `input` always contains at least 5 elements
pos = std::min(pos, input.begin() + 5);
sum = std::accumulate(input.begin(), pos, 0);
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 was able to get this to run in 1.65 secs but I have a feeling that it could be faster. Doubles maybe?
#include<iostream>
using namespace std;
bool isPrime(int n) {
if(n%2 == 0 && n!=2) return false;
for(int i=3; i<n/2; i++) {
if(n%i == 0) return false;
}
return true;
}
int main() {
int num, i;
i=1000000007;
num = 1000000008;
for(;i<num; i++) {
if(isPrime(i)) cout << i << endl;
}
return 0;
}
You have no increment in the for loop in "isPrime". You have:
for(int i=3; i<n/2;)
You should have:
for(int i=3; i<n/2; i++)
Edit: since a commenter brought up optimizations, there are two things you can do to easily and greatly reduce the number of operations for large values of n.
The first is, as commented, to increment i by 2 (I am leaving my answer as is, since the point of the question was "why doesn't the code work" and not "how do I optimize the code," and it's easier for novice programmers to see the fix in its simplest form) since you already know you've eliminated all even numbers from the prior conditional.
The second is to only check up to the square root of n and not n divided by 2. The reason is as follows: if n is not prime, then there are two numbers greater than 1 and less than n that satisfy the condition
n = x * y
If both x and y are greater than the square root of n, then x * y is greater than n. Thus, if you haven't found any factors by time you iterate past the square root of n, n is prime.
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 am trying to create a template function in C++ that return the sum of the elements of an array of different data types. I am having issues when I try to get my result. I print out an address in memory (I guess). This is for my last homework in C++, so please some help in here ;-)
this is what I have so far:
template <class T>
int sum(T array, int size)
{
int i;
int result;
for(i = 0; i < size; ++i)
{
result += array[i];
}
return result;
}
and my main() looks like
int main()
{
cout << "Printing Array sum..." << endl;
len = sizeof(intArr) / sizeof(int);
//len = sizeof(strArr) / sizeof(int);
cout << sum(intArr, len)<<endl;
//cout << sum(strArr, len)<<;
return 0;
}
my output in the command line is a random number
Please a hint or help in how to solve this
You didn't initialize result in sum, so it contains stack garbage. Then you add everything in array to stack garbage, which gives you garbage.