triangle pattern centered - geometry

i want to create a pattern in c++ that looks like a trianlge(or half a diamond)
using asteriscks: the pattern should have 1, 2, 3, 4, and end in 5 stars like this
*
**
***
****
*****
(but straight!)
my code is as follows:
-`#include
using namespace std;
int main()
{
int size;
cout<<"size:"<<endl;
cin>>size;
int blank=size/2;
int newsize=1;
for (int i=0; i<=size/2; i++)
{
for(int j=blank;j>0;j--)
cout <<" ";
blank--;
for(int j=newsize; j>0; j--)
cout <<"*";
newsize+=2;
cout <<endl;
}
return 0;
}
`
my only problem with it is that it displays 1, 3,and 5 stars like this.
*
***
*****
its just a minor problem but although i have changed different parts of the code
i dont seem to get it right.
any suggestions?
thanks
:)

I'm not sure what you mean by "but straight", so I'll just ignore that for now...
Start with blank the same value as size, so that you can decrement the value each time without having to decrement by a half:
int blank=size;
Loop up to size instead of size/2 to get more lines:
for (int i=0; i<=size; i++)
Decrement by two in the loop for spaces to get half the number of spaces:
for(int j=blank;j>0;j-=2)
Increase the size by one instead of two to get the slower increase:
newsize++;
That should produce the output that you showed.
Edit:
I tested this to be sure, and the output is:
*
**
***
****
*****
******
To get the exact output that you asked for, start with blank one less:
int blank=size - 1;

Did I get it right: you want to place some asterisks on borders of character places? If so, it isn't possible. Every asterisk (or any other symbol), when displayed in monospace fonts, will reside in a middle of a character place, like in a grid. You can place asterisks inside the cells, but you cannot place asterisks on the borders of the grid.

int NUMLINES = 5;
void display(int, char);
void main(){
for (int i=1; i<= NUMLINES; ++i){
display((NUMLINES + 1 - i), ' ');
display(( 2 * i - 1 ), '*');
cout << endl;
}
}
void display (int howmany, char symbol){
for (int i = 1; i<=howmany; ++i)
cout << symbol;
}

Related

stuck on CS50x left aligned to right aligned mario pyramid

I have been trying to make my pyramid from left aligned to right aligned but i am confused on how to do it. This is the code i am using.
Edit: i have changed the code but i have been getting an error
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
//asks user for number between 1 and 8
height = get_int("please give height: ");
}
while (height < 1 || height > 8);
//prints rows (i)
for (int rows = 0; rows < height; rows++)
{
//prints spaces (j)
for (int spaces = 0; spaces < height - rows; spaces++)
{
printf(".");
}
printf("\n");
}
for (int hashes = 0; rows < height - rows; hashes++)
{
printf("#");
}
printf("\n");
}
user gets prompted and writes number between 1 and 8
user types 4
Expected
...#
..##
.###
####
Actual output
....
...
..
.
mario.c:24:48: error: use of undeclared identifier 'rows'
for (int hashes = 0; rows < height - rows; hashes++)
^
mario.c:24:32: error: use of undeclared identifier 'rows'
for (int hashes = 0; rows < height - rows; hashes++)
^
2 errors generated.
<builtin>: recipe for target 'mario' failed
make: *** [mario] Error 1
i am trying to print hashes and use the rows interger but for some reason the error says it is am undefined interger.
I think the error is because you're curly brackets {} in your first and second for loops are mixed up. It looks like you're trying to do three loops that are nested inside each other; however, your third loops is outside the first one because you have an extra } in the middle of your code for the second loop. The variable row is declared in the first loop and the third loop doesn't know what that means since it is outside the first loop.
Sticking to the class's recommendations about indentation helped me keep this straight.

How to trigger a race condition?

I am researching about fuzzing approaches, and I want to be sure which approach is suitable for Race Condition problem. Therefor I have a question about race condition itself.
Let's suppose we have a global variable and some threads have access to it without any restriction. How can we trigger the existing race condition? Is it enough to run just the function that uses the global variable with several threads? I mean just running the function will trigger race condition anyway?
Here, I put some code, and I know it has race condition problem. I want to know which inputs should give the functions to trigger the corresponding race condition problem.
#include<thread>
#include<vector>
#include<iostream>
#include<experimental/filesystem>
#include<Windows.h>
#include<atomic>
using namespace std;
namespace fs = experimental::filesystem;
volatile int totalSum;
//atomic<int> totalSum;
volatile int* numbersArray;
void threadProc(int startIndex, int endIndex)
{
Sleep(300);
for(int i = startIndex; i < endIndex; i++)
{
totalSum += numbersArray[i];
}
}
void performAddition(int maxNum, int threadCount)
{
totalSum = 0;
numbersArray = new int[maxNum];
for(int i = 0; i < maxNum; i++)
{
numbersArray[i] = i + 1;
}
int numbersPerThread = maxNum / threadCount;
vector<thread> workerThreads;
for(int i = 0; i < threadCount; i++)
{
int startIndex = i * numbersPerThread;
int endIndex = startIndex + numbersPerThread;
if (i == threadCount - 1)
endIndex = maxNum;
workerThreads.emplace_back(threadProc, startIndex, endIndex);
}
for(int i = 0; i < workerThreads.size(); i++)
{
workerThreads[i].join();
}
delete[] numbersArray;
}
void printUsage(char* progname)
{
cout << "usage: " << fs::path(progname).filename() << " maxNum threadCount\t with 1<maxNum<=10000, 0<threadCount<=maxNum" << endl;
}
int main(int argc, char* argv[])
{
if(argc != 3)
{
printUsage(argv[0]);
return -1;
}
long int maxNum = strtol(argv[1], nullptr, 10);
long int threadCount = strtol(argv[2], nullptr, 10);
if(maxNum <= 1 || maxNum > 10000 || threadCount <= 0 || threadCount > maxNum)
{
printUsage(argv[0]);
return -2;
}
performAddition(maxNum, threadCount);
cout << "Result: " << totalSum << " (soll: " << (maxNum * (maxNum + 1))/2 << ")" << endl;
return totalSum;
}
Thanks for your help
There may be many cases of race conditions. One of example for your case:
one thread:
reads commonly accessible variable (1)
increments it (2)
sets the common member variable to resulting value (to 2)
second thread starts just after the first thread read the common value
it read the same value (1)
incremented the value it read. (2)
then writes the calculated value to common member variable at the same time as first one. (2)
As a result
the member value was incremented only by one (to value of 2) , but it should increment by two (to value of 3) since two threads were acting on it.
Testing race conditions:
for your purpose (in the above example) you can detect race condition when you get different result than expected.
Triggerring
if you may want the described situation always to happen for the purpose of - you will need to coordinate the work of two threads. This will allow you to do your testing
Nevertheless coordination of two threads will violate definition race condition if it is defined as: "A race condition or race hazard is the behavior of an electronics, software, or other system where the system's substantive behavior is dependent on the sequence or timing of other uncontrollable events.". So you need to know what you want, and in summary race condition is an unwanted behavior, that in your case you want to happen what can make sense for testing purpose.
If you are asking generally - when a race condition can occur - it depends on your software design (e.g you can have shared atomic integers which are ok to be used), hardware design (eg. variables stored in temporary registers) and generally luck.
Hope this helps,
Witold

check50 error messages: On my Mario.c pset1 solution

:( handles a height of 0 correctly \ expected an exit code of 0, not output of "\n Please enter a positive integer valu..."
:( rejects a non-numeric height of "" \ expected output, not a prompt for input
https://sandbox.cs50.net/checks/5593ad8059ce4492804c07aff8e377eb
I think I should put part of my code too:
#include <stdio.h>
int clean_stdin()
{
while (getchar()!='\n');
return 1;
} //snippet gotten from http://stackoverflow.com/questions/14104013/prevent-users-from-entering-wrong-data-types
int main (void)
{
int row, pyramid_height, space, hash;
char c;
do
{
printf("\n Please enter a positive integer value, less than 24 as the height: ");
}
while (((scanf("%i%c", &pyramid_height, &c) != 2 || c!='\n') && clean_stdin()) || pyramid_height < 1 || pyramid_height > 23);
//snippet gotten from http://stackoverflow.com/questions/14104013/prevent-users-from-entering-wrong-data-types
Please help:
Also, Is there an easier way to prevent users from entering wrong data?
Thank you.
You should do something like this to ask the user for input
printf("Enter height < 23 and a non-negative number\n");
do{
printf("Height: ");
height = GetInt(); // ask user again until valid input is given
}while(height < 0 || height >23);
If you don't want to use GetInt() you can do this with scanf too. Just replace the GetInt line with scanf("%d",&height);. It'll work the same except when you enter a wrong number it'll yell at you by saying Height:
rather than Retry:.
And you should remove that clean_stdin function. That level of precision is not required in pset1.
Now the remaining part is the nested for loops which you've not provided in the question so, I am assuming that you have a problem there too since your program can't handle 0 properly.
Try something like this in place of the for loops.
for(int i=1; i<=height; i++){ // i number of #s in each step
for(int j=0; j<height-i; j++){ //print appropriate number of spaces
printf(" ");
}
for(int k=0; k<=i; k++){ //print #s
printf("#");
}
printf("\n"); //change line
}

How do I properly use unordered_map?

I'm writing a program that is supposed to count amount of times a string 3 characters long appears. I have a loop that makes substrings of 3 characters from a larger string, but when I try to insert them into an unordered_map, I get a bunch of errors. What am I doing wrong?
int a =0;
std::string subs= "";
std::unordered_map <std::string,int> mapp = {};
int count=0;
for(int i=0; i<ss.length(); i++){
subs= ss.substr(a,k);
if(subs.length()<k){
return -1;
}
std::cout << "Substring: " << subs << std::endl;
a++;
mapp.insert(std::make_pair<std::string,int>(subs,count));
}

QT. Is any way to multiplicate string several times?

In python i can write
s = "dad" * 3
Result will be: s = "daddaddad"
I want to append "tabs" to my string. Something like:
QString tabs = "\t" * count;
What would be a simple, idiomatic way to do it?
You can do it quite simply with a loop:
QString mystring("somestring");
QString output;
for (int i = 0; i < 3; ++i)
output.append(mystring);
//'output' will contain the result string
Please note that the code I provide is in C++, not Python, but the concept still applies (and should be easily ported).
EDIT:
If you need to concatenate single characters, you could do it more easily like this:
int size = 5;
QString output(size, QChar('\t'));
//'output' contains 5 tab characters
Or, if you need to assign to another string (output is already created):
int size = 5;
output.fill(QChar('\t'), size);
//'output' contains 5 tab characters
#include <QString>
QString s;
for(int i = 0; i < 3; ++i)
{
s << "dad";
}

Resources