I'm working on an assignment that allows a user to enter integers (up to 20 entries) and displays a list of odd entries and even entries, when '0' is entered. The assignment requires the user to input a single integer per line.
I have managed to extract and segregate the odd and even entries, however the assignment requires that the odds be displayed on a single line, and the evens on another single line below that.
For example, if the user entered integers 1-9:
Odds: 1 3 5 7 9
Evens: 2 4 6 8
Currently, it returns:
Even: 2
Even: 4
Even: 6
Odd: 1
Odd: 3
Odd: 5
etc...
I am hoping that my program will even allow this, but I suspect the problem lies in the way I have set up the loops.
#include <iostream>
using namespace std;
bool isEven(int x) {
if ((x%2) == 0) {
return true;
} else {
return false;
}
}
int main(){
const int x = 20;
int list[x];
int counter;
cout<<"Enter up to 20 integers or press 0 to display list"<<endl;
for (counter=0; counter<x; counter++) { //main loop
cout<<"Enter number: ";
cin>>list[counter];
if (list[counter]==0) {
for (int i =0; i<counter; i++) {
if (isEven(list[i])==true) {
cout<<"Even: "<<list[i];
}
}
for (int j = 0; j<counter; j++) {
if (isEven(list[j])==false) {
cout<<"Odd: "<<list[j];
}
}
break;
}
}
return 0;
}
Split input and output to separate loops:
for (counter=0; counter<x; counter++) {
// input
}
for (counter=0; counter<x; counter++) {
// output
}
Print labels before going through each value and use \n to print a newline:
cout << "Even: ";
for (int i =0; i<counter; i++) {
if (isEven(list[i])==true) {
cout << list[i];
}
}
cout << "\nOdd: ";
for (int j = 0; j<counter; j++) {
if (isEven(list[j])==false) {
cout << list[j];
}
}
cout << "\n";
Related
I have a big while loop that read integers from a text file into 2-D array(s) and assesses array(s’) length. This loop works perfectly fine.
#include <iostream>
#include <fstream>
#include <string>
#define MAX_ROWS 3
#define MAX_COLUMNS 2
using namespace std;
int main()
{
string fileName = "inFilePgm2A.txt";
ifstream inFile;
inFile.open(fileName);
int checkNbr;
int ArrB[MAX_ROWS][MAX_COLUMNS];
bool bad = false;
bool invalidnum = false;
while (!inFile.eof())
{
bad = false;
for (int i = 0; (i < MAX_ROWS) && !bad; i++) {
for (int j = 0; (j < MAX_COLUMNS) && !bad; j++) {
inFile >> ArrB[i][j];
if (ArrB[i][j] == -1) {
bad = true;
cout << "\nThe array does not have enough integers\n";
}
else {
if (ArrB[i][j] < 1) {
invalidnum = true;
}
}
if (!bad) {
cout << *(*(ArrB + i) + j) << " ";
}
}
}
if (bad == false) {
inFile >> checkNbr;
if (checkNbr == -1) {
cout << "\nThe size of the array is correct." << endl;
}
else {
while (checkNbr != -1)
{
cout << checkNbr;
cout << " ";
inFile >> checkNbr;
}
cout << "\nYou have too many numbers in this array\n";
}
}
if (invalidnum == true) {
invalidnum = false;
cout << "\nThere is/are negative number(s) or zero(s) in the array imported from your text file.\n";
}
}
return 0;
}
For example, if my text file contains the following integers:
1 2 3 4 5 6 -1 1 2 3 7 5 8 -1 -5 9 4 -1
This will be the result:
The problem is, I don’t know how to print a 2-D array in matrix format when the array is in a while loop.
So, instead “1 2 3 4 5 6”, I want it to display
1 2
3 4
5 6
The size of the array is correct….
Usually, I can use the code below to print out an array in matrix format
for(int i = 0; i < MAX_ROWS; i++)
{
for(int j = 0; j < MAX_COLUMNS; j++)
{
cout<<ArrB[i][j]<<"\t";
}
cout<<endl;
}
But this code is not working in the while loop, if I put the code above in my while loop, (with the exactly same integers in the text file), it will just output a bunch of random values…
This is an example, I tested the below code for printing a 2D array in matrix format. You can use printf("%5d"....) instead of cout. %[n]d, where n is the integer adding that many spaces.
while (!inFile.eof())
{
bad = false;
for (int i = 0; (i < MAX_ROWS) && !bad; i++) {
for (int j = 0; (j < MAX_COLUMNS) && !bad; j++) {
inFile >> ArrB[i][j];
if (ArrB[i][j] == -1) {
bad = true;
cout << "\nThe array does not have enough integers\n";
}
else {
if (ArrB[i][j] < 1) {
invalidnum = true;
}
}
if (!bad) {
printf("%3d",ArrB[i][j]);
//cout << *(*(ArrB + i) + j) << " ";
}
}
printf("\n");
}
Output:
1 2
3 4
5 6
The size of the array is correct.
1 2
3 7
5 8
The size of the array is correct.
-5 9
4
The array does not have enough integers
There is/are negative number(s) or zero(s) in the array imported from
your text file.
I have been working on a USACO problem and devised this (see below) algorithm for some test cases. However, for the input "brbrrrbbbrrrrrbrrbbrbbbbrrrrb", I am getting 9. I don't understand how this can be possible. Can anyone help me find the problem.
P.S: These are the outputs of first loop without any values in the second loop:
-10
-10
-10
3
3
5
-10
2
2
-10
4
4
-10
0
#include <iostream>
#include <vector>
using namespace std;
int main() {
string necklace;
cin >> necklace;
vector <int> neck;
int c_it = 0;
for(unsigned int i = 0; i < necklace.length(); i++){
if(necklace[i] == necklace[i+1] | 'w' == necklace[i+1]){
c_it++;
}
else{
if (c_it >= 1){
cout << c_it+1 << endl;
}
else{
cout << "-10" << endl;
}
c_it = 0;
}
}
int maximum = 0;
for(int i=0; i < neck.size(); i++){
for(int j=1; j<= neck.size(); j++){
int valueToCompare = neck[i] + neck[j];
if(valueToCompare > maximum){
maximum = valueToCompare;
}
i++;
j++;
}
}
cout << maximum;
}
The reason is you have an error is because of the "|" in your first if statement. It should be the boolean operator "||" instead.
To simplify it, I need to read numbers from a file and store them in a 2D array. I then must check to make sure that the there were enough numbers in the file to fill the array.
the first two numbers in the file are the ones that declare how many rows and columns there should be for the array.
The part I am struggling with is that the numbers in the file can also include a 0 in them.
I was using this method to test if an element was empty
double numbers[MAX_ROW][MAX_COL];
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!numbers[i][n]){
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
return 0;
}
}
}
But then I realized that the program would exit if the file contained the number 0. Which is something that I don't want to happen.
I also tried to using a pointer and testing for NULL but that gave me a warning about (comparison between NULL and non-pointer) and it would still do the same thing, if there was a 0 in the file it would just exit.
double (*ptrNumbers)[MAX_COL] = numbers;
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(ptrNumbers[i][n] == NULL){
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
return 0;
}
}
}
Example files:
This one works fine
3 3
1 3 4
3 2 4
3 5 2
This will not works because of the zero in the file
3 3
1 3 4
3 0 4
3 5 2
This is the type of error i would like to test for.
It says there are 3 rows and 3 columns but there aren't numbers to fill the rest of the array. Therefore they will be initialized to 0 which as you can conclude will also cause the same problem.
3 3
1 3 4
3 2 4
3
Anyone have any idea how I can test for "empty" elements but not elements containing 0s?? Or am I just doing something wrong?
Thanks in advance for any help :)
After I altered my program from the previous recommendations.
I set up a bool function to return a false statement if there was not enough numbers in the file. However even if the file had the correct amount of numbers the file would still execute the if statement and return a false value. Is my syntax wrong in some way?
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
else {
inFile >> numArray[i][n];
}
}
}
return true;
You have to catch error while reading the contents of the file.
std::ifstream ifile("The input file");
ifile >> row >> col;
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if( ! (ifile >> ptrNumbers[i][n]))
{
// Problem reading the number.
cout << "Error: There is not enough data found file :(...." << endl;
cout << "The Program will now exit....." << endl;
}
}
}
Update
The updated function is faulty.
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
else {
// You are now reading into the same element
// of the array again.
inFile >> numArray[i][n];
}
}
}
return true;
You don't need the else part in that function.
for(int i = 0; i <= row; i++) {
for(int n = 0; n <= col; n++) {
if(!(inFile >> numbers[i][n])) {
return false;
}
}
}
return true;
I wrote a simple C++ program that finds how many duplicates are in the array.
This works perfectly for me but this is very long code. And I would like to know if there is any short code which may perform this task successfully:
#include<iostream>
using namespace std;
int main()
{
int a[10];
int reper=0,word=0,flage=0,number[10]={
0
};
//Getting Input From User
for (int i = 0; i <=9; i++)
{
cout<<"Enter The Value For "<<i<<" Index"<<endl;
cin>>a[i];
}
//Checking The Duplicates Numbers
for (int i = 0; i <= 9; i++)
{
reper=0;
flage=0;
for (int j = 0; j <=9; j++)
{
if (a[i]==a[j])
{
if (i!=j)
{
reper++;
}
}
}
number[i]=a[i];
for (int k = 0; k <=9; k++)
{
if (i!=k)
{
if(number[i]==number[k])
{
flage=1;
break;
}
}
}
//If There Are Duplicates Then Prints That Numebr, How Many Times It Repeated And Total Occurance Of That Number In The Array
if (reper!=0&&flage==0)
{
cout<<"Repeated Number Of The Array Is : "<<a[i]<<" ";
cout<<"And This Number Repeated "<<reper<<" Times "<<"And Total Occurance Of This Number is : "<<reper+1<<endl;
word=a[i];
}
}
//If There Is Nothing Any Duplicate In The Array Then Simply Prints This Message On Console
if (reper==0&&word==0)
{
cout<<"There Is Nothing Any Repeated Number Of This Array: "<<endl;
}
system("Pause");
return 0;
}
IMHO the easiest way to implement this - using http://en.cppreference.com/w/cpp/container/multiset. It has logarithmic complexity and inner methods to count repeated items.
Refer an example below:
#include <iostream>
#include <set>
int main(int argc, char *argv[])
{
std::multiset<int> ms;
//Getting Input From User
for (int i = 0; i <=9; i++)
{
std::cout<<"Enter The Value For "<<i<<" Index"<<std::endl;
int val;
std::cin>>val;
ms.insert(val);
}
bool repeated_number_found=false;
std::multiset<int>::const_iterator it = ms.begin();
while (it != ms.end()) {
int reper=ms.count(*it);
if (reper > 1){
std::cout << "Number " << *it << " repeated for " << reper << " times" << std::endl;
repeated_number_found=true;
}
it = ms.upper_bound(*it);
}
if (!repeated_number_found){
std::cout<<"There Is Nothing Any Repeated Number Of This Array"<<std::endl;
}
return 0;
}
But using this container you will loose first entrance of repeated number, if it matters to you, I will recommend using struct or std::pair to hold entrance number with entered number. In this case you will need to provide custom comparator also (refer to doc.)
I think the better way to achieve this would be to sort the array and do something like this :-
(include the header file algorithm before doing this.)
vector <int> a (10,0);
for (int i = 0; i <=9; i++)
{
cout<<"Enter The Value For "<<i<<" Index"<<endl;
cin>>a[i];
}
int count = 0;
sort(a.begin(), a.end());
for(int i = 0; i < a.size() - 1; i++) {
if (a[i] == a[i + 1]) {
count++;
}
}
cout << count << endl;
for(int width=1; width<=5; width++) {
if(width <= 1) {
for(int width=1; width<=5; width++) {
cout<<" "<<width<<" ";
}
} else if(width<5) {
cout<< endl;
for(int width2=5; width2<=9; width2++) {
if(width2==5 || width2==9)
cout<<" "<<width2<<" ";
else
cout<< " ";
}
} else {
cout<< endl;
for(int width3=13; width3>=9; width3--) {
cout<<" "<<width3<<" ";
}
}
}
this code which I have posted above draws this shape
1 2 3 4 5
5 9
5 9
5 9
13 12 11 10 9
but I actually want my code to print it like this, I have tried a lot changing things but all in vain. so, I'm looking forward to you guys.
1 2 3 4 5
16 6
15 7
14 8
13 12 11 10 9
If you print something on the console, going back in lines and carriage returns will be very messy.
The trick is to seperate the problem in 3 stages:
stage1: print the top line, simple enough
stage2: print the largest number wrapping around, then print some empty space and finish with the number at the end, make sure to increment and decrement the numbers accordingly.
stage3: print the last line.
Here is the code for the algorithm I just described:
#include <iostream>
using namespace std;
int main()
{
const int width=6;
const int height=6;
int numberInFront=(height-1)*2 + (width-1)*2;
int numberAtTheEnd= width;
for(int i=1; i<width; ++i) cout<<i<<"\t"; //print top line
cout<<endl;
for(int i=0; i<height-1; ++i)
{
cout<<numberInFront<<"\t";
for(int j=0; j<width-3; j++) cout<<"\t"; //print inner space
cout<<numberAtTheEnd<<endl;
numberInFront--;
numberAtTheEnd++;
}
//print last line:
int counter = numberInFront;
while(counter!=numberAtTheEnd-1)
{
cout<<counter<<"\t";
counter--;
}
return 0;
}
It helps to avoid magic numbers in your code using #defines or const variables. This makes it more readable and more extensible. For example if you wanted to make a square that was 20x20, your code would require a complete rewrite!
Start from this working solution to implement this principle into your coding.
#include <iostream>
using namespace std;
#define SIDE 4
int main(){
int perimeter = SIDE * 4;
for(int width=0; width<=SIDE; width++)
{
if(width < 1) {
for(int width=0; width <= SIDE; width++) {
cout<<" "<<width + 1<<" ";
}
cout<< endl;
}
else if(width < SIDE)
{
cout<<" "<<perimeter - width + 1 << "\t\t" << (SIDE + width) + 1;
cout<< endl;
}
else
{
for(int width3 = perimeter - SIDE; width3 >= perimeter - 2 * SIDE; width3--) {
cout<<" "<<width3 + 1<<" ";
}
cout<< endl;
}
}
return 0;
}
Here is solution
int width =6;
int total = (width-1)*4;
for(int row=1; row <=width; row++)
{
if(row == 1 )
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<pr<<" ";
}
cout<<"\n";
}
else if( row == width)
{
for(int pr=1; pr<=width; pr++)
{
cout<<" "<<(total-row-pr+3)<<" ";
}
}
else
{
for(int pr=1; pr<=width; pr++)
{
if(pr ==1 )
cout<<" "<<(total-row+2)<<" ";
else if(pr ==width)
cout<<" "<<(width+row-1)<<" ";
else
cout<<" "<<" "<<" ";
}
cout<<"\n";
}
}