Write a C++ program that takes 2 characters (c and d), and a positive integer (n) and outputs the following
drawing of size n n made of the characters c and d, as shown below:
Enter two characters and an integer: # _ 6
#_#_#_
_#_#_#
#_#_#_
_#_#_#
#_#_#_
_#_#_#
Press any key to continue . . .

this is the question..
I did till here but I don't know how to continue
#include <iostream>
using namespace std;

int main()
{
int n;
char c, d;
cout << "Enter two characters and an integer: " << flush;
cin >> c >> d >> n;

someone plz help me..thanks...:S....

I came up with a way to output the characters and semi commented what is going on.

#include <iostream>

using namespace std;

int main()
{
    int n;
    char in[2]; //change to an array (see output)
    cout << "Enter two characters and an integer: " << flush;
    cin >> in[0] >> in[1] >> n;

    for( int i = 0; i < n; i++ )
    {
    	for( int c = 0; c < n; c++ )
    		cout << in[((c%2)+(i%2))%2]; //output the character based on the row and col and then mod by 2 so it does not leave the array's range
    	cout << endl;
    }
    return 0;
}

This should do it:

bool toggle = 1;
for(int i=0;i<n;i++) {
    for(int y=0;y<n;y++) {
            if(toggle) cout << c;
            else cout << d;
            toggle = !toggle;
    }
    cout << endl;
}
void print(char c,char d,int n)
{
    for(int i = 0;i<n;i++)
    {
       for(int j = 0;j<n;j++)
       {
           printf("%c%c",c,d);
       }
       char temp = c;
       c = d;
       d = temp;
       printf("\n");
    } 
}

Edited 6 Years Ago by sundip: n/a

Well since everyone is posting their solution, might as well post mines :

void printPattern(char ch1, char ch2, const int MAX){	
	for(int r = 0; r != MAX; ++r){
		for(int c = 0; c != MAX; ++c){
			cout << (c % 2 == 0 ? ch1 : ch2 ) ;
		}
		cout << endl;
	}
}

Well since everyone is posting their solution, might as well post mines :

void printPattern(char ch1, char ch2, const int MAX){	
	for(int r = 0; r != MAX; ++r){
		for(int c = 0; c != MAX; ++c){
			cout << (c % 2 == 0 ? ch1 : ch2 ) ;
		}
		cout << endl;
	}
}

Problem here is that it does not change based on the rows. For even rows it should output the 1st char and odd ones should output 2nd char.

This article has been dead for over six months. Start a new discussion instead.