I can't understand what's wrong with the code. I've changed it many times, but errors are always similar.Can anyone please check the code and tell what's wrong?
3 Answers
1. You are declaring h
2 times. You will either have
int h;
h = GetInt();
or you will do it together as
int h = GetInt();
2. Your second for loop is not declared correctly. Usually they follow the following example
for (int i = 0; i < final_value; i++)
{
// do stuff here
}
Maybe you are trying to use a while
loop? Then it should be
while (s > 0 && s < 2*h-1)
{
// do stuff here
}
Let's start from the top.
- On line 8, inside the
do-while
loop, you're redeclaring the variableh
. - On line 13, in the loop's condition, you're not allowing for the posibility of height being
0
as per the pset's spec. - On line 16, in the
for
loop, you need to adjust yourinitialization statements
andcondition logic
to handle height being0
. - On line 20, you're redeclaring
s
again. - On line 21, you're using the
for
loop incorrectly, did you mean to use thewhile
loop?
After you're done with this I would suggest going through your logic again and checking if the algorithm you've come up with can produce the output you're expecting.
Here I could see a couple of errors and bugs. From Pset 1 (Mario), what I understood is you are creating a pyramid with a height greater than 0 and less than 23. The probs of your programs are,
Your condition in the first do-while loop says "get me an integer, greater than 23 and less than 1". Logically and theoretically such a condition never exists.
The for loop has three parts i. Initialization part, ii. Condition checking iii. Increment or decrement part. And also 'the variable' in the initialization part is known as the iteration variable. The changes in this value is helping the loop to be a loop or for the iteration. You seem to have forgotten that rule in line 25.
A hint from my side for this problem set is Nested for loop.