Pattern

10:35 0 Comments A+ a-

Problem :
Write a C++ program which prints the following pattern by taking the height and width from the user. For example, if the user enters height to be 5 and width to be 11, the following pattern should be displayed on screen:
+++++++++++
+  +  +  +   +  +
+++++++++++
+  +   +  +  +  +
+++++++++++
In order to display the above pattern, your program should use ONLY following THREE cout statements:
cout << "+"; cout << " "; cout << endl;
Input validation: Your program should make sure that both height and width are odd numbers. Moreover, the value of height should be at least 3 and value of width should be at least 5. In case of invalid input, your program should keep prompting the user again and again till the user provides valid input.
Solution:

# include <iostream>
using namespace std;
int main()
{
int height; //height of pattern initialized
int width; //Width of pattern initialized
cout<<"Please enter the Height of Pattern (must be >=3 and odd)"<<endl;
cin>>height; //height of pattern declared
cout<<"Please enter the Width Of Pattern (must be >=5 and odd)"<<endl;
cin>>width; //Width of pattern declared
while(height<3 || width<5) //check for if height is less than three or width is less than five and to take input accordingly which value is entered wrong
{
if(height<3){ //Height check for <3
cout<<"Invalid input for Height of Pattern"<<endl;
cout<<"Enter the Height of Pattern again (must be >=3 and odd)"<<endl;
cin>>height; //Input for height again
}
else if(width<5) //Width check for <5
{
cout<<"Invalid input for Width of Pattern"<<endl;
cout<<"Enter the Width of Pattern again (must be >=5 and odd)"<<endl;
cin>>width; //Input for width again
}
}
if(height>=3 && width>=5) //check for if height or width are odd or even??
{
while(height%2==0 && height>=3) //check for height is either odd or not and also greater than 3 or not in case of again input
{
cout<<"Height must be odd number"<<endl;
cout<<"Enter the Height of Pattern again (must be >=3 and odd)"<<endl;
cin>>height; //Input for height again
}
while(width%2==0 && width>=5) //check for width is either odd or not and also greater than 5 or not in case of again input
{
cout<<"Width must be odd number"<<endl;
cout<<"Enter the Width of Pattern again (must be >=5 and odd)"<<endl;
cin>>width; //Input for width again
}
}
for(int i=0;i<height;i++) //Control of rows
{
if(i%2==0) //check for rows either even or odd
{
for(int j=0;j<width;j++) //display of even numbered row
{
cout<<"+";
}
cout<<endl;
}
else //check for rows either even or odd
{
for(int k=0;k<width;k++) //display odd numbered rows
{
if(k%2==0)
{
cout<<"+";
}
else
{
cout<<" ";
}
}
cout<<endl;
}

}


system("pause");
return 0;
}