Is it possible to output the numpad's pattern using loops? - c

I just started learning C (coding in general) a few months ago. Earlier today when I was in class, I looked at the numpad and wondered whether I would be able to replicate the pattern using nested loops in C.
7 8 9
4 5 6
1 2 3 // This pattern.
I tried to do it myself for a bit, using for loops primarily. Thanks for any help.
#include<stdio.h>
int main()
{
int row, col, i;
printf("Up to what integer? ");
scanf("%d", &row);
for(i=1; i<=row; i++)
{
for(col=1; col<=10; col++)
{
printf(" %d ", i*col);
}
printf("\n");
}
}
Edit: Added supplementary code. Something like this, except to print 3 rows and 3 columns.

The numpad pattern has the equation 3*i + j with i going from 2 to 0 and j going from 1 to 3.
So use these values as upper and lower limits of i and j in nested for loops.
#include <stdio.h>
int main(){
for(int i = 2; i >= 0; i--){
for(int j = 1; j <= 3; j++)
printf("%d ", 3 * i + j);
printf("\n");
}
return 0;
}
See it live here.

Here's how you can do it:
for(int i = 0; i < 3; ++i){
for(int j = 3; j > 0; --j)
printf("%d ", (10 - j) - i * 3);
printf("\n");
}

Related

I want to print c pattern as upper triangle

I want to print some C pattern for upper triagnle which sholud print numeric value 1 to 10.
Now my code is like this:-
#include <stdio.h>
int main() {
int j = 1, k, l, i;
for (i = 4; i >= 1; i--) {
for (k = i - 1; k >= 0; k--) {
printf(" ");
}
for (l = 4; l >= i; l--) {
printf("%2d", j);
j++;
}
printf("\n");
}
return 0;
}
Its output is fine but when my value reach near 10 it's space is missing.
How can I resolve it?
My output looks like
1
2 3
4 5 6
7 8 910
It should be:
1
2 3
4 5 6
7 8 9 10
You can change the alignment by using the - sign. This makes it left-justified.
Replace
printf("%2d",j);
with
printf("%-2d",j);
Live demo
If you want the bottom of the pyramid to be completely to the left with no space you can replace
for (k = i - 1; k >= 0; k--)
with
for (k = i - 1; k > 0; k--)
EDIT:
As #chqrlie pointed out this will leave a trailing blank space in every line except the last one, this can be fixed like:
//...
for (i = 4; i >= 1; i--)
{
for (k = i - 1; k > 0; k--) // change from k >= 0 to k > 0
{
printf(" ");
}
for (l = 4; l >= i; l--)
{
printf(" %d", j); // change from "%2d" to " %d"
j++;
}
printf("\n");
}
//...
Live demo
For this problem, with n lines of output, you need to produce n - i spaces at the beginning of line i and i numbers each preceded by a space. Instead of "%2d", use " %d" and output one less space at the start of each line. You can use printf to output an arbitrary number of spaces using %*s and an empty string.
Here is a modified version:
#include <stdio.h>
int main() {
int i; // line number
int j = 1; // starting number
int n = 4; // number of lines
int k;
for (i = 1; i <= n; i++) {
printf("%*s", n - i, ""); // output n - i spaces
for (k = 0; k < i; k++) {
printf(" %d", j);
j++;
}
printf("\n");
}
return 0;
}
Output:
1
2 3
4 5 6
7 8 9 10
It can be solved in two ways:
One way to resolve this is by simply add spacing (padding) for each character you are printing.
#include<stdio.h>
int main()
{
int j=1,k,l,i;
for(i=4;i>=1;i--){
for(k=i-1;k>=0;k--){
printf(" ");
}
for(l=4;l>=i;l--){
printf(" %2d ",j); //Padding added
^ ^
j++;
}
printf("\n");
}
return 0;
}
Secondly you can change the alignment by using - sign
#include<stdio.h>
int main()
{
int j=1,k,l,i;
for(i=4;i>=1;i--){
for(k=i-1;k>=0;k--){
printf(" ");
}
for(l=4;l>=i;l--){
printf("-%2d",j); //Left justified
^
j++;
}
printf("\n");
}
return 0;
}
Amongst the other good answers, another way is to use printf("%d ", j); instead of printf("%2d", j); - Note the white space ' ' behind the %d format specifier. - This method has the disadvantage that you have a trailing white space after 10 but it accomplishes the (obvious) desired output:
Online example
#include <stdio.h>
int main (void)
{
int j = 1, k, l, i;
for (i = 4; i >= 1; i--){
for (k = i - 1; k >= 0; k--) {
printf(" ");
}
for(l = 4; l >= i; l--) {
printf("%d ", j);
j++;
}
printf("\n");
}
return 0;
}
Output:
1
2 3
4 5 6
7 8 9 10

What's wrong with my program which about Select sorting?

This is an example of a textbook. But when I verified the program, I found that the answer in the book was wrong. I can't find the wrong place for the code.
Thank you for your help!
I have already run the code. There are no syntax errors.
#include<stdio.h>
int main() {
int a[10], i, j, k, x;
printf("Input 10 numbers:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &a[i]);
}
printf("\n");
for (i = 0; i < 9; i++) {
k = i;
for (j = i + 1; j < 10; j++) {
if (a[j] < a[k]) {
k = j;
}
if (i != k) {
x = a[i];
a[i] = a[k];
a[k] = x;
}
}
}
printf("the sorted numbers:\n");
for (i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
The output is wrong.
For example:
Input 10 numbers:
1 3 2 4 6 5 7 8 11 9
the sorted numbers:
1 3 2 4 5 6 7 8 9 11
The problem is the swap check is in the wrong place. It's in the inner loop, but it needs to be after the inner loop (but inside the outer loop). The sort portion of the code should be:
for(i=0; i<9; i++){
k=i;
for(j=i+1; j<10; j++){
if(a[j]<a[k]){
k=j;
}
}
if(i!=k){
x=a[i];
a[i]=a[k];
a[k]=x;
}
}
Notice that the if(i!=k) check is now after the inner loop, rather than inside it.
With the following input:
Input 10 numbers:
1 3 2 4 6 5 7 8 11 9
It now produces:
the sorted numbers:
1 2 3 4 5 6 7 8 9 11
After indenting your code correctly it is clear: The if (i != k) {... is placed inside the loop. Put it one level higher.
Please adopt a good coding style (there are a lot) and stick to it. You will learn how many errors you will find with correct indentation.

How to write the algorithm of this matrix in this ascending order in C.Where is error in my code?

I am writing this code to print the following matrix in this spiral order(spiral by column).But my code is printing totally different thing.
a a+7 a+8 a+15
a+1 a+6 a+9 a+14
a+2 a+5 a+10 a+13
a+3 a+4 a+11 a+12
Here is what i did:
int main() {
int a;
int Sum = 0;
int i = 0, j = 0,n;
printf("Insert the value of n: ");
scanf("%d",&n);
printf("Insert the value of a number: ");
scanf("%d",&a);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",a);
a = a + 7;
printf("\t");
}
printf("%d",a);
a = a + 1 ;
printf("\n");
}
return 0;
}
The way I approached this is to build the matrix of values you actually want, but doing so in column order, where we can relatively easily control the logic of value progression by row. Then, with that matrix in hand, print out the values in row order, as you want the output:
int main()
{
int a = 7;
int n = 4;
int array[4][4];
for (int c=0; c < n; ++c)
{
for (int r=0; r < n; ++r)
{
// values ascending for even columns
if (c % 2 == 0)
{
array[r][c] = a + c*n + r;
}
// values descending for odd columns
else
{
array[r][c] = a + c*n + n-r-1;
}
}
}
for (int i=0; i < n; ++i)
{
for (int j=0; j < n; ++j)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
}
Output:
Demo here:
Rextester
Instead of using this complex mechanism to keep track of all elements you can just calculate the value to add at any time by simple arithmetic.
See this
int row;
int column;
printf("\n");
for (row = 0; row < n; row++) {
for (column = 0; column < n; column++) {
int base;
int flag;
if (column % 2 != 0) {
base = (column+1)/2 * 2*n - 1;
flag = -1;
}else {
base = column/2 * 2*n;
flag = 1;
}
printf( "%d ", a + base + flag * row);
}
printf("\n");
}
I hope you are able to follow this logic. If not feel free to ask.
Demo here:
Ideone
There seem to be two issues with your code as it is. As mentioned in the above comment, you are using the variable a in the loop calculation, so it is constantly being updated. This means your loop becomes invalid after a few iterations. If you define a dummy variable, this would avoid the problem. Secondly the implementation of the spiralling is close to being right, but it's not quite there.
Consider in the case n = 4. When you print along each row, the difference between a new element and the last alternates between values of (2n - 1) = 7 and 1. To take this into account, you could for example check every time you want to print whether the column index (j) is odd or even, and use this to determine which difference to add. Once you have the row machinery fixed, it shouldn't be difficult to extend it to the columns.
Simple solution using a matrix to calculate values before print them
#include <stdio.h>
int main(void)
{
int a;
int i = 0, j = 0, n;
printf("Insert the value of n: ");
scanf("%d", &n);
printf("Insert the value of a number: ");
scanf("%d", &a);
int matrix[n][n];
for (i=0; i< n*n; i++)
{
// even columns ascending
if (((i/n) % 2) == 0)
{
matrix[i%n][i/n] = a++;
}
// odd column descending
else
{
matrix[n-(i%n)-1][i/n] = a++;
}
}
for (i=0; i< n; i++)
{
for (j=0; j< n; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output
Insert the value of n: 4
Insert start value: 1
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13

C Programming and Matrix multiplication output issue

I'm currently learning C programming, to better my understanding of matrices in C I've tried to make this program.
I seem to be having problems with the output, as you can see the program has 3 functions.
The first one allows you to input the values for the array and then displays it. The second function performs the multiplication and the last should display the output of the multiplied matrix.
However the output is strange. Here is my code. The output is just below the code.
#include <stdio.h>
void read_matrix(int m2[][3] )
{
int i, j;
printf("input values for matrix in order of rows first \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d",&m2[i][j]);
}
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m2[i][j]);
}
printf("\n");
}
}
void multiply_matrices(int m1[][3], int m2[][3] ,int m3[][3])
{
int i, j, k;
for (i = 0; i < 3; i++){
for (j = 0; j < 3; j++){
for (k = 0; k < 3; k++){
m3[i][j] +=m1[i][k]*m2[k][j];
}
}
}
}
void write_matrix(int m3[][3] )
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", m3[i][j]);
}
printf("\n");
}
}
int main(void)
{
int matrix1[3][3], matrix2[3][3], matrix3[3][3];
read_matrix(matrix1);
read_matrix(matrix2);
multiply_matrices(matrix1, matrix2, matrix3);
write_matrix(matrix3);
return 0;
}
and this is the output!
input values for matrix in order of rows first
1
2
3
2
2
2
1
2
2
1 2 3
2 2 2
1 2 2
input values for matrix in order of rows first
2
1
1
1
2
1
2
1
2
2 1 1
1 2 1
2 1 2
-858993450 -858993452 -858993451 /*This is the multiplied matrix output!*/
-858993450 -858993452 -858993452
-858993452 -858993453 -858993453
Press any key to continue . . .
I fear it may be just a silly mistake; if so I'm sorry, but I can't see where I am going wrong at this moment.
Any help would be greatly appreciated.
You need to initialize all elements of matrix m3 to 0 before performing this operation
m3[i][j] +=m1[i][k]*m2[k][j];
in function multiply_matrices.
Initialize matrix3 in the function multiply matrix like this
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
m3[i][j]=0;
}
}
After this, do the multiplication and everything will work perfectly.
int m3[][]={};
It initially stores 0 for all available index of m3

How to remove characters from console output in C

Code1:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
putchar('\n');
}
return 0;
}
Output of Code1:
0 1 2 3
4 5 6 7
Remarks of Code1:
Space after 3 and 7
Newline after 7 (Stackoverflow has removed it)
Code2:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
{
printf("%hu", j);
if (j + 1 != k) putchar(' ');
}
if (i + 1 != 2) putchar('\n');
}
return 0;
}
Output of Code2:
0 1 2 3
4 5 6 7
Remarks of Code2:
No space after 3 and 7
No newline after 7
Additional remark of Code2:
The problem of Code2 is that the algorithm always compares two values in the if blocks and so Code2 is not efficient. I want to use Code1 and change these:
Code3
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 2; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k; j++)
printf("%hu ", j);
printf("\b\n");
}
putchar('\b');
return 0;
}
These do not show the same output of Code2 because \b does not erase anything.
My question:
Is there any standard way to do so what I've tried in Code3?
Remark of my question:
I have searched the internet but have not determined the solution.
Edit the question if it is not clear.
Edit: I don't know why my question is not useful or constructive. Though the above is an arbitrary small example, but performance might be an issue when processing very large amount of data. I thought that the way of removing character from console output might improve performance and there might be a specific way to do so. That's why I've asked the question. I could write the following codes in the answers. Now I've known via comments that removing character from console output is not possible because it is implementation dependent.
The usual approach to this is to treat either the first or the last printf as a special case (outside of the loop):
for(ii=0; ii<2; ii++) {
jj = 0;
printf("%d", jj); // first number printed without space.
for(jj=1; jj<4; jj++) {
printf(" %d", jj); // include the space before the number printed
}
if(ii<2-1) printf("\n");
}
Obviously I simplified how the loops are constructed and what is printed - for simplicity. You could make the first printf statement
printf("\n%d", jj);
then you have a newline at the start of your output (often a good thing) and then you don't need the if statement later - you just don't have a newline printed at the end of the line (because it will be printed at the start...)
There are marginally more efficient ways of doing this that would involve no if statements at all - but these all come at the expense of less readable code. For example, here is a "no loop unrolling and no additional if statements" version of the code:
http://codepad.org/01qPPtee
#include <stdio.h>
int main(void) {
int ii, jj;
ii = 0;
while(1) {
jj = 0;
while(1) {
printf("%d", jj); // include the space before the number printed
jj++;
if(jj<4) printf("."); else break;
}
ii++;
if(ii<2) printf("*\n"); else break;
}
return 0;
}
Output:
0.1.2.3*
0.1.2.3
Basically I have taken the functionality of the for loop and made it explicit; I also use a . rather than a and "*\n" rather than "\n" to show in the printout that things behave as expected.
It does what you asked without extra evaluation of the condition. Is it more readable? Not really...
If it really bothers you, you can unroll your loops a little so that you treat the last item as a special case:
#include<stdio.h>
int main()
{
unsigned short i, j, k;
for (i = 0; i < 1; i++)
{
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu\n", j);
}
k = i * 4 + 4;
for (j = k - 4; j < k - 1; j++)
{
printf("%hu ", j);
}
printf("%hu", j);
return 0;
}
#include <stdio.h>
int main(){
unsigned short num = 0, to=8;
while(num < to){
printf("%hu", num++);
if(num < to)
putchar(num % 4 == 0 ? '\n' : ' ');
}
#if 0
do{
printf("%hu", num++);
}while(num < to && putchar(num % 4 == 0 ? '\n' : ' '));
#endif
return 0 ;
}
Well, to try to answer your question, here's how I would do it:
for (i = k = 0; i < 2; i++){
if (i > 0) printf("\n");
for (j = 0; j < 4; j++, k++){
if (j > 0) printf(" ");
printf("%d", k);
}
}
I do it this way because I want to be sure every line but the first starts with a \n, and every item is separated by a space from the one before it.
Also, I do not want the row and column position to be intimately tied to the content of what is being printed.
In terms of performance, keep in mind that these if statements cost about 1 cycle, while each character printed costs at least hundreds if not thousands. printf goes through many layers of system calls to interpret its format string, build a buffer, send the buffer to the system I/O routines, which then cause repainting and scrolling of the console window. Get the idea?
DO NOT WORRY about performance unless you know you have a problem.
Then, don't guess. Use a diagnostic. Here's what I do.

Resources