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
}
}
Related
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
im trying to write this code but i couldn't
the q is :
by using for loop, write a program to receive input for any 5 numbers and display the total of even an odd numbers. the output should be as shown below
---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------
and this is what i did:
#include<iostream>
using namespace std;
int main()
{
int i,j=0,c=0;
for(i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>i;
}
if(i==0)
{
cout<< "0 is not even number"<<endl;
}
else if(i%2==0)
{j++;}
else if(i%2 !=0)
{c++;}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Going through your code step by step (notice the changed formatting!):
#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
int i, j=0, c=0;
for(i = 0; i < 5; i++)
{
cout << "enter 5 numbers " << i;
cin >> i; // you are overwriting your loop variable!!!
// how do you think your program will go on if you enter
// e. g. 7 right in the first loop run?
// additionally, you did not check the stream state afterwards
// if user entered something invalid (e. g. S), cin sets the
// fail flag and stops further reading - attemps doing so yield
// 0 (since C++11) or don't modify the variable (before C++11)
}
// this section is outside the loop already!
// so you are only checking the number you read in your loop in the very last run
if(i == 0)
{
cout << "0 is not even number" << endl;
}
else if(i % 2 == 0)
{
j++;
}
// this check is redundant: it is the complement to your previous
// check, so if the first went wrong, the second cannot be false any more
// (compare: you did not check for i != 0 either before doing the modulo check)
else /* if(i % 2 != 0) */
{
c++;
}
cout << "total exists even: " << j << endl;
cout << "total exists odd: " << c << endl;
return 0;
}
Changed code:
#include<iostream>
int main()
{
// several serious coding guide lines mandate: only one variable per line:
unsigned int odd = 0;
unsigned int even = 0;
// I used unsigned int here, negative counts are just meaningless...
// I'm consequent in these matters, but range of (signed) int suffices anyway,
// so you can use either one...
// C++ is not C (prior to C99) - keep scope of variables as local as possible
// (loop counter declared within for header, local variable within body)
for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n; // separate variable!
if(!(std::cin >> n))
{
// some appropriate error handling!!! e. g.:
std::cout << "invalid value entered";
return -1;
}
// this now resides INSIDE the for loop
if(n == 0)
{
cout << "0 is not even number" << endl;
}
else
{
// this is an ALTERNATIVE calculation
n %= 2; // gets either 0 or 1...
odd += n;
even += 1 - n;
// (I personally prefer avoiding conditional branches but you *can*,
// of course, stay with the if/else you had before, too...
// - just don't check the complement as shown above)
}
}
cout << "total exists even: " << even << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
About the unsigned: Sometimes these are of advantage:
void f(int n) { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }
but sometimes one has to handle them with care:
for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;) { /* ... */ } // correct variant
(the first one would have worked with signed int, but it is not the fault of the unsigned type, but the programmer's fault who did not chose the right type for what he or she intended...).
Just for completeness: Assuming we could drop the mathically incorrect statement that zero wasn't even, we could have it even much simpler:
unsigned int constexpr LoopRuns = 5u;
int main()
{
unsigned int odd = 0; // just one single variable...
for(unsigned int i = 0; i < LoopRuns; i++)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n;
if(!(std::cin >> n))
{ /* ... */ }
odd += n %= 2;
}
// one single difference instead of five additions...
cout << "total exists even: " << LoopRuns - odd << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
This program will help you out.
#include <iostream>
int main () {
int num[5], even = 0, odd = 0;
bool hasZero = false;
std::cout << "Enter 5 numbers:"
for (int i = 0; i < 5; i++) {
std::cin >> num[i];
}
for (int i = 0; i < 5; i++) {
if (num[i] == 0) { // Checking if the current number is zero
hasZero = true;
} else if (num[i] % 2 == 0 ) { // Checking if the current number is even
++even;
} else { // If the number is not even, then it must be odd
++odd;
}
}
if (hasZero) { // If the input has zero then print following statement
std::cout << "0 is not an even number" << std::endl;
}
std::cout << "Total even count: " << even << std::endl;
std::cout << "Total odd count: " << odd << std::endl;
return 0;
}
If you are unable to understand any line, then you're most welcome in the comments section below ;)
The problem with your code:
In the for statement, you're using the same variable for both counter and input , i.e., i. This will allow neither for loop to execute properly nor the input to be captured properly.
You're overwriting the i variable everytime you take any input, then only the last input (out of 5 inputs) will be stored in memory.
You're just checking the last input, by using if statement, because the loop is already ended before.
If you want your code to run properly, then these modifications will make that work:
#include<iostream>
using namespace std;
int main()
{
int num,j=0,c=0; // Change the name to num here, because i will be used later as a counter variable.
for(int i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>num;
// Don't end for loop here, this will not allow every input to be checked.
if(num==0)
{
cout<< "0 is not even number"<<endl;
}
else if(num%2==0)
{
j++;
}
else if(num%2 !=0) // Or just add a *else* here instead of *else if*, they will work exactly the same here.
{
c++;
}
} // End of for loop
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Firstly, 0 is an even number, and your code needs to be properly indented, just so you can see that you are indeed reading the input into a single integer, which also controls the loop, and your if statement is outside the for loop (despite the misleading indentation. Here's a simple example implementation, but you can (and should) fix the bugs I pointed out in your own code:
#include <iostream>
int main() {
std::cout << "Enter 5 numbers\n";
int cnt(5);
int n, odd(0), even(0);
while(cnt-- && (std::cin >> n))
n % 2 ? ++odd : ++even;
std::cout << odd << " odd, "
<< even << " even numbers" << std::endl;
return 0;
}
Note the post decrement and the fact the && short-circuits.
This should be your code:
you take an array of integer where you store the input value. Head over to https://www.tutorialspoint.com/cprogramming/c_arrays.htm to learn more abour arrays..
#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
cout<<"enter 5 numbers "<<i ;
cin>>numbers[i];
}
for(i=0;i<5;++i){
if(numbers[i]==0)
{
cout<< "0 is not even number"<<endl;
}
else if(numbers[i]%2==0)
{j++;}
else if(numbers[i]%2 !=0)
{c++;}
}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
using namespace std;
int main()
{
int * Array = new int[5];
int even(0), odd(0);
for(int i = 0; i < 5; i++)
{
cout<<"enter "<< i+1 << "-th number: " << flush;
cin>>Array[i];
if(!Array[i])
{
cout<< "0 is not even number... input again"<<endl;
i = i-1;
}
else
{
if(Array[i]&1) odd++;
else even++;
}
}
cout<<"total exists even : "<<even<<endl;
cout<<"total exists ODD : "<<odd<<endl;
cin.get(); cin.get();
delete[] Array;
return 0;
}
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;
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.