Today was a good day. I solved 4 coding problems for practice.
// in C++ , 2D array is an 1D array which consist pointer list to other 1D arrays.
- 1st : spiral printing of matrix elements:
#include<iostream>
using namespace std;
class Matrix{
int r,c;
int **mat;
public:
Matrix(){
int i,j;
cout<<"No. of rows: "<<endl;
cin>>i;
cout<<"No. of columns: "<<endl;
cin>>j;
r=i;
c=j;
mat = new int* [c];
for(int i=0; i<c; i++){
mat[i]=new int[r];
}
cout<<"Enter matrix elements:"<<endl;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
cout<<"mat["<<i<<"]["<<j<<"]= ";
cin>>mat[i][j];
}
}
}
void printMat(){
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
cout<<mat[i][j]<<"\t";
}
cout<<endl;
}
}
void spiralPrint(){
int i=0;
int j=0;
cout<<"Sprial print: \n";
while(i<r){
while(j<c){
cout<<mat[i][j]<<" ";
j++;
}
i++;
j=c-1;
while(j>=0){
cout<<mat[i][j]<<" ";
j--;
}
j=0;
i++;
}
}
};
int main(){
Matrix n;
n.printMat();
n.spiralPrint();
}
- 2nd: decide if given matrices are identical:
#include<iostream>
using namespace std;
#define N 2
class MatrixId{
public:
int r,c;
int **mat;
MatrixId(){
r=2;
c=2;
mat = new int* [c];
for(int i=0;i<c;i++){
mat[i]=new int[r];
}
cout<<"Enter matrix elements:"<<endl;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
cout<<"mat["<<i<<"]["<<j<<"]= ";
cin>>mat[i][j];
}
}
}
int areSame(int **A,int **B){
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(A[i][j]!=B[i][j]){
cout<<A[i][j]<< "!= "<<B[i][j];
return 0;
}
}
}
return 1;
}
};
int main(){
MatrixId A;
MatrixId B;
int t=A.areSame(A.mat,B.mat);
if(t==1)
cout<<"equal";
else if(t==0)
cout<<"not equal";
}
- 3rd: Move all hyphens at the beginning of string:
#include<iostream>
#include<string>
using namespace std;
void moveHype(string A){
int i=0;
string b,c;
while(A[i]){
if(A[i]=='-'){
// cout<<A[i];
b=b+A[i];
}
else{
//cout<<A[i];
c=c+A[i];
}
i++;
}
cout<<b+c;
}
int main(){
string st;
cout<<"Enter a string with hyphen";
cin>>st;
moveHype(st);
}
- 4th: pythagoras triplet up to given limit
#include<iostream>
using namespace std;
class Pythagorous{
public:
int lim;
Pythagorous(){
cout<<"Limit : "<<endl;
cin>>lim;
}
void triplet(int l){
int c=1,a=1,b=1;
int flg=0;
while(c<=l){
for(a=1;a<c;a++){
for(b=1;b<c;b++){
if((a*a)+(b*b)==(c*c)){
cout<<a<<" "<<b<<" "<<c<<endl;
flg=1;
break;
}
}
if(flg==1){
flg=0;
break; //if we got one pair of a and b for c then no other pair can be formed using either a or b for same c
}
}
c++;
}
}
};
int main(){
Pythagorous p;
p.triplet(p.lim);
return 0;
}
Comments
Post a Comment