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.