Home > Net >  Regarding print a pattern
Regarding print a pattern

Time:11-25

Question How can I give spaces between numbers? When I add a <<" " after cout<<j the pattern changed. Is there any other way to give spaces between numbers?

code

#include<iostream>
using namespace std;
int main(){
int i,j=1,space,star,n;
cin>>n;
i=1;

Looping

while(i<=n){
space=n-i;
 while(space){
    cout<<" ";
    space--;
 }
star=i;
while(star){
cout<<j<<" ";
j  ;
star--;
}
cout<<"\n";
   i  ;
}
return 0;

}

output for n=4

    1
   23
  456
 78910

I want this output :-

      1
    2 3
  3 4 5
7 8 9 10

CodePudding user response:

For the expected output you only need to add a second space in the while(space) loop:

    space = n - i;
    while (space) {
        std::cout << "  "; // note: two spaces
        space--;
    }

or multiply space by 2 before the loop:

    space = 2 * (n - i);
    while (space) {
        std::cout << ' ';
        space--;
    }

You could also #include <string> and skip the loop:

    space = 2 * (n - i);
    std::cout << std::string(space, ' ');

Another way of skipping the loop is to #include <iomanip> and use std::setw.

Note that you can use std::setw and std::left to correct the while (star) loop too to make this pattern hold for up to n = 13.

    space = 2 * (n - i)   1;
    std::cout << std::setw(space) << "";

    while (star) {
        std::cout << std::setw(2) << std::left << j;
        j  ;
        star--;
    }

Demo

  • Related