Getting the wrong output from arrays - c++

#include <iostream>
const int turns = 2022;
int processing(int array[], int number, int index);
int main()
{
int numLine[turns]; //actual number line
//int counter = 0; //turns since last refference??
int previousNumber;
for (int i = 0; i < 7; i++) //for seven turns
{
std::cout << "Seed Number " << i+1 << ": "; //Seed Numer 1,2,3... :
std::cin >> numLine[i]; //input number
std::cout << std::endl; // endline
}
for (int i = 7; i < turns; i++) //for the entire length of the turns after 7
{
previousNumber = numLine[i - 1];
numLine[i] = processing(numLine, previousNumber, i-2); //set the current element of numLine to the processed number
std::cout << numLine[i] << " ";
}
}
int processing(int array[], int number, int index) //processing seeded with int number
{
int counter = -1; // number of turns since last referrence
for (int i = index; i >= 0; i--) //searches down from index to 0
{
if (array[i] == number) {
counter = i; //times since its been said
}
}
if (counter == -1)
{
return 0;
}
else
return counter;
//has been seen before so return the count
}
// 13,16,10,12,1,5,8 (seed numbers)
This is my code, this is the prompt that I was given to design my program: http://cis.scc.losrios.edu/~TownJ/dinosaur/memory.html
When inputting the seed numbers required for the prompt, the output I receive is 9 (for the 2022nd element of the array, this code outputs all the elements) but when putting that into the website, it is incorrect, as is the number before it. I can't see what I am doing wrong, could someone with more experience tell me what I messed up?

Thank you to everyone for your help, the following is my code and commented within is an explanation of such, the list of changes I made was big.
#include <iostream>
const int turns = 2022;
int processing(int array[], int number, int index);
int main()
{
int numLine[turns]; //actual number line
int previousNumber;
for (int i = 0; i < 7; i++) //for seven turns
{
std::cout << "Seed Number " << i+1 << ": "; //Seed Numer 1,2,3... :
std::cin >> numLine[i]; //input number
std::cout << std::endl; // endline
}
for (int i = 7; i < turns; i++) //for the entire length of the turns after 7
{
previousNumber = numLine[i - 1];
numLine[i] = processing(numLine, previousNumber, i); //set the current element of numLine to the processed number
std::cout << numLine[i] << " "; //displays current value with space
}
}
int processing(int array[], int number, int index) //processing seeded with array, previous value
//on numLine and index position of the for loop (which mirrors the array element index)
{
int counter = 0; //
for (int i = 0; i < index-1; i++) //loop starting at 0 and moving up to the position we are at in the array
{
if (array[i] == number) { //if the array element value at loop iteration i is the same as the previous number, then:
counter = index - i - 1; //set counter to the index position passed, minus the search loop iteration, minus 1
}
}
return counter; //return the current value of counter
}
// 13,16,10,12,1,5,8 (seed numbers)

Related

Printing out a diceplot histogram

When I complie and run my code I get the same output everytime despite having a random function. It defaults to the trial output shown on the assignment guide. I've tried to alter what's inside the print_histogram however each time I get the message in terminal that says I haven't declared "blank".
// ============================================================================
// diceplot.cpp
//
//
// ============================================================================
#include <iostream>
#include <cstdlib>
using namespace std;
// Prototype/define functions anywhere below
//loop that rolls dice and returns the dice number
int roll() {
int dice = rand() % 6 + 1;
return dice;
}
//loop that arranges the numbers and prints it out starting from index
void print_histogram(int list[], const int number_rolls){
for (int count = 0; count < number_rolls; count++){
cout << "\n" << count + 4 << ": ";
for (int index = 0; index < list[count]; index++){
cout << "X";
}
}
}
//given code
int main() {
int seed, n;
cout << "Enter a positive interger: " << endl;
cin >> seed >> n;
// Seed the pseudo-random number generator for repeatable results
srand(seed);
// Your code here
// keeps track of the outputs from the rolls
int list[21];
for (int count = 0; count < 21; count ++){
list[count] = count / 2;
}
//adds the roll of each experiment
int sum = 0;
for(int count = 0; count < n; count++) {
int dice_1 = roll();
int dice_2 = roll();
int dice_3 = roll();
int dice_4 = roll();
sum = dice_1 + dice_2 + dice_3 + dice_4;
if (sum == 21){
list[25 - 4]++;
break;
}
}
// prints out the histogram
print_histogram(list, 21);
return 0;
}
I copied the code you posted, formatted it, removed all of the comments, and then added my own comments:
#include <iostream>
#include <cstdlib>
using namespace std;
int roll() {
int dice = rand() % 6 + 1;
return dice;
}
void print_histogram(int list[], const int number_rolls) {
for (int count = 0; count < number_rolls; count++) {
cout << "\n" << count + 4 << ": ";
for (int index = 0; index < list[count]; index++) {
cout << "X";
}
}
}
int main() {
int seed, n;
cout << "Enter a positive interger: " << endl;
cin >> seed >> n;
// Here srand is called which does indeed seed the calls to rand. However,
// that doesn't change your output because your output is not showing
// anything that has to do with rand being called
srand(seed);
// This has exactly 21 elements, not n elements. Not sure if that was
// something you wrote or a default from your assignment
int list[21];
for (int count = 0; count < 21; count++) {
// This right here is what your histogram is currently showing. There
// is nothing random here, the value is the same every time
list[count] = count / 2;
}
int sum = 0;
for (int count = 0; count < n; count++) {
int dice_1 = roll();
int dice_2 = roll();
int dice_3 = roll();
int dice_4 = roll();
sum = dice_1 + dice_2 + dice_3 + dice_4;
// I don't know why the condition exists. As the code is currently
// written the dice rolls essentially have a chance to add up to 21 and
// cause the code inside the if statement to be executed
if (sum == 21) {
// 25 minus 4 is 21. Writting to index 21 is out of bounds because
// list only has 21 elements. This is undefined behavior
list[25 - 4]++;
break;
}
}
print_histogram(list, 21);
return 0;
}
I would suggest removing this section:
for (int count = 0; count < 21; count++) {
// This right here is what your histogram is currently showing. There
// is nothing random here, the value is the same every time
list[count] = count / 2;
}
... and replacing it with code that sets all elements of list to 0. Later on in the for loop responsible for rolling the four dice you can increment elements of list based on what the sum of the rolls are
Get rid of this:
if (sum == 21) {
// 25 minus 4 is 21. Writting to index 21 is out of bounds because
// list only has 21 elements. This is undefined behavior
list[25 - 4]++;
break;
}
... and replace it with code that increments the appropriate element of list regardless of what the value of sum is

Counting times that a number repeats without array(c++)

I need a program to get 100 numbers between 0-20 and count the repition of the most repeated number.
Here is what I got for less amount for input (10 instead of 100) but ofc it's wrong.
#include <iostream>
using namespace std;
int main() {
int num, x,c;
for(int i=1; i<=10; i++) {
cin >> num;
if(num==x)
c++;
else
x=num;
}
cout << c;
return 0;
}
Assuming you mean the longest continuous sequence, here's one way you can do it:
#include <iostream>
int main() {
int max_val = 0, max_len = 0; // Overall longest
int cur_val = 0, cur_len = 0; // Current
for (int i = 0; i < 10; ++i) {
int val;
std::cin >> val; // read 1 number
if (val == cur_val) // if still counting the same, increment the length
++cur_len;
else { // else, set the max and reset current
if (cur_len > max_len) {
max_len = cur_len;
max_val = cur_val;
}
cur_len = 1;
cur_val = val;
}
}
// consider the very last sequence
if (cur_len > max_len) {
max_len = cur_len;
max_val = cur_val;
}
// Result
std::cout << "Longest seq: " << max_val << ", length: " << max_len << '\n';
}

Save first n prime numbers in an array without overwriting it

I'm trying to save first 20 prime numbers that are greater or equal than entered number.
Right now the output is 20 times 997 because values overwrite previous ones. I can't figure out what to do to limit them. When the array is full stop the loop or something so the overwriting won't happen?
bool is_prime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
void fillArr(int arr[20], int num) {
for (int index = num; index <= 1000; index++) { //don't know how to set up
//2nd condition, depends on entered number
if (is_prime(index)) {
//save first 20 prime numbers that are >= num into an array
//Code fills the array with every prime it finds, setting it for all
//values and overwriting any previous primes it has found. Right now
//output would be the same 20 prime numbers closest to index 1000,
//based on second condition
for (int i = 0; i < 20; i++) {
arr[i] = index;
}
}
}
//print test
for (int i = 0; i < 20; i++) {
std::cout << arr[i] << "\t";
}
}
int main() {
int arr[20];
int num;
std::cout << "Enter number: ";
std::cin >> num;
fillArr(arr, num);
return 0;
}
In your code, initialize i to 0 at the beginning. Each time you encounter a prime, add it to your array and increment i. Break when i >= 20.
void fillArr(int arr[20], int num) {
int i = 0;
for (int index = num; index <= 1000 && i < 20; index++) {
if (is_prime(index)) {
arr[i++] = index;
}
}
//print test
for (int i = 0; i < 20; i++) {
std::cout << arr[i] << "\t";
}
}
Also note that this is not the most optimal way to find primes. For finding whether a given number is prime, you only need to check for whether it is divisible by primes uptil square root of the number (and not till n/2). You may also want to read about the Seive of Eratosthenes.
As also specified in the comments, it's better to use std::vector or std::array rather than raw arrays. In that case, you'd simply want to push_back(index) and break when vector's size >= 20.

Shift array elements

I need some help, I know this question was asked before but I don't get it and I cant solve it, so I need help. I need to move the elements of my array to a position to left. So if the input will be 1,2,3,4,5 then the output will be 2,3,4,5,1. I have done the same to right but to left I cant figure it out, please also explain the logic , thanks.
#include <iostream>
using namespace std;
int a[100],n,i,tempr,templ;
int main()
{
cin>>n;
for(i=1;i<=n;i++) cin >> a[i];
for(i=1;i<=n;i++)
{
tempr = a[n];
a[n] = a[i];
a[i] = tempr;
cout<<"Right: "<<a[i]<<endl;
}
for(i=1;i<=n;i++)
{
templ = a[2];
a[2] = a[i];
a[i] = templ;
cout<<"Left: "<<a[i]<<endl;
}
return 0;
}
Please help!
First problem is bad indexing:
for(i=1;i<=n;i++) cin >> a[i]; //wrong logic, C++ indexing start from 0
Correct approach:
for(i=0;i<n;i++) //all your loops
Second problem is wrong logic for shifting elements:
Corrected version:
//input example: 1 2 3 4 5
//to the left
int temp = a[0]; //remember first element
for(i=0;i<n-1;i++)
{
a[i] = a[i+1]; //move all element to the left except first one
}
a[n-1] = temp; //assign remembered value to last element
//output: 2 3 4 5 1
cout << "To left: " << endl;
for(i=0;i<n;i++)
cout << a[i] << endl;
//to the right
temp = a[n-1]; //remember last element
for(i=n-1;i>=0;i--)
{
a[i+1] = a[i]; //move all element to the right except last one
}
a[0] = temp; //assign remembered value to first element
//output: 1 2 3 4 5 because elements are shifted back by right shift
cout << "To right: " << endl;
for(i=0;i<n;i++)
cout << a[i] << endl;
EDIT:
How to display both shifts:
#include <iostream>
using namespace std;
int to_left[5], to_right[5],n,i,tempr,templ;
int main()
{
cout << "Input array size: ";
cin >> n;
for(i=0;i<n;i++)
{
cin >> to_left[i]; //read values to first array
to_right[i]=to_left[i]; //then copy values to second one
}
//shift first array to left
int temp = to_left[0];
for(i=0;i<n-1;i++)
{
to_left[i] = to_left[i+1]; //move all element to the left except first one
}
to_left[n-1] = temp; //assign remembered value to last element
//output: 2 3 4 5 1
cout << "To left: " << endl;
for(i=0;i<n;i++)
cout << to_left[i] << endl;
//shift second array to right
temp = to_right[n-1]; //remember last element
for(i=n-1;i>=0;i--)
{
to_right[i+1] = to_right[i]; //move all element to the right except last one
}
to_right[0] = temp; //assign remembered value to first element
//output: 1 2 3 4 5 because elements are shifted back by right shift
cout << "To right: " << endl;
for(i=0;i<n;i++)
cout << to_right[i] << endl;
return 0;
}
Note that your code look very much like C code. In C++, you can declare variables in any segment of code, not just at the beginning. In C++, you can declare variable in for loop like this: for(int i=0; i<...) - no need for global variable i
For reference, this would be good C++ code example that satisfies problem you are facing:
#include <iostream>
#include <vector>
int main()
{
std::size_t n; //size_t is unsiged type used for various sizes of containers or types
std::cout << "Input array size: ";
std::cin >> n;
std::vector<int> to_left(n), to_right(n); //two dynamic arrays containing integers, takin n as their size
for(std::size_t i=0;i<to_left.size();++i) //use vector size(), instead of n, also ++i in considered better for loops that i++ (may be faster)
{
std::cin >> to_left[i];
to_right[i]=to_left[i];
}
int temp = to_left[0]; //declare temp here, not at the begining of code
for(std::size_t i=0;i<n-1;++i)
to_left[i] = to_left[i+1];
to_left[n-1] = temp;
std::cout << "To left: " << std::endl;
for(std::size_t i=0;i<n;++i)
std::cout << to_left[i] << std::endl;
temp = to_right[n-1]; //reuse temp
for(int i=to_right.size()-1;i>=0;--i) //note int, not std::size_t, because size_t is always >=0, loop would never end.
to_right[i+1] = to_right[i];
to_right[0] = temp;
std::cout << "To right: " << std::endl;
for(std::size_t i=0;i<n;i++)
std::cout << to_right[i] << std::endl;
return 0;
}
And here would be ideal C++ code:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::size_t n;
std::cout << "Input array size: ";
std::cin >> n;
std::vector<int> to_left(n), to_right(n);
for(std::size_t i=0;i<to_left.size();++i)
{
std::cin >> to_left[i];
to_right[i]=to_left[i];
}
// rotate first array to the left
std::rotate(to_left.begin(), to_left.begin() + 1, to_left.end());
// rotate second array to right
std::rotate(to_right.rbegin(), to_right.rbegin() + 1, to_right.rend());
std::cout << "To left:" << std::endl;
for(auto x : to_left) //C++11 feature, x iterates through container
std::cout << x << std::endl;
std::cout << "To right:" << std::endl;
for(auto x : to_right)
std::cout << x << std::endl;
return 0;
}
Or you can use memmove(...) projected exactly for those purpose, here your sample:
#include <iostream>
#include <cstring>
using namespace std;
//rotate Left
void r_left(int *a,int n)
{
int tmp=a[0];
memmove(a,a+1,sizeof(int)*(n-1));
a[n-1]=tmp;
}
//rotate right
void r_right(int *a,int n)
{
int tmp=a[n-1];
memmove(a+1,a,sizeof(int)*(n-1));
a[0]=tmp;
}
void show(int *a,int n)
{
while(n--)
cout<<*a++<<' ';
cout<<endl;
}
int main()
{
int ar[]={1,2,3,4,5};
int n=sizeof(ar)/sizeof(ar[0]);
r_left(ar,n);
show(ar,n);
r_right(ar,n);
show(ar,n);
return 0;
}
easiest way to swap elements in C++ is to use std::iter_swap()
so for an array of 4 elements to swap elements 1 and 4 you would do the following
int a[4];
std::iter_swap(a, a+3);
note that you also need to #include <algorithm> for this to work
the basic logic of the function is that you give the location in memory of the 2 elements, so as the first element of an array is also its location in memory, you can pass a + n, when n is equal to the n-1 index number of the element you want to swap
As other already have stated it's all about indices. In a for-loop you are almost always in trouble if your stop condition is i <= size, because arrays in C++ are zero-indexed.
Where Black Moses alogrithm is far the easiest to understand (and probably the fastes), I read your code as if you try to swap the first value of the array through the array to the last position. Below I have tried to pin out this approach.
#include <stdio.h>
#include <tchar.h>
#include <iostream>
void ShiftLeft(int* pArr, size_t length)
{
for (size_t i = 1; i < length; i++)
{
int tmp = pArr[i - 1]; // Preserves the previous value
pArr[i - 1] = pArr[i]; // Overwrites the previous position with the current value
pArr[i] = tmp; // Stores the previous value in the current position
// All in all the first value is swapped down the array until it is at the length - 1 position
// and all the other values are swapped to the left.
/* For an array with 4 values the progression is as follows:
i = 0: 1 2 3 4
i = 1: 2 1 3 4
i = 2: 2 3 1 4
i = 3: 2 3 4 1
*/
}
}
void ShiftRight(int* pArr, size_t length)
{
for (size_t i = length - 1; i > 0; i--)
{
// This code does exactly the same as for ShiftLeft but the loop is running backwards
int tmp = pArr[i - 1];
pArr[i - 1] = pArr[i];
pArr[i] = tmp;
}
}
void Print(int* pArr, size_t length)
{
for (size_t i = 0; i < length; i++)
{
std::cout << pArr[i] << " ";
}
std::cout << std::endl;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
size_t length = sizeof(arr) / sizeof(arr[0]);
Print(arr, length);
ShiftLeft(arr, length);
Print(arr, length);
ShiftRight(arr, length);
Print(arr, length);
return 0;
}
#include <iostream>
using namespace std;
int a[100], outR[100], outL[100], n, i;
int main() {
cin >> n;
for (i = 0; i < n; i++) cin >> a[i];
// Right
for (i = 0; i < n; i++) {
outR[i+1]= a[i];
}
outR[0] = a[n-1]; // add first number
// Left
for (i = 1; i < n; i++) {
outL[i-1]= a[i];
}
outL[n-1] = a[0]; // add last number
// Answer
cout << "Right:\n";
for(i=0; i<n; i++) {
cout << outR[i] << endl;
}
cout << "Left:\n";
for(i = 0; i < n; i++) {
cout << outL[i] << endl;
}
return 0;
}
Simple answer where you can easily see everything, good luck.
You may be interested in ,,vector coding", it seems be easier if you spend some time on this:
#include <iostream>
#include <vector>
using namespace std;
vector <int> a, outR, outL;
size_t i;
int main () {
int n, temp_int;
cin >> n;
while (n--) {
cin >> temp_int; // here you read number to your vector
a.push_back(temp_int); // here you add this to vector
// remember that vector start from element 0 as like arrays
}
// Left
// remember that last element will be first
// you may have acces to size of your vector easily
for (i = 0; i < (a.size()-1); i++) {
outL.push_back(a.at(i+1)); // here you create new vector
}
outL.push_back(a.at(0)); // add last elemet which rotated
// Right
// to rotate left first you have push last element so
outR.push_back(a.at(a.size()-1)); // add first elemet which rotated
for (i = 1; i < a.size(); i++) {
outR.push_back(a.at(i-1)); // here you push rest
}
cout << "Left" << "\n";
for (i = 0; i < a.size(); i++) {
cout << outL.at(i) << endl; // here you print value
}
cout << "Right" << "\n";
for (i = 0; i < a.size(); i++) {
cout << outR.at(i) << endl; // here you print value
}
return 0;
}
int* leftShiftOneByOneWIthoutTemp(int arr[], int sz)
{
for (int i=0 ;i < sz-1; i++)
{
arr[i] = arr[sz-1] + arr[i];
arr[sz-1] = arr[i] - arr[sz-1] ;
arr[i] = arr[i] - arr[sz-1] ;
std::cout << "iter "<< i << std::endl;
printArray(arr,5);
}
std::cout << "final "<< std::endl;
printArray(arr,5);
return arr;
}
Replace your code (to shift array left) with below code.
templ = a[0];
for(i=0;i<n-1;i++)
{
a[i] = a[i+1];
cout<<"Left: "<<a[i]<<endl;
}
a[n-1] = templ;
cout<<"Left: "<<a[n-1]<<endl;

C++ max of an array using recursion issue

I have this program that finds the largest integer in an array using recursion, but it keeps returning the last number entered no matter what the value instead of the largest number. How do i fix this?
#include <iostream>
using namespace std;
int maximum(int digits[], int size, int largest, int i);
void main()
{
const int size = 3;
int digits[size];
int n = 0, x = 0;
for(int a = 0; a < size; a++)
{
cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
cin >> digits[n];
}
cout << "\nThe largest digit is, " << maximum(digits, size, 0, 0) << ", thank you!\n";
cout << endl;
}
int maximum(int digits[], int size, int largest, int i)
{
if ( i < size )
{
if ( largest < digits[i])
largest = digits[i];
maximum( digits, size, largest, i + 1);
}
return largest;
}
First use the index variable properly in main()
for(int a = 0; a < size; a++)
{
cout << "Enter an integer <" << ++x << " out of " << size << ">: ";
cin >> digits[a];//-->Use the index varible correctly.
}
int maximum(int digits[], int size, int largest, int i)
{
if(i==size-1)
return digits[i]; //The base case is specified here.
if ( i < size )
{
int temp= maximum( digits, size, largest, i + 1);
if ( digits[i] < temp)
largest =temp;
else
largest=digits[i];
}
return largest;
}
Please check out the changes. Carefully read the code. You will understand your mistakes.
When designing recursion think of few things first-
The base condition. (This stops the recursion).
The recursive step. (Where you will calculate something based on previous calculation)
Combine step- You have to combine them (value at this stage and value got from recusive step) to get the correct answer. This step is not required in some cases.
It should be return maximum( digits, size, largest, i + 1);
Live example.
int biggestOne(int integerArray[], int lengthOfArray, int max)
{
if (lengthOfArray==0) return max;
if (max < integerArray[lengthOfArray-1]) max = integerArray[lengthOfArray-1];
return biggestOne(integerArray,lengthOfArray-1,max);
}
int main()
{
int array[] = {7,2,9,10,1};
int arrSize = sizeof(array)/sizeof(array[0]); //returns length of the array
cout <<"Biggest number in the array: " << biggestOne(array,arrSize,0) << endl;
return 0;
}