I am solving the following simple problem(on one of OnlineJugde sites which is in Russian, so I won't give a link here:). It is easier to state the problem via an example than definition.
Input:
10 // this is N, the number of the integers to follow
1 1 1 2 2 3 3 1 4 4
Output:
3 times 1.
2 times 2.
2 times 3.
1 times 1.
2 times 4.
Constraints:
All the numbers in the input(including N) are positive integer less than 10000.
Here is the code I got Accepted with:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
while(n --> 0) // do n times
{
cin >> currentNumber;
if(currentNumber != prevNumber)
{
if(currentCount != 0) //we don't print this first time
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else //if(currentNumber == prevNumber)
{
++currentCount;
}
}
cout << currentCount << " times " << prevNumber << "." << endl;
}
Now here's my problem. A little voice inside me keeps telling me that I am doing this line two times:
cout << currentCount << " times " << prevNumber << "." << endl;
I told that voice inside me that it might be possible to avoid printing separately in the end. It told me that there would then be perhaps way too many if's and else's for such a simple problem. Now, I don't want to make the code shorter. Nor do I want do minimize the number of if's and else's. But I do want to get rid of the special printing in the end of the loop without making the code more complicated.
I really believe this simple problem can be solved with simpler code than mine is. Hope I was clear and the question won't be deemed as not constructive :)
Thanks in advance.
i came up with this. no code duplication, but slightly less readable. Using vector just for convenience of testing
EDIT my answer assumes you know the numbers ahead of time and not processing them on the fly
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(3);
numbers.push_back(1);
numbers.push_back(4);
numbers.push_back(4);
for (int i=0; i<numbers.size(); i++)
{
int count = 1;
for (int j=i+1; j<numbers.size() && numbers[i] == numbers[j]; i++, j++)
{
count++;
}
cout << count << " times " << numbers[i] << "." << endl;
}
My version: reading the first value as a special case instead.
#include <iostream>
int main()
{
int n;
std::cin >> n;
int value;
std::cin >> value;
--n;
while (n >= 0) {
int count = 1;
int previous = value;
while (n --> 0 && std::cin >> value && value == previous) {
++count;
}
std::cout << count << " times " << previous << ".\n";
}
}
Run your loop one longer (>= 0 instead of > 0), and in the last round, instead of reading currentNumber from cin, do currentNumber = lastNumber + 1 (so that it's guaranteed to differ).
slightly more CREATIVE answer, this one does not make assumption about input being all known before the start of the loop. This prints the total every time, but makes use of \r carriage return but not line feed. A new line is inserted when a different number is detected.
int prev_number = -1;
int current_number;
int count = 0;
for (int i=0; i<numbers.size(); i++)
{
current_number = numbers[i];
if (current_number != prev_number)
{
count = 0;
cout << endl;
}
count++;
prev_number = current_number;
cout << count << " times " << numbers[i] << "." << "\r";
}
only problem is that the cursor is left on the last line. you may need to append cout << endl;
I think this will work:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
int i = 0;
while(i <= n)
{
if(i != n) cin >> currentNumber;
if(currentNumber != prevNumber || i == n)
{
if(currentCount != 0)
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else
{
++currentCount;
}
i++;
}
}
I would use a for loop, but I wanted to stay as close to the original as possible.
Related
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;
}
My program has to count how many numbers in a range are even and how many of them are odd but I can't seem to figure it out.It kinda works
but when I put numbers in it spouts out nonsense. I'm an extreme nooob when it comes to programing, I think that the problem has to be at line 21 for (i=n; i<=m; i++) { ?
But I'm not sure. I have a programing book but it does not help much,maybe someone can help?
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i;
}
else {
b=b+i;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
Assuming you mean even and odd numbers your problem lies in this code:
for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i; // increase number of even numbers by i
}
else {
b=b+i; // increase number of odd numbers by i
}
}
What you might want do to do is add 1 (instead of whatever i is):
for (i = n; i <= m; ++i) {
if (i % 2 == 0)
++a; // increase number of even numbers by one
else
++b; // increase number of odd numbers by one
}
Also I'd suggest using better variable names, for example even and odd instead of a and b and so on. It makes code easier to understand for everybody, even for you.
Just a little more tips. Assigning variables as soon as you declare them is good practice:
int m = 0;
You can declare variable inside of for loop, and in your case there is no need to declare it out of it:
for (int i = n; i <= m; ++i) { ... }
Example how it can change look and clarity of your code:
#include <iostream>
using namespace std;
int main() {
int from = 0,
to = 0,
even = 0,
odd = 0;
cout << "Enter a number that begins interval: ";
cin >> from;
cout << "Enter a number that ends interval: ";
cin >> to;
for (int i = from; i <= to; ++i) {
if (i % 2 == 0)
++even;
else
++odd;
}
cout << " even numbers: " << even << endl;
cout << " odd numbers: " << odd << endl;
return 0; // don't forget this! main is function returning int so it should return something
}
Ok, so as per the new clarification the following should work
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;
for (i=n; i<=m; i++) {
if (i%2 == 0){
a++;
}else {
b++;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
So the following changes were done:
The for loop was closed
a = a + i or b = b + i was wrong as you are adding the counter value to the count which should be a++ or b++. Changed that also
The last two lines where you are showing your result was out of the main method, brought them inside the main method
Hope you find this useful.
You don't need to use loop to count even and odd numbers in a range.
#include <iostream>
int main ()
{
int n,m,even,count;
std::cin >> n >> m;
count=m-n+1;
even=(count>>1)+(count&1 && !(n&1));
std::cout << "Even numbers: " << even << std::endl;
std::cout << "Odd numbers: " << count-even << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
int n, i;
cin >> n;
cout << " even : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 == 0)
cout << i << " ";
}
cout << " odd : ";
for (i = 1; i <= n * 2; i++)
{
if (i % 2 != 0)
cout << i << " ";
}
return 0;
}
//input n = 5
// output is even : 2 4 6 8 10
// odd : 1 3 5 7 9
#include <iostream>
using namespace std;
int main()
{
int n;
int m;
int i;
int a;
int b;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a = 0;
b = 0;
for (i = n; i < = m; i++) {
if (i%2 == 0){
a = a + 1;
} else {
b = b + 1;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;
}
Not sure why you are looping through all the elements (half of them are going to be even and the other half odd). The only case where you have to consider when the interval length is not divisible by two.
using namespace std;
int main()
{
int n;
int m;
int x;
int odds;
int evens;
cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
cout << n << " " << m << endl;
x = m - n + 1;
odds = x / 2;
evens = odds;
if (x % 2 != 0) {
if (n % 2 == 0) {
evens++;
} else {
odds++;
}
}
cout << " even numbers: " << evens << endl;
cout << " odd numbers: " << odds << endl;
}
This is a more readable version of #Lassie's answer
So, I'm creating a coin change algorithm that take a Value N and any number of denomination and if it doesn't have a 1, i have to include 1 automatically. I already did this, but there is a flaw now i have 2 matrix and i need to use 1 of them. Is it possible to rewrite S[i] matrix and still increase the size of array.... Also how can i find the max denomination and the second highest and sooo on till the smallest? Should i just sort it out in an highest to lowest to make it easier or is there a simpler way to look for them one after another?
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
You could implement it with std::vector, then you only need to use push_back.
std::sort can be used to sort the denominations into descending order, then it's just a matter of checking whether the last is 1 and adding it if it was missing. (There is a lot of error checking missing in this code, for instance, you should probably check that no denomination is >= 0, since you are using signed integers).
#include <iostream> // for std::cout/std::cin
#include <vector> // for std::vector
#include <algorithm> // for std::sort
int main()
{
std::cout << "Enter the value N to produce:\n";
int N;
std::cin >> N;
std::cout << "Enter the number of different denominations:\n";
size_t denomCount;
std::cin >> denomCount;
std::vector<int> denominations(denomCount);
for (size_t i = 0; i < denomCount; ++i) {
std::cout << "Enter denomination #" << (i + 1) << ":\n";
std::cin >> denominations[i];
}
// sort into descending order.
std::sort(denominations.begin(), denominations.end(),
[](int lhs, int rhs) { return lhs > rhs; });
// if the lowest denom isn't 1... add 1.
if (denominations.back() != 1)
denominations.push_back(1);
for (int coin: denominations) {
int numCoins = N / coin;
N %= coin;
if (numCoins > 0)
std::cout << numCoins << " x " << coin << '\n';
}
return 0;
}
Live demo: http://ideone.com/h2SIHs
I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}
I'm taking my first programming course and am new to this forum. Any help will be greatly appreciated! For one of my class assignments I had to write a program that would find the factors of a given number, I've got the program up and running but one of the stipulations is that the output must be displayed four to a line and that's where I'm running into trouble. I've read around on some other forums as well as here but I guess I'm not grasping what I would have to do in my particular case.
Here's my code as is:
#include <iostream>
using namespace std;
int main(){
int n;
while (cout << "Please enter a number: " && !(cin >> n) || (n < 0.0) || cin.peek() != '\n')
{
cout << "Input must be a positive number!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
for (int i=2; i <= n; i++)
{
while (n % i == 0)
{
n /= i;
cout << "*" << i;
}
}
cout << endl;
system ("PAUSE");
return 0;
}
You're going to need to add a counter outside the loop.
//int counter = 0;
for (int i=2; i <= n; i++)
{
while (n % i == 0)
{
n /= i;
cout << "*" << i;
}
}
The counter will need to keep track of how many entries have been printed.
Once you have seen 4 entries printed:
print an extra newline
and set the counter back to 0
You may use the following:
void display_factors(std::size_t n, std::size_t factor_by_line)
{
const char* sep = "";
std::size_t count = 0;
std::cout << n << " = ";
for (int i = 2; i <= n; ++i) {
while (n % i == 0) {
n /= i;
if (count == factor_by_line) {
std::cout << std::endl;
count = 0;
}
++count;
std::cout << sep << i;
sep = " * ";
}
}
std::cout << std::endl;
}
Live Demo