For loop Help

Hi everyone, So my program needs to print out an inverted pyramid of numbers. I have a working code but I don't think i am allowed to use if and else statements to complete it. Is there anyway to write the code without the use of if and else. The assignment says to use a while loop to repeatedly prompt the user. In this case, n must be odd and positive. I have tried a few ways and cant get anywhere. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#include <iostream>
using namespace std;

int main()
{
  int n;
  cout<<"Please Enter the number n : ";
  cin>>n;

  int j,k;
  int i=0;
  while(i<=n/2)
    {
      if(n<=0 || (n%2)==0)
	{
	  cout<<"Enter a positive off number. Try again: ";
	  cin>>n;
	  cout<<endl;
	}
      else
	{
	  for(k=0 ; k<i ;k++)
	    cout<<" ";
	  for(j=n-i;j>i;j--)
	    {
	      cout<<j%10;
	    }
	  cout<<endl;
	  i++;
	}
    }
  return 0;
}
use a while loop to repeatedly prompt the user

Does that mean that once a pyramid has been printed, the programs asks for a new number for a new pyramid? How should one stop such outmost loop?

An input of integer has three possible outcomes:
1. Failed input. Stream in error state. Could be due to EOF or non-digits in input.
2. An integer
2a Invalid
2b Valid; odd and positive

There is usually some testing in the form of if. It does depend on how you need to handle each case.

One scenario is to continue only until the input is not odd and positive:
1
2
3
4
5
6
7
8
9
int value = 0;
std::cout << "Enter an odd, positive integer:\n";
while ( std::cin >> value && 0 < value && 1 == (value%2) ) {
  // print the pryramid with value

  // next round
  std::cout << "\nEnter an odd, positive integer:\n";
}
std::cout << "Input was not an odd, positive integer. Goodbye!\n";
I got it but thanks. I had my for loop inside the while which is what was wrong. Thanks :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

int main()
{
  int n;
  cout<<"Please Enter the number n : ";
  cin>>n;

  int j,k;
  int i=0;
  while((n<=0 || (n%2)==0))
    {
      cout<<"Enter a positive odd number. Try again: ";
      cin>>n;
    }

  cout<<endl;

  for(i=0;i<=n/2;i++)
    {
      for(k=0 ; k<i ;k++)
	cout<<" ";
      for(j=n-i;j>i;j--)
	{
	  cout<<j%10;
        } 
      cout<<endl; 
    }
  return 0;
}
Topic archived. No new replies allowed.