How would I print the index of an array? C++ - c++

I was just wondering how do I print off the Index position of an array? I know there's an if loop involved but I just can't seem to understand it properly.
I want the code to be able to print off what the element of the Array is and the position number. I should also mention that this is for a function as well. Any help will be appreciated. Below is my code
int index_of(string names[], int size)
{
string name;
int index;
for(int i = 0; i < size; i++)
{
if (to_lowercase (names[i]) == to_lowercase(name));
{
return;
}
}
}

What you are trying to do is called "searching".
You have a string which (potentially) is the known content of an entry in an array, but at an unknown index.
What you need to do is to find the index which, used for accessing the entry at that index, yields content which is identical to what you are looking for.
The code you show is more or less pseudo code for doing exactly that.
However, the shown code will not work for the following reasons:
it does not correctly return the index in question, it should return i;
it only returns explicitly in case of finding something, it should, after the loop, return -1;(as a proposal how to communicate failure)
it incorrectly compares (the == operator cannot meaningfully be used on "strings", which in C are only pointers to characters), it should use strncmp(), see e.g. https://en.cppreference.com/w/c/string/byte/strncmp
it does not actually print anything, but I think that is a problem of phrasing your goal and you can easily add a print outside of the shown code, using the (now hopefully correct and correctly returned) return value of the shown function
it has the problem mentioned by Nathan Pierson, see their comment/answer

This is what managed to print the indexes, you guys were actually able to help me understand what I was doing
int index_of(string names[], int size, string name)
{
for(int i = 0; i < size; i++)
{
if (to_lowercase (names[i]) == to_lowercase(name));
{
return i;
}
return -1;
}
}

Related

how can I find struct data in vector's element?

I am working on client/server project. i am struggling with how to find vector's information in database to match client's account number that requested.
header file
struct storeData
{
int iAccountNumber;
int iPin;
double dBalance;
string sFirstName;
string sLastName;
string sMiddleInitial;
};
vector <storeData> storeDataArray;
storeData dataObj;
in server file..
int MyThread::findAccountNumberInStore(int iAccountNumber)
{
int iIndex = -1;
for(int unsigned i = 0; i <= storeDataArray.size(); i++)
{
//i got error message in if statement. i dont know how to fix it.
if(iAccountNumber == storeDataArray.at(dataObj.iAccountNumber))
{
return i;
}
}
return iIndex; //no account is found...
}
Also how can I store the struct's data in vector (all data in one element)?
From vector.at description:
Returns a reference to the element at position n in the vector.
The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater or equal than its size). This is in contrast with member operator[], that does not check against bounds.
You can read more about this function here:
vector.at
also you can read a discution about it here:
vector::at vs. vector::operator[]
to your practical problem i suggest using it like this:
if(iAccountNumber == storeDataArray.at(i).iAccountNumber)
You almost have it - the bracket is in the wrong place, and you didn't index the vector correctly, you have
if(iAccountNumber == storeDataArray.at(dataObj.iAccountNumber))
Should be
if(iAccountNumber == storeDataArray.at(i).iAccountNumber)
Also I see you use <= on array size check - this is incorrect. Vector bounds are from 0 to size()-1

Having trouble passing array to recursive function c++

When I run the function "check_row" within itself, there is a problem with the way I'm trying to pass in the array "sudoku_temp", but I'm not sure what I'm doing wrong. Am I missing something?
int check_row(int j_position, int generated_value, int sudoku_temp[][9]){
for (int i_position = 0; i_position < 9; i_position++)
{
if (generated_value == sudoku_temp[i_position][j_position])
{
generated_value = generate_number();
check_row(j_position, generated_value, sudoku_temp[][j_position]);
}
else
return generated_value;
}
}
To clarify, the problem is when I try to call on the function within itself. Thanks.
When you want to extract a value from an array, you cannot leave empty brackets like you did. On the other hand, the function prototype looks similar and it's perfectly fine. Why?
int sudoku_temp[][9] // A 2D array of integers second dimension of which is of size 9
Or in other words, an array (of unknown size) of arrays of size 9. We are not telling the compiler how big the array really is and we don't have to in this case as it is simply given to us as an argument.
When accessing elements on the other hand, we cannot leave empty brackets for a simple reason: we want to access an element and the compiler has to know which one. Cutting to the chase - removing the empty [] should solve your problem.
use a variable instead of fixed length like 9. since in recursion the argument may be different.
int check_row(int j_position, int generated_value, int sudoku_temp[][n])
{
for (int i_position = 0; i_position < n; i_position++)
{
if (generated_value == sudoku_temp[i_position][j_position])
{
generated_value = generate_number();
check_row(j_position, generated_value, sudoku_temp[][j_position]);
}
else
return generated_value;
}
}

Recursive call segmentation fault issue

quick question again.
I'm creating a recursive function that will look for elements in a array of "source" rules and apply those rules to an "target array" of rules if the "source" rule type is the same as the target character. Furthermore the function checks to see if the target character is in an array of symbols or not and adds it if it is not (and throws a few flags on the newly applied rule as well). This is all driven by a recursive call that uses a counter to determine how many iterations have passed and is used to determine the spot in the target array the new rule should be applied, so we don't overwrite.
I've put in a little debugging code to show the results too.
Here's the function itself:
//Recursively tack on any non terminal pointed elements
int recursiveTack(rule * inrule[], char target, rule * targetrule[],
int counter, char symbols[])
{
printf("Got into recursiveTack\n");
printf("target is %c\n", target);
printf("counter is %d", counter);
for (int k = 0; k < sizeof(inrule); k++)
{
if (inrule[k]->type == target)
{
//doublecheck to see if we're trying to overwrite
if (targetrule[counter]->used = true)
{
counter++;
}
targetrule[counter]->head = inrule[k]->head;
targetrule[counter]->type = inrule[k]->type;
targetrule[counter]->used = true;
//Check to see if the elements are new to the symbols table and need to be added
if (!contains(returnGotoChar(targetrule[counter]), symbols))
{
//If not then add the new symbol
addChar(returnGotoChar(targetrule[counter]), symbols);
//Also set the goto status of the rule
targetrule[counter]->needsGoto = true;
//Also set the rule's currentGotoChar
targetrule[counter]->currentGotoChar = returnGotoChar(
targetrule[counter]);
}
counter++;
//recursivly add elements from non terminal nodes
if (isNonTerm(targetrule[counter]))
{
char newTarget = returnGotoChar(targetrule[counter]);
counter = recursiveTack(inrule, newTarget, targetrule, counter,
symbols);
}
}
}
//return how many elements we've added
return counter;
}
Here's the call:
if(isNonTerm(I[i+first][second]))
{
printf("Confirmed non termainal\n");
printf("Second being passed: %d\n", second);
//Adds each nonterminal rule to the rules for the I[i+first] array
second = recursiveTack(I[i], targetSymbol, I[i+first], second, symbols[first]);
}
All the arrays being passed in have been initialized prior to this point.
However, the output I get indicates that the recursion is getting killed somewhere before it gets off the ground.
Output:
Second being passed: 0
Confirmed non termainal
Got into recursiveTack
target is E
Segmentation fault
Any help would be great, I've got the rest of the program available too if needs be it's around 700 lines including comments though. I'm pretty sure this is just another case of missing something simple, but let me know what you think.
for(int k = 0; k < sizeof(inrule); k++)
sizeof(inrule) is going to return the size of a pointer type (4 or 8). Probably not what you want. You need to pass the size of the arrays as parameters as well, if you are going to use these types of structures.
It would be better to use Standard Library containers like std::vector, though.
if(targetrule[counter]->used = true){
counter++;
}
// what is the guarantee that targetrule[counter] is actually valid? could you do a printf debug before and after it?
The biggest thing I see here is:
for(int k = 0; k < sizeof(inrule); k++)
This isn't going to do what you think. inrule is an array of pointers, so sizeof(inrule) is going to be the number of elements * sizeof(rule*). This could very quickly lead to running off the end of your array.
try changing that to:
for (int k = 0; k < sizeof(inrule) / sizeof(rule*); ++k)
Something else you might consider is an fflush(stdout); after your print statements. You're crashing while some output is still buffered so it's likely hiding where your crash is happening.
EDIT:
That won't work. If you had a function that did something like:
int x[10];
for (int i = 0; i < sizeof(x) / sizeof(int); ++i) ...
It would work, but on the other side of the function call, the type degrades to int*, and sizeof(int*) is not the same as sizeof(int[10]). You either need to pass the size, or ... better yet, use vectors instead of arrays.

Print statement changing output of function?

I have a bit of c++ code that's supposed to look at the derivative of a function and collect the points that have a slope greater than some threshold. It's been giving me troubles, so I've been putting print statements everywhere to figure out what is going wrong. I stumbled upon a baffling issue where when I used std::cout<< to print the size of an array, it changed the output of the function! Here's the code snippet:
int* Tools::findPoi(float* y, int size, float threshold, int width, float step, int* outsize){
int poi[size];
float* derive = derivative(smooth(y,size,width),size, step);
int n = 0;
std::cout<<size<<" data size\n";
for(int i = 0; i<size; i++) {
if(derive[i] > threshold) {
poi[n] = i;
n++;
}
}
*outsize = n-1;
return poi;
}
without the commented out line "std::count..." I get 82 poi. But if I comment it out or remove it I get 84 poi. Nothing else changes, only this print statement. I am so confused as to why or even how it could possibly change the output. Any help would be greatly appreciated.
EDIT: ok, so actually, it's just random. The variable n is different everytime I run it, which leads me to believe that something weird is going on in memory.
There is a significant problem with the line:
return poi;
This returns the address of a local object. The array no longer exists when it goes out of scope at the end of the function. For a wonderful explanation see: Can a local variable's memory be accessed outside its scope?.
Since this is C++ and you want a dynamic array I suggest you use std::vector. It solves many problems such as this.

C++ program to compute lcm of numbers between 1 to 20 (project euler )

as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;