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
How to Execute a Command and Get the Output of the Command Within C++ Using Posix
Print Heart Shape With Words Inside
Count How Many Times Elements in an Array Are Repeated
How to Get Installed Windows Sdk Version
Get Current Time in Milliseconds, or Hh:Mm:Ss:Mmm Format
Vector of Structs Initialization
Checking the Neighbour Values of Arrays
Method That Converts Uint8_T to String
Writing a Sequence of Numbers Like: 1 22 333 4444 55555
Find Middle Elements from an Array
C++: Modifying Array Via Function
How to Cast Const Uint8_T* to Char*
How to Calculate and Display the Average of the 5 Numbers in C++
Check If Element Found in Array C++