Following is the program to print diamond using for loop in any programming language.
#include<iostream>
using namespace std;
int main()
{
int row,c,k,space=1;
cout<<"enter number of rows that you want to see=";
cin>>row;
space=row-1;
for(k=1;k<=row;k++)
{ //for loop to print space
for(c=1;c<=space;c++)
{
cout<<" ";
}
space--; //decrement the number of spaces by 1 each time
//for loop to print stars
for(c=1;c<=2*k-1;c++)
{
cout<<"*";
}
cout<<"\n";//move to the next line
}
//following will print second half of diamond
space=1;
//here we need to increment the space from 1 2 3 4 and so on
for(k=1;k<=row-1;k++)
{
for(c=1;c<=space;c++)
{
cout<<" ";
}
space++;// increment the number of space by 1 each time
for(c=1;c<=2*(row-k)-1 ;c++)
{
cout<<"*";
}
cout<<"\n";
}
return 0;
}
No comments:
Post a Comment