My assignment is to : Create a method to search an un-ordered array of integers for a value,
if the value is found return the index of its position in the array, if not found, return -1.
It is only finding the number I enter if it is in Index 0, otherwise it is saying it is not found. I am not sure what went wrong, it was working when I had initialized my own array, but now it won't since I have the user create their own array.
Any help would be great! thanks!
So far my code is:
#include <iostream>
using namespace std;
//SearchArray prototype
int SearchArray( int arInt[], int elementAmount, int intSearched);
int main()
{
int arInt[50];
int elementAmount;
int intSearched = 0;
int i;
cout << "How many elements would you like to add to your array?\n";
cin >> elementAmount;
for( i = 0; i < elementAmount; i++)
{
cout << "Enter Number: ";
cin >> arInt[i];
}
cout << "Search array for integer:\n";
cin >> intSearched;
//Call search array method
SearchArray(arInt, elementAmount, intSearched);
system("pause");
return 0;
}
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
int i;
bool foundInt = false;
for (i=0; i < elementAmount; i++)
{
if( arInt[i] == intSearched)
{
foundInt = true;
cout << "Integer was found in array at index " << i << endl;
}
else if (!foundInt)
{
cout << "Integer was not found in array\n";
system("pause");
return -1;
}
}
}
Added the following code to the SearchArray method in your code, and it works fine
int SearchArray( int arInt[], int elementAmount, int intSearched)
{
for(int i=0; i< elementAmount; i++)
{
if (arInt[i] == intSearched)
return i;
}
// element not found!
return -1;
}
And add the following at the end of your main to retrieve the ans
int ans = SearchArray(arInt, elementAmount, intSearched);
cout<<"Indexed of the element"<<ans<<endl;
That's because you always end your search on first element. Suppose array is
arr=[3,5,7] and intSearched is 5.
Now in your SearchArray() function foundInt is initially set to false. So when i = 0 and arInt[i] == intSearched condition is not true, it goes to else statement since foundInt is false. And from there you return -1. Something like below would be simpler and do the job:
int SearchArray(int *arInt, int elementAmount, int intSearched)
{
int i;
for(i=0; i < elementAmount; i++)
{
if(arInt[i] == intSearched)
{
cout << "Integer was found in array at index " << i << endl;
return 1;
}
}
cout << "Integer was not found in array\n";
system("pause");
return 0;
}
Related
I need to build a code where it takes a 2d array of char and checks if its palindrome the second function uses the first one to see how many arrays are palindrome my issue with the code is that every time I get count is 0; I know the issue is in the second function but don't know where
#include <iostream>
using namespace std;
int CountPal(char M[][5], int rows);
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
}
int main() {
int x;
cout << "please enter the number of rows " << endl;
cin >> x;
char M[5][5];
cout << "before test" << endl;
cout << CountPal(M, x) << endl;
cout << "After test" << endl;
system("pause");
}
int CountPal(char M[][5], int rows) {
int count = 0;
cout << "please enter the string " << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < 5; j++) {
cin >> M[i][j];
}
for(int i = 0; i < rows; i++) {
char* S;
S = &M[i][0];
if(pal(S) == 1) count++;
}
}
return count;
}
I think your problem is in int pal(char* S) function. You want it to return 1 if a given string of your 2d array is a palindrome to up your count by 1. And anything other than 1 would be non palindrome string.
So i think you should add a return statement after the end of your int pal(char* S) function like this;
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
return flag;
}
You could even change your function to bool data type. It's more proper because you only want to return "true" or "false" values.
I am trying to implement the algorithm RLE with simple input like:
ddddddddddhhhhhhhhhhhhhhhttttttttttttt
code:
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main() {
vector<char> read;
ifstream file;
file.open("file.txt");
if (!file) {
cout << "Unable to open";
}
char v;
while(file>>v) {
read.push_back(v);
}
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
x = read[i];
if(x != read[++i]) {
cout << x << "1";
}
while(x == read[++i]) {
count++;
}
cout << x << count;
count = 0;
}
return 0;
}
The output I am getting is:
d9d1h12h1t10t1
Please help me with the code.
Update: I have updated the question as I have realized few things.
Plus: This code produced no output, is there anything wrong which I am doing wrong?
char o;
char n;
int count=0;
for(int i=0; i<read.size(); i++) {
o = read[i];
n = read[++i];
while(o == n) {
count++;
}
cout << o << count;
if(o != n) {
cout << o << "1";
} count = 0;
}
return 0;
This loop:
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
int j=i;
x = read[i];
if(x != read[++j]) {
cout << x << "1";
}
while(x == read[++j]) {
count++;
}
cout << x << count;
}
Has several errors. First, you should use two indices, i and j. i is going through each element of read, but then j is iterating through a subsequence too. What you want is to go through each element only once, and in each case either print or increase the count. However having a for loop and moving the index inside too is not a very good practice, is rather error-prone. Also you have to cout statements that are do not run at the right time (you don't wan to print something on every iteration, only when the character changes). You could do it with a while loop, or using a simpler structure like:
// If there are no characters finish
if (read.empty()) {
return 0;
}
// Get the first character
char lastChar = read[0];
int count = 1; // We have counted one character for now
// Go through each character (note start from 1 instead of 0)
for(int i = 1; i < read.size(); i++) {
// Get the next char
char newChar = read[i];
// If it is different, print the current count and reset the counter
if (lastChar != newChar) {
cout << lastChar << count;
count = 1;
lastChar = newChar;
} else { // Else increase the counter
count++;
}
}
// Print the last one
cout << lastChar << count;
return 0;
I have big problem.
The task is:
Write a function in C ++ that takes a array of ints tab, array size n, and the number k. The function returns returns true if each of the numbers in the table tab, at least k digits long, and false otherwise. Checking how many digits has the number should be included in the additional auxiliary functions that call from inside a basic function. You should also write the main function that reads the data, calls the base and outputs its result.
For calls (record [] is an array):
f ([123,4425,2224,222,55553], 5, 3)
The function should return true. Since each of the numbers 123,4425,2224,222,55553 at least three digital
Calls for:
f ([123,4425,2,222,5], 5, 2)
The function should return false
Because there are a number, for example 2 which is a digital one and is less than 1 k = 2
My code :
#include <iostream>
int ile_cyfr(int a)
{
int temp=0;
do
{
a = a/10;
temp++;
} while(a>0);
return temp;
}
bool funkcja(int *tab, int n, int k)
{
bool stan = false;
for (int i=0; i<n; i++)
{
if (ile_cyfr(tab[i])<k)
{
stan = false;
if (stan == false)
{
return stan;
return 0;
}
}
else
{
stan = true;
return stan;
}
}
}
int main() {
using namespace std;
int n=0, k=0;
int *tab = new int[n];
cout << "Podaj ilosc liczb: " << endl;
cin >> n;
cout << "\nPodaj liczby: " << endl;
for (int i=0; i<n; i++) {
cin >> tab[i];
}
cout << "\nPodaj minimalna ilosc liczb: " << endl;
cin >> k;
cout << funkcja([444,856,671,321], n, k);
return 0;
}
The problem is that the line:
cout << funkcja([444,856,671,321], n, k);
For starters the function funkcja is invalid. It returns true in case when the first element of the array has the number of digits greater than or equal to k. As I have understood you have to check that all elements of the array satisfy the condition.
The function can be written the following way
bool funkcja( const int *tab, int n, int k )
{
int i = 0;
while ( i < n && !( ile_cyfr( tab[i] ) < k ) ) i++;
return n != 0 && i = n;
}
As for this statement
cout << funkcja([444,856,671,321], n, k);
then it has an incorrect syntax.
You have to pass the variable tab as the first argument of the function call. These values 444,856,671,321 should be assigned to elements of the array pointed to by the pointer tab.
Thus write
cout << funkcja( tab, n, k );
I'm trying to write a simple program which takes an array of chars, and spits it out backwards. I know there are plenty of other ways to shorten this using a library header function, but I wanted to do it using for loops just to get used to them.
#include<stdio.h>
#include<iostream>
using namespace std;
char string1[10];
int count = 0;
char stringy[10];
void enterString()
{
cout << "please enter a string: " << endl;
cin >> string1;
}
void stringCounter(const char stringLength[])
{
//initiate for loop i = 0
//if stringLength[i] does not does not equal 'i' then carry on
//increment i
for (int i = 0; stringLength[i] != '\0'; i++)
{
count++;
}
cout << "size of string is: " << count << endl;
}
void reverseString(int arraySize, char string2[])
{
int counter = 0;
for (int i = arraySize; i >= 0; string2[i--])
{
stringy[counter] = string2[i];
counter++;
}
stringy[count] = '\0';
cout << stringy << endl;
}
int main()
{
enterString();
stringCounter(string1);
reverseString(count, string1);
return 0;
}
This is the whole program. The program is failing in function reverseString. I can't work out how to successfully read the last index of the char array string2[] and copy it into the first index of char array stringy.
One, If the user enters a string more than 10 characters long then your enterString() function will access the array out of its bound, at cin>>string1. So better to use getline to make sure you don't read more than what your array can hold.
Two, with your current implementation the reverseString() function will write to the first element of the array with the null terminator character,if the arraySize<=10, and trying to display that string will not show you anything.
This:
cin >> string1;//will try to access the array out of its bound if user give more than it can hold,i.e 10 characters
...
for (int i = arraySize; i >= 0; string2[i--])
{
stringy[counter] = string2[i];//the first iteration will put the '\0' character as the first elements of stringy
counter++;
}
Should be changed to:
cin.getline(string1,10);//make sure to get not more than 10 characters,including the null terminator
.....
for (int i = arraySize-1; i >= 0; i--)
{
stringy[counter] = string2[i];
counter++;
}
There are many mistakes in your program. If this is the exact code you are compiling then it should throw many errors.
Following might help.
#include<iostream>
using namespace std;
void reverseString(int , char *);
int stringCounter(const char );
int stringCounter(const char stringLength[])
{
int count = 0;
for (int i = 0; stringLength[i] != '\0'; i++)
count++;
cout << "size of string is: " << count << endl;
return count;
}
void reverseString(int arraySize, char string2[])
{
int counter = 0;
char stringy[100];
for (int i = arraySize - 1; i >= 0; i--)
{
stringy[counter] = string2[i];
counter++;
}
stringy[counter] = '\0';
cout << stringy << endl;
}
int main()
{
char str[] = "string";
reverseString(stringCounter(str),str);
return 0;
}
I have a task to create a program which makes array via user input and then in new function to create another array which only consists of even elements and then the result should be returned via pointer to the newly created array.
Bear in mind that I just started learning C++ so pointers here are not on spot.
#include <iostream>
using namespace std;
int* getEven(int *niz, int *n)
{
int i;
for(i = 0 ; i < *n ; i++)
{
if(niz[i] % 2 == 0)
cout << niz[i];
}
}
int main()
{
int n, i;
int *niz;
cout << "Enter positive and larger number than 50: ";
cin >> n;
if(n <= 50)
cout << n;
else
{
cout << "Error. Number is lower than 50." << endl;
abort;
}
niz = new int[n];
for(i = 0 ; i < n ; i++)
{
cout << "Enter next element:" << endl;
cin >> niz[i];
}
int *a = getEven(niz, n);
cout << endl;
cout << a[0] << endl;
system("pause");
return 0;
}
If you are intending to create a new array which might not contain all the elements from the first one, you need an additional parameter to keep track of the number of elements in the new array. Here is how you do it:
int* getEven(int *inputArray, int inputLength, int *outputLength)
{
int *outputArray = new int[inputLength];
*outputLength = 0;
for(int i = 0; i < inputLength; i++)
{
if(inputArray[i] % 2 == 0)
{
outputArray[*outputLength] = inputArray[i];
outputLength++;
}
}
return outputArray;
}
And here is an example on how to use it in main:
int outLen = 0;
int *a = getEven(niz, n, &outLen);
for(i = 0; i < outLen; i++)
cout << a[i] << endl;
Also, bear in mind that you will need to manually delete the dynamically allocated arrays to prevent memory leaks. This applies to the array created in the main function too. Therefore, you need to do this:
delete []niz;
delete []a;