The Definitive C++ Book Guide and List

Pattern problem in C programming language

The problem with your code is your special case will only fire on the first and fourth row. We can see this a little better if we space things out.

if( 
(i==1 && j>=i) || // `i==1` only on the first row
(i==4 && j<=i) // `i==4` only on the fourth row
) {
printf("%c",65+1);
}

Every other iteration will use your else block that just prints A.

else {
printf("%c",65);
}

Note: 'A' is much easier to read than 65, and 'B' much easier than 65+1.


There's plenty of ways to do this. Here's one elegant way with a single loop.

We can observe that we want to print BBBB at the start and every third row. If we start iterating at 0 we can do this when i is divisible by 3. 0/3 has a remainder of 0. 3/3 has a remainder of 0. We use the modulus operator % to get the remainder.

for(int i = 0; i < 4; i++) {
if( i % 3 == 0 ) {
puts("BBBB");
}
else {
puts("BAAB");
}
}

This will continue to repeat the pattern if you extend the loop. 6/3 has a remainder of 0. 9/3 has a remainder of 0. And so on.

(You could also start with i=1 and check i%3 == 1, but get used to starting counting at 0; it makes a lot of things easier.)

Using named_scope to get row count

The functionality you're looking for is built in.

Foobar.count # SELECT count(*) AS count_all FROM "foobars"
Foobar.named_scope.count # SELECT count(*) AS count_all FROM "foobars" WHERE ....

If you run script/server in dev mode, you'll see the queries as they get executed.



Related Topics



Leave a reply



Submit