Skip to main content

Calculating the sum of diagonal elements and then finding the difference in C++

 


                          #add of diagonal of 2d array                          

#include <iostream>
using namespace std;
#include <math.h>
int main() {
    int arr[3][3] = {1, 4, 2, 5, 2, 8, 2, 5, 9};
    int sum1 = 0 , sum2 = 0; 
    for (int i = 0; i < 3; i++) {
        sum1 += arr[i][i]; 
        sum2 += arr[i][2 - i]; 
    }
    int d = abs(sum1 - sum2);
    cout << "Sum of diagonal1: " << sum1 << endl;
    cout << "Sum of diagonal2: " << sum2 << endl;
    cout << "Diff between the sums: " << d << endl;
    return 0;
}

Comments

Popular posts from this blog

Flow Charts - What Is a Flow Chart? When to Use a Flowchart? Flowchart Symbols & Components

  Flow Charts     Flow charts are a useful tool in many situations, as we make a process easy to understand at a glance. Using just a few words and some simple symbols, they show clearly what happens at each stage and how this affects other decisions and actions.   What Is a Flow Chart?     In 1921, the Frank and Lillian presented what was only a "graphic-based method" in a presentation titled: “ Process Charts: First Steps in Finding the One Best Way to do Work ”, to members of the American Society of Mechanical Engineers (ASME). When to Use a Flowchart?     Flowchart is a very simple yet powerful tool to improve productivity in both our personal and work life. Here are some ways flowchart can be helpful:   ·      Document a process ·      Present solution to a problem ·      Brainstorm ideas in a meeting ·      Design an operation system ·    ...

Most Asked Pattern Programs in C

  Pattern Programs in C  

Constructors and Destructors in C++

  Constructors and Destructors in C++ Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object. Following is the syntax of defining a constructor function in a class: class A {  public:      int x;      // constructor      A ()      {          // object initialization      } };   While defining a  constructor  you must remember  that the  name of constructor  will be same as the  name of the class , and    constructor  will never have a return type. Constructors can be defined either inside the class definition or outside class definition us...