Sum of the first 5 even numbers from the array [closed] - c++

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);

Related

unable out figure out error in below program [closed]

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.

Problem with the validation for hangman game [closed]

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].

Value of array index not increasing [closed]

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 4 years ago.
Improve this question
Here if the condition occurs the value of i store in the array prime. But the index of the array is not increasing, all the values are storing at [0] index and destroy the previous value.
Tried all the other methods but didn't find anything.
I tried prime[x++] and prime[x+1], but they both didn't work for me. If someone gives me a solution then I'll be very thankful to you.
#include<iostream>
using namespace std;
int main()
{
int num = 20, prime[20], x;
for (int i = 1; i <= num; i++) {
if (i % 2 != 0) {
prime[x] = i;
}
}
for (int k = 1; k <= num; k++) {
cout << prime[x] << "\t";
}
}
You have the variable x un-initialized and you are using it, in the line
prime[x] = i;
assuming that it has been initialized. This invokes undefind behavior in your program and the result could not be predicted. Initialize it with the appropriate number to make the program to have a defined behavior.
Regarding prime numbers, see this SO post: Printing prime numbers from 1 through 100.
defining x as uninitialized is a undefined behaviour.
Initialize x as 0 (int x = 0;)
Try with bellow :
int x = 0;
for(int i=1; i<=num; i++){
if(i%2!=0){
prime[x] = i;
x++;
}
}
Now you have the number of prime array elements :
Now print prime array :
for(int k=0; k<x; k++){
cout << prime[k] << "\t";
}
The output (it seems your code detect odd numbers) :
1 3 5 7 9 11 13 15 17 19
Test the code online

C++ - Printing prime numbers till N [closed]

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 4 years ago.
Improve this question
Question says:
You are given an integer N. You need to print the series of all prime numbers till N.
I want to know what's wrong with my code and suggestions will also be of great help.
#include<iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int u;
for(int i = N; i > 0; i--)
{
u = 0;
for(int j = 2; j < N-1; j++)
{
if(i % j == 0)
{
u = 1;
}
}
if(u == 0)
{
cout << i << " ";
}
}
return 0;
}
First for future reference you should probably post that on code review, unless there is a specific problem then you should create a Minimal, Complete, and Verifiable post.
There is nothing inherently wrong other than you do not check that N>0 which could lead to an infinite loop, j should be going to i not N, and I think this would print 1 as a prime number which it is not. Here are some pointers:
Why are you going from N to 0? That seems a little counter intuitive compared from going from 2 to N (you can skip 1 since it is not prime)
If you are going to use a flag (u) then you should make it a bool which forces it to be either true or false
You do not need to do a flag, instead as soon as you find a divisor print the number and then break the inner loop like
for(j=2; j< N-1; j++){
if(i%j==0){
cout << i << " ";
break;
}
}
You do not need to have j go all the way to i, just the sqrt(i) since anything greater then the sqrt(i) that divides i must must be multiplied by some number smaller then the sqrt(i). So if i is not prime, then there must be a divisor below sqrt(i)

C++ malloc(): memory corruption [closed]

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
I am currently going through a fibonacci practice problem on hackerrank and am having a malloc memory corruption error. This is the link to the problem I am doing:
https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-returns/
Input is 0-10, each number separated by a new line.
For each input, the value at that point in the sequence is printed. It works for small inputs, but after 6 it gets the malloc error. It doesn't seem that the size of the sequence is an issue either, just how many are done in succession.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> bigFib(1);
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int x;
while(cin >> x){
if(bigFib.size()-1 >= x){
cout << bigFib[x] << endl;
}
else{
vector<int> fib(x);
fib[0] = 0;
fib[1] = 1;
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
bigFib = fib;
cout << fib[x] << endl;
}
}
return 0;
}
I am pretty new to C++ and can't find the problem. Thanks for your time.
When you create std::vector of size N, you can access elements with index [0, N-1] - which is N elements. You create vector of size x and in your loop:
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
and in this statement
cout << fib[x] << endl;
you try to access element with index equal to x, which is UB. If you do need to access index x create vector with at least x+1 size
In vector<int> fib(x); you declare a vector<int> that has x elements. Those elements are fib[0] through to fib[x - 1]. However, in for(int j = 2; j <= x; j++){ fib[j] = ... you assign to an element out of bounds.
Imagine if x is 1, then you'd expect your fib vector to contain only one element: fib[0]... yet your loop is assigning to fib[1]. Problem? Yup.
I reckon for(int j = 2; j <= x; j++){ should probably be for(int j = 2; j < x; j++){...
... and cout << fib[x] << endl; should be cout << fib[x - 1] << endl;