need some printing number pyramid - c

I need to program a number pattern pyramid like that:
Here is my code:
#include<stdio.h>
int main()
{
int i, j, rows = 5;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d ", j);
}
printf("\n");
}
for (i = 0; i <= 5; i++)
{
for (j = 0; j <= i; j++)
{
printf("%d ", j);
}
printf("\n");
}
}
Where am I doing wrong? I need to flip somehow the first triangle pattern and mix it with the second. Please help.

Your pyramid is 6 levels high. The max number is 5. This is not a coincidence. There is a direct relationship.
If n is 5, you need to do something 6 times, from 0 to n. There's a loop.
for (int i = 0; i <= n; i++) {
...
}
On each row you need to do print from i to 0, and then from 1 to i. That's two loops.
for (int j = i; j > 0; j--) {
...
}
for (int j = 1; j <= i; j++) {
...
}
Of course, you also need to indent a number of spaces inversely related to i, which is another loop.
for (int j = 0; j <= /* Fill in here for inverse relationship */; j++) {
...
}

I need to flip somehow the first triangle pattern and mix it with the second.
TL;DR The trick is very simple: your row index i should start from |n - j| (or abs(n - j)) where j is the column index and n is the number.
Here is how you can do it:
for (int j = 0; j < ncols; ++j) {
for (int i = abs(n - j); i < nrows; ++i) {
matrix[i][j] = '0' + abs(n - j);
}
}
Explanation:
Imagine you have a matrix. In order to build a pyramid with a number n, you will need:
n + 1 rows (since you will have 0 included in the top). Let's call it nrows.
2n + 1 columns (2n because the numbers will appear twice in a row, 1 because you will have one 0 per row). Let's call it ncols.
0 1 2 3 4 5 6 7 8 9 10
- - - - - - - - - - -
0 | 0
1 | 1 0 1
2 | 2 1 0 1 2
3 | 3 2 1 0 1 2 3
4 | 4 3 2 1 0 1 2 3 4
5 | 5 4 3 2 1 0 1 2 3 4 5
First, you want to fill the first half, i.e. from column 0 to n: for (int j = 0; j <= n; ++j).
J | End | Start | Pattern of Start
---------------------------------------
0 | N | N | N - 0
---------------------------------------
1 | N | N - 1 | N - 1
---------------------------------------
2 | N | N - 2 | N - 2
---------------------------------------
... | ... | ..... | N - J
---------------------------------------
N | N | 0 | N - N
The pattern is: for (int i = n - j; i < nrows; ++i). You would fill that first half with n - j.
Second, you want to fill the second half, i.e. from column n + 1 to 2n: for (int j = n + 1; j < ncols; ++j).
J | End | Start | Pattern of Start
------------------------------------------
N + 1 | N | 1 | N + 1 - N = J - N
------------------------------------------
N + 2 | N | 2 | N + 2 - N = J - N
------------------------------------------
N + 3 | N | 3 | N + 3 - N = J - N
------------------------------------------
..... | ... | ..... | N + X - N = J - N
------------------------------------------
2N | N | N | 2N - N = J - N
The pattern is: for (int i = j - n; i < nrows; ++i). You would fill that second half with j - n.
Now, you can do two separate for loops to fill the first and second halves.
// Fill first half
for (int j = 0; j <= n; ++j) {
for (int i = n - j; i < nrows; ++i) {
matrix[i][j] = '0' + n - j;
}
}
// Fill second half
for (int j = n + 1; j < ncols; ++j) {
for (int i = j - n; i < nrows; ++i) {
matrix[i][j] = '0' + j - n;
}
}
You can write one for loop by replacing n - j and j - n with abs(n - j), since both of them are positive values (see TL;DR above, or the code below).
Full functionning code:
#include <stdio.h>
#include <stdlib.h>
void print_matrix(const int nrows, const int ncols, const char matrix[nrows][ncols])
{
for (int i = 0; i < nrows; ++i) {
for (int j = 0; j < ncols; ++j)
printf("%c ", matrix[i][j]);
printf("\n");
}
}
void init_matrix(const int nrows, const int ncols, char matrix[nrows][ncols], const char value)
{
for (int i = 0; i < nrows; ++i)
for (int j = 0; j < ncols; ++j)
matrix[i][j] = value;
}
void print_pyramid(const int n)
{
// Calculate the number of rows and columns
const int nrows = n + 1;
const int ncols = n * 2 + 1;
char matrix[nrows][ncols];
// Initialization
init_matrix(nrows, ncols, matrix, '\0');
// Fill the matrix
for (int j = 0; j < ncols; ++j) {
for (int i = abs(n - j); i < nrows; ++i) {
matrix[i][j] = '0' + abs(n - j);
}
}
// Printing
print_matrix(nrows, ncols, matrix);
}
int main(void)
{
print_pyramid(5);
}

You have to include all 3 for loops in one for loop which runs 6 times. First you have to print spaces. Then first half of the triangle and then the other half. After that you have to print \n .
#include<stdio.h>
int main()
{
int i, j,k,l;
for (i = 0; i <=5; i++)
{
for (j = 5; j > i; j--)
{
printf(" ");
}
for (k = i; k >=0; k--)
{
printf("%d ", k);
}
for (l = 1; l <=i; l++)
{
printf("%d ", l);
}
printf("\n");
}
}

Related

Printing A Pattern in C

I am a beginner in programming, I studied all about C, I started to solve problems from hackerrank.com, there I faced a problem to print a pattern like given below
(the output of problem program):
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
the input will be an integer which will provide the data for the length of pattern square, here it is 4 in image,
I tried a lot to type a proper logic and I end up with this useless code bellow:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int array[n- 1 + n][n - 1 + n];
array[(n - 1 + n) / 2][(n - 1 + n) / 2] = 1;
int f[n];
for(int i = 0; i < n; i++) {
f[i] = i;
}
for(int i = 0; i < n - 1 + n; i++) {
for(int j = 0; j < n - 1 + n; j++) {
array[j][i] = n - f[j]; //top
array[i][j] = n - f[j]; //left
array[(2 * n - 1 - 1) - i][j] = n - f[i]; //bottem
array[j][(2 * n - 1 - 1) - i] = n - f[i]; //rigth
}
}
for(int i = 0; i < n - 1 + n; i++) {
for(int j = 0; j < n - 1 + n; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
return 0;
}
my logic was to make all four borders correct in for loop which will end at center, but its not working, I want a new logic or to improve my logic, if you want to help me out then please give me the way to solve problem instead of giving me a direct code.
It is observable that the pattern consists of n stacked squares:
Square #0 is drawn with ns.
Square #1 is drawn with n-1s.
...
Square #n-1 is drawn with 1s.
Implementing the above:
void draw_pattern(const size_t n)
{
const size_t dim = 2*n-1;
int array[dim][dim];
for (size_t i = 0; i < n; ++i) { // Outer square #i
// Row #0 of the outer square #i
for (size_t j = i; j < dim-i; ++j)
array[i][j] = n-i;
// Row #n-1 of the outer square #i
for (size_t j = i; j < dim-i; ++j)
array[dim-i-1][j] = n-i;
// Col #0 of the outer square #i
for (size_t j = i; j < dim-i; ++j)
array[j][i] = n-i;
// Col #n-1 of the outer square #i
for (size_t j = i; j < dim-i; ++j)
array[j][dim-i-1] = n-i;
}
print_array(dim, array);
}
This is print_array():
void print_array(const size_t dim, int array[dim][dim])
{
for (size_t i = 0; i < dim; ++i) {
for(size_t j = 0; j < dim; ++j)
printf("%d ", array[i][j]);
printf("\n");
}
}
Output:
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
The worst case time complexity is O(n2).
When you get a problem like this, try to dumb it down as much a possible. This square can be separated into 8 same, just rotated "slices" that look like:
4 | 4444 | 4444 | 4
43 | 333 | 333 | 34
432 | 22 | 22 | 234
4321 | 1 | 1 | 1234
... and the same for the bottom half, just flipped.
You can see this in the code bellow, to check what line is writing what part of the square, comment it and you will see what section shows zeroes.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
int array[2 * n - 1][2 * n - 1];
for(int i = 0; i < 2 * n - 1; i++){
for(int j = 0; j < 2 * n - 1; j++){
array[i][j] = 0;
}
}
int f[n];
for(int i = 0; i < n; i++)
{
f[i] = i;
}
for(int i = 0; i < n; i++)
{
for(int j = i; j < n; j++)
{
array[i][j] = n - i;
array[j][i] = n - i;//top left
array[j][2*n - i - 2] = n - i;
array[i][2*n - j - 2] = n - i;//bottom left
array[2*n - j - 2][i] = n - i;
array[2*n - i - 2][j] = n - i;//top right
array[2*n - i - 2][2*n - j - 2] = n - i;
array[2*n - j - 2][2*n - i - 2] = n - i;//bottom right
}
}
for(int i = 0; i < n - 1 + n; i++)
{
for(int j = 0; j < n - 1 + n; j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
return 0;
}

How could I align my output to the center?

#include<stdio.h>
int main()
{
int n ;
printf("Input the number of rows: ");
scanf("%d", &n);
for(int i = 1; i <= n ; i++)
{
for(int j = 1 ; j <= i ; j++)
{
if(j == i + 1)
{
break;
}
printf("%3d", j);
}
for(int j = i - 1 ; j > 0; j--)
{
if(j == 0)
{
break;
}
printf("%3d", j);
}
printf("\n");
}
}
Program session
Number of rows for this output n = 3
My output:
1
1 2 1
1 2 3 2 1
Preferred output:
1
1 2 1
1 2 3 2 1
This here is an exercise where I have to print a pyramid of numbers where the central number of the pyramid is the number of the row. I understand the logic but as you can see I have not been able to fulfill the task successfully. Any tips?
As pointed out by #WeatherWane, you need to add logic to add extra spaces. If you notice carefully, number of spaces on each line(excluding padding you add with %3d is equal to 3 * (n - i)). You can create a simple method like this to add spacing:
void addSpaces(int N, int currentIndex, int padding) {
for (int index = currentIndex; index < N; index++)
for (int spaces = 0; spaces < padding; spaces++)
printf(" ");
}
then you can call it from your first for loop like this:
for(int i = 1; i <= n ; i++)
{
addSpaces(n, i, 3);
for(int j = 1 ; j <= i ; j++)
{
// ...
I tested it and it seems to align it correctly:
c-posts : $ ./a.out
Input the number of rows: 5
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

Sorting a 2D Array c++

I am bubble sorting a 2D array that looks like this. I am confuse on how to make my largest value as 1 and make the 2nd row's value follow to 1st row's counterpart.
Input:
13 9 1 8 5
1 2 3 4 1
Actual output:
1 5 8 9 13
1 2 3 4 1
This is the expected output that i am trying to make.
Output:
5 8 9 13 1
1 4 2 1 1
Here is my code for sorting the cards (col = 5 and row = 2):
void sortedCards(int card[][col])
{
int i, j, k, temp;
printf("\n\nSorted Cards\n");
for (k = 0; k < 10; k++)
{
for (i = 0; i < row - 1; i++)
{
for (j = 0; j < col - 1; j++)
{
if (card[i][j] > card[i][j + 1])
{
temp = card[i][j];
card[i][j] = card[i][j + 1];
card[i][j + 1] = temp;
}
}
}
}
for (i = 0; i < row; i++)
{
if (i == 1)
{
printf("\n");
}
for (j = 0; j < col; j++)
{
printf("%i ", card[i][j]);
}
}
}
If your sorting is only dependent on the first row, there is no need to iterate through the second row. Just set both rows at the same time while checking the first row.
Also, if you want 1 to be treated as larger than all other numbers, you need to add that to your Boolean logic. Adjusting your for loop like below should do it.
int j, k, temp, temp2;
for (k = 0; k < 10; k++)
{
for (j = 0; j < col-1; j++)
{
//here we only test row 0, and we check if the value is 1
if (card[0][j] == 1 || (card[0][j] > card[0][j+1] && card[0][j+1] != 1))
{
//all other reassignment is the same but you do both rows at the same time
temp = card[0][j];
temp2 = card[1][j];
card[0][j] = card[0][j + 1];
card[1][j] = card[1][j + 1];
card[0][j + 1] = temp;
card[1][j + 1] = temp2;
}
}
}

unswitch while loop optimization in c

I'm having a hard time optimizing the following while loop by means of Loop Unswitching. I have tried applying the example from wiki, however I am having a hard time applying it to a while loop. I have the following code:
int n = 5,
m = 5,
i = 0,
val = 0;
while (i < n ) {
j = 0;
while (j < m ) {
if (i < j ) {
val = val + i ;
}
else if ( j == i ) {
val = val - 1;
}
else {
val = val + j ;
}
j = j + 1;
}
i = i + 1;
}
And have tried unswitching it the following way:
while (i < n ) {
j = 0;
if (i < j ) {
while (j < m ) {
val = val + i;
j = j + 1;
}
}
if ( j == i ) {
while (j < m) {
val = val - 1;
j = j + 1;
}
}
if (i > j) {
while (j < m) {
val = val + j;
j = j + 1;
}
}
i = i + 1;
}
What could I be doing wrong.
Such loops are best unrolled with the help of pencil and paper. You want the sum of the following grid:
0 1 2 3 4 | 5 n
0 -1 0 0 0 0 | 0 0
1 0 -1 1 1 1 | 1 1
2 0 1 -1 2 2 | 2 2
3 0 1 2 -1 3 | 3 3
m 0 1 2 3 -1 | 4 4
The grid can be subdivided into three parts: the diagonal, the upper and lower triangles next to the diagonal in the square part and the rectangular block when n and m differ.
Let's represent the dimension of the grid by means of the square part, k² and the rectangular part, k·r:
k = min(n, m)
r = max(m, n) - k
Now you can see which sums the three parts contribute:
val = 2·∑(k - i - 1)·i # two triangles
+ r·∑(i) # rectangle
- k # diagonal
(All sums run from i = 0; i < n; i++.) This sum can be rearranged to:
val = 2·(k - 1)·∑(i) - 2*∑(i²) + r·(i) - k
= (2·k + r - 2)·∑(i) - 2*∑(i²) - k
This reduces your two nested loops two two independent loops to do the sums of the natural numbers and of their squares. Fortunately, these sums can be expressed by simple relations:
∑(i) = (n - 1)·n / 2
∑(i²) = (2·n - 1)·(n - 1)·n / 6
You now have a constant-time formula for your resulting sum:
int val(int n, int m)
{
int k = (n < m) ? n : m;
int r = ((n > m) ? n : m) - k;
return (2*k + r - 2) * (k - 1) * k / 2
- (2*k - 1) * k * (k - 1) / 3 - k;
}
All this doesn't have anything to do with loop unrolling, of course.
Loop unswitching according to wikipedia is a compiler optimization so I'm a little confused about why you'd need to do this yourself, but I think this is as good as it gets in terms of breaking apart the for..ifs
for (i = 0; i < n; ++i) {
// j < i
for (j = 0; j < i; ++j) {
val = val + j;
}
// j == i
val = val - 1;
// j > i
for (j = i + 1; j < m; ++j) {
val = val + i;
}
}
This is not a loop you can traditionally unswitch because the conditional variable here is the loop variable.

2d-arrays in bubble sorting

I'm trying to create a 2d-array in bubble sort, arranged 25 numbers 5 by 5 in ascending order
my inputs
Enter 25 integers:
Input No.[0][0]: 4
Input No.[0][1]: 5
Input No.[0][2]: 8
Input No.[0][3]: 9
Input No.[0][4]: 4
Input No.[1][0]: 2
Input No.[1][1]: 1
Input No.[1][2]: 0
Input No.[1][3]: 2
Input No.[1][4]: 4
Input No.[2][0]: 6
Input No.[2][1]: 7
Input No.[2][2]: 4
Input No.[2][3]: 5
Input No.[2][4]: 5
Input No.[3][0]: 4
Input No.[3][1]: 8
Input No.[3][2]: 9
Input No.[3][3]: 1
Input No.[3][4]: 2
Input No.[4][0]: 4
Input No.[4][1]: 5
Input No.[4][2]: 2
Input No.[4][3]: 1
Input No.[4][4]: 9
my output shows
Ascending:
4 4 5 8 9
0 1 2 2 4
4 5 5 6 7
1 2 4 8 9
1 2 4 5 9
as you can see its not in proper arranged, it only arranged the 5 numbers each lines not the whole numbers
can anybody help arranged my integers like this
Ascending:
0 1 1 1 2
2 2 2 4 4
4 4 4 4 5
5 5 5 6 7
8 8 9 9 9
this is my code so far
int main(){
int rows = 5, cols = 5;
int arr[rows][cols];
int i,j,k,swap;
printf("Enter 25 integers:\n");
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
printf("Input No.[%d][%d]: ", i+0,j+0);
scanf("%d", &arr[i][j]);
}
}
for(k = 0; k < rows; k++){
for(i = 0 ; i < cols; i++){
for(j = i + 1; j < cols; j++){
if(arr[k][i] > arr[k][j]){
swap = arr[k][i];
arr[k][i] = arr[k][j];
arr[k][j] = swap;
}
}
}
}
printf("Ascending:\n");
for( i = 0 ; i < rows; i++){
for( j = 0 ; j < cols; j++){
printf("%3d", arr[i][j]);
}
printf("\n");
}
getch();
}
Improving on Ahmad's answer, I would like to add the following code (for shorting the table in ascending order):
#include <stdio.h>
#define COL 5
#define ROW 6
int main()
{
int temp, t, i, j;
int arr[ROW][COL]={30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
for(t=1; t<(ROW*COL); t++)
{
for(i=0; i<ROW; i++)
{
for(j=0; j<COL-1; j++)
{
if (arr[i][j]>arr[i][j+1])
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
}
for(i=0; i<ROW-1; i++)
{
if (arr[i][COL-1]>arr[i+1][0])
{
temp=arr[i][COL-1];
arr[i][COL-1]=arr[i+1][0];
arr[i+1][0]=temp;
}
}
}
for(i=0; i<ROW; i++)
{
printf("\n");
for(j=0; j<COL; j++)
printf("%3d", arr[i][j]);
}
return 0;
}
replace the input with your table and the definitions with the size of your given array and you're done.
output of the above when executed:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
void twoDimBubbleSort(int** arr, int row, int col) {
for (int i = 0; i < (row * col); ++i) {
for (int j = 0; j < (row * col) - 1; ++j) {
int cr = j / col; // current row
int cc = j % col; // current column
int nr = (j + 1) / col; // next item row
int nc = (j + 1) % col; // next item column
if (arr[cr][cc] > arr[nr][nc])
swap(&arr[cr][cc], &arr[nr][nc]); // any way you want to swap variables
}
}
}
You don't necessarily need to create a 1D array, you can consider your 2D array is a 1D array and transform coordinates when you set/get them.
Consider a structure point with x and y, and ARR_LEN is 5.
int from2Dto1D(point p){ return p.x+ p.y*ARR_LEN;}
Point from1Dto2D(int i){ Point p; p.x = i%ARR_LEN; p.y=i/ARR_LEN; return p;}
Now you can use the normal bubble sorting algorithm with a 1D index on 2D squares array, you just need to convert your index into 2 Point and access/switch data using these Point. (2 because you need a Point with index and a Point with index+1
Put all the array elements from 2-D array to 1-D array then
sort that 1-D array and then put 1-D array in the matrix format
Try this code ....works according to the above given logic
#include<stdio.h>
int main(){
int arr[5][5],l=0;
int result[25],k=0,i,j,temp;
arr[0][0]= 4;
arr[0][1]= 5;
arr[0][2]= 8;
arr[0][3]= 9;
arr[0][4]= 4;
arr[1][0]= 2;
arr[1][1]= 1;
arr[1][2]= 0;
arr[1][3]= 2;
arr[1][4]= 4;
arr[2][0]= 6;
arr[2][1]= 7;
arr[2][2]= 4;
arr[2][3]= 5;
arr[2][4]= 5;
arr[3][0]= 4;
arr[3][1]= 8;
arr[3][2]= 9;
arr[3][3]= 1;
arr[3][4]= 2;
arr[4][0]= 4;
arr[4][1]= 5;
arr[4][2]= 2;
arr[4][3]= 1;
arr[4][4]= 9;
//convert 2 D array in 1 D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
result[k++]=arr[i][j];
}
}
// sort 1 D array
for(i=0;i<25;i++){
for(j=0;j<24;j++){
if(result[j] > result[j+1]){
temp=result[j];
result[j]=result[j+1];
result[j+1]=temp;
}
}
}
/*
for(i=0;i<25;i++){
printf("\n%d",result[i]);
}*/
// convert 1 D array to 2 D array
i=0;
l=0;k=0;
while(i<25){
for(j=0;j<5;j++){
arr[k][j]=result[l];
l++;
}
k++;
i=i+5;
}
//Print matrix i.e 2D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
}
}
}
This works !
#define COL 5
#define ROW 2
int main(){
int temp ;
int arr[2][5]= {2,15,26,14,12,18,1,2,3,4 };
int arr2[10] = {0};
int index = 0 ;
for(int t = 0 ; t<50 ; t++ ){
for (int i =0 ; i < ROW ; i++){
for( int j = 0; j < 5-1 ; j++){
if (arr[i][j] > arr[i][j+1]){
temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
//checking for
for( int k = 0 ; k < ROW-1 ; k++){
if (arr[k][COL-1] > arr[k+1][0]){
temp = arr[k][COL-1];
arr[k][COL-1] = arr[k+1][0];
arr[k+1][0] = temp ;
}
}
//---------
}
}
return 0 ;
}

Resources