How to fix this pyramid pattern in C++? - c++

I'm trying to make this output:
This is my code, what I have so far:
#include <iostream>
using namespace std;
int main() {
int number;
bool flag;
do {
cout << "\t\t\Menu\n";
cout << "Enter a number between 6 and 12.\n";
cin >> number;
if (number > 5 && number < 13) {
flag = true;
for(int index = 1; index <= number; ++index) {
//Loop for spaces.
for(int spaces = index; spaces < number; ++spaces) {
cout << " ";
}
//Loop for numbers.
int counter = index;
int counter2 = 1;
for(int index2 = 1; index2 <= (2 * index - 1); ++index2) {
if (counter > 0) cout << counter--;
else cout << ++counter2;
}
cout << "\n";
}
} else cout << "Enter a valid number!\n";
} while (!flag);
return 0;
}
My output:
How to fix my output with proper spaces, I tried to concatenate with spaces but it doesn't fit good, how to fit it properly?

First, you want to output a few more spaces here:
for(int spaces = index; spaces < number; ++spaces) {
cout << " ";
}
To handle different number length well, I suggest C++'s equivalent of printf() and format string, cout << setw():
#include <iomanip>
cout << setw(4) << number;
... or just use printf:
printf("%4d", number);

Related

Reversing the order of a for loop output

I am currently writing a task where the user will input a number and it'll output a number of "*" depending on the number. Eg if the user inputted a 5, the answer would be:
*
**
***
****
*****
This is my current code:
#include <iostream>
using namespace std;
int number;
char star = '*';
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
for (int i = 0; i < number; i++)
{
for (int j = i; j < number; j++)
{
cout << star;
}
cout << " " << endl;
}
return 0;
}
If the number 5 was inputted, this would output:
*****
****
***
**
*
How would I go about reversing the order so that it is ascending order rather than descending.
You would need to use the for loop in descending instead of ascending order.
Example:
cout << "Input a number between 1 and 10" << endl;
cin >> number;
for (int i = number -1; i >= 0; i--) {
for (int j = i; j < number; j++) {
cout << star;
}
cout << "*" << endl;
}
return 0;
}
You can do that by just reversing the order of the change of i:
#include <iostream>
using namespace std;
int number;
char star = '*';
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
//for (int i = 0; i < number; i++)
for (int i = number - 1; i >= 0; i--)
{
for (int j = i; j < number; j++)
{
cout << star;
}
cout << "*" << endl;
}
return 0;
}
(Just how to reverse the order of the change of i is shown. The output of this program is not as expected.)
My preference is using i as the number of stars to print and avoiding using gloval variables and using namespace std;:
#include <iostream>
int main()
{
int number;
char star = '*';
std::cout << "Input a number between 1 and 10" << std::endl;
std::cin >> number;
for (int i = 1; i <= number; i++)
{
for (int j = 0; j < i; j++)
{
std::cout << star;
}
std::cout << std::endl;
}
return 0;
}
Just go from number all the way down instead of up:
for (int i = number; i > 0; i--)
{
for (int j = i; j > 0; j--)
{
cout << star;
}
std::cout << '\n';
}
Instead of j<number use j<i and instead of j=i use j=0:
#include <iostream>
using namespace std;
int number;
char star = '*';
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
for (int i = 0; i < number; i++)
{
for (int j = 0; j < i; j++)
{
cout << star;
}
cout << "*" << endl;
}
return 0;
}
there are multiple ways to achieve what you want. You can insert everything inside and array and print the array backwards, insert everything inside an array (starting from last position) and then print it in natural order, you can do it only by using indexes (like i and a lot of other persons did here). I also added a little input check, and put the code in functions for clearness:
#include <iostream>
using namespace std;
int number;
char star = '*';
void version1();
void version2();
int main()
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
while(number < 1 || number > 10)
{
cout << "I SAID BETWEEN 1 AND 10, IS EASY, RIGHT?" << endl;
cin >> number;
}
version1();
version2();
return 0;
}
void version1()
{
cout <<"Version 1: "<<endl;
for (int i = 0; i < number; i++)
{
for (int j = i; j < number; j++)
{
cout << star;
}
cout << endl;
}
}
void version2()
{
cout << "Version 2: (only by using indexes)" << endl;
int cap_index = 0;
for (int i = 0; i < number; i++)
{
cap_index = i + 1;
for (int j = 0; j < cap_index; j++)
{
cout << star;
}
cout << endl;
}
}
btw this is a more serious (and simple) way to check input:
do
{
cout << "Input a number between 1 and 10" << endl;
cin >> number;
}while(number < 1 || number > 10);
In my case i put it this way:
starting from 0 print '*' up to i + 1 times, this way you have an ascending order print:
first time (from 0 to 1) print '*' -> print once
second time (from 0 to 2) print '*' -> prints twice
and so on up to the inserted number
Obviously this isn't not the best way to do this nor the most elegant, like in nearly every situation there are a lot of possibilities.
ps. i'm not sure, but you have an error in your code, as it prints a '*' more, each time, i don't know how is your output like that
By using a std::string, you can avoid the need of an explicit inner loop.
#include <iostream>
#include <string>
int main()
{
int number;
char star = '*';
std::cout << "Input a number between 1 and 10" << "\n";
std::cin >> number;
for (int i = 0; i < number; i++)
{
std::cout << std::string (i+1, star) << "\n";
}
return 0;
}
Changing the second 'for' loop condition, in your function --
From,
for (int j = i; j < number; j++)
Change it to ,
for (int j = 0; j <= i; j++)

Using an Array[10] and incrementing it with a While loop using modulo 10 to Pair User inputs together

#include <iostream>
using namespace std;
int main()
{
long int number;
int digits;
cout << "Enter Number: ";
cin >> number;
int counter[10] = { 0,0,0,0,0,0,0,0,0,0 };
while (number != 0) {
digits = number % 10;
counter[digits] = counter[digits] + 1;
number = number / 10;
}
for (int i = 0; i<10; i++) {
if (counter[i] != 0) {
cout << i << ": " << counter[i] << endl;
}
}
return 0;
system("pause");
}
I'm having an issue with my code that when I run it and enter a Number nothing really happens. It is supposed to run something like 1234556789 and the output should look like
1 : 9
2 : 8
3 : 7
4 : 6
5 : 5
I know sometimes if there isn't a system pause this happens where it runs part of the code and just ends, but I'm not sure whats wrong here.
#include <iostream>
using namespace std;
int main()
{
long int number;
int digits;
cout << "Enter Number: ";
cin >> number;
int counter[10]={0},a=0;
while (number != 0) {
digits = number % 10;
counter[a] = digits; //made changes to this line
number = number / 10;
++a;
}
for (int i = 0; i<10; i++) {
if (counter[i] != 0) {
cout << i << ": " << counter[i] << endl;
}
}
return 0;
}
All you are doing right now is printing how many digits there are of each number 0-9 in the number. If you want to pair elements together, then you can use std::vector and iterators. The number of digits in your input can be either even or odd and you would have to account for both cases.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
long int number;
cout << "Enter Number: ";
cin >> number;
vector<int> digits;
if (number == 0)
{
digits.push_back(number);
}
while (number != 0)
{
digits.push_back(number % 10);
number /= 10;
}
auto it_begin = digits.begin();
auto it_end = digits.end() - 1;
if (digits.size() % 2 == 1)
{
for (; it_end != it_begin; ++it_begin, --it_end)
{
cout << *it_end << ": " << *it_begin << endl;
}
cout << *it_end << endl;
}
else
{
for (; it_begin < it_end; ++it_begin, --it_end)
{
cout << *it_end << ": " << *it_begin << endl;
}
}
}
With number = 1234556789, the output is:
1: 9
2: 8
3: 7
4: 6
5: 5
If you want first 10 no. Only use this code
include using namespace std;int main() {long int number;cout << "Enter Number: ";cin >> number;for (int i = 1; i<=10; i++) {cout << i << ": "<

How do you get cin to only accept numbers from user input? [duplicate]

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 !";
}

How do I make this program to list out if I have entered two consecutive zeros?

#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;

how to process an array of even numbers from a users input and display them with spaces in C++

I need help with getting this users input of an integer and retrieving the even numbers and displaying them with spaces.I already have the input processed into an array and have it reversed (thanks to stackoverflow) now need to extract the even numbers from the array and display them.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int evenNumbers(char even[], int num[], int indexing[]);
int main()
{
char integers[5];
int numbers[5];
int even[5] = {0,2,4,6,8};
int evens;
cout << "Please enter an integer and press <ENTER>: " << endl;
for (int j = 0; j < 5; j++)
cin >> integers[j];
for (int j = 0; j < 5; j++)
{
numbers[j]= integers[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << integers[j - 1] << " ";
}
cout << endl;
//having problems finding the even numbers and displaying the even numbers
//from the users input of integers, i have only learned how to display the
//subscript by a linear search
evens = evenNumbers(integers, numbers, even);
if (evens == -1)
cout << "There are no even numbers" << endl;
else
{
cout << "The even numbers are: " << (evens + 1) << endl;
}
system("pause");
return 0;
}
int evenNumbers(char even[], int num[], int indexing[])
{
int index = 0;
int position = -1;
bool found = false;
for (int j = 0; j < 5; j++)
{
num[j]= even[j] - '0';
}
while (index < 5)
{
if (num[index] == indexing[index])
{
found = true;
position = index;
}
index++;
}
return position;
}
If you want to display the even numbers from the array integers you can use a simple for loop and if statement:
for(int i = 4; i >= 0; i--)
{
if(integers[i] % 2 == 0)
cout << integers[i] << " ";
}
Your approach is all wrong, you can't detect even numbers by searching a list, you need a mathematical test for evenness. Write a function called is_even which tests one number and returns true if it is even and false if it is not. Then you can use that function, very simply, like this
for (int j = 0; j < 5; j++)
{
if (is_even(integers[j]))
cout << integers[j] << " ";
}
cout << endl;
Now you just need to write the is_even function.
void evennumbers(int num[])
{
for(int i=0;i<5;i++)
{
if(num[i]%2==0)
cout<<num[i]<<" ";
}
}
And avoid taking input to char what if user enters a number with more than one digit
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
void validNum(char valid[]);
void reverseNum(char rev[], int num2[]);
void evenNumbers(char even[], int num3[]);
void oddNumbers(char odd[], int num4[]);
int main()
{
char integer[5];
int number[5];
cout << "Your number is: ";
validNum(integer);
cout << "Your number in reverse is: ";
reverseNum(integer, number);
cout << "Even numbers: ";
evenNumbers(integer, number);
cout << endl;
cout << "Odd numbers: ";
oddNumbers(integer, number);
cout << endl;
system("pause");
return 0;
}
void validNum(char valid[])
{
char ch;
cout << "Please enter an integer and press <ENTER>: " << endl;
ch = cin.get;
while (ch < 0 || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
{
cout << "ERROR: Please enter a positive integer and press <ENTER>: ";
for (int i = 0; i < 5; i++)
cin >> valid[i];
}
for (int j = 0; j < 5; j++)
{
cout << valid[j] - '0';
}
}
void reverseNum(char rev[], int num2[])
{
for (int j = 0; j < 5; j++)
{
num2[j]= rev[j] - '0';
}
cout << endl;
for (int j = 5; j > 0; j--)
{
cout << rev[j - 1]<< " ";
}
cout << endl;
}
void evenNumbers(char even[], int num3[])
{
for (int i = 0; i < 5; i++)
{
if (even[i] % 2 == 0)
{
cout << num3[i] << " ";
}
}
}
void oddNumbers(char odd[], int num4[])
{
for (int i = 0; i < 5; i++)
{
if (odd[i] % 2 == 1)
{
cout << num4[i] << " ";
}
}
}