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
Related
I have a problem with this piece of code, I'm trying to print the EVEN and ODD numbers, but there is a problem when it comes to show them, the vectors don't save the numbers as I'm expecting.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n]; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[i] = vect[i]; // I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[i] == vect[i];
}
}
for(int i = 1; i <= n; ++i) {
cout << even[i] << " " << endl; /// PRINTING THE ODD AND EVEN numbers.
cout << odd[i] << " " << endl;
}
return 0;x
}
I have fixed the problem, thanks all for help.
Now it works perfectly.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n], z = 0, x = 0; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[1+z] = vect[i];
z++;
// I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[1+x] = vect[i];
x++;
}
}
for(int i = 1; i <= x; i++) {
cout << even[i] << " ";
}
cout << endl;
for(int i = 1; i <= z; i++) {
cout << odd[i] << " ";
}
return 0;
}
Considering the hints of the comments, your program shall be changed into this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, number;
cin >> n;
vector<int> vect, even, odd; // CREATING DYNAMIC VECTORS
for(int i = 0; i < n; ++i) { // ENTERING THE ELEMENTS IN VECTOR
cin >> number;
vect.push_back(number);
}
for(int i = 0; i < n; ++i) {
if(vect[i] % 2 != 0) { /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
odd.push_back(vect[i]);
}
else {
even.push_back(vect[i]);
}
}
for (int i = 0; i < n; ++i)
cout << vect[i] << " ";
cout << endl;
/// PRINTING THE ODD AND EVEN NUMBERS.
for (auto& val : odd)
cout << val << " ";
cout << endl;
for (auto& val : even)
cout << val << " ";
cout << endl;
return 0;
}
It uses the vector container of STL for your arrays, start the indexing at 0 and prints out the resulting arrays separately, as the number of odd and of even entries might be different.
Hope it helps?
With standard, you might use std::partition (or stable version) to solve your problem:
void print_even_odd(std::vector<int> v)
{
auto limit = std::stable_partition(v.begin(), v.end(), [](int n){ return n % 2 == 0; });
std::cout << "Evens:";
// Pre-C++20 span:
// for (auto it = v.begin(); it != limit; ++it) { int n = *it;
for (int n : std::span(v.begin(), limit)) {
std::cout << " " << n;
}
std::cout << std::endl;
std::cout << "Odds:";
for (int n : std::span(limit, v.end())) {
std::cout << " " << n;
}
std::cout << std::endl;
}
Demo
I am having troubles with some of the inputs for my addition/multiplication table, and am hoping to find some help towards fixing this. I will begin by posting what I have for the program.
The code is as follows :
#include <iostream>
using namespace std;
void die() {
cout << "BAD INPUT!" << endl;
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
cout << "Choose:\n";
cout << "1. Addition Table\n";
cout << "2. Times Table\n";
cin >> choice;
if (!cin) die();
if (choice != ADD and choice != MULTIPLY) die();
cout << "Please enter the smallest number on the table:\n";
cin >> min;
if (!cin) die();
cout << "Please enter the largest number on the table:\n";
cin >> max;
if (!cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
cout << '+';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
cout << '\n';
}
}
if (choice == MULTIPLY) {
for (int i = min; i <= max; i++) {
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
cout << '\n';
}
}
}
Now, here are the mistakes that I am getting from this code that I cannot seem to resolve. First, when doing the MUlTIPLY table with min = 1, max = 1, I am getting:
X 1
when I should be getting (I believe)
X 1
1 1
Secondly, while doing the MULTIPLY table with min = 1, max = 12, I am getting:
X 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
when I should be getting
X 1 2 3 4 ... 12
1 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
And finally, when using the ADD table with min = 21, max = 40, I cannot post all of the code since it is such a mess, but basically the columns/rows are as follows:
+ 21 22 23 24 25 ...
5
1
6
2
7
3
8
When obviously, the code should output the rows and columns to be 21 - 40 evenly. As you can see in the last example, my rows are outputting properly, but somehow my columns are a complete, garbled mess.
I have been sitting and staring at this code for awhile, and can't seem to fix these issues at hand. Can anyone help lead me in the right direction? I really appreciate any help and hints :)
Check this out. Might not be fully optimized, but works
if (choice == ADD) {
cout << '+';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
}
}
if (choice == MULTIPLY) {
cout << 'X';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
}
}
See output here.
#include <iostream>
#include <iomanip>
#include <cstdio>
void die()
{
std::cout << "BAD INPUT!" << "\n";
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
std::cout << "Choose:\n";
std::cout << "1. Addition Table\n";
std::cout << "2. Times Table\n";
std::cin >> choice;
if (!std::cin) die();
if (choice != ADD and choice != MULTIPLY) die();
std::cout << "Please enter the smallest number on the table:\n";
std::cin >> min;
if (!std::cin) die();
std::cout << "Please enter the largest number on the table:\n";
std::cin >> max;
if (!std::cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
printf(" +");
else
printf("%3d", i);
printf(" ");
for (int j = min; j <= max; j++) {
printf("%3d ", i + j);
}
printf("\n");
}
}
if (choice == MULTIPLY) {
/* for printing header of the multiplication table */
std::cout << "X\t";
for (int j = min; j <= max; j++) {
std::cout << min * j << "\t";
}
std::cout << "\n";
/* for printing rest of the table */
for (int i = min; i <= max; i++) {
std::cout << i << "\t";
for (int j = min; j <= max; j++) {
std::cout << i * j << '\t';
}
std::cout << '\n';
}
}
}
The crucial mistake in your code for multiplication was that, you were trying to print (max - min + 1) + 1 rows in total, the extra +1 for the header. While your code was printing the first row as header and then starting directly with the second row.
Your code for addition table was correct, but 21 to 40 with tab character in between was too taking too much space for a typical laptop screen, not to say the output won't be pretty.
On my system, the output of tput lines and tput cols was 38 and 144 resp.
which wasn't sufficient for your code.
you can format the output with printf using printf fixed width output.
Considering you are not much familiar with C++, I would like to state that
using the std namespace as default namespace will work for this program, but when you working with larger projects, you should always prefix it.
I haven't enough reputation to add comment
if I were, I was commenting these lines
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';
This question already has answers here:
How to make cin take only numbers
(2 answers)
Closed 6 years ago.
So the requirements for this program is to be able to increment arrays of the same size (size from 5 to 15 indexes) and increment each element in the array by one using for and while loops. The last task is to take values from the first array and put them in reverse order and assign them to the second array.
So everything works as normal, and the program rejects invalid inputs and does not go into an infinite loop. However, the program accepts some inputs that are not wanted.
For example, I would input something like '12 a' or '7 asdfkla;j lasnfg jasklgn asfg' and it would go through. It is interesting too because the code registers only 12 or 7 and completely ignores the rest. I think it is because once it hits a non-integer character, it would stop ignore the rest.
Why is it ignoring the rest of the input? And is there a way to catch this error from going through?
Also, if you see anything that catches your eye, feel free to critique c: I am always looking to improving.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int x;
int j = 0;
bool not_valid = true;
system("color f");
cout << "Program will ask for an input for the size of an array.\n"
<< "With the array size defined, program will generate semi-\n"
<< "true random integers from 0 to 8. First array will then\n"
<< "be assigned to the second in reverse (descending) order.\n\n";
do {
cout << "Enter array size (0 - 15): ";
cin >> x;
if (x >= 5 && x <= 15) {
not_valid = false;
cout << "\nArray size: " << x << endl;
}
else {
cout << "Invalid input.\n\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
} while (not_valid);
int *arr0;
int *arr1;
arr0 = new int[x];
arr1 = new int[x];
for (int i = 0; i < x; i++) {
arr0[i] = rand() % 9;
}
for (int i = 0; i < x; i++) {
arr1[i] = rand() % 9;
}
cout << "\nARRAY 0 (unmodified, for):\n";
for (int i = 0; i < x; i++) {
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 0 (modified, for):\n";
for (int i = 0; i < x; i++) {
arr0[i]++;
cout << arr0[i] << "\t";
}
cout << "\n\nARRAY 1 (unmodified, while):\n";
for (int i = 0; i < x; i++) {
cout << arr1[i] << "\t";
}
cout << "\n\nARRAY 1 (modified, while):\n";
while (j < x) {
arr1[j]++;
cout << arr1[j] << "\t";
j++;
}
int second = x - 1;
for (int i = 0; i < x; i++) {
arr1[second] = arr0[i];
second--;
}
j = 0;
cout << "\n\nARRAY 1 (array 0, descending):\n";
while (j < x) {
cout << arr1[j] << "\t";
j++;
}
cout << endl << endl;
system("pause");
return 0;
}
Take input in string and then check if it's a number or not.
Example:
#include<iostream>
#include<sstream>
#include <string>
using namespace std;
int main()
{
string line;
int n;
bool flag=true;
do
{
cout << "Input: ";
getline(cin, line);
stringstream ss(line);
if (ss >> n)
{
if (ss.eof())
{
flag = false;
}
else
{
cout << "Invalid Input." << endl;
}
}
}while (flag);
cout << "Yo did it !";
}
#include <iostream>
using namespace std;
int main ()
{
int A[20], i, k;
cout << "Write 20 random numbers: "<<endl;
for(i=0; i<20; i++){
cout << "A[" << i << "]: ";
cin >> A[i];
}
k=0;
if (i+1 == k){
cout << "The program has two consecutive zeros";
}
else if (i+1 != k){
cout << "The program doesn't own two consecutive zeros";
}
char ch1;
cin>>ch1;
return 0;
}
This is my code but I don't know how to configure out the if to show me a message first, if there are two zeros, and second if there aren't. If there are, I need to make it so the numbers on which these zeros are shown. I'm a student please help, I really have no idea how to do it
I did it for the most part. Thank you everyone for your help! What's left now is to make it so it shows to which respective numbers the zeros are. How do I do that? I did as varleti suggested but it only shows 20 and 21
You already have a loop that you use to collect the data.
cout << "Write 20 random numbers: "<< endl;
for(i=0; i<20; i++) {
cout << "A[" << i << "]: ";
cin >> A[i];
}
You have collected the data into a 20 element array A[20].
You need to walk through the array again and test the values for 2 consecutive zeros.
two_zeros = 0;
for(i=1; i<20; i++) { // Note, starting from element [1]
if( A[i] == 0 && A[i-1] == 0 ) { // Test this and previous element for zeroness
two_zeros = 1;
}
}
if( two_zeros == 1 ) {
cout << "The program has two consecutive zeros";
} else {
cout << "The program doesn't own two consecutive zeros";
}
See this code snippet:
#include <iostream>
using namespace std;
int main ()
{
int A[20], i, k;
cout << "Write 20 random numbers: "<<endl;
for(i=0; i<20; i++){
cout << "A[" << i << "]: ";
cin >> A[i];
}
int count = 0; /* To count number of consecutive zeroes */
int flag = false; /* check wheather consecutive zeroes are found or not */
for(i=0; i<20; i++) {
if(A[i] == 0) {
count++;
if(count == 2) {
flag = true;
cout << "The program has two consecutive zeros" << endl;
break;
}
} else {
count = 0;
}
}
if(flag == false) {
cout << "The program doesn't own two consecutive zeros";
}
return 0;
}
Let me know, if having any doubt regarding anything.
You don't need any array, you only need to remember whether the last number you read was zero.
int main ()
{
bool last_zero = false;
bool two_zeros = false;
cout << "Write 20 random numbers: "<<endl;
for(int i = 0; i < 20; i++){
int x = 0;
cin >> x;
if (x == 0)
{
if (last_zero)
{
two_zeros = true;
}
last_zero = true;
}
else
{
last_zero = false;
}
}
if (two_zeros){
cout << "The program has two consecutive zeros";
}
else {
cout << "The program doesn't own two consecutive zeros";
}
}
#include <iostream>
using namespace std;
int main ()
{
int A[20], i, k=0;
cout << "Write 20 random numbers: "<<endl;
cout << "A[0]";
cin >> A[0];
for(i=1; i<20; i++)
{
cout << "A[" << i << "]: ";
cin >> A[i];
if( A[i] == 0 && A[i-1] == 0 )
{
cout << "The program has two consecutive zeros";
k=1;
break;
}
}
if(k==0)
cout << "The program hasn't two consecutive zeros";
return 0;
}
int count = 0;
for (int j = 0; j<20 - 1; j++)
{
if (arr[j] == 0 && arr[j + 1] == 0)
{
count++;
break;
}
}
if (count == 1)
{
cout << found;
}
else
cout << not found;
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.