1Print triangle of 0s and 1s Write a C program that prompts
1-Print triangle of 0s and 1s:
Write a C++ program that prompts the user for a positive number n. The program then prints the triangle containing the n number of lines, as shown below: each line alternately starts with 1 and 0.
2- Patterns:
Write a C++ program that prompts the user for a positive number. The program then prints the pattern given below. Hint: think in terms of triangle making about the square.
Solution
1)
#include<bits/stdc++.h>
#include <ctime>
using namespace std;
int main() {
int i, j;
int count = 1;
int n;
cout<<\"Enter number of rows\ \";
cin>>n;
int start_s=clock();
for (i = 1; i <= n; i++) {
cout<<\"\ \";
for (j = 1; j <= i; j++) {
cout<<(count % 2);
count++;
}
if (i % 2 == 0)
count = 1;
else
count = 0;
}
int stop_s=clock();
cout << \"\ Execution Time : \" << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;
return(0);
}
================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ alternate.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Enter number of rows
5
1
01
101
0101
10101
Execution Time : 0.095
=================================================
2)
#include<bits/stdc++.h>
#include <ctime>
using namespace std;
int main() {
int i, j;
int count = 1;
int n;
cout<<\"Enter number of rows\ \";
cin>>n;
int start_s=clock();//start time
int m[n][n];//create matrix
memset(m,0,sizeof(m));
for (i = 0; i <n; i++)
{
int k=1;
int m1=i;
for (j = 0; j <(n); j++)
{
if(j>i)
{
m[i][j]=k;
k++;
}
if(j<i)
{
m[i][j]=m1;
m1--;
}
}
cout<<endl;
}
for (i = 0; i <n; i++) //print matrix
{
int k=1;
for (j = 0; j <(n); j++)
{
cout<<m[i][j]<<\" \";
}
cout<<endl;
}
int stop_s=clock();
cout << \"\ Execution Time : \" << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;
return(0);
}
========================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ squre.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Enter number of rows
5
0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0
Execution Time : 0.139


