Reputation: 47
I'm trying to create a C program that prints a triangular pattern according to height by only using 1, 2 and 3 to generate the patterns:
Enter the height:
7
Pattern:
1
22
333
1111
22222
333333
1111111
I am only able to print the numbers but I do not know how to print only using 1, 2 and 3
This is my code so far:
printf("Enter the height: \n");
scanf("%d", &height);
if(height <0 || height > 10){
printf("Please enter height within 1 to 10!");
}
else{
printf("Pattern: \n");
for(row=1; row<=height; row++){
for(int col=1; col<=row; col++){
printf("%d", row );
}
printf("\n");
}
return 0;
}
The output:
Enter the height:
7
Pattern:
1
22
333
4444
55555
666666
7777777
Thank you
Upvotes: 1
Views: 424
Reputation: 7
#include<stdio.h>
#include<conio.h>
int main(){
int n; int l=1;
scanf("%d",&n);
for(int i=1;i<=n;i++){
int j=i;
while(j!=0){
printf("%d",l);
j--;
}
l++;
if(l==4){
l=1;
}
printf("\n");
}
}
Upvotes: 1
Reputation: 10460
I am only able to print the numbers but I do not know how to print only using 1, 2 and 3
This is because of you have been printing the row number in your code. There are many ways to achieve the same thing.
To solve your problem, you can have a variable (number
in my program below) and keep on incrementing
it in the outer for
loop and once it becomes more than 3
, then reset it to 1
.
void print_pattern(unsigned height)
{
unsigned row,number,column;
for (row=0, number=1; row < height; row++) {
for (column=0; column <= row; column++)
printf("%u", number);
printf("\r\n");
if (++number > 3)
number = 1;
}
}
Or You can use the operator modulus %
. You can apply it on row
variable (see the program below) to get the the number to be printed at a particular row.
void print_pattern(unsigned height)
{
unsigned row,column;
for (row=0; row < height; row++) {
for (column=0; column <= row; column++)
printf("%u", (row % 3) + 1);
printf("\r\n");
}
}
Upvotes: 2
Reputation: 20931
Just change your print statement like,
printf("%d", (row % 3) > 0 ? row % 3 : 3);
Upvotes: 3
Reputation: 643
use the mod operation % .. (number%4) is between 0 and 3 .. since you want it from 1 to 3 then take (number%3+1) ..
printf("Enter the height: \n");
scanf("%d", &height);
if(height <0 || height > 10){
printf("Please enter height within 1 to 10!");
}
else{
printf("Pattern: \n");
for(row=1; row<=height; row++){
for(int col=1; col<=row; col++){
printf("%d", (row%3)+1 );
}
printf("\n");
}
return 0;
}
Upvotes: 1
Reputation: 3764
The change would be:
for(row=1; row<=height; row++){
int num = row%3;
if(num==0)
num = 3;
for(int col=1; col<=row; col++){
printf("%d", num );
}
printf("\n");
}
Logic:
1. Divide the value of row
by 3 and get the remainder (i.e., perform row % 3
).
2. If the remainder is 0, it means that the row number is a multiple of 3. Therefore, print 3s.
3. Otherwise, print the remainder.
Upvotes: 2