Printing a hollow right-triangle - c++

I'm having issues with this c++ code. It is supposed to print a hollow right isosceles triangle, but instead just prints asterisks over and over, so the for loops seem to be stuck.
#include "pch.h"
#include <string>
#include <iostream>
int main() {
int row;
std::string s = " ";
std::string a = " *";
int rows = 10;
for (int i = 0; i < rows; i++) {
if (i = 0) {
std::cout << a << std::endl;
}
while (i > 2 && i < rows) {
std::cout << a;
for (int pos = 0; pos < i; pos++) {
std::cout << s;
}
std::cout << a << std::endl;
}
std::cout << a << a << a << a << a << a << a << a << a << std::endl;
}
}

your while loop condition will never become false, AND you need to use comparison (==) instead of assignment in this line:
if (i = 0) {

Supposing that what you want to print is something of the following form:
Eg. for rows = 5
*
**
* *
* *
*****
Your code should have the following structure:
for (int i = 1; i <= rows; ++i)
{
//special case for the first line
if (i == 1)
std::cout << asterisk << std::endl;
//for each of the other lines print 2 asterisks and the rest spaces
if (i > 1 && i <= rows - 1)
{
//one at the start of the line
std::cout << asterisk;
//print line - 2 spaces
for (int j = 0; j < i - 2; ++j)
std::cout << space;
//one at the end of the line
std::cout << asterisk << std::endl;
}
//special case for the last line
if (i == rows)
{
for (int j = 1; j <= i; ++j )
std::cout << asterisk;
std::cout << endl;
}
}
https://ideone.com/peGRUG

Your while loop condition is the issue here, also you should use == instead of = inside if condition. Anyways,Here is a small fix in your solution..
void printTriangle() {
int row;
std::string s = " ";
std::string a = " *";
int rows = 10;
for (int i = 1; i < rows-1; i++) {
for (int j = 1; j <= i; ++j)
{
if (j == 1 || j == i)
std::cout << a;
else
std::cout << s;
}
std::cout << std::endl;
}
for (int i = 1; i < rows; ++i)
std::cout << a;
}

Related

Display first even and then odd elements in a C++array

I'm a C++ newb. I need to insert numbers to an array and then display first the odd numbers and then the even numbers in a single array. I've managed to create two separate arrays with the odd and even numbers but now I don't know how to sort them and put them back in a single array. I need your help to understand how to do this with basic C++ knowledge, so no advanced functions. Here's my code:
#include <iostream>
using namespace std;
int main()
{
int N{ 0 }, vector[100], even[100], odd[100], unify[100], i{ 0 }, j{ 0 }, k{ 0 };
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++) {
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++) {
if (vector[i] % 2 == 0) {
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0) {
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++) {
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++) {
cout << " " << odd[i] << " ";
cout << endl;
}
return 0;
}
If you don't need to store the values then you can simply run through the elements and print the odd and the even values to different stringstreams, then print the streams at the end:
#include <sstream>
#include <stddef.h>
#include <iostream>
int main () {
std::stringstream oddStr;
std::stringstream evenStr;
static constexpr size_t vecSize{100};
int vec[vecSize] = {10, 5, 7, /*other elements...*/ };
for(size_t vecIndex = 0; vecIndex < vecSize; ++vecIndex) {
if(vec[vecIndex] % 2 == 0) {
evenStr << vec[vecIndex] << " ";
} else {
oddStr << vec[vecIndex] << " ";
}
}
std::cout << "Even elements are:" << evenStr.rdbuf() << std::endl;
std::cout << "Odd elements are:" << oddStr.rdbuf() << std::endl;
}
Storing and sorting the elements are always expensive.
Basically, it would be better to sort them first.
#include <iostream>
using namespace std;
int main()
{
int numbers[5];
int mergedArrays[5];
int evenNumbers[5];
int oddNumbers[5];
for(int i=0;i<5;i++){
cin>>numbers[i];
}
int temp=numbers[0];
//bubble sort
for(int i = 0; i<5; i++)
{
for(int j = i+1; j<5; j++)
{
if(numbers[j] < numbers[i])
{
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
int nEvens=0;
int nOdds=0;
for(int i = 0; i<5; i++)
{
if(numbers[i]%2==0)
{
evenNumbers[nEvens]=numbers[i];
nEvens++;
}
else if(numbers[i]%2!=0)
{
oddNumbers[nOdds]=numbers[i];
nOdds++;
}
}
int lastIndex=0;
//copy evens
for(int i = 0; i<nEvens; i++)
{
mergedArrays[i]=evenNumbers[i];
lastIndex=i;
}
//copy odds
for(int i =lastIndex; i<nOdds; i++)
{
mergedArrays[i]=oddNumbers[i];
}
return 0;
}
If you have to just output the numbers in any order, or the order given in the input then just loop over the array twice and output first the even and then the odd numbers.
If you have to output the numbers in order than there is no way around sorting them. And then you can include the even/odd test in the comparison:
std::ranges::sort(vector, [](const int &lhs, const int &rhs) {
return ((lhs % 2) < (rhs % 2)) || (lhs < rhs); });
or using a projection:
std::ranges::sort(vector, {}, [](const int &x) {
return std::pair<bool, int>{x % 2 == 0, x}; });
If you can't use std::ranges::sort then implementing your own sort is left to the reader.
I managed to find the following solution. Thanks you all for your help.
#include <iostream>
using namespace std;
int main()
{
int N{0}, vector[100], even[100], odd[100], merge[100], i{0}, j{0}, k{0}, l{0};
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++)
{
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++)
{
if (vector[i] % 2 == 0)
{
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0)
{
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++)
{
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++)
{
cout << " " << odd[i] << " ";
cout << endl;
}
for (i = 0; i < k; i++)
{
merge[i] = odd[i];
}
for (int; i < j + k; i++)
{
merge[i] = even[i - k];
}
for (int i = 0; i < N; i++)
{
cout << merge[i] << endl;
}
return 0;
}
You can use Bubble Sort Algorithm to sort whole input. After sorting them using if and put odd or even numbers in start of result array and and others after them. like below:
//Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already
// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
// Insert In array
int result[100];
if(odd[0]<even[0])
{
for (int i = 0; i < k; i++)
{result[i] = odd[i];}
for (int i = 0; i < j; i++)
{result[i+k] = even[i];}
}else
{
for (int i = 0; i < j; i++)
{result[i] = even[i];}
for (int i = 0; i < k; i++)
{result[i+k] = odd[i];}
}

Program to swap row that contains the smallest number with row that contains the biggest number in a twodimensional array

I am trying to create a program that swaps the row that contains the min number with the row that contains the max number in a n x m twodimensional array (c++)
#include <iostream>
using namespace std;
int main()
{
int i, j, n, m, imin, imax, jnm, jnv;
cin >> n >> m;
int k[n][m];
int max = 0;
int min = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cout << "a[" << i << "][" << j << "]" << endl;
cin >> k[i][j];
}
}
cout << endl
<< endl;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cout << k[i][j];
}
cout << endl;
}
cout << endl
<< endl;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (k[i][j] > max) {
max = k[i][j];
imax = i;
}
}
cout << endl;
}
min = max;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (k[i][j] < min) {
min = k[i][j];
imin = i;
}
}
cout << endl;
}
cout << endl
<< endl;
if (imax == imin) {
cout << endl
<< "Min & Max are in the same row!" << endl;
}
else {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (i == imax) {
k[i][j] = k[imin][j];
}
else if (i == imin) {
k[i][j] = k[imax][j];
}
cout << k[i][j];
}
cout << endl;
}
}
return 0;
}
I know the code isn't the cleanest and most professionally written, and that isn't important, as I'm currently preparing for a coding competition where the only thing that matters is functionality of the program.
When I execute this program, it usually swaps one row but the other is still the same.
You could use function swapif you want to swap. At the moment you assignments are wrong.
So, simply write:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int i, j, n, m, imin=0, imax=0;
cin >> n >> m;
vector<vector<int>> k(n, vector<int>(m, 0));
int max = 0;
int min = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cout << "a[" << i << "][" << j << "]" << endl;
cin >> k[i][j];
}
}
cout << endl
<< endl;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cout << k[i][j] << ' ';
}
cout << endl;
}
cout << endl
<< endl;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (k[i][j] > max) {
max = k[i][j];
imax = i;
}
}
cout << endl;
}
min = max;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (k[i][j] < min) {
min = k[i][j];
imin = i;
}
}
cout << endl;
}
cout << endl
<< endl;
if (imax == imin) {
cout << endl
<< "Min & Max are in the same row!" << endl;
}
else {
for (j = 0; j < m; j++)
swap(k[imin][j], k[imax][j]);
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cout << k[i][j] << ' ';
}
cout << endl;
}
}
return 0;
}
And sorry, I cannot write int k[n][m]; because this is not C++ and my compiler cannot compile it. But vector can be used in the same way.
If you are not allowed to use std::swapyou can use instead:
for (j = 0; j < m; j++) {
int tmp = k[imin][j];
k[imin][j] = k[imax][j];
k[imax][j] = tmp;
}
For the competition you could also get the min and max values already during input and write:
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
int main()
{
// Read matrix size
size_t rows{}, columns{};
if (std::cin >> rows >> columns) {
// Here we will store our matrix
std::vector<std::vector<int>> matrix(rows, std::vector<int>(columns, 0));
// Initilize min max values
int maxElement = std::numeric_limits<int>::min();
int minElement = std::numeric_limits<int>::max();
size_t indexMaxRow{}, indexMinRow{};
// Enter values in matrix
for (size_t row{}; row < rows; ++row) {
for (size_t column{}; column < columns; ++column) {
std::cout << "array[" << row << "][" << column << "]\n";
if (std::cin >> matrix[row][column]) {
// Already during input find the min and max values
if (matrix[row][column] > maxElement) {
maxElement = matrix[row][column];
indexMaxRow = row;
}
if (matrix[row][column] < minElement) {
minElement = matrix[row][column];
indexMinRow = row;
}
}
}
}
// Show original matrix
std::cout << "\n\n\nYou entered:\n\n";
for (const auto& row : matrix) {
for (const auto& col : row) std::cout << col << ' ';
std::cout << '\n';
}
// Swap
std::swap(matrix[indexMaxRow], matrix[indexMinRow]);
// Show swapped matrix
std::cout << "\n\n\nSwapped:\n\n";
for (const auto& row : matrix) {
for (const auto& col : row) std::cout << col << ' ';
std::cout << '\n';
}
}
else std::cerr << "\nError while reading size\n";
}

Assigning values to multidimensional vector

I´m trying to assign values to a multidimensional vector, but I always get an "R6010 - abort()" error from visual studio.
What I want is an two dimensional vector, where the second dimension is exactly as large as needed. (Important because I don't now how many input values and I want to use later myvector.at(i).size();
So to formulate it short: Why is the following example not working?
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < vector < int > > Vektor;
Vektor.resize(10);
int tmp;
while (true) {
cout << "Please enter a value: " << endl;
cin >> tmp;
int size;
if (tmp > 0 & tmp < 11) {
Vektor.at(tmp - 1).push_back(tmp);
}
for (int i = 1; i < 11; i++) {
size = Vektor.at(i).size();
for (int j = 0; j < size; j++) {
cout << "Value at " << i << " , " << j << " : " << Vektor.at(i).at(j) << endl;
}
}
}
return 0;
}
You are using wrong indices in the lines:
for (int i = 1; i < 11; i++) {
size = Vektor.at(i).size();
Change the lines to:
| ||
v vv
for (int i = 0; i < 10; i++) {
size = Vektor.at(i).size();
As already answered by #RSahu, you use wrong indices in a loop. In stead of correcting the values, I'll suggest that you avoid hard coded values.
That can be done in several ways. By using vector.size() your code is easy to fix. Just use these two lines instead of your current two lines:
if (tmp > 0 & tmp <= Vektor.size()) {
for (int i = 0; i < Vektor.size() ; i++) {
An alternative way of printing could be
size_t i = 0;
for (const auto& v : Vektor)
{
size_t j = 0;
for (const auto e : v)
{
cout << "Value at " << i << " , " << j << " : " << e << endl;
++j;
}
++i;
}

Printin a X with *

i wanna print a X with * , i have done the left side of the X but i don't know how to print the other side (flip/mirror) .
if you run this codes it will print just the left side of (X) and now i wanna print the right side of (X) ? so what should i do to complete the (X) using stars(*)? thank you guys.
i was wondering is it possible to do this?(i'm a newbie to programming)
#include <iostream>
// Expected output pattern:
//
// * *
// * *
// * *
// *
// * *
// * *
// * *
using namespace std;
int main() {
cout << "Printing X with star(*)" << endl;
cout << endl;
int i;
int p;
for (i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if (j > i) break;
cout << " ";
cout << "\t";
}
cout << "\t\t\t\t";
for (p = 1; p <= 10; p++) {
cout << "*";
}
cout << endl;
}
for (i = 10; i >= 1; i--) {
for (int j = 1; j <= 10; j++) {
if (j > i) break;
cout << " ";
cout << "\t";
}
cout << "\t\t\t\t";
for (p = 1; p <= 10; p++) {
cout << "*";
}
cout << endl;
}
return 0;
}
You're on the right track, to do the right hand side you have to print more **** on each line in addition to what you already have done. It might help to think of printing each line of the X as printing some **** then some spaces then more **** and reduce the number of spaces each time you get closer to the cross-over point. Does that make sense? This might help get you further (. = space):
*......*
.*....*
..*..*
...**
and so on
This is one of many ways you could get there:
int main()
{
int size = 8;
int spacesBefore;
int spacesBetween = size;
int numStars = 1;
// Top half:
int i, j;
for ( i = 0; i < size/2; i++ ) {
spacesBetween = size - ( 2 * ( i + 1 ) );
spacesBefore = i;
for ( j = 0; j < spacesBefore; j++ ) // before
cout << " ";
for ( j = 0; j < numStars; j++ ) // * left
cout << "*";
for ( j = 0; j < spacesBetween; j++ ) // between
cout << " ";
for ( j = 0; j < numStars; j++ ) // * right
cout << "*";
cout << endl;
}
// bottom half, do the same kind of thing but changing the spacings
// ...
}
ok thank you every one that helped me , i found the answer i wanted after almost 6 hours and here is the answer:
#include <iostream>
using namespace std;
int main() {
cout << "Printing X with stars" << endl;
cout << endl;
int i;
int p;
int k;
int s;
int count = 72;
for (i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
if (j > i) break;
cout << " ";
cout << "\t";
}
cout << "\t\t\t\t";
for (p = 1; p <= 10; p++) {
cout << "* ";
}
for (k=1; k<=count; k++){
cout << " ";
}
count-=8;
for (s=1; s<=10; s++){
cout << "* ";
}
cout << endl;
}
count = 0;
for (i = 10; i >= 1; i--) {
for (int j = 1; j <= 10; j++) {
if (j > i) break;
cout << " ";
cout << "\t";
}
cout << "\t\t\t\t";
for (p = 1; p <= 10; p++) {
cout << "* ";
}
for (k=1; k<=count; k++) {
cout << " ";
}
count +=8;
for (s=1; s<=10; s++){
cout << "* ";
}
cout << endl;
if (count == 80) break;
}
return 0;
}

Print array 3 lines

I am trying to print this array of 9 elements out in 3 lines.
I want to print it out in 3 lines with 3 rows such as .
xxx
xxx
xxx
But i am not sure how to tackle that.
void ticTacToeBoard ()
{
for (int i = 0; i < 9; i++)
{
cout << ticTacBoard[i] << " ";
}
}
I like to be verbose with my loops, so try this:
void ticTacToeBoard ()
{
for (int y = 0; y < 3; y++)
{
for (int x = 0; i < 3; x++)
{
cout << ticTacBoard[3 * y + x] << " ";
}
cout << endl;
}
}
Basically, I iterate over your board in rows (y), and then in columns (x), allowing me to print each cell and control the flow.
I just print a newline (endl) after each row.
Change ticTacBoard to a two dimensional array and do
using namespace std;
int main()
{
int ticTacBoard[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << ticTacBoard[i][j] << " ";
}
cout << endl;
}
return 0;
}
A two dimensional array will be easier to understand.
Use the modulo operator to detect every third iteration. Then print a newline.
void ticTacToeBoard ()
{
for (int i = 0; i < 9; i++)
{
cout << ticTacBoard[i] << " ";
if((i + 1) % 3 == 0) {
cout << endl;
}
}
}
You can switch frot the offset in a single-dimensional array (say i) to the offset in a bi-dimensional via this simple formula:
row = i div width
column = i mod width
So, basically:
for(int i = 0; i < 9; i++) {
cout << ticTacBoard[i];
if(i % 3 == 2)
cout << endl;
else
cout << ' ';
}