how to solve this using Arrays? - c++

I'm new to programming is there a way to solve this:
Take 10 integer inputs from user and print the following
number of positive numbers.
number of negative numbers.
number of odd numbers.
number of even numbers
#include <iostream>
using namespace std;
int main()
{
int numArray[10];
cout<<"Enter Number :";
for(int i=0; i<10; i++)
{
cin>>numArray[i];
}
for(int i=0; i<numArray[i]; i++)
{
if(numArray[i]>0)
{
cout<<"Positive Number "<<numArray[i] <<endl;
}
else
{
cout<<"Negative Number "<<numArray[i]<<endl;
}
if(numArray[i]%2==0)
{
cout<<"Odd number "<<numArray[i]<<endl;
}
else
{
cout<<"even number "<<numArray[i]<<endl;
}
}
return 0;
}

You could do this without arrays but I'm just gonna stick with your original intent for clarity.
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int, 10> numArray; //an array of ints, size 10. this is CPP style array, it is 'safer' than C-style array. (someone correct me)
//get your 10 inputs.
cout << "Enter Number :";
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
}
int positive_count = 0;
int negative_count = 0;
int even_count = 0;
int odd_count = 0;
//loop thru your 10 inputs, increment counters accordingly.
for(size_t i = 0; i < numArray.size(); i++)
{
if (numArray[i] < 0)
{
negative_count += 1;
}
if (numArray[i] > 0)
{
positive_count += 1;
}
if (numArray[i] % 2 == 0)
{
even_count += 1;
}
else
{
odd_count += 1;
}
}
cout << "Positive Number " << positive_count << endl;
cout << "Negative Number " << negative_count << endl;
cout << "even number " << even_count << endl;
cout << "Odd number " << odd_count << endl;
return 0;
}

You could do it in input loop:
int positives = 0, zeros = 0, odds = 0;
int negatives = 0, evens = 0;
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
// increment number of odds
odds += numArray[i] & 0x1;
// odds += numArray[i] % 2;
// increment number of positives
positives += (numArray[i] > 0);
// positives += (numArray[i] > 0 ? 1 : 0);
// increment zeros
zeros += !(numArray[i] | 0);
}
evens = 10 - odds;
negatives = 10 - zeros - positives;
cout << "Positive count " << positives << endl;
cout << "Negative Number " << negatives << endl;
cout << "Even number " << evens << endl;
cout << "Odd number " << odds << endl;
and here is newbie friendly version:
int positives = 0, zeros = 0, odds = 0;
int negatives = 0, evens = 0;
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
// increment number of odds
if (numArray[i] % 2 == 1)
odds++;
if (numArra[i] == 0)
zeros++;
else if (numArray[i] > 0)
positives++;
}
evens = 10 - odds;
negatives = 10 - zeros - positives;
cout << "Positives " << positives << '\n';
cout << "Negatives " << negatives << '\n';
cout << "Evens " << evens << '\n';
cout << "Odds " << odds << '\n';

Related

Decimal point not displaying

I intend to let user key in positive integer value only but I realized that the output is wrong. For example largest value I entered is 100.6, the largest value displayed is only 100. I believe the problems come from atoi. Can anyone look at my code and tell me whats wrong?
#include<iostream>
#include<string>
using namespace std;
int main()
{
const int SIZE = 12;
string month[SIZE] = { "Jan", "Feb", "Mar","April","May","June","July","August","Sept","October","Nov","Dec"};
string highestMonth, lowestMonth;
char temp[SIZE];
double rainFall[SIZE], total = 0.0, average, highest, lowest;
bool flag;
int i = 0;
do{
flag = false;
cout << "Enter rainfall for " << month[i] << " : ";
cin >> temp;
for (int j = 0; j < strlen(temp); j++)
{
if (!isdigit(temp[j]))
{
if (temp[j] == '.')
continue;
cout << "Enter positive integer value only" << endl;
flag = true;
break;
}
}
if (flag == false)
{
rainFall[i] = atoi(temp);
total += rainFall[i];
i++;
}
} while (i < SIZE);
average = total / 12.0;
lowest = rainFall[0];
lowestMonth = rainFall[0];
for (int i = 1; i < SIZE; i++)
{
if (rainFall[i] < lowest)
lowest = rainFall[i];
lowestMonth = rainFall[i];
}
highest = rainFall[0];
highestMonth = rainFall[0];
for (int i = 1; i < SIZE; i++)
{
if (rainFall[i]>highest)
highest = rainFall[i];
highestMonth = rainFall[i];
}
cout << "Total rainfall:" << total << endl;
cout << "Average:" << average << endl;
cout << "Highest:" << highest << " in " << highestMonth << endl;
cout << "Lowest:" << lowest << " in " << lowestMonth << endl;
system("pause");
return 0;
}
atoi convert string representation of a number into an integer so "100.6" is converted into 100.
You can use atof
You set flag to true if the input has a decimal point and you have no code to process the decimal input whatsoever.
if (flag == false)
{
rainFall[i] = atoi(temp);
total += rainFall[i];
i++;
}
This code processes the input if flag is false, but there's no analogous code to handle decimals if flag is true.

Why is my function not working properly

My function that checks if numbers in the vector are even or odd doesn't work properly.
This function prints the numbers that i have typed in the vector and puts them in 2 categories EVENS/ODDS. But if i have a negative number there is a problem with the odds not printing it but evens work.
problematic code is here:
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1) // Here is the problem.
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
Or more exactly this line: if (new_v1.at(i) % 2 == 1)
It prints the numbers that are odd but only the positive ones not the negative ones.
But if i change it to if (new_v1.at(i) % 2 != 0) then it works correctly.
Why does that happen and is there a problem with the equal operator?
If yes then why are the evens getting printed even if they are negatives while still using the equal operator?
Code here for reference.
clude <iostream>
#include <vector>
using namespace std;
void fillVector(vector <int>&);
void printVector(const vector <int>&);
void printEvensAndOddsVector(const vector <int>&); // Prints Evens and Odds.
int main()
{
vector <int> v1;
fillVector(v1);
printVector(v1);
printEvensAndOddsVector(v1);
cout << "\n\n\n";
system( "pause");
return 0;
}
// Function Definitions
void fillVector(vector <int>& new_v1)
{
int number;
cout << "Type in numbers and type -100 to stop: ";
cin >> number;
while (number != -100)
{
new_v1.push_back(number);
cin >> number;
}
}
void printVector(const vector <int>& new_v1)
{
cout << "\nVector: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
cout << new_v1.at(i) << " ";
}
cout << " \n";
}
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
This line: if (new_v1.at(i) % 2 == 1). It prints the numbers that are odd but only the positive ones not the negative ones.
For negative n, n % 2 returns either 0 or -1 in C++. It never returns 1, so the condition cannot be true for negative inputs.
As you've discovered, comparing to zero would work.
See Modulo operator with negative values

the arrays won't add up the votes correctly?

I am writing a program that will tally votes from each counties up to 4 for two candidates. Basically it will ask you to add the votes in each counties for each candidate. Then it will tally the votes and display the winner. This mostly works but It won't add up the votes and declare the winner correctly? I suspect it is something wrong with the loop at line 37 to line 40.
#include<iostream>
using namespace std;
int tier1();
int main(void)
{
int return_val = tier1();
if (return_val < 0) // print an error
return 0;
}
int tier1(){
int votes[7];
int i, j, N; // variables
int k = 0;
for (i=0; i<4; i++)
{
cout << "county" << i << "\n"; // lists the 4 counties/candidates
for (j=0; j<2; j++)
{
cout << "How many votes did the candidate " << j << " get?\n";
N=0;
cin >> N;
votes[k++] = N;;
}
if (votes[k-2] + votes[k-1] > 100) //checking if it goes over 100 votes
{
cout << "County has too many votes. Exiting!\n"; // Print an error
exit(1);
}
}
int candidate0Votes = 0; //resetting
int candidate1Votes = 0;
for (i = 0; i < 7; i++)
{
cout << votes[i+1] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i+1];
candidate1Votes += votes[i+1];
}
if (candidate0Votes > candidate1Votes){
cout << "The winner of the election is candidate 0.\n";
}
else
{
cout << "The winner of the election is candidate 1.\n";
}
cout << "Here is the voting results:\n";
cout << "candidate 0 got ";
cout << candidate0Votes;
cout << " votes\n";
cout << "candidate 1 got ";
cout << candidate1Votes;
cout << " votes\n";
return 0;
}
Let me know if there is any other revision that I should do!
Thanks!
Your votes array is short.
It seems you have 4x2 entries, but the array is only 7 elements.
Here's a version that I could live with:
Live On Coliru
#include <iostream>
#include <numeric>
using namespace std;
int tier1();
int main(void) {
return tier1();
}
static int getnumber(std::string prompt) {
if (!std::cin)
return 0;
int i;
std::cout << prompt;
std::cin >> i;
while(!std::cin) {
if (std::cin.eof()) {
exit(1);
}
std::cin.clear();
std::cin.ignore(1<<30, '\n');
std::cout << prompt;
std::cin >> i;
}
return i;
}
#include <map>
#include <algorithm>
int tier1() {
using namespace std;
using county = int;
static constexpr int number_of_counties = 4;
static constexpr int number_of_candidates = 2;
map<county, size_t[number_of_candidates]> votes;
for (int cty = 0; cty < number_of_counties; cty++) {
for (int cand = 0; cand < number_of_candidates; cand++) {
votes[cty][cand] = getnumber("How many votes did the candidate " + to_string(cand) + " get in county " + to_string(cty) + "? ");
}
if (std::accumulate(begin(votes[cty]), end(votes[cty]), 0u) > 100)
cout << "County has too many votes. Exiting!\n"; // Print an error
}
size_t totals[number_of_candidates] = { 0 };
for(auto& cty: votes) {
for (auto in = begin(cty.second), accum = begin(totals); accum < end(totals);) {
*accum++ += *in++;
}
}
auto winner = max_element(begin(totals), end(totals));
cout << "The winner of the election is candidate " << distance(totals, winner) << "\n";
cout << "Here is the voting results:\n";
for (int cand = 0; cand < number_of_candidates; cand++) {
cout << "candidate " << cand << " got " << totals[cand] << " votes\n";
}
return 0;
}
In addition to sehe's observation, I also see you have the following:
for (i = 0; i < 7; i++)
{
cout << votes[i+1] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i+1];
candidate1Votes += votes[i+1];
}
This should probably be (after you make your array size 8):
// Loop through all countries
for (i = 0; i < 8; i = i + 2)
{
// Print out the candidate's votes per country
cout << votes[i] << "\n";
cout << votes[i+1] << "\n";
// Total up each candidate's votes
candidate0Votes += votes[i];
candidate1Votes += votes[i+1];
}
Here is an improved suggestion which structures the code in a way that makes more sense (altough my original suggestion is probably easier):
You could use a two dimensional array as follows:
int votes[2][4]; //Store the votes in the format [candidate 0 or 1][country 0 to 3]
The loop in question would then become:
// Loop through all countries
for (i = 0; i < 4; i++)
{
// Print out the candidate's votes per country
cout << votes[0][i] << "\n";
cout << votes[1][i] << "\n";
// Total up each candidate's votes
candidate0Votes += votes[0][i];
candidate1Votes += votes[1][i];
}
The rest of the code would need to be modified to adapt to that structure as well. Since this could be a bit confusing, I left it as a separate answer. It is probably a bit better way to structure the program, but my original answer should fix the problem.
I think this is what you want. The array size was changed to 8, and the for loop in line 37 to 40 was also modified.
#include<iostream>
using namespace std;
int tier1();
int main(void)
{
int return_val = tier1();
if (return_val < 0) // print an error
return 0;
}
int tier1(){
int votes[8];
int i, j, N; // variables
int k = 0;
for (i=0; i<4; i++)
{
cout << "county" << i << "\n"; // lists the 4 counties/candidates
for (j=0; j<2; j++)
{
cout << "How many votes did the candidate " << j << " get?\n";
N=0;
cin >> N;
votes[k++] = N;;
}
if (votes[k-2] + votes[k-1] > 100) //checking if it goes over 100 votes
{
cout << "County has too many votes. Exiting!\n"; // Print an error
exit(1);
}
}
int candidate0Votes = 0; //resetting
int candidate1Votes = 0;
for (i = 0; i < 8; i+=2)
{
cout << votes[i] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i];
candidate1Votes += votes[i+1];
}
if (candidate0Votes > candidate1Votes){
cout << "The winner of the election is candidate 0.\n";
}
else
{
cout << "The winner of the election is candidate 1.\n";
}
cout << "Here is the voting results:\n";
cout << "candidate 0 got ";
cout << candidate0Votes;
cout << " votes\n";
cout << "candidate 1 got ";
cout << candidate1Votes;
cout << " votes\n";
return 0;
}

Print an array in C++

I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}

Converting the bits of a vector to a decimal integer

I am trying to convert the bits of a vector into a decimal integer. My program is a variable linear feedback shift register. At first it asks the user for the length of the initial sequence of the LFSR, then it asks for the sequence itself and the position of the bits to be xored. So if I entered 4 for the length of the sequence, 1110 for the bit sequence and 20 for polynomial, the key is 0111100, it is stored in a vector keyReg, I tried converting it into a decimal number by using a for condition:
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(2^i);
cout << key << "\n";
}
}
But that is not producing the correct decimal equivalent to 0111100. What to do?
Here is the full program:
#include <iostream> //Standard library.
#include <boost/dynamic_bitset.hpp> //Library for 10 handling.
#include <vector> //Variable size array.
#include <algorithm> //We use sorting from it.
using namespace std;
int main()
{
int y = 0;
int turnCount = 0;
int count1 = 0, count0 = 0;
int xx = 0;
int polyLoc;
int key = 0;
boost::dynamic_bitset<> inpSeq(5);
boost::dynamic_bitset<> operSeq(5);
boost::dynamic_bitset<> bit(5);
vector <int> xorArray;
vector <int> keyReg;
cout << "What is the legnth of the sequence?";
cin >> xx;
inpSeq.resize(xx);
operSeq.resize(xx);
bit.resize(xx);
cout << "Enter a bit sequence: \n";
cin >> inpSeq;
int seq_end = inpSeq.size() - 1;
cout << "Enter polynomial:";
cin >> polyLoc;
while(polyLoc>0)
{
xorArray.push_back(polyLoc%10);
polyLoc/=10;
}
sort(xorArray.rbegin(), xorArray.rend());
cout << "\n";
operSeq = inpSeq;
keyReg.push_back(inpSeq[0]);
int x = xorArray[0];
do {
for (unsigned int r = 1; r < xorArray.size(); r++)
{
bit[seq_end] = operSeq[x];
y = xorArray[r];
bit[seq_end] = bit[seq_end] ^ operSeq[y];
}
operSeq >>= 1;
operSeq[seq_end] = bit[seq_end];
keyReg.push_back(operSeq[0]);
turnCount ++;
cout << operSeq << "\n";
}
while ((operSeq != inpSeq) && (turnCount < 1024));
cout << "Generated key is: ";
for (unsigned int k = 0; k < keyReg.size(); k++)
{
cout << keyReg[k];
}
cout << "\n";
cout << "Bit 1 positions: ";
for ( unsigned int g = 0; g < xorArray.size(); g++)
{
cout << xorArray[g];
}
cout << "\n";
cout << "Key length is: " << keyReg.size();
cout << "\n";
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
count1++;
}
else {
count0++;
}
}
cout << "Number of 0's: " << count0 << "\n";
cout << "Number of 1's: " << count1 << "\n";
if ( keyReg.size()%2 ==0)
{
cout << "key length is even. \n";
if (count1==count0)
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
else
{
cout << "key length is odd. \n";
if ((count1==count0+1) || (count0==count1+1))
{
cout << "Key is perfect! \n";
}
else {
cout << "Key is not perfect! \n";
}
}
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(2^i);
cout << key << "\n";
}
}
cout << "Key is " << key << "\n";
cin.get();
}
I think you meant:
for ( unsigned int i = 0; i < keyReg.size(); i++)
{
if (keyReg[i]==1)
{
key = key+(1 << i); // this is 2^i
cout << key << "\n";
}
}
^ is a bitwise operator for XOR so the code was "valid" from the compiler's point of view.
Why it works:
I cannot find a relevant question but "(1 << i)" was explained somewhere else. 1 is treated as an integer. Then operator<< on integer is a bitwise left shift (by i places).
So it makes 000001 and shifts it left, e.g. when i is 3 it produces 001000. Effectively producing 2^i integer.
Of course one could use something more explicit, however std::pow is defined only for floating point types, so one would need to use some conversions.
(1 << i) also poses some safety concerns. You need to take care of the type of the values you use for shifting (their size), and value you use for shifting, writing (1<<128) might give some unexpected results. Anyway it is the best way to get 2^i for most cases IMO.