Introduction to C Programming
Operators in C Part 1
Operators in C Part 2
Precedence and Associativity Of Operators in C
If else Statements in C
Switch Statement in C
Loops in C
While and Do-While loops in C
Nested loops in C
Loop Control Statements in C
1D Arrays in C
2D Arrays in C
Pattern Printing in 2D arrays
Functions in C
Pointers in C
ASCII Encoding and Typecasting in C
More about 2D arrays
In this article, we will learn about some core concepts in 2D arrays such as Printing
the left diagonal, right diagonal elements or Printing the elements forming the lower and
upper triangle. These problems are extremely important for your exams and placement tests!
- The left diagonal
- The right diagonal
- The lower triangle
- The upper triangle
Jump to specific sections
The left diagonal
To access the elements lying on the left diagonal we write -
#include <stdio.h>
void main()
{
int a[3][3]={
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i = 0 ; i < 3 ; i++)
{
for(int j = 0 ; j < 3 ; j++)
{
if(i == j)
printf("%d",a[i][j]);
printf(" ");
}
printf("\n");
}
}
Output
1
5
9
The right diagnol
To print all the elements lying on the right diagonal we write -
#include <stdio.h>
void main()
{
int a[3][3]={
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i = 0 ; i < 3 ; i++)
{
for(int j = 0 ; j < 3 ; j++)
{
if(i+j == 2)
printf("%d",a[i][j]);
printf(" ");
}
printf("\n");
}
}
Output
3
5
7
The lower triangle
All the elements present on the left diagonal or lying below the left diagonal are included
in the lower triangle. To print all the elements lying on the lower triangle, we write -
#include <stdio.h>
void main()
{
int a[3][3]={
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i = 0 ; i < 3 ; i++)
{
for(int j = 0 ; j < 3 ; j++)
{
if(i >= j)
printf("%d",a[i][j]);
printf(" ");
}
printf("\n");
}
}
Output
1
4 5
7 8 9
The upper triangle
All the elements present on the right diagonal or lying below it are included
in the upper triangle. To print them, we write -
#include <stdio.h>
void main()
{
int a[3][3]={
{1,2,3},
{4,5,6},
{7,8,9}
};
for(int i = 0 ; i < 3 ; i++)
{
for(int j = 0 ; j < 3 ; j++)
{
if(i <= j)
printf("%d",a[i][j]);
else
printf(" ");
printf(" ");
}
printf("\n");
}
}
Output
1 2 3
5 6
9