Sunday, 21 December 2014

Learn to print a cross pattern in C++ (With Comments)

PRINT A CROSS Pattern !!
Problem:
                       Print Cross on Console
Solution:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int size , half , su , sl; /* half for printing both halves , su and sl for setw of upper and lower half*/
cout << "Please Enter the size of cross (must be odd and >3): ";
cin >> size;

while(size % 2 == 0 || size < 3)
{
cout << "Invalid input !! Enter again(must be odd and >3): ";
cin >> size;
}

half = size/2;
int a = 1; //a is taken to set the value of setw on the left hand side *
su = size - 1; //su is taken 1 less than size because 1 * is already printed
sl = 2; //sl is taken 2 as because after the middle line the * are two spaces away from each         other.
for(int i=0 ; i<half ; i++)  //for loop to control upper half rows 
{
cout << setw(a)<< "*";
cout << setw(su)<< "*"<< endl;
a++;
su -= 2; /*2 is subtracted from s each time this loop runs as the upper left * moves right                 by 1 value and right * moves left by 1 each time*/
}

cout << setw(half + 1) << "*" << endl; //to display center row
int b = size/2;

for(int i=0 ; i<half ; i++) //for loop to control lower half rows
{
cout << setw(b)<< "*";
cout << setw(sl)<< "*" << endl;
b--;  //1 is subtracted from b each time as the the lower left * moves left in each turn.
sl += 2; //2 is added in t as the lower right and left * moves away by value 1 each.
}

return 0;
}


No comments:

Post a Comment