How do i draw a filled square with a pattern in cpp - c++

I was given an assignment to make a program in cpp where you give it the width and length of the square and it will go into a pattern of *s and #s but I can't wrap my head around it. So I'm asking you people at stackoverflow to help me if you can. For reference when you would give an input of
6 6
the output would be:
######
#****#
#*##*#
#*##*#
#****#
######
and an input of
4 3
will give an output of:
####
#**#
####

This assignment is meant to help you understand how to use nested for loops.
for (int i = 0; ...)
{
for (int j = 0; ...)
{
// Do stuff here
}
}
Think about how a row can be formed by repeating a specific action. Then think about how a square can be formed by repeating the action of creating a row.
As for '*' vs '#', you always have access to both the x and y coordinate of the "current cell" you are about to print from inside the inner loop, because they are the counter variables for the two for loops. Remember: i and j are just arbitrary names. You could name those variables anything you want. You also have access to the length of each row and column, because they are given as input. Ask yourself: "what test can I make on the x or y coordinate that will tell me if it is the first or last column"?
Looping (or "iteration") is an extremely important concept in programming. Hopefully this gives you a hint in the right direction without giving too much away. :)

Related

How to generate derivative list with frequencies

I have some C++ code that picks a random item from a list. I need it to weight that randomness so that an item at place "n" has a chance equal to x/n where "x" is the chance that item one in the list will be selected. My current code is like this:
srand(time(NULL));
string a[≈9000] = {"String#1", "String#2", . . ., "String #≈9000"};
int value = rand() % ≈9000;
cout << a[value]
Note that the number notated as "≈9000" is a precise integer obscured for confidentiality. Variable names may be changed.
How can I weight it? I've come up with an equivalent formula
List B[≈9000] = "Item 'n' of 'a' times ≈9000 ÷ n"
Though you might notice that that isn't accurate CPP notation. Do y'all have any ideas how I can implement this?
This is not possible.
You need somehow to allow a variation on your conditions to have a proper distribution.

How to use a string or a char vector (containing any chemical composition respectively formula) and calculate its molar mass?

I try to write a simple console application in C++ which can read any chemical formula and afterwards compute its molar mass, for example:
Na2CO3, or something like:
La0.6Sr0.4CoO3, or with brackets:
Fe(NO3)3
The problem is that I don't know in detail how I can deal with the input stream. I think that reading the input and storing it into a char vector may be in this case a better idea than utilizing a common string.
My very first idea was to check all elements (stored in a char vector), step by step: When there's no lowercase after a capital letter, then I have found e.g. an element like Carbon 'C' instead of "Co" (Cobalt) or "Cu" (Copper). Basically, I've tried with the methods isupper(...), islower(...) or isalpha(...).
// first idea, but it seems to be definitely the wrong way
// read input characters from char vector
// check if element contains only one or two letters
// ... and convert them to a string, store them into a new vector
// ... finally, compute the molar mass elsewhere
// but how to deal with the numbers... ?
for (unsigned int i = 0; i < char_vec.size()-1; i++)
{
if (islower(char_vec[i]))
{
char arr[] = { char_vec[i - 1], char_vec[i] };
string temp_arr(arr, sizeof(arr));
element.push_back(temp_arr);
}
else if (isupper(char_vec[i]) && !islower(char_vec[i+1]))
{
char arrSec[] = { char_vec[i] };
string temp_arrSec(arrSec, sizeof(arrSec));
element.push_back(temp_arrSec);
}
else if (!isalpha(char_vec[i]) || char_vec[i] == '.')
{
char arrNum[] = { char_vec[i] };
string temp_arrNum(arrNum, sizeof(arrNum));
stoechiometr_num.push_back(temp_arrNum);
}
}
I need a simple algorithm which can handle with letters and numbers. There also may be the possibility working with pointer, but currently I am not so familiar with this technique. Anyway I am open to that understanding in case someone would like to explain to me how I could use them here.
I would highly appreciate any support and of course some code snippets concerning this problem, since I am thinking for many days about it without progress… Please keep in mind that I am rather a beginner than an intermediate.
This problem is surely not for a beginner but I will try to give you some idea about how you can do that.
Assumption: I am not considering Isotopes case in which atomic mass can be different with same atomic number.
Model it to real world.
How will you solve that in real life?
Say, if I give you Chemical formula: Fe(NO3)3, What you will do is:
Convert this to something like this:
Total Mass => [1 of Fe] + [3 of NO3] => [1 of Fe] + [ 3 of [1 of N + 3 of O ] ]
=> 1 * Fe + 3 * (1 * N + 3 * O)
Then, you will search for individual masses of elements and then substitute them.
Total Mass => 1 * 56 + 3 * (1 * 14 + 3 * 16)
=> 242
Now, come to programming.
Trust me, you have to do the same in programming also.
Convert your chemical formula to the form discussed above i.e. Convert Fe(NO3)3 to Fe*1+(N*1+O*3)*3. I think this is the hardest part in this problem. But it can be done also by breaking down into steps.
Check if all the elements have number after it. If not, then add "1" after it. For example, in this case, O has a number after it which is 3. But Fe and N doesn't have it.
After this step, your formula should change to Fe1(N1O3)3.
Now, Convert each number, say num of above formula to:
*num+ If there is some element after current number.
*num If you encountered ')' or end of formula after it.
After this, your formula should change to Fe*1+(N*1+O*3)*3.
Now, your problem is to solve the above formula. There is a very easy algorithm for this. Please refer to: https://www.geeksforgeeks.org/expression-evaluation/. In your case, your operands can be either a number (say 2) or an element (say Fe). Your operators can be * and +. Parentheses can also be present.
For finding individual masses, you may maintain a std::map<std::string, int> containing element name as key and its mass as value.
Hope this helps a bit.

Why is this code fragment returning unexpected results?

I am currently learning C++ at my school, and am making a word sleuth as part of a project that I have to submit. For this, I have already made the grid of alphabets and other necessary things (clues, rules, etc.). I am taking the input in the form of coordinates in an integer array whereby the user enters 4 values in the array, signifying the initial row and column number and the final row and column number, corresponding to which are the first and last alphabets of a particular word.
After doing this, I am now comparing the array input by the user with the array I have already defined that has the coordinates of that particular word. This is shown here :
cout<<"Enter the coordinates of starting and final characters : row1 col1 row2 col2 "<<endl;
for (z = 0; z < 4; z++) //first for loop
cin>>p[z]; //taking the input as an array 'p'
for (b = 0; b < 4; b++) //second for loop
{
if (p[b] == messi[b])
b+=0;
}
if (b == 4)
cout<<"Great!!!! You have answered the question correctly"<<"\n\n";
else
cout<<"You got this one wrong mate! Try again :)"<<"\n\n";
Here, messi[b] is the array which has the coordinates corresponding to the word 'MESSI' in the grid. Now, to my mind, the 'if' statement after the second for loop must contain the condition to check if b = 3. However, when I do that, the output always comes out to be what the 'else' statement says i.e. "You got this..." for every input. However, when I impose the condition to check if b = 4, the output comes out to be what the 'if' statement says i.e. "Great!!..." for every input.
What wrong am I doing? I hope I am clear enough in explaining the problem to you. I am using CodeBlocks 16.01.
It's a bit unclear what you are doing, as the program stands, b will always be equal to 4 after the second for-loop since the last time to condition was true, b < 4. So after the increment, it will be 4.
Inside the second for-loop you also have the NOP code b += 0; which does absolutely nothing to the code. What is the intention here?

Creating a histogram with C++ (Homework)

In my c++ class, we got assigned pairs. Normally I can come up with an effective algorithm quite easily, this time I cannot figure out how to do this to save my life.
What I am looking for is someone to explain an algorithm (or just give me tips on what would work) in order to get this done. I'm still at the planning stage and want to get this code done on my own in order to learn. I just need a little help to get there.
We have to create histograms based on a 4 or 5 integer input. It is supposed to look something like this:
Calling histo(5, 4, 6, 2) should produce output that appears like:
*
* *
* * *
* * *
* * * *
* * * *
-------
A B C D
The formatting to this is just killing me. What makes it worse is that we cannot use any type of arrays or "advanced" sorting systems using other libraries.
At first I thought I could arrange the values from highest to lowest order. But then I realized I did not know how to do this without using the sort function and I was not sure how to go on from there.
Kudos for anyone who could help me get started on this assignment. :)
Try something along the lines of this:
Determine the largest number in the histogram
Using a loop like this to construct the histogram:
for(int i = largest; i >= 1; i--)
Inside the body of the loop, do steps 3 to 5 inclusive
If i <= value_of_column_a then print a *, otherwise print a space
Repeat step 3 for each column (or write a loop...)
Print a newline character
Print the horizontal line using -
Print the column labels
Maybe i'm mistaken on your q, but if you know how many items are in each column, it should be pretty easy to print them like your example:
Step 1: Find the Max of the numbers, store in variable, assign to column.
Step 2: Print spaces until you get to column with the max. Print star. Print remaining stars / spaces. Add a \n character.
Step 3: Find next max. Print stars in columns where the max is >= the max, otherwise print a space. Add newline. at end.
Step 4: Repeat step 3 (until stop condition below)
when you've printed the # of stars equal to the largest max, you've printed all of them.
Step 5: add the -------- line, and a \n
Step 6: add row headers and a \n
If I understood the problem correctly I think the problem can be solved like this:
a= <array of the numbers entered>
T=<number of numbers entered> = length(a) //This variable is used to
//determine if we have finished
//and it will change its value
Alph={A,B,C,D,E,F,G,..., Z} //A constant array containing the alphabet
//We will use it to print the bottom row
for (i=1 to T) {print Alph[i]+" "}; //Prints the letters (plus space),
//one for each number entered
for (i=1 to T) {print "--"}; //Prints the two dashes per letter above
//the letters, one for each
while (T!=0) do {
for (i=1 to N) do {
if (a[i]>0) {print "*"; a[i]--;} else {print " "; T--;};
};
if (T!=0) {T=N};
}
What this does is, for each non-zero entered number, it will print a * and then decrease the number entered. When one of the numbers becomes zero it stops putting *s for its column. When all numbers have become zero (notice that this will occur when the value of T comes out of the for as zero. This is what the variable T is for) then it stops.
I think the problem wasn't really about histograms. Notice it also doesn't require sorting or even knowing the

Build a pyramid with numbers between 1 and the inserted integer

i'm trying to build a pyramid with numbers between 1 and the inserted number. For example, if i insert 6 to the integer, that the piramid will be as there:
12345654321
234565432
3456543
45654
565
6
I tried using a for loop but i get in any line one or ++ numbers to 6.
This is the code:
#include<stdio.h>
#include <iostream>
#include <conio.h>
int main()
{
int i,j,d;
std::cin >> d;
for(i=1;i<=d;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
getch();
return 0;
}
How can i solve this problem building a pyramid like the shown.
Since this is homework, I won't paste an algorithm, but here's a few hints:
This 12345654321 can be printed by counting from one to six and then back to one.
This __3456543__ means that for numbers smaller than n, you have to output a _ instead, where n depends on the level you are printing.
Define your loop variables within the loop: for(int i=1;i<=d;i++) ... They are only interesting within the loop, and access outside the loop is usually an error, which is then flagged by the compiler.
There's no need to for the getch(); at the end. When you're in the debugger, you can put a breakpoint on the last line. If you aren't you don't want to have to press a key just to end your program.
If you use std::cout << j and std::cout << '\n' for outputting, you don't need printf() either. (Once you want formatting, many will tell you that printf format strings are easier. I don't believe that, but would accept it, if it weren't that you can crash any application with an ill-formed printf format string, while it's much harder to come up with a way to crash your app using streams.)
There you go:
for(j=i;j<=d;j++)
Also you forgot about formatting and the right side of the pyramid, but I think that's out of scope for this question and you can figure the code yourself :)
Try to have the first line working the way you want.
Repeat it d times, where d is the number entered by the user.
Notice that on line l, numbers < l are replaced by spaces.
Consider this: you have D rows, 1..D. Six rows means your rows are numbered 1 to 6. Now, for each row d:
print d-1 space characters. First row has no spaces, second has one and so on.
print the numbers d..D. So on the first line you print 1..6, on the second you print 2..6.
print the numbers D-1..d. So on the first line you print 5..1, on the second you print 5..2
print a new line