Hackerrank's Problem Solving solutions( A Very Big Sum, Diagonal Difference, Plus Minus ) :

Problem 4: A Very Big Sum

Solution: (in c++)


( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,j,i;
long long sum;
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sum=0;
for(j=0;j<n;j++)
{
sum=sum+a[j];
}
cout<<sum;
}

This code is simple. There's no need for any explanation.
 

 

 

 

Problem 5: Diagonal Difference

Solution: (in c++)


( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,a[100][100],sum,summ,i,d,j; //summ = sum of '/' diagonal
cin>>n;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
cin>>a[i][j]; //made a matrix
}
sum=0;
for(i=0;i<n;i++)
{
sum=sum+a[i][i]; //sum = sum of '\' diagonal
}
summ=0;
j=n-1;
for(i=0;i<n;i++)
{
summ=summ+a[i][j]; //see note below
j--;
}
d=abs(sum-summ);
cout<<d;
}

Let a 3*3 matrix and the position of  a given element is represented in the form of (i,j) :

       0       1        2
0  (0,0)  (0,1)  (0,2)

1  (1,0)  (1,1)  (1,2)

2  (2,0)  (2,1)  (2,2)

Here we can see  for diagonal \ , the elements can be represented by (i,i) but for the diagonal / , the elements can't be represented in a general form. But we can observe that on traversing this diagonal from top right to bottom left i value increases by 1 while j value decreases by 1. This is what i have done in the above code.


 

 

Problem 6: Plus Minus

Solution: (in c++)


( please guys before moving to the solution try it yourself at least 3-4 times , if you really wanna become a good coder)

#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[100];
int n;
float c1=0,c2=0,c3=0;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int j=0;j<n;j++)
{
if(a[j]>0)
{
c1++;
}
else if(a[j]==0)
{
c2++;
}
else {
c3++;
}
}
float r1,r2,r3;
r1=c1/n;
r2=c2/n;
r3=c3/n;
cout<<r1<<endl<<r3<<endl<<r2;
}

This code is simple. There's no need for any explanation.
 

 

 

Guys , if you have any queries related to a question or need more explanation for a question , comment below!

Comments

Popular posts from this blog

Coursera's Algorithmic toolbox assignment solutions( Sum of Two Digits, Maximum Pairwise Product ) :

HackerEarth's basic programming solutions( Seating Arrangement, Zoos, Anagrams ) :

HackerEarth's basic programming solutions( Minimize Cost, Magical Word, Best Index ) :