Home > Back-end >  How i can print a number triangle in c
How i can print a number triangle in c

Time:09-22

#include<iostream>
using namespace std;
int main(){
int i=1;
do{
    if(i < 10){
        cout<<"00"<<i<<" ";
    }
    else if (i < 100){
        cout<<"0"<<i<<" ";
    }
    else {
        cout<<i<<" ";
    }
    if(i%10 ==0){
        cout<<endl;
    }
    i  ;        
}while (i <= 100);
return 0;
}

this is output

001 002 003 004 005 006 007 008 009 010
011 012 013 014 015 016 017 018 019 020
021 022 023 024 025 026 027 028 029 030
031 032 033 034 035 036 037 038 039 040
041 042 043 044 045 046 047 048 049 050
051 052 053 054 055 056 057 058 059 060
061 062 063 064 065 066 067 068 069 070
071 072 073 074 075 076 077 078 079 080
081 082 083 084 085 086 087 088 089 090
091 092 093 094 095 096 097 098 099 100

this is output that I want:

001
011 012
021 022 023
031 032 033 034
041 042 043 044 045
051 052 053 054 055 056
061 062 063 064 065 066 067
071 072 073 074 075 076 077 078
081 082 083 084 085 086 087 088 089
091 092 093 094 095 096 097 098 099 100

CodePudding user response:

You can do it with the help of a nested loop:

#include <iostream>
#include <iomanip>

int main() {
    for (int i = 0; i < 10; i  ) {
        for (int j = 1; j <= i   1; j  )
            std::cout << std::setw(3) << std::setfill('0') << i * 10   j << " ";
        std::cout << std::endl;
    }
}

CodePudding user response:

When looking at the expected output, I see two patterns:

001 
011
021
031
041
051
061
071
081
091

This could be produced by

for(int y = 0; y < 10;   y) { 
    int yval = y * 10   1;
    // see below
}

The column values to actually print seems to follow this pattern

for(int x = 0; x <= y;   x) {
    int xval = yval   x;
    // print xval
}

Now, it's only a matter of combining the two and to format the output correctly.

CodePudding user response:

You already know how to print the individual numbers, only the larger pattern is wrong. As the pattern is 2D, your code will be easier when that 2D aspect is also present in your code. What I mean: Instead of iterating i you can iterate row and column:

for (int row=0; row<10;   row) {
    for (int col=0; col<10;   col) {
        if ( ...... ) {
            print_number(row,col);
        }
    }
    std::cout << "\n";
}

After each row a newline is printed and you just need to figure out the right condition for the if and implement a print_number function (you already have most of what is needed for that function).

For bonus points you can read about break to improve the logic of the above loop. Alternatively adjust the bounds of the inner loop in such a way that you can remove the if.

  • Related