creating hollow square c++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have written this code but somehow when it asks the user to enter a new number to create a square, it doesn't print the square. Could anyone anyone explain / help me please?
// ask user to repeat the process again at end of the first promt
while ( num > 1 || num < 20 )
{
ask user to repeat the process again at end of the first promt
while ( num > 1 || num < 20 )
{
// ask user t enter a square
cout << "Please enter size of square between #1-20: \n";
cin >> buf; num = atoi (buf.c_str());
cin.ignore(1000, 10);
// process of printing square
while ( num >= a)
{
b = 1;
while ( num >= b )
{
if ( a == 1 || a == num || b == 1 || b == num )
cout << "*";
else
cout << " ";
b++;
}
cout << endl;
a++;
}

I see no code where you initialise a to 1 so it may be it has some arbitrary value. If that arbitrary value is greater than num, the outer loop will never start.
For what it's worth, I would be using for loops in this case since you know in advance what the limits are, something like the following pseudo-code:
# Top line
for i = 1 to num (inclusive):
output "*"
output newline
# Middle lines
for i = 2 to num-1:
output "*" # Left char
for j = 2 to num-1: # Middle chars
output " "
output "*" and newline # Right char
# Bottom line
for i = 1 to num (inclusive):
output "*"
output newline
Then you don't have to worry about condition checking within the loop body.
A good rule of thumb is to use for for a known-before-the-start count of iterations, while for a loop where you don't know in advance how often you'll iterate.
Another likely problem is your condition:
while ( num > 1 || num < 20 )
Regardless of the value of num, that is always true, since you're using logical-or ||. Think of the possibilities:
num <= 1 : false or true -> true
num == 2..19 : true or true -> true
num >= 20 : true or false -> true
If you want to continue looping while you have a value outside of the range 1..20, you should use:
while ( num < 1 || num > 20 )
and you then end up with the following:
num <  1     : true or false -> true
num == 1..20 : false or false -> false
num >  20    : false or true -> true
There are quite a few other potential problems with your code, to wit:
You appear to have the outer loop in there twice.
You don't appear to define b or num.
You don't appear to set num before the outer loop (which checks it).
I suspect you meant to close the while ( num > 1 || num < 20 ) loop immediately after the cin.ignore() call since it's meant to keep going until you get a value from 1 to 20 and then draw the square. As it stands, a square will be drawn even if you enter 99.

Probably not the best code - but it can be done in six lines. Here goes.
for (int y = o; y < height; ++ y) {
for (int x = 0; x < width; ++x) {
cout << (y == 0 || y == (height - 1) || x == 0 || x == (width - 1) ? '*' : ' ' );
}
cout << endl;
}

Related

if statements and relational and comparison operators: "Exceptions" When comparing three values/variables [duplicate]

This question already has answers here:
Is (4 > y > 1) a valid statement in C++? How do you evaluate it if so?
(5 answers)
Closed 1 year ago.
Context
Taking a c++ course and if statements and relational and comparison operators came up. I don't know enough c++ vocabulary so I apologize if this question has been asked before. I tried searching around, but I didn't find anything.
Problem
Below illustrates an example of what I am confused about.
int n = 1;
if(2 < n <1){
cout << n << endl;
}
When the program is ran, the cout statement gets printed to the console (which is surprising to me).
Question
How is C++ interpreting the values and relational and comparison operators within the if statement?
If there are any other interesting "exceptions" like this documented somewhere could you please reference it for me, thank you.
Ans Attempt
I'm not totally sure what is going on. To me it seems like the middle number is getting skipped?
After playing with the numbers a few times I've now been able to confirm that the middle number is getting skipped, but I have no idea why.
If I add arguments by scaling the problem up:
if(2 < n < 0 <1){
cout << n << endl;
}
and also:
if(2 < n < 1 < 1 < 1){
cout << n << endl;
}
Now I get really confused. It seems like whatever "thing" is in the middle gets ignored. But I found an exception to my pattern when n = 3 causes the if statement to be "false":
int n = 3
if(2 < n < 1 < 1 <1){
cout << n << endl;
}
But then if I change n to what seems like "any" (not exhaustive) other number the if statement will yield true again.
The 2 < n < 1 ain't does what you think it should:
Because these operators group left-to-right, the expression a<b<c is
parsed (a<b)<c, and not a<(b<c) or (a<b)&&(b<c) - cppreference.com
The 2 < n part will return a Boolean value which in turn will be compared in the < 1.
2 < n < 1;
// equal to
(2 < n) < 1;
So, in total, the 2 < n < 1 flows like so:
(2 < n) < 1. Is n greater than 2? No, return false.
false < 1. The false is promoted to an integer, to 0. Is 0 less than 1? Yes, the if condition is true.
That's why when n == 3 in the 2 < n < 1 < 1 < 1, the overall you get false:
(2 < 3) < 1 < 1 < 1. Is 3 greater than 2? Yes! Returns 1 (true)
(1 < 1) < 1 < 1. Is 1 less than 1? No! Return 0 (false)
(0 < 1) < 1. Is 0 less than 1? Yes! Return 1 (true)
1 < 1. Is 1 less than 1? No! Return 0 (false)
It is nonsensical as you can see. In order to make it work, you will have to make explicit checks:
(n < 2) && (n > 1)
// is n less than 2 AND is n greater than 1

Issue while testing a C++ program that measure levels above the sea

I have a uni project the task is We flew from Europe to North America, and we measured the height above the sea level at equal sequences. The first and last measurements were either above a continent or the sea. We measured positive height, where we were above some land, and 0, where we were above the sea
I tried to make the code and now i have the code and when i enter the inputs it gives me the same output as it is supposed to be in the task.
The problem is that the code doesn't work in the university online marking system, because
I checked it in case there are no islands, the program prints 0 0, but it should print a single 0.
Also, when all the islands have 0 valleys, the program should just show output of the first island, right now the maximum selection doesn't work for this case (do you think it can fixed by changing only the initial value of maxV)
Can you please help me with these two points?
#include <iostream>
int main() {
// Gets the number of heights
unsigned int height_count;
std::cin >> height_count;
// Get every height recorded and put it in an array
unsigned short* heights = new unsigned short[height_count];
for (int i = 0; i < height_count; ++i)
std::cin >> heights[i];
// We need to keep track of the following things:
int island_start = -1, max_island_start = -1, max_island_end = -1;
unsigned current_valley_count = 0, max_valley_count = 0;
for (int i = 1; i < height_count-1; ++i) {
if (heights[i] > 0 && heights[i-1] == 0) // If the coast starts
island_start = i;
else if (heights[i] > 0 && heights[i] <= heights[i-1] && heights[i] <= heights[i+1] && !(heights[i] == heights[i-1]) + (heights[i] == heights[i+1]) == 1) // If there is a valley
++current_valley_count;
else if (heights[i] > 0 && heights[i+1] == 0) { // If the coast ends
// Checks if the last island checked had the most valleys
if (current_valley_count > max_valley_count) {
max_island_start = island_start;
max_island_end = i;
max_valley_count = current_valley_count;
}
island_start = -1;
current_valley_count = 0;
}
}
std::cout << max_island_start+1 << " " << max_island_end+1 << std::endl;
return 0;
}
To print single 0 instead of 0 0, you should add if statement to check if there were no islands and change what to print according to that.
Also, the initial value of max_valley_count should be -1 instead of 0 so that the (first) island with 0 valleys can appear in the output.
I don't think the issue can be fixed by changing initial value of maxV because maxV is not used in this code.
As one more point, the problem statement says
but only one of B=A and B=C is true
On the other hand, your program says
!(heights[i] == heights[i-1]) + (heights[i] == heights[i+1]) == 1
This part of code means "only one of B!=A and B=C is true".
You should delete the !.

Solving a dp problem from codeforces - Cut Ribbon

I was trying to solve this problem and from the comments section in the editorial, I was directed to the following solution :
#include <bits/stdc++.h>
using namespace std;
#define MAX(a,b,c) max(a,max(b,c))
int n,a,b,c,dp[4001];
int f(int x)
{
if (x == 0) return 0;
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
}
int main()
{
cin >> n >> a >> b >> c;
memset(dp,0,sizeof(dp));
cout << f(n) << endl;
}
I wanted to know:
What is the need of the if statement that returns 0xACCE97ED for the test case:
4000 1 2 3. This test case dosen't work when that specific if statement is missing.
Why specifically 0xACCE97ED is being returned? Because when I tried to return any other number (say 9999), then the output is expected output + 9999.
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // -1395746835
Well looking at the dp function, it is basically maximizing values and this specific if statement is saying:
if x < 0
the length of the ribbon you cut is negative (which should be impossible)
or if x > 0 and x < a, b, c which means you can still cut X but all available sizes would result into having a ribbon of negative length
return 0xACCE97ED; return a random negative value which happens to spell out ACCEPTED because this state is invalid
And since the third if statement will try to get the max value, 0xACCE97ED will never be selected as the max value.
0xACCE97ED means "ACCEPTED" in the 1ee7 speech. nothing else specific about this value.
What is the need of the if statement that returns 0xACCE97ED for the test case: 4000 1 2 3
if (x < 0 || (x > 0 && x < a && x < b && x < c))
return 0xACCE97ED; // <- **I have doubt here**
because the function f is recursive, in the next line it calls itself:
if (!dp[x]) dp[x] = MAX(f(x-a),f(x-b),f(x-c)) + 1;
return dp[x];
with a smaller values for x so presumable it will eventually make that if statement true and will return "accepted" (0xACCE97ED).

There is an error in this program. Please can anyone identify it? Thanks [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hi all there seems to be an error in this program in the sense it is showing wrong output. Rather than showing number of consonants and vowels it is printing the length of the string.
#include<iostream>
using namespace std; // program to display the vowels and consonants of a string
int countvowels(char a[])
{
int count =0;
for(int i =0; a[i]!='\0';i++)
{
if((a[i]>=65 && a[i]<=90) || (a[i]>=97 && a[i]<=122)) // ignores digits,special characters
{
if((a[i]=65) || (a[i]=69) || (a[i]=73) || (a[i]=79) || (a[i]=85) || (a[i]=97) || (a[i]=101) || (a[i]=105) || (a[i]=111) || (a[i]=117) ) //ignores consonants
{
count++; //counts filtered out vowels
}
}
}
return count; // returns number of vowels which will be captured by x of main function
}
int countconsonants(char a[])
{
int count =0;
for(int i =0; a[i]!='\0';i++)
{
if((a[i]>=65 && a[i]<=90) || (a[i]>=97 && a[i]<=122)) // ignores digits,special characters
{
if((a[i]!=65) || (a[i]!=69) || (a[i]!=73) || (a[i]!=79) || (a[i]!=85) || (a[i]!=97) || (a[i]!=101) || (a[i]!=105) || (a[i]!=111) ||(a[i]!=117) ) //ignores vowels
{
count++; //counts filtered out consonants
}
}
}
return count; // returns number of consonants which will be captured by y of
main function
}
int main()
{
char a[100];
cout<<"Enter the string"<<endl;cin.get(a,100);
int x = countvowels(a);
int y = countconsonants(a);
cout<<"Number of vowels is"<<x<<endl; //nothing much to say about this part of the program. x just displays it and y does the same
cout<<"Number of consonants is"<<y<<endl;
return 0;
}
Here are the ASCII values of vowels.
A , a = 65,97
E,e = 69, 101
I,i = 73, 105
O,o = 79,111
U,u = 85,117
You have two problems with your code:
In checking for equality. To check if two value are equal you should use double equals== instead of a single equals. A single equal sign will mean assignment not equality check
In logical condition in count_consonants. a != 1 || a != 2 will always evaluate to true

Help me add parameters to a function that draws a pattern

Please help me answer this question , void Function with parameters. I do not understand it very well
I want to write a program so that the user can input both characters that form the pattern
I need to define two (characters) variables which are (star) and (next), the statement must include three parameters – one that will be an (int) for the pattern
and two that will be (characters) for the character to display the pattern.
I have to change the function (drawpattern) to have three values parameters
an (int) parameter indicating the size of the pattern and two (characters) indicating the character that will be used to display the pattern .
input (4) for size, (Y) for the character to be used to start the pattern and (+) for the second and every alternate group
This is what I have done so far and I do not now if is okay:
#include <iostream>
using namespace std;
void drawPattern(int size, char start, char next)
{
for (int i = 0; i <= size; i++)
for (int j = 0; j <= size; j++)
{
if ((i / size) % 3 == 0)
if ((j / size3) % 3 == 0)
cout << '4';
else
cout << 'Y';
else
if ((j / size) % 3 == 0)
cout << '+';
else
cout << '4';
}
}
int main ()
{
int size;
char start, next;
cout << "Please enter number ( 4 ) for the size of the pattern : ";
cin >> size;
cout << " Now enter leter ( Y ) to start the pattern: ";
cin >> start;
cout << "Lastly enter the ( + ) for the other pattern: ";
cin >> size;
cout << " This is the output pattern: " << endl;
drawPattern(size, start, next);
return 0;
}
It looks like you are hard coding your output in the drawPattern function and ignoring the actual input from the user. I think you should probably replace the 'Y' and '+' with the corresponding argument passed to the function, since I'm pretty sure the professor would not be happy about hard coded values.
At line 11, you have a typo. It says size3 where it should say size.
You are also making a logical mistake.
This code
if ((i / size) % 3 == 0)
is wrong in concept. At least as the code is written now. Normally you would write like this:
if (i % 3 == 0)
This if statement will be true every third row. The % (modulu) calculates the remainder of the integer (whole number) division firstnumber / secondnumber. If you have a sequence of i going from 0 to 10, this is what i % 3 outputs
i: 0 1 2 3 4 5 6 7 8 9 10
i%3: 0 1 2 0 1 2 0 1 2 0 1
As you can see, i % 3 == 0 is true when i is divisible by 3.
Your code does something different. Let's say size = 10. Then you calculate the (integer) division i / size. Lastly you calculate (i / size) % 3. However i is always less than size, except at the last turn of the loop. Let's look at the values again:
i: 0 1 2 3 4 5 6 7 8 9 10
size: 10 10 10 10 10 10 10 10 10 10 10
i/size: 0 0 0 0 0 0 0 0 0 0 1
Since the value of i / size only changes once, the calculation (i / size) % 3 is meaningless.