Variable not declared within this scope Array Linear Search - c++

I am trying to make a program in C++ that will search for a desired value in an array of size 10 using a separate search function. Below is the code:
main.cpp
#include <iostream>
#include <array>
using namespace std;
int main()
{
cout << "Welcome to the array linked list program.";
int sanadA[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int d = 0;
cin >> d;
while (d =! 0)
{
cout << "Number to be found";
cin >> d;
bool found = seqSearch1(sanadA, 10, d, -1);
cout << found;
}
}
seqSearch1.cpp
#include <iostream>
using namespace std;
bool jw_search (int *list, int size, int key, int*& rec)
{ //Basic sequential search.
bool found = false;
int i;
for(i=0;i<size;i++)
{
if (key == list[i])
{
break;
}
if (i < size)
{
found = true;
rec = &list[i];
}
}
return found;
}
I get the errors:
C:\Users\tevin\Documents\sanad\main.cpp|13|warning: suggest parentheses around assignment used as truth value [-Wparentheses]|
C:\Program Files (x86)\CodeBlocks\MinGW\lib\gcc\mingw32\5.1.0\include\c++\bits\c++0x_warning.h|32|error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.|
C:\Users\tevin\Documents\sanad\main.cpp|19|error: 'seqSearch1' was not declared in this scope|
I need help figuring why this happens.

I assume that the error occurs on this line:
bool found = seqSearch1(sanadA, 10, d, -1);
The problem is that you have not declared any function named seqSearch1(). Instead you have a function named jw_search(). So you can change the line to this:
bool found = jw_search(sanadA, 10, d, -1);
But you also need a header file called seqSearch1.h with the following line:
bool jw_search (int *list, int size, int key, int*& rec);
And finally add this line to the top of main.cpp:
#include "seqSearch1.h"
When you compile your code, you will need to include all source files in the command. For example, if you are using g++, you can do something like this:
g++ main.cpp seqSearch1.cpp
To understand how this works, you need to learn about header files and the difference between a function declaration and a function definition. You should also learn about the difference between the compiler and the linker.

Code-Apprentice has the direct answer to your question. If you want the code in multiple files then a declaration of the seqSearch1 function will need to be main.cpp or included via #include directive
The code has multiple problems. I've fixed it up a bit for you and put it in a single file.
#include <iostream>
#include <array>
using namespace std;
bool seqSearch1 (int *list, int size, int key, int& rec)
{//Basic sequential search.
bool found = false;
int i;
for(i=0;i<size;i++)
{
if (key == list[i])
{
found = true;
rec = i;
break;
}
}
return found;
}
int main()
{
cout << "Welcome to the array linked list program." << endl;
int sanadA[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int d = -1;
while (d != 0)
{
cout << "Number to be found, 0 to end?";
cin >> d;
if(d == 0) break;
int index = -1;
bool found = seqSearch1(sanadA, 10, d, index);
if(found) cout << "Found" << endl;
else cout << "Not Found" << endl;
}
}
Several issues:
The function was referred to by the wrong name.
The loop structure was a confused.
The fourth argument to seqSearch1 had type confusion.

Related

Calling name for passing two arrays (a string and an int) to a function in C++

I'm aware that when you write the call for your function you write it as displayArray(seasons,10)
with the name of one array and its size. I'm stuck on how you would right the arguments to pass the two arrays listed in my code, seasons and cartoons.
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
void displayArray(string car[], int sea[], int size);
int main()
{
int seasons[] = {5,10,8,2,12,7,31,9,3,4};
string cartoon[] = { "Steven Universe","Adventure Time","Regular Show","Gravity Falls",
"Spongebob Squarepants","Futurama","The Simpsons","Bob's Burgers","Avatar: The Last Airbender","Rick and Morty"};
displayArray() // Error Message here
}
void displayArray(string car[], int sea[], int size)
{
for (int x = 0; x < size; x++)
{
cout << " " << car[x] << "\t\t" << sea[x] << right << endl;
}
}
So you have to first create an array to pass your values with. Then just pass the array.
void function(int arr[]) {}
int arr[] = { 1, 2, 3, 4, 5 };
function(arr);
So in your code above, it should look like this:
int main()
{
int seasons[] = {5,10,8,2,12,7,31,9,3,4};
string cartoon[] = { "Steven Universe","Adventure Time","Regular Show","Gravity Falls",
"Spongebob Squarepants","Futurama","The Simpsons","Bob's Burgers","Avatar: The Last Airbender","Rick and Morty"};
displayArray(cartoon, seasons, 10);
}
Hope this helps :)
displayArray(cartoon, seasons, 5);
This seems to work fine for me. You just pass each array in according to whichever is declared first in the function argument list. Am I misunderstanding your question?

SC_FIFO write : First chance exception

I've written a simple program which will send data from a 2D array from one module to another module, however it does not seem to work and I am not sure why. Here is my code:
Server.h
#include <iostream>
#include "stdafx.h"
using namespace std;
SC_MODULE(Server){
sc_in <bool> clock;
sc_fifo_out <sc_uint<20> > writePath;
bool init_flag;
int numRobots;
void Server_Main();
SC_CTOR(Server){
init_flag = 0;
numRobots = 4;
SC_METHOD(Server_Main){ sensitive << clock.pos(); }
}
};
Server.cpp
#include "stdafx.h"
#include "Server.h"
void Server::Server_Main(){
if (init_flag == 0){
int robotPath[4][5] = {
{ 1, 2, 3, 4, 1 },
{ 2, 1, 6, 3, 4 },
{ 3, 2, 9, 5, 1 },
{ 4, 1, 6, 8, 7 }
};
//Write robot path to Sensor
for (int i = 0; i < numRobots; i++){
for (int j = 0; j < 5; j++){
cout << "SERVER MODULE: Write Robot Paths " << i << ": " << robotPath[i][j] << endl;
writePath.write(robotPath[i][j]);
}
}
init_flag = 1;
}
else{ sc_stop(); }
}
Sensor.h
#include <iostream>
#include "stdafx.h"
using namespace std;
SC_MODULE(Sensor){
//sc_in <bool> clock;
sc_fifo_in <sc_uint<20> > readPath;
int robotPath[4][5];
void loadPath();
//void Sensor_Main();
SC_CTOR(Sensor){
//SC_METHOD(Sensor_Main){ sensitive << clock.pos(); }
SC_THREAD(loadPath){}
}
};
Sensor.cpp
#include "stdafx.h"
#include "Sensor.h"
void Sensor::loadPath(){
int i = 0;
int j = 0;
while (1){
robotPath[i][j] = readPath.read();
cout << "SENSOR MODULE: Read Robot " << i << " Path " << j << " : " << robotPath[i][j] << endl;
if (j == 4){
j = 0; //Set index to beginning of array
i++; //Move to next robot
}
else{ j++; } //Continue loading path for current robot
}
}
Main.cpp
#include "stdafx.h"
#include <iostream>
#include "Sensor.h"
#include "Server.h"
using namespace std;
int sc_main(int argc, char* argv[])
{
sc_clock clock("sysclock", 50, SC_MS, .5);
sc_fifo <sc_uint<20> > robotPath;
Sensor sensor_mod("Sensor");
sensor_mod.readPath(robotPath);
Server server_mod("Server");
server_mod.clock(clock);
server_mod.writePath(robotPath);
sc_start();
return 0;
}
Here's what my output looks like:
Here's the error i get from VS2013:
The program seems to throw an exception when it tries to write robotPath[3][1] to the fifo but im not sure why. I specified my fifo size to be 20 so that it can store 20 values at once but I dont send more than 20 values and this exception is happening when i try to write the 17th value so maybe im misunderstanding the use of sc_fifo_out. It might be some obvious mistake im overlooking but im kind of burnt out at this point and cannot figure out what it is im messing up.
Are you trying to model a Hardware design using SystemC or trying to use SystemC for software modelling?
It seems you have mixed up the contexts.
Here are a list of pointers you need to consider:
In Server module Server_Main() should be registered as a SC_THREAD:
SC_THREAD(Server_Main);
sensitive << clk.pos();
Since you are using sc_fifo's write method which internally calls wait(), in SystemC it is illegal to use wait in a SC_METHOD.
Modify the Server.cpp as mentioned below:
void Server::Server_Main() {
int robotPath[4][5] = {{ 1, 2, 3, 4, 1 },
{ 2, 1, 6, 3, 4 },
{ 3, 2, 9, 5, 1 },
{ 4, 1, 6, 8, 7 }};
//Write robot path to Sensor
for (int i = 0; i < numRobots; i++){
for (int j = 0; j < 5; j++){
cout << "SERVER MODULE: Write Robot Paths " << i << ": " << robotPath[i][j] << endl;
writePath.write(robotPath[i][j]);
wait(); //< Notice this wait statement.
}
}
}
Add a wait() statement in the while loop of the Sensor.cpp.
Also sc_fifo< sc_uint<20> > is not instantiating a sc_fifo with depth 20 as you might think.
It is actually instantiating a sc_fifo with sc_uint<20> as the datatype which is used for modelling a 20-bit unsigned integer, and the default depth of fifo as 16 as per the SystemC specs.
You can instantiate a sc_fifo<> with depth 20 as mentioned below:
sc_fifo<sc_uint<20> > robotPath("robotPath", 20);
Note: You don't need to do this since the above change from SC_METHOD to SC_THREAD and also updating the Server_Main will invalidate this behavior.

using enum for an array index in c++

#include <stdlib.h>
#include <stdio.h>
using namespace std;
void main(){
char *resolutions[] = { "720x480", "1024x600", "1280x720", "1920x1080" };
int x = 0;
enum ResMode
{
p480,
p600,
p720,
p1080
};
ResMode res = p480;
printf("\nPlease enter the resolution you wish to use now by entering a number");
printf("\n480p[0], 600p[1], 720p[2], 1080p[3]");
gets(res);
printf("\nThe resolution you have selected is %s", resolutions[res]);
}
so basically i want to be able to press 1 and have it select p600 from enum and out put it as 1024x600 in the next line. I am getting a type conversion error.
How can i fix this?
Looks like you want to associate some items with other items. Usually associations are described in lookup tables or maps.
std::map<ResMode, std::string> map_table =
{
{p480, string("720x480")},
{p600, string("1024x600")},
{p720, string("1280x720")},
{p1080, string("1920x1080")},
};
int main(void)
{
cout << map_table[p480] << "\n";
return EXIT_SUCCESS;
}
Likewise, you can map menu selections to enums.
Edit 1
std::map<unsigned int, ResMode> selection_map =
{
{0, p480}, {1, p600}, {2, p720}, {3, p1080},
};
int main(void)
{
cout << "\n"
<< "Please enter the resolution you wish to use now by entering a number\n"
<<"480p[0], 600p[1], 720p[2], 1080p[3]";
unsigned int selection = 0;
cin >> selection;
if (selection < 4)
{
Resmode resolution_index = selection_map[selection];
cout << "You chose: "
<< map_table[resolution_index]
<< "\n";
}
return EXIT_SUCCESS;
}
int's are not implicitly convertible to an enum. You will have to read in an int and then cast it yourself. Example,
int resInt;
scanf("%d", &resInt);
res = static_cast<ResMode>(resInt);//Note that this does not do bound checking.
You can use "scanf" instead of "gets", something like this:
scanf("%d",&res); // I recommend use scanf_s
Or the iostream library with std::cin. But after taking the input, always, check if the input is the correct one.
As otehrs pointed out, there is no direct way of doing this. However, there are some recipes/tricks that you can use. I modified your code as follows:
#include <stdlib.h>
#include <stdio.h>
#define SOME_ENUM(DO) \
DO(_720x480) \
DO(_1024x600) \
DO(_1280x720) \
DO(_1920x1080)
#define MAKE_ENUM(VAR) VAR,
enum class RESOLUTIONS
{
SOME_ENUM(MAKE_ENUM)
};
#define MAKE_STRINGS(VAR) #VAR,
const char* const
RESOLUTION_NAMES[] =
{
SOME_ENUM(MAKE_STRINGS)
};
const char *
GET_RESOLUTION_NAME(RESOLUTIONS type)
{
return RESOLUTION_NAMES[static_cast<int>(type)];
}
int
GET_RESOLUTION_VALUE(RESOLUTIONS type)
{
return static_cast<int>(type);
}
RESOLUTIONS
GET_RESOLUTION(int i)
{
return static_cast<RESOLUTIONS>(i);
}
using namespace std;
int main(){
printf("\nPlease enter the resolution you wish to use now by entering a number");
printf("\n480p[0], 600p[1], 720p[2], 1080p[3]");
int res_type;
cin >> res_type;
RESOLUTIONS selected_res = GET_RESOLUTION(res_type);
printf("\nThe resolution you have selected is %s\n\n", GET_RESOLUTION_NAME(selected_res));
return 0;
}
Sorry for not providing an explanation, as I have to go now. This recipe can be found here. The code works and compiles for c++11.

Check if element found in array c++

How can I check if my array has an element I'm looking for?
In Java, I would do something like this:
Foo someObject = new Foo(someParameter);
Foo foo;
//search through Foo[] arr
for(int i = 0; i < arr.length; i++){
if arr[i].equals(someObject)
foo = arr[i];
}
if (foo == null)
System.out.println("Not found!");
else
System.out.println("Found!");
But in C++ I don't think I'm allowed to search if an Object is null so what would be the C++ solution?
In C++ you would use std::find, and check if the resultant pointer points to the end of the range, like this:
Foo array[10];
... // Init the array here
Foo *foo = std::find(std::begin(array), std::end(array), someObject);
// When the element is not found, std::find returns the end of the range
if (foo != std::end(array)) {
cerr << "Found at position " << std::distance(array, foo) << endl;
} else {
cerr << "Not found" << endl;
}
You would just do the same thing, looping through the array to search for the term you want. Of course if it's a sorted array this would be much faster, so something similar to prehaps:
for(int i = 0; i < arraySize; i++){
if(array[i] == itemToFind){
break;
}
}
There are many ways...one is to use the std::find() algorithm, e.g.
#include <algorithm>
int myArray[] = { 3, 2, 1, 0, 1, 2, 3 };
size_t myArraySize = sizeof(myArray) / sizeof(int);
int *end = myArray + myArraySize;
// find the value 0:
int *result = std::find(myArray, end, 0);
if (result != end) {
// found value at "result" pointer location...
}
Here is a simple generic C++11 function contains which works for both arrays and containers:
using namespace std;
template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };
Simple usage contains(arr, el) is somewhat similar to in keyword semantics in Python.
Here is a complete demo:
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>
template<typename C, typename T>
bool contains(C&& c, T e) {
return std::find(std::begin(c), std::end(c), e) != std::end(c);
};
template<typename C, typename T>
void check(C&& c, T e) {
std::cout << e << (contains(c,e) ? "" : " not") << " found\n";
}
int main() {
int a[] = { 10, 15, 20 };
std::array<int, 3> b { 10, 10, 10 };
std::vector<int> v { 10, 20, 30 };
std::string s { "Hello, Stack Overflow" };
check(a, 10);
check(b, 15);
check(v, 20);
check(s, 'Z');
return 0;
}
Output:
10 found
15 not found
20 found
Z not found
One wants this to be done tersely.
Nothing makes code more unreadable then spending 10 lines to achieve something elementary.
In C++ (and other languages) we have all and any which help us to achieve terseness in this case. I want to check whether a function parameter is valid, meaning equal to one of a number of values.
Naively and wrongly, I would first write
if (!any_of({ DNS_TYPE_A, DNS_TYPE_MX }, wtype) return false;
a second attempt could be
if (!any_of({ DNS_TYPE_A, DNS_TYPE_MX }, [&wtype](const int elem) { return elem == wtype; })) return false;
Less incorrect, but looses some terseness.
However, this is still not correct because C++ insists in this case (and many others) that I specify both start and end iterators and cannot use the whole container as a default for both. So, in the end:
const vector validvalues{ DNS_TYPE_A, DNS_TYPE_MX };
if (!any_of(validvalues.cbegin(), validvalues.cend(), [&wtype](const int elem) { return elem == wtype; })) return false;
which sort of defeats the terseness, but I don't know a better alternative...
Thank you for not pointing out that in the case of 2 values I could just have just if ( || ). The best approach here (if possible) is to use a case structure with a default where not only the values are checked, but also the appropriate actions are done.
The default case can be used for signalling an invalid value.
You can use old C-style programming to do the job. This will require little knowledge about C++. Good for beginners.
For modern C++ language you usually accomplish this through lambda, function objects, ... or algorithm: find, find_if, any_of, for_each, or the new for (auto& v : container) { } syntax. find class algorithm takes more lines of code. You may also write you own template find function for your particular need.
Here is my sample code
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
/**
* This is old C-like style. It is mostly gong from
* modern C++ programming. You can still use this
* since you need to know very little about C++.
* #param storeSize you have to know the size of store
* How many elements are in the array.
* #return the index of the element in the array,
* if not found return -1
*/
int in_array(const int store[], const int storeSize, const int query) {
for (size_t i=0; i<storeSize; ++i) {
if (store[i] == query) {
return i;
}
}
return -1;
}
void testfind() {
int iarr[] = { 3, 6, 8, 33, 77, 63, 7, 11 };
// for beginners, it is good to practice a looping method
int query = 7;
if (in_array(iarr, 8, query) != -1) {
cout << query << " is in the array\n";
}
// using vector or list, ... any container in C++
vector<int> vecint{ 3, 6, 8, 33, 77, 63, 7, 11 };
auto it=find(vecint.begin(), vecint.end(), query);
cout << "using find()\n";
if (it != vecint.end()) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
using namespace std::placeholders;
// here the query variable is bound to the `equal_to` function
// object (defined in std)
cout << "using any_of\n";
if (any_of(vecint.begin(), vecint.end(), bind(equal_to<int>(), _1, query))) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
// using lambda, here I am capturing the query variable
// into the lambda function
cout << "using any_of with lambda:\n";
if (any_of(vecint.begin(), vecint.end(),
[query](int val)->bool{ return val==query; })) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
}
int main(int argc, char* argv[]) {
testfind();
return 0;
}
Say this file is named 'testalgorithm.cpp'
you need to compile it with
g++ -std=c++11 -o testalgorithm testalgorithm.cpp
Hope this will help. Please update or add if I have made any mistake.
If you were originally looking for the answer to this question (int value in sorted (Ascending) int array), then you can use the following code that performs a binary search (fastest result):
static inline bool exists(int ints[], int size, int k) // array, array's size, searched value
{
if (size <= 0) // check that array size is not null or negative
return false;
// sort(ints, ints + size); // uncomment this line if array wasn't previously sorted
return (std::binary_search(ints, ints + size, k));
}
edit: Also works for unsorted int array if uncommenting sort.
You can do it in a beginners style by using control statements and loops..
#include <iostream>
using namespace std;
int main(){
int arr[] = {10,20,30,40,50}, toFind= 10, notFound = -1;
for(int i = 0; i<=sizeof(arr); i++){
if(arr[i] == toFind){
cout<< "Element is found at " <<i <<" index" <<endl;
return 0;
}
}
cout<<notFound<<endl;
}
C++ has NULL as well, often the same as 0 (pointer to address 0x00000000).
Do you use NULL or 0 (zero) for pointers in C++?
So in C++ that null check would be:
if (!foo)
cout << "not found";

C++, using stack.h read a string, then display it in reverse

For my current assignment, I have to use the following header file,
#ifndef STACK_H
#define STACK_H
template <class T, int n>
class STACK
{
private:
T a[n];
int counter;
public:
void MakeStack() {
counter = 0;
}
bool FullStack() {
return (counter == n) ? true : false ;
}
bool EmptyStack() {
return (counter == 0) ? true : false ;
}
void PushStack(T x) {
a[counter] = x;
counter++;
}
T PopStack() {
counter--;
return a[counter];
}
};
#endif
To write a program that will take a sentence, store it into the "stack", and then display it in reverse, and I have to allow the user to repeat this process as much as they want. The thing is, I am NOT allowed to use arrays (otherwise I wouldn't need help with this), and am finding myself stumped.
To give an idea of what I am attempting, here is my code as of posting, which obviously does not work fully but is simply meant to give an idea of the assignment.
#include <iostream>
#include <cstring>
#include <ctime>
#include "STACK.h"
using namespace std;
int main(void)
{
auto time_t a;
auto STACK<char, 256> s;
auto string curStr;
auto int i;
// Displays the current time and date
time(&a);
cout << "Today is " << ctime(&a) << endl;
s.MakeStack();
cin >> curStr;
i = 0;
do
{
s.PushStack(curStr[i]);
i++;
} while (s.FullStack() == false);
do
{
cout << s.PopStack();
} while (s.EmptyStack() == false);
return 0;
} // end of "main"
UPDATE
This is my code currently
#include <iostream>
#include <string>
#include <ctime>
#include "STACK.h"
using namespace std;
time_t a;
STACK<char, 256> s;
string curStr;
int i;
int n;
// Displays the current time and date
time(&a);
cout << "Today is " << ctime(&a) << endl;
s.MakeStack();
getline(cin, curStr);
i = 0;
n = curStr.size();
do
{
s.PushStack(curStr[i++]);
i++;
}while(i < n);
do
{
cout << s.PopStack();
}while( !(s.EmptyStack()) );
return 0;
You're on the right track, but you shouldn't be looping until the stack is full -- there are no guarantees curStr consists of at least 256 characters. Instead, loop like as follows...
int n = curStr.size();
do {
s.PushStack(curStr[i++]);
} while (i < n);
Now, you should really not write <bool-expr> == false or <bool-expr> == true... instead, merely write !<bool-expr> and <bool-expr>, respectively. You don't need all of your auto storage specifiers on the local variables, either. Your professor should also look into using the constructor rather than using MakeStack.
edit: It appears you had some trouble translating my code. You only need to i++ once per loop -- this increments our position in the string. As you are doing it now, you are actually incrementing the position twice and thus only pushing every other character.
Use a linked list instead of array in stack.
In the linked list, always store the tail pointer of your list's last node. Each node maintains a reference to your prev node.
A <--- B <---- C (tail)
push:
A <--- B <---- C <---- D (tail)
pop:
A <--- B <---- C (tail)
// D is popped out
when the tail == null, you know it is an empty stack