I am having a problem with this program which is to print out a list forwards and backwards, however When I print out the list backwards the first number in the list is a random massive number rather than the right number. e.g.
0 1 2 3 4 5 6 7 8 0
4286398 8 7 6 5 4 3 2 1 0
can anyone explain what is wrong with my code please.
Also Can anyone tell me how I could pass the counter from the printList function to a new function called checkList() so that the counter has the same value in checkList() as what it is at the end of printList().
code:
void printList(int array1[]){
int counter = 0;
int x;
ifstream theFile("list.txt");
while(theFile >> x){
array1[x] = x;
cout << array1[x] << " ";
counter = counter + 1;
}
cout << endl << counter << endl;;
int n = counter;
for(int i = n -1; i >= 0; i--){
cout << array1[i] << " ";
}
Here's the culprit:
array1[x] = x;
If your array input values are 0 1 2 3 4 5 6 7 8 0, then at the last iteration of your loop you're doing array1[0] = 0. That overwrites the first item in your array, while incrementing the counter. Then, when you reverse it array[9] contains garbage value because you never set it.
You have a problem because of the line array1[x]=x;. Your code would actually work if the numbers in your file were 0..9, but the final number is another 0, so you don't set array1[9] to anything.
You should have some variable for indexing the array, something like:
int counter = 0;
while(theFile >> x){
array1[counter] = x;
cout << array1[counter] << " ";
counter = counter + 1;
}
you are doing
array1[0] = 0;
array1[1] = 1;
array1[2] = 2;
array1[3] = 3;
array1[4] = 4;
array1[5] = 5;
array1[6] = 6;
array1[7] = 7;
array1[8] = 8;
array1[0] = 0; // here
array1[9] is uninitialized
You have some serious issues in the code:
ifstream theFile("list.txt");
while(theFile >> x){
array1[x] = x;//^^this is evil
cout << array1[x] << " ";
counter = counter + 1;
}
cout << endl << counter << endl;;
//^^extra colon, though not wrong here but not good practice
You read from file and fill the array, in your special case, you have:
0 1 2 3 4 5 6 7 8 0
You have 10 elements, but your array1 will end up with 9 since the last read was 0 and array1[0] was written as 0 again. So when you output your array1, you will never get 10 numbers since your array actually stores 9 numbers. that's why you saw garbage value if you try to access array1[9], which value has not been filled, some garbage raw memory value.
Instead, you can try to do the following:
int counter = 0;
int x;
ifstream theFile("list.txt");
while(theFile >> x){
array1[counter] = x;
cout << array1[counter] << " ";
counter = counter + 1;
}
cout << endl << counter << endl;;
You are counting wrong upwards and eventually hit uninitialized memory AFTER your array. You should pass the length of your array as a parameter to your function.
As arrays decay to pointers you won't be able to recover its length.
void printList(int array1[], into size){ }
Then thou don't need to figure out its length so complicated.
Related
I am trying to add numbers one after the other to my array and so far I have this:
int main(){
DynamicArray<int> intArray(5);
int num = 0;
int point;
intArray.addElement(20);
intArray.addElement(10);
intArray.addElement(30);
intArray.addElement(60);
intArray.addElement(21);
for(int x = 0; x < 5; ++x){
intArray[x] = rand() % 100;
std::cout << intArray[x] << " ";
}
std::cout << endl;
std::cout << "\n" "Enter the number :" << endl;
cin >> num;
std::cout << "\n" "What point ?" << endl;
cin >> point;
for(int x = 0; x > point; --x){
intArray[x] = intArray[x-1];
}
intArray[point] = num;
for(int x = 0; x < 5; x++){
std::cout << intArray[x] << " ";
}
std::cout << endl;
return 0;
}
but when I run it I get this:
7 49 73 58 30
Enter the number :
2
What point ?
0
2 49 73 58 30
the question is how do I add the element 2 to position 0 without getting rid of the 7 and by resizing the array?
Thank you any assistance would be appreciated.
To resize the DynamicArray you need to set the length properties to the value you want, in your case lenght + 1 to do this you can use this:
intArray.Length = intArray.Length + 1;
Then you can move and add your element as you want.
Pay attention to the index you use in the for cicle, it can contains some errors.
Note: For the code above, maybe is better to use the std::vector.
I am programming a guessing game where the user will define the first array to scale from 1 to whatever number inputed. I have a function that will randomise the numbers, then the second array will be the user input guesses. I am trying to make a for loop that will cycle through both arrays and print "O" if array values match, and "X" if they do not. It looks like the first iteration of the loop works and prints "O" but then prints a lot of X's after that.
#include <iostream>
using namespace std;
void createArray() {
int n;
int counter = 0;
cout << "Enter total number: ";
cin >> n;
// for loop to generate array to scale from 1 -
user input.
int *arr1 = new int[n];
for (int i = 1; i < n + 1; i++){
arr1[i] = i;
// Counter is used to track the size of array
counter++;
}
// for loop used to print the values of array (just for development and my reference)
for (int i = 1; i < n + 1; i++){
cout <<"[" << arr1[i] << "]";
}
cout << endl;
cout << counter << endl << "Number Guessing" << endl;
cout << "Enter " << counter << " digits (1-" << counter << ")" << endl;
// initialize user input array to be the same size as first array
int arr2[counter];
for (int i =0; i < counter; i++){
cin >> arr2[i];
}
cout << endl;
// here I am trying to cycle through both arrays and print "O" if the values match in each array.
for (int i = 0; i < n; i++){
arr1[i] = i;
bool correct = true;
for (int j = 0; j < n; j++){
arr2[j] = j;
if (arr1[i] != arr2[j]){
correct = false;
cout << "X";
}
if (correct){
cout << "O";
}
}
}
cout << endl;
}
int main(){
createArray();
}
This is the output:
Enter total number: 6
[1][2][3][4][5][6]
Number Guessing Enter 6 digits (1-6)
1 2 3 4 5 6
OXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Your loops are not comparing the arrays side by side but rather every element in array 1 is being compared to every element in array 2.
Since both arrays are reset by arr[i]=i & arr2[j]=j then they both are {0,1,2,3,4,5}.
The first innerloop will net a 'O' if(0==0) where i=0 & j=0, the next 5 innerloops if(0==1..5) where i=0 & j=1..5, are an 'X'.
The problem is on the next outerloop. Correct is reset to true by the outerloops second pass of i=1, but immediately the innerloop tests if(1==0) where i=1 & j=0, which is false and thus sets Correct to false.
So on the second pass thru the innerloop if(1==1) is true where i=1 & j=1, BUT there is no statement in the inner loop to set **Correct back to true.
Also, where as the X is printed as the result of the equality test, the O is outputted only when Correct is still true, which it is not. In fact, for every outloop after the first one, there will be an innerloop equality test which sets Correct to false before any a subsequent true equality tests.
The results are one 'O' followed by a 30 'X'. One 'X' for every false; 6 outerloops, and foreach, 5 of the six innerloops will be false. Five of the 'O's will simply not print because the 'O' does not print as a result of the equality test.
You dont need two loops
for (int i = 0; i <= n; ++i) {
if (arr1[i] == arr2[i]) {
std::cout << "0";
}
else {
std::cout << "X";
}
}
You should put your expected output for us to know what you want
I'm trying to solve one of the questions on a task sheet I've been received, to help me further in my understanding of C++ code from my class.
The question is (and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen
Creates a second array of size 5 and fills it with zeros
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
The problem is how to go about checking how many times a number was entered. I was thinking of a for loop, but the way I wrote it is fundamentally incorrect, so I find myself struggling to see the mistake I am having. Perhaps I am missing something simple? Any help would be great.
Here is my (terrible) for loop attempt, so you can see my error.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int input[10];
const int MAX_NO = 5;
int COUNT[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
}
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
// show how many times 1 number appears
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
for (int i = 0; i < MAX_NO; i++)
{
cout << i + 1 << " appears " << COUNT[i]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
Put
COUNT[ input[i]-1 ]++;
in your first loop (after validation). Once you do that, you don't need a second loop to tally up the results.
This works from the inside out by first getting what input[i] is, then using it to modify the (input[i]-1)'th location in the COUNT array. If the user enters 4 on the first run of the loop, then i == 0 and input[i] == 4. Since arrays are 0-based, it will increment COUNT[input[i]-1] which in this case is COUNT[4-1] == COUNT[3].
After your initial loop runs the number of 1's will be in COUNT[0], the number of 2's will be in COUNT[1] and so on.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
//declare a constant values
int input[10];
int count = 10; //all constant MUST be in capital letters
//second array filled with zeros
const int MAX_NO = 5;
int COUNT[5] = { 0, 0, 0, 0, 0 };
//ask user for 10 input values
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
//check if input numbers are between 1 and 5 inclusive
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
/* show how many times 1 number appears.
this section should be in the main loop which would enable the program to check how many times a
number is entered so that it is stored in the second array. changed i to secondCount because this is the counting index of the second array not the first which you've called i (one of the reason you'd all zero as output when u ran your code)*/
for (int secondCount = 1; secondCount <= MAX_NO; secondCount++)
{
if (input[i] == secondCount)
{
COUNT[secondCount-1]+= 1; //use minus 1 from i and increment. += 1 is the same as COUNT++
}
}
}
//display number entered in the first array
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
//display how many times a number is entered.
for (int secondCount = 0; secondCount < MAX_NO; secondCount++)
{
cout << secondCount + 1 << " appears " << COUNT[secondCount]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
OUTPUT:
Please enter a number for value 1 = 1
Please enter a number for value 2 = 1
Please enter a number for value 3 = 1
Please enter a number for value 4 = 2
Please enter a number for value 5 = 3
Please enter a number for value 6 = 2
Please enter a number for value 7 = 4
Please enter a number for value 8 = 4
Please enter a number for value 9 = 3
Please enter a number for value 10 = 2
You entered: 1 1 1 2 3 2 4 4 3 2
1 appears 3 times in the input
2 appears 3 times in the input
3 appears 2 times in the input
4 appears 2 times in the input
5 appears 0 times in the input
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
Let's examine what this is doing. It starts by checking input[1]. (This should be input[0] as array indices start at 0). Then it checks if input[1] is equal to 1. If it is, then it increments COUNT[1].
Next, it checks input[2]. Then it checks if input[2] is equal to 2. If it is, it increments COUNT[2]. And so on until it has gone through input[5].
Do you see the problem with this? You're only checking the first 5 inputs and only checking them against a single value.
I have to write the program, when after terminating infinite while loop "while(cin>>a)" by, let's say "-1", program says me how many times value increased. For input "0 0 2 2 3 4 8 8 8 -1" it should print "4". First part isn't problem, but I have no idea how to count how many times it had changed over time. Any tips? Thanks a lot.
You should use counters which will basically increase each time your value increases. Check the code bellow:
int value, highestValue, counter = 0, counter2 = 0;
do{
cout << "Enter the value: ";
cin >> value;
if(counter2 == 0){
highestValue = value;
}
if(value > highestValue){
counter++;
highestValue = value;
}
counter2++;
}while(value != -1);
cout << "The number increased " << counter << " times!\n";
The second counter (counter2) is required in the first if statement to store the first value you enter as the highest value.
int p = -1, k, a, b;
while( cin >> a ) //infinite loop
{
if ( k != a )
p++;
b = a - k;
if(a=-1)
exit(0);
k = a;
}
cout << "value increased by" << b;
cout << "number of times it has changed over time = " << p;
Can anyone fix this sample code that will print a file in 2D array. Here is the code and the output.
while (!file.eof())
{
int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
The output is not in table form.
The output is:
Index Size Weight (lb/ft) Diameter (in) 0 2 0.167 0.250 1 3 0.376 0.375 2 4 0.668 0.500 3 5 1.043 0.625 4 7 1.502 0
6 9 2.670 1.000 7 12 3.400 1.128 8 14 4.303 1.270 1.270
Press any key to continue . . .
Two options:
Define coutner as static
while (!file.eof())
{
static int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
or have it define external to the while loop:
int counter = 0;
while (!file.eof())
{
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
If you define it and initialized it to 0 in ever iteratoin of the while loop - it will never reach 5 to print endl;
It seems to be that not only the counter is initialized in every loop, as others pointed out before me, but moreover, it is never actually increased. The only increase I see is within the condition that it is equal to five. As it is never increased outside the condition, it never reaches five (even if it is declared as static or outside the loop), hence the condition is never met.
You have an uneven number of opening and closing curly braces, too.
I am not exactly sure what you want to achieve. If you want a line break after every fifth iteration, the following should work:
int counter = 0;
cout << setw(4) // suffice to set once
while (!file.eof())
{
file >> n;
cout << n << " ";
if (++counter == 5) // increase here before checking condition
{
cout << endl;
counter = 0;
// do not increase here again
}
}