C++ Linear search returning just 0 [closed] - c++

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
So I am a newbie in C++, I do code in JS, for some reason I can't figure out the mistake here, please help me out. thanks!
#include <iostream>
using namespace std;
int search(char input, char sentence[]){
for(int i = 2; i != '\0'; i++){
if(sentence[i] == input){
return i;
}else{ return -1; }
}
}
int main()
{
char key[20] = "hey my name is sid!";
char ser = 'm';
cout << search(ser,key);
return 0;
}

Your condition in the for loop is wrong, you are not checking the string only the index. Also if your character did not match, you do not want to exit immediately.
The correct code would be:
for(int i = 0; sentence[i] != '\0'; i++)
{
if(sentence[i] == input)
{
return i;
}
}
return -1;
If you want to start the search at the third character you should first ensure that your string has at least three elements:
if(strlen(sentence)>=3)
{
for(int i = 2; sentence[i] != '\0'; i++)
{
...
}
...
}

For your search function, you are only really checking the first character in the loop, then returning. You should move "return -1;" outside of the for loop as then it will only be called after the entire string was checked for the value and it was not found.
int search(char input, char sentence[]) {
for (int i = 2; sentence[i] != '\0'; i++) {
if (sentence[i] == input) {
return i;
}
}
return -1;
}
in addition to changing the conditions of the for loop as other users mentioned.

Related

Running a C++ code with no syntax error but something strange terminates [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 16 days ago.
Improve this question
My code has something strange. It doesn't have any syntax errors, and when I run it, it runs and takes input, and then immediately terminates. What is the issue?
I have tried to run the code in VS Code and Codeblocks, and I am faced with the same error. I am stuck right now.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int>a(2 * n);
for (int i = 0;i < 2 * n;i++)
{
cin >> a[i];
}
int mx = 0;
vector<int>w;
for (int i = 0;i < 2 * n;i++)
{
vector<int>::iterator it = find(w.begin(), w.end(), a[i]);
if (it != w.end())
{
w.push_back(a[i]);
}
else
{
w.erase(it);
}
if (mx < w.size())
{
mx = w.size();
}
}
cout << mx << endl;
}
In your 2nd loop, you are calling w.erase(it) when it is w.end(), which is undefined behavior:
https://en.cppreference.com/w/cpp/container/vector/erase
The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.
You are trying to push the integer if it is found, and erase it if it is missing. That logic is backwards. You need to use == instead of != in your if condition to reverse the logic:
if (it == w.end()) // <--
{
w.push_back(a[i]);
}
else
{
w.erase(it);
}

To check if there are capital in a array c++ [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 last year.
Improve this question
I'm trying to write a c++ function to find if the array has capital, but somehow it kept returning true.
Here is my function:
bool hasNoCapitals (const string array[], int n)
{
bool result = true;
for (int i = 0; i<0; i++)
{
for (size_t k = 0; k < array[i].size(); k++)
{
char word = array[i][k];
if (word == tolower(word))
{
result = true;
}
else{
result = false;
k = array[i].size();
return result;
}
}
}
return result;
}
int main()
{
string arr[] = {"sa","DDDD","DDDDDDDDD","ffdd","sa"};
cout << hasNoCapitals(arr, 5);
return 0;
}
The function always returns true because of a typo: you have for (int i = 0; i<0; i++), which should be for (int i = 0; i<n; i++) instead.
So your loop is always empty.

c++ why is my code creating extra elements in my vector? [closed]

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
My code counts the frequency of letters in a file. My code:
void incCount (int i, vector<CCount> &chars)
{
int n;
n = chars[i].i;
n++;
chars[i].i = n;
}
void procWord(string word, vector<CCount> &chars)
{
for (int i=0; i<word.length(); i++)
{
bool found = false;
char a = word[i];
for (int j=0; j<chars.size(); j++)
{
if (a == chars[j].c)
{
bool found = true;
incCount(j, chars);
}
}
if (found == false)
{
CCount c; //CCount is a class with a char and int data type.
c.c = a;
c.i = 1;
chars.push_back(c);
}
}
}
int main ()
{
vector<CCount> chars;
string word;
//opening file code here
while (fin >> word) {
procWord(word, chars);
}
return 0;
}
class CCount
{
public:
char c;
int i;
};
the code does accumulate the letter count however when i print the the vector elements I get this. I use "this is a test data" as the test input in the file
You are defining found again. See commented line.
You are defining variable with same name and most local variable will be preferred.
bool found = false;
char a = word[i];
for (int j=0; j<chars.size(); j++)
{
if (a == chars[j].c)
{
bool found = true; //this is wrong, just make it found = true;
incCount(j, chars);
}
}

Sum of the first 5 even numbers from the array [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
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);

Array of Structs (expected expression error) C++ [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 8 years ago.
Improve this question
I have the following code. I am trying to populate an array with a deck of cards, and I keep encountering the same error "expected expression error" no matter how I code the loops to populate the array.
Can anybody see where I'm going wrong. I think its something painfully simple, that I, who am new to C++, am just missing.
Thanks!!
#include <iostream>
using namespace std;
struct playingCard{
char suit; // heart (1), club (2), spade (3), diamond (4)
int value; // 1 to 13 (ace is LOW)
};
void printArray(playingCard playingCardArray[], int size){
for (int i = 0; i < size; i ++){
cout << playingCardArray[i].suit << ":\t" << playingCardArray[i].value << endl;
}
}
int main()
{
const int ARRAY_SIZE = 52;
playingCard playingCardArray[ARRAY_SIZE];
int i = 1;
int suitLoop = 1;
while (suitLoop == 1){
for (int valueLoop = 1; valueLoop <= 13; valueLoop++){
playingCardArray[i] = {suitLoop, valueLoop},
}
}
printArray(playingCardArray, ARRAY_SIZE);
return 0;
}
To resolve your compilation issue change you inner for loop like this:
for (int valueLoop = 1; valueLoop <= 13; valueLoop++){
playingCardArray[i].suit = suitLoop;
playingCardArray[i].value = valueLoop;
}
Other than compilation your code also has Infinite loop , to resolve this you need to change your main somewhat like this:
int main()
{
const int ARRAY_SIZE = 52;
playingCard playingCardArray[ARRAY_SIZE];
int i = 1;
int suitLoop = 0;
while (suitLoop < ARRAY_SIZE){
for (int valueLoop = 1; valueLoop <= 13; valueLoop++){
playingCardArray[suitLoop].suit = (suitLoop/13 + 1);
playingCardArray[suitLoop++].value = valueLoop;
}
}
printArray(playingCardArray, ARRAY_SIZE);
return 0;
}
Exchanging the comma with a semicolon at the end of playingCardArray[i] = {suitLoop, valueLoop}, solves the problem.