In the below code on method called get_array() problem occurs because the capacity variable change to after first input given by user in the console
and capacity value assign to what value given by user
I am not sure what's happening but it's kind of irritating me or did I missed some basic knowledge ? Please help
#Software
I am using CodeBlocks v17.12
#OS
Windows 10 Home
#include <iostream>
using namespace std;
class LinearSearch
{
int my_arr[];
int capacity, c, val;
public:
LinearSearch()
{
this->capacity = 0;
this->c = 0;
this->val = 0;
}
void get_array()
{
cout << "Define number of elements in the array: ";
cin >> this->capacity;
for( int i = 0; i < this->capacity; i++ )
{
cout << "Enter value " << i+1 << " - " << this->capacity << " : ";
cin >> this->my_arr[i];
}
for( int k = 0; k < capacity; k++ )
{
cout << my_arr[k] << endl;
}
cout << endl;
}
void search_value()
{
cout << endl << "Enter a value to search: ";
cin >> this->val;
for(int j = 0; j < capacity; j++)
{
if(my_arr[j]==val)
{
cout << endl << this->val << " value found in the array at index array[" << j << "] value number " << j+1 << "." << endl << endl;
c++;
break;
}
}
if(this->c==0)
cout<<endl<<this->val<<" value not found in the array."<<endl<<endl;
}
};
int main()
{
int choice;
LinearSearch obj;
while( true )
{
cout << "0) Exit\n1) Insert Data\n2) Search Data\n\nEnter Option: ";
cin >> choice;
switch( choice )
{
case 0:
return 0;
case 1:
obj.get_array();
break;
case 2:
obj.search_value();
break;
default:
cout << "\nWrong Option!!\n\n";
break;
}
}
return 0;
}
int my_arr[]; is not valid standard C++ and even in C it must appear only at the end of the member list as so-called flexible array member.
You should use std::vector<int> my_arr; instead. (Requires #include<vector>.)
You can then add new elements to it with my_arr.push_back(/*some number here*/); or you can resize the array with my_arr.resize(/*new size here*/);.
Related
I have to ask the user to put in an array size and then to ask the user to fill it out. When the user puts in a duplicate, the program should say "invalid" and the user is asked to replace the number. I am supposed to use traversing array search.
Like this example here:
Enter list size: 4
Enter value for index 0: 1
Enter value for index 1: 1
Invalid. Enter a new number: 2
Enter value for index 2: 5
Enter value for index 3: 6
This is my code so far:
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Enter list size: ";
cin >> size;
int array1[size];
for (int i = 0; i < size; i++) {
cout << "Enter value for index " << i << ": ";
cin >> array1[i];
for (int j = i + 1; j < size; j++) {
if (array1[i] == array1[j]) {
cout << "Invalid! Enter a new value for index " << i << ": ";
cin >> array1[i];
}
}
}
return 0;
}
It does what was specified but the exercise probably was to write std::ranges::find.
#include <iostream>
#include <vector>
#include <cstddef>
#include <algorithm>
int main() {
size_t size;
std::cout << "Enter list size: ";
std::cin >> size;
std::vector<int> arr;
arr.reserve(size);
while(arr.size() < size) {
int t;
std::cout << "Enter value for index " << arr.size() + 1 << ": ";
std::cin >> t;
if (std::ranges::find(arr, t) == arr.end()) {
arr.push_back(t);
} else {
std::cout << "Invalid! ";
}
}
}
Try this approach, Every time user enter value helper function will check duplicate from already filled array
#include<iostream>
// Helper Function that will check duplicate from array
bool IsDuplicate (int arr[] ,const int idxSoFar, int element){
for(int i =0 ; i < idxSoFar ; i += 1 )
if( arr[i] == element){
std::cout << "Invalid! Enter a new value for index "<< idxSoFar + 1 << " : ";
return arr[i] == element;
}
return false;
}
int main () {
int size;
std::cout << "Enter list size: ";
std::cin >> size;
int array1[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter value for index " << i << ": ";
do
std::cin >> array1[i];
while(IsDuplicate(array1 , i , array1[i]));
}
return 0;
}
I am messing around with dynamic arrays for a user defined amount of inputs for an and gate.
The issue I am running into is that I don't know how many inputs the user is going to test and I need to be able to have an if-else statement that tests each input.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput = 0;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1 = 0;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
return 0;
}
Here is the code that I am currently trying to find a solution for.
To implement an AND gate with n inputs you can simply do:
int output = 1;
for (int i = 0; i < n; ++i)
{
if (!and_gate [i])
{
output = 0;
break;
}
}
// ...
Use Vector data structure, you don't need to tell its size while declaring, unlike array, and it can grow automatically.
To read input till it's arriving, put cin inside while loop condition. I used getline to read whole line and work with it, so that whenever user presses enter button at empty line, program will think that no more input is coming anymore, and will start calculating 'And' of inputs.
//don't forget to import vector
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
logic_gate(){ //default constructor
}
logic_gate(int k){ //another constructor needed
x = k;
}
};
int main(){
cout << endl << "Please enter the values of each bit below . . ." << endl;
vector<logic_gate> and_gate; //no need to tell size while declaration
string b;
while(getline(cin, b)){ //read whole line from standard input
if (b == "\0") //input is NULL
break;
and_gate.push_back(logic_gate(stoi(b))); //to convert string to integer
}
if (!and_gate.empty()){
int output = and_gate[0].x;
for (int i = 1; i < and_gate.size(); i++){
output = output & and_gate[i].x;
}
cout << "And of inputs is: " << output << endl;
}
else{
cout << "No input was given!\n";
}
return 0;
}
Feel free to ask if some doubts linger
I figured out what I wanted to do. Thanks to everyone who helped and especially Paul Sanders. Below is my final code.
#include <iostream>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput;
int output = 1;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
if (userInput == 1) {
output = userTest1;
cout << "The test of " << userTest1 << " is " << output << endl << endl;
}
else if (userInput > 1) {
for (int i = 0; i < userInput; i++) {
if (!and_gate[i].x)
{
output = 0;
break;
}
}
cout << "The test of ";
for (int i = 0; i < userInput; i++) {
cout << and_gate[i].x;
}
cout << " is " << output << endl << endl;
}
return 0;
}
(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}
So, I'm creating a coin change algorithm that take a Value N and any number of denomination and if it doesn't have a 1, i have to include 1 automatically. I already did this, but there is a flaw now i have 2 matrix and i need to use 1 of them. Is it possible to rewrite S[i] matrix and still increase the size of array.... Also how can i find the max denomination and the second highest and sooo on till the smallest? Should i just sort it out in an highest to lowest to make it easier or is there a simpler way to look for them one after another?
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
You could implement it with std::vector, then you only need to use push_back.
std::sort can be used to sort the denominations into descending order, then it's just a matter of checking whether the last is 1 and adding it if it was missing. (There is a lot of error checking missing in this code, for instance, you should probably check that no denomination is >= 0, since you are using signed integers).
#include <iostream> // for std::cout/std::cin
#include <vector> // for std::vector
#include <algorithm> // for std::sort
int main()
{
std::cout << "Enter the value N to produce:\n";
int N;
std::cin >> N;
std::cout << "Enter the number of different denominations:\n";
size_t denomCount;
std::cin >> denomCount;
std::vector<int> denominations(denomCount);
for (size_t i = 0; i < denomCount; ++i) {
std::cout << "Enter denomination #" << (i + 1) << ":\n";
std::cin >> denominations[i];
}
// sort into descending order.
std::sort(denominations.begin(), denominations.end(),
[](int lhs, int rhs) { return lhs > rhs; });
// if the lowest denom isn't 1... add 1.
if (denominations.back() != 1)
denominations.push_back(1);
for (int coin: denominations) {
int numCoins = N / coin;
N %= coin;
if (numCoins > 0)
std::cout << numCoins << " x " << coin << '\n';
}
return 0;
}
Live demo: http://ideone.com/h2SIHs
i am relatively new to programming, i just learned c++ and i am getting 2 errors for a HW assignment from school;
Error 2 error C4700: uninitialized local variable 'searchValueptr' used Line 83
and
Error 3 error C4703: potentially uninitialized local pointer variable 'createdArray' used
Line 70
I cannot for the life of me figure out why or how to fix it can some one help me please.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// prototypes
int *createArray(int &size);
void findStats(int *arr, int size, int &min, int &max, double &average);
int *searchElement(int *arr, int size, int *element);
int main ()
{
int choice, size;
bool menuOn = true;
while (menuOn == true)
{
cout << "1 - Create and initialize a dynamic array.\n";
cout << "2 - Display statistics on the array.\n";
cout << "3 - Search for an element.\n";
cout << "4 - Exit.\n";
cout << "Enter your choice and press return: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
int *createdArray;
cout << "Please enter a size for the array: ";
cin >> size;
createdArray = createArray(size);
for (int x=0; x < size; x++)
{
cout << "Value of array at index " << x << ": " << createdArray[x] << endl;
}
cout << endl;
break;
case 2:
int minNum;
int maxNum;
double avgNum;
findStats(createdArray, size, minNum, maxNum, avgNum);
cout << endl << "The maximum number is: " << maxNum;
cout << endl << "The minimum number is: " << minNum;
cout << endl << "The average number is: " << avgNum;
cout << endl << endl;
break;
case 3:
int *searchValueptr;
int searchValue;
cout << "Enter a value to search for: ";
cin >> searchValue;
*searchValueptr = searchValue;
searchElement(createdArray, size, searchValueptr);
break;
case 4:
cout << "Thanks for using this program";
menuOn = false;
break;
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
cout << endl;
system("pause");
return 0;
} // end function main ()
int *createArray(int &size)
{
unsigned seed = time(0);
srand(seed);
int *randArray = new int [size];
for (int x=0; x < size; x++)
{
randArray[x] = rand();
}
cout << endl;
return randArray;
}
void findStats(int *arr, int size, int &min, int &max, double &average)
{
min = arr[0];
max = arr[0];
double sum = 0;
for (int count = 0; count < size; count++)
{
if (min >= arr[count])
{
min = arr[count];
}
if (max <= arr[count])
{
max = arr[count];
}
sum += arr[count];
}
average = sum/size;
}
int *searchElement(int *arr, int size, int *element)
{
bool match = false;
for (int count = 0; count < size; count++)
{
if (arr[count] == *element)
{
match = true;
}
}
if (match)
{
cout << "Match Found at: " << element;
return element;
}
else
{
cout << "No Found";
return 0;
}
}
either use
searchValueptr = &searchValue;
or send the pass the address of searchValue
searchElement(createdArray, size, &searchValue);
break;