Hello guys in this Post we will be seeing a program to calculate the sum of the corner elements using c language.
First we declare two variables n and sum, where n is the number of rows and columns for our matrix and sum is the variable which will Store the added values. Initially we will assign it to 0.
int n,sum=0;
We will be getting input from the user in the console. By using the "scanf" function in C.
The scanf function accepts various Parameters in C.
Like we have %d - for getting integer input
%c - for getting character input
%s - for getting String input
these are some commonly used functions in scanf.
In this Program we will be using the %d for getting the input from the user a integer.
scanf("%d",&n);
We will declare an array in c named arr which will store the value of the matrix. It contains two fields one is for the number of rows and other is for the number of columns.
int arr[n][n];
After Creating the array we will get the array element from the user. This can be achieved by using the for loop. Two for loops are used for this process. One is for the Number of rows and other is for the number of columns. We use Scanf for storing the value.
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",arr[i][j]);
}
}
Finally we move to the Logic part to add the corner elements.
In a matrix,
First row elements have the index of 0 in the array [i=0].
First column element have the index of 0 in the array[[j=0].
Last row elements have the index of n-1 in the array [i=n-1].
Last column elements have the index of n-1 in the array [j=n-1].
So if we map the values of these indexes we will get the corner element. So we create another for loop and by using the if statement and by combining these indexes by using or operator. We are finding that the element is the corner element and finally we are adding those values by using the += operator.
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if((i==0 && j==0)||(i==0 && j==n-1)||(i==n-1&&j==0)||(i==n-1&&j==n-1)){
sum+=arr[i][j];
}
}}
At Last, We are printing the value of sum to the console.
Program:
int main()
{
int n,sum=0;
scanf("%d",&n);
int arr[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",arr[i][j]);}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if((i==0 && j==0)||(i==0 && j==n-1)||(i==n-1&&j==0)||(i==n-1&&j==n-1)){
sum+=arr[i][j];}
}
}
printf("%d",sum);
}
Please feel free to comment below if you have any queries. You can also Reach me out anytime.
The Star Casino | Oklahoma Casinos
ReplyDeleteLocated 파라오 바카라 in the heart of 10벳 the Great Smoky Mountains of 먹튀 사이트 먹튀 프렌즈 Western 먹튀검증 abc-1111 North Carolina, The Star Casino offers everything you need for 바카라검증 a great escape from the