I got this output
Learning how to use arrays and I got an exercise to check if the array is in an ascending order, after the first run, this is what I got and I cant find the problem.
when I'm printing the array it shows in the last array some garbage.
#include <iostream>
using namespace std;
const int CAPACITY1 = 5;
int main()
{
int arr1[CAPACITY1];
bool a = false;
//init the first input
cout << "Enter 6 numbers: " << endl;
cin >> arr1[0];
int max = arr1[0];
int NoE = 1;
//init the loop to insert numbers
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
if (a == true)
cout << "The array is not in an ascending order" << endl;
else
cout << "The array is in an ascending order" << endl;
cout << NoE;
//end
cout << endl;
return 0;
}
Indexes in arrays in C++ are zero based. That means, that array with capacity of N, declared as T arr[N], have indexes starting at 0 and ending with N - 1.
For accessing such array using for loop, use this
for (int index = 0; index < N; ++index)
Your loop here operates from 1 to 5:
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
So you only enter five numbers and you never put anything in arr1[0] and you do put something in arr[5] which is invalid.
Aside from that, I suspect you may have missed the point of the exercise. If this is a homework assignment then I imagine they want you to iterate over an existing array and report if it is in ascending order.
Your for loop is wrong, and is going out of bounds.Note that arrays in C++ start at 0, not 1. The correct for loop is as follows:
for (int i = 0; i < CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
These 2 lines:
int CAPACITY1 = 5;
int arr1[CAPACITY1];
mean that the size of your array arr1 is 5, that is, it has 5 elements, from 0 to 4. Trying to access the element at position 5 is wrong.
That said, in your cout messages you talk about 6 numbers. If you want to store 6 elements, change the value of CAPACITY1 to 6, like:
const int CAPACITY1 = 6;
By your comments I think you are getting confused with the size of the array, possibly because you have heard something like "The index of the last element is always off by 1". Yes it is, but it doesn't mean that to store 6 elements you should use the number 5 when you define it! If you want 6 elements, the size must be 6, there is no trap here. The tricky part is that the index will start from 0, and therefore the last element is at position [size - 1], not at [size]. To clarify:
If you declare int arr1[5]; you will have 5 elements, with the index ranging from 0 to 4.
If you declare int arr1[6]; you will have 6 elements, with the index ranging from 0 to 5.
By the way, this shows why it would be a good idea to avoid hard-coded numbers (6, in this case) and always use variables. Try with
cout << "Enter " << CAPACITY1 << " numbers: " << endl;
This way, the size of the array and the messages will always match.
To summarize, if you want to work with 6 numbers, you need to use
const int CAPACITY1 = 6;
and, since you deal with the first element (at index 0) before the loop, the loop must start at 1 and run until the last element, which has index 5, so:
for (int i = 1; i < CAPACITY1; i++) {
On a side note, your logic to check whether the array is in ascending order is confusing. For you, a == true means it is not ascending. It works, but it is counter-intuitive. I would suggest to change it.
Related
Newer to coding and im stuck, Need to make a array thats stores 5 numbers (1-9), then i need to check that array for duplicates if there is duplicates i need to replace that number either with a whole new random line no duplicates (seems like the easier option) or just replace that one number,
after that wants me to get users 5 numbers guess store that in a array, display that array at the bottom along with these under each of the numbers
// The * = means the number is in the exact location
// The - = means the array does not contain that number
// The + = means the array contains the number but its not in the right location
All the arrays want the digits to be entered one at a time
repeat steps till user gets all the numbers to * then end game with completion msg.
My true problem lies with step 4 and step 7;
Below is the code ive been working on today but any help would be truly appreciated
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void game_instructions(int n);
bool search_array(int a[], int n, int t);
int main()
{
//Step 1: Declare your variables and constants
const int SIZE = 5; //this constant stores the length/size of the code
int randcode[SIZE]; //this array stores the code generated randomly by the computer
int guess[SIZE]; //this array stores the code inputted by the player/user
//you may add more variables as needed
//Step 2: Output game instructions by calling function game_instructions
game_instructions(SIZE);
//Step 3: Generate a random code and store it in the array randcode one digit at a time.
//Each digit should be between 0 and 9 and should be stored as one array element
//Recall that rand() % 10 can be used to generate a number between 0 and 9
srand(time(0));
for(int i=0;i<SIZE;i++)
randcode[i]= (rand() % 10); //Computers random 5 numbers generated
cout<<"\nRandom C-numbers::"<<endl;
for(int i=0;i<SIZE;i++)
cout<<randcode[i] << " ";
//Step 4: Repeat step 3 if the array randcode contains duplicates
//You must use function contains_duplicates to implement this step
//Step 5: Ask the user for his guess and store it in the array guess.
//Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
for (int i=0; i<SIZE; i++) {
cout<<"\nEnter Digit "<< i+1 << ": ";
cin >> guess[i];}
cout << endl;
//Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
for (int n=0; n < SIZE; ++n) {
cout << guess[n] << " ";
}
//Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
//and display feedback for each digit as: *, + or –, as explained below:
//For each digit in the user's guess do the following:
// If it matches the digit from the random code (both value and position), output *
// Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
// Otherwise, output -
//Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
//Step 9: Output congratulations message
cout << endl << endl;
cout << "Good job! You guessed the code!";
return 0;
}
void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
cout << "For every digit you will receive feedback in the form of *, + or - \n";
cout << " * means the digit is in the code and it is in the correct position.\n";
cout << " + means the digit is in the code but it is not in the correct position.\n";
cout << " - means the digit is not in the code.\n";
}
bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
for (int i = 0; i < n; i++)
{
if (a[i] == t) return true;
}
return false;
}
bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
for (int i = 0; i < n; i++)
{
//compare element a[i] with all the remaining elements from index i+1 to n
for (int j = i+1; j < n; j++)
{
if (a[i] == a[j]) return true;
}
}
return false;
}
I got most the side code done but im just stumped on how to get this array to match any help would be nice
Here is how I would implement the program to generate the number without duplicate:
Step3 would look like this:
int tempNumber;
int i = 0;
while (i < SIZE) {
tempNumber = (rand() % 10);
if (contains_duplicates(randcode, tempNumber, i) == false) {
// every time there is no duplicate we push and add i by 1;
randcode[i] = tempNumber; // Computers random 5 numbers generated
i++;
}
}
contains_duplicates function would look like this:
bool contains_duplicates(int arr[], int tempNum, int currentArrSize)
// This function searches the array a (of size n) and returns true if the
//array
// contains duplicates; otherwise, it returns false.
{
for (int j = 0; j <= currentArrSize; j++) {
// if the array[index] not equal generated number the loop will
//iterate again without going to the line below
if (arr[j] != tempNum) {
continue;
}
// if the array[index] equal the function will return true and end
//the function
// uncomment this to check how many time it duplicate (not
//necessary tho)
//cout << "if return true, this will appear"<< endl;
return true;
}
// if the loop is done and no duplicate, function will return false
return false;
}
With this method it is not necessary to do step 4 because we already prevent duplicate array!
Here is the last problem from your question which is step 7:
cout << endl;
for (int i = 0; i < SIZE; i++) {
if (guess[i] == randcode[i]) {
cout << "* ";
} else if (search_array(randcode, SIZE, guess[i])) {
cout << "+ ";
} else {
cout << "- ";
}
}
Seems like the problem has been solved, now try to implement step 8 by yourself, good luck :)
my question has to do with sorting an integer array into descending order, but I've got a very specific problem and was wondering if there's a way to solve it without destroying the binary search function I also implemented.
My project overall is perfect, but has one problem which is a dealbreaker according to my instructor. I read a txt file into an array and list them, then sort them into descending order, and have a function to binary search for what index a number is in. My numbers are sorted in descending order and print as such (144, 115, 100, 89, etc). This is GOOD. This is what we want. But when reading the index, 144 is listed as index[19], 115 as index[18] and so on. This is BAD. I would like to maintain the exact same output, but have the highest number be at index[0], then index[1], and be ordered like that.
Here is a picture of what my program looks like.
I'm a little confused as to how to accomplish this. I've tried a few things but regardless of how I do the sorting, the highest numbers are at the highest point on the index.
Here are the relevant bits of my code.
int binarySearch(int array1[], int p, int r, int num) {
if (p <= r) {
int mid = (p + r) / 2;
if (array1[mid] == num)
return mid;
if (array1[mid] > num)
return binarySearch(array1, p, mid - 1, num);
if (array1[mid] < num)
return binarySearch(array1, mid + 1, r, num);
}
return -1;
}
int main() {
int array1[20]{}; //The array that stores the numbers.
char letters[15]{}; //The array that stores the characters.
ifstream inputData("input.txt"); //This assumes input.txt is stored in the same folder.
int n = 0; //Counter for the arrays
int num; //This is for the binary search function.
char x{};
// Error checking for making sure the file can open
if (!inputData)
{
cout << "Cannot open file.\n";
return 0;
}
else {
cout << "The unsorted list of integers: \n";
for (int n = 0; n <= 19; n++) {
inputData >> array1[n];
if (inputData.fail()) break;
cout << array1[n] << " ";
}
cout << "\n\nThe sorted list of integers in descending order: \n";
int n = sizeof(array1) / sizeof(array1[n]); //I have also tried replacing this line with just "int n = 20" and it didn't appear to make any real difference.
sort(array1, array1 + n);
for (int n = 19; n >= 0; n--)
cout << array1[n] << " ";
//When copy-pasting my code across I might be missing a curly bracket or two, don't worry about that stuff.
cout << "\n \nEnter an integer to search: ";
cin >> num;
int index = binarySearch(array1, 0, n - 1, num);
if (index == -1) {
cout << num << " could not be found. Please restart the program and try another number.";
}
else {
cout << "Integer " << num << " found at index [" << index << "] in the sorted integer array.";
}
I feel like I must be missing something obvious. Please help, because I cannot get this array working properly. Occasionally when I mess about, it also stops my binary search from working properly, and it can't detect anything, so I need to tread carefully.
In the code, you sort the array with
sort(array1, array1 + n);
That will be ordered using the less-than < operator, which will sort it in ascending order.
But when you display it:
for (int n = 19; n >= 0; n--)
cout << array1[n] << " ";
which you do in reverse order (making it seem like it's sorted in descending order). If you display it in the right order, from 0 to 19 then it will be shown in the actual sorted order.
To sort in descending order you need to use std::greater instead:
std::sort(array1, array1 + n, std::greater{})
And display in the correct order:
for (int value : array1)
std::cout << value << ' ';
I got this output
Learning how to use arrays and I got an exercise to check if the array is in an ascending order, after the first run, this is what I got and I cant find the problem.
when I'm printing the array it shows in the last array some garbage.
#include <iostream>
using namespace std;
const int CAPACITY1 = 5;
int main()
{
int arr1[CAPACITY1];
bool a = false;
//init the first input
cout << "Enter 6 numbers: " << endl;
cin >> arr1[0];
int max = arr1[0];
int NoE = 1;
//init the loop to insert numbers
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
if (a == true)
cout << "The array is not in an ascending order" << endl;
else
cout << "The array is in an ascending order" << endl;
cout << NoE;
//end
cout << endl;
return 0;
}
Indexes in arrays in C++ are zero based. That means, that array with capacity of N, declared as T arr[N], have indexes starting at 0 and ending with N - 1.
For accessing such array using for loop, use this
for (int index = 0; index < N; ++index)
Your loop here operates from 1 to 5:
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
So you only enter five numbers and you never put anything in arr1[0] and you do put something in arr[5] which is invalid.
Aside from that, I suspect you may have missed the point of the exercise. If this is a homework assignment then I imagine they want you to iterate over an existing array and report if it is in ascending order.
Your for loop is wrong, and is going out of bounds.Note that arrays in C++ start at 0, not 1. The correct for loop is as follows:
for (int i = 0; i < CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
These 2 lines:
int CAPACITY1 = 5;
int arr1[CAPACITY1];
mean that the size of your array arr1 is 5, that is, it has 5 elements, from 0 to 4. Trying to access the element at position 5 is wrong.
That said, in your cout messages you talk about 6 numbers. If you want to store 6 elements, change the value of CAPACITY1 to 6, like:
const int CAPACITY1 = 6;
By your comments I think you are getting confused with the size of the array, possibly because you have heard something like "The index of the last element is always off by 1". Yes it is, but it doesn't mean that to store 6 elements you should use the number 5 when you define it! If you want 6 elements, the size must be 6, there is no trap here. The tricky part is that the index will start from 0, and therefore the last element is at position [size - 1], not at [size]. To clarify:
If you declare int arr1[5]; you will have 5 elements, with the index ranging from 0 to 4.
If you declare int arr1[6]; you will have 6 elements, with the index ranging from 0 to 5.
By the way, this shows why it would be a good idea to avoid hard-coded numbers (6, in this case) and always use variables. Try with
cout << "Enter " << CAPACITY1 << " numbers: " << endl;
This way, the size of the array and the messages will always match.
To summarize, if you want to work with 6 numbers, you need to use
const int CAPACITY1 = 6;
and, since you deal with the first element (at index 0) before the loop, the loop must start at 1 and run until the last element, which has index 5, so:
for (int i = 1; i < CAPACITY1; i++) {
On a side note, your logic to check whether the array is in ascending order is confusing. For you, a == true means it is not ascending. It works, but it is counter-intuitive. I would suggest to change it.
Just started studying C++ for a couple weeks now, and been running through some exercises. Though I am stuck on trying to return the array name which is holding the highest number in the array. For example, I made an array for 10 people, for each person I am having them enter the number of pancakes they ate, now I want to return the person who ate the most pancakes. just not sure how to do it. It falls apart at the second if statement.
int main()
{
int pancakes[9] = {0,0,0,0,0,0,0,0,0};
int max = pancakes[0];
int i;
int p;
for (int x=0; x<=9; x++)
{
cout << "Enter number " << endl;
cin >> i;
pancakes[x] = i;
if(i > max)
max = i;
pancakes[x] = p;
}
cout << endl;
cout << p << " ate the most pcakes # " << max << endl;
return 0;
}
I'm on my phone, so I do apologize if there is formatting problems.
You say that your code falls apart at your second if-statement yet there is only one if-statement, so I am assuming it is the second line in the if-statement. However, there are two problems with this.
You aren't recording the person properly with this:
pancakes[x]=p;
This "should be":
p=x;
You need to put curly braces around the entire statement. For example:
if (i > max) {
max= i;
p=x;
}
Your loop and if statement should be as follow. See details and explanation in comments:
for (int x=0; x<9; x++) // You need to exclude 9 (do not use <=) because the index start at 0
{
cout << "Enter number " << endl;
cin >> i;
//pancakes[x] = i; <-- This line and the array is not needed. With this also you actually don't need to
// store/save what people enter. You just need to keep the max and index
if(i > max) // if i (number entered) is bigger than the current max of pancakes
{
max = i; // You update the max to the new number entered (i)
p = x + 1; // you store in p the array index + 1 (your array index start at 0 not 1)
// of the current person who eat the max number of pancakes
}
}
For the initialization:
//int pancakes[9] = {0,0,0,0,0,0,0,0,0}; <- The array is not needed. See my comment in above code
int max = 0; // More clean and readable
A few things:
1) Your iteration is wrong. It should be:
for (int x = 0; x < 9; ++x)
If you use x <= 9 you will actually do 10 iterations of the loop and the last iteration will run off the end of the pancakes array and corrupt memory.
2) When you find a new max, also set p equal to x to remember who had the most pancakes.
3) You initialize max to be pancakes[0]. While that will actually give you the right answer in this instance, you should instead explicitly initialize max = -1 to indicate an invalid maximum when you start. You also should initialize p = -1 to indicate an invalid eater when you start. These initializations would allow you to distinguish and handle the case when there is no input too.
4) Optimization: you really don't need an array to remember the # of pancakes each person ate if this is all you are doing. You can just loop as many times as you want reading input and compare against max.
I have been working on this all day but just cant get the output right.
What I want to do is input two numbers, which would be pushed into two arrays so we can subtract or add them and display the result. Seems simple, but there are few catches
Input must be pushed into the array, from the user, one by one.
In case I don't enter a value, code should assume it to be '0' or 'null'. '0' if its in the beginning and 'null' if its in the end. for example if 1st number is 234 and second number is 23 then code should make it into '023' and if I enter first number as 2, 2nd number as 3 but don't enter anything in the end then code should assume it to be null.
Problems
I cant take 'carry' to the next set, in case the sum is greater than 10. Which means the value I m getting is just addition of two numbers doesn't matter if its greater than 10 or not. for example addition of 234 and 890 is giving me [10, 12, 4]
Here is the code.....
#include<iostream>
using namespace std;
main() {
int first[10], second[10], result[10], c, n;
cout << "Enter the number of elements in the array ";
cin >> n;
if (n > 10 || n < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
cout << "Enter elements of first array " << endl;
for (c = 0; c < n; c++) {
cin >> first[c];
if (first[c] > 9 || first[c] < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
}
cout << "Enter elements of second array " << endl;
for (c = 0; c < n; c++)
cin >> second[c];
cout << "Sum of elements of two arrays " << endl;
for (c = 0; c < n; c++)
cout << first[c] + second[c] << endl;
if ((first[c] + second[c]) > 9) {
cout << "overflow" << endl;
}
//result[c] = first[c] + second [c];
//cout << result[c] <<endl;
system("PAUSE");
return 0;
}
I would really appreciate some suggestions.
In case your intention is to have the result of e.g.
234 + 890 = 1124
then your summation loop should be in reverse order.
(Since you are reading number of elements of the array from the prompt, you may use this information to input first/second numbers into each array in the order preferred for the following summation loop.)
For the carry problem, you need to setup a variable and use it in the loop like this, for example.
int sum[10] = {0};
int c;
int carry = 0;
for (c = 0; c < n; c++)
{
sum[c] = first[c] + second[c] + carry;
carry = sum[c] / 10;
}
if (c < n)
sum[c] = carry;
else
cout << "overflow";
Use std::vector and learn how to use reverse iterators. So if someone enters 234 you push_back(2), push_back(3), push_back(4) and have [0]=2,[1]=3,[2]=4. Then if the next number is 23 you have [0]=2,[1]=3. Now walk both vector with reverse iterators so the first call to rbegin() will give a pointer to [2]=4 and the other vector will give [1]=3. Now add and carry using push_back into a third vector to store the result. Output the result using reverse iterators to print the result.
This looks like homework, so no sample code.