I started to learn C + + on my own and I would like to ask for some help about an exercise that I got from a site and I couldn't find a solution. :(
The site asks you to calculate the Euclidean norm of any matrix and then show it to the user.
First thing I tried to do, was ask the user for the number of rows and columns of the matrix, but I think the way I did the numbers are not being stored.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int main() {
int i,j,m,n,matrix[10][10],sum=0;
double norm;
cout << "Number of rows:" ;
cin>>m;
cout<<"Number of columns:";
cin>>n;
for ( int i = 0; i < m; i++ ) {
for ( int j = 0; j < n; j++ ) {
cout<<"Nummber["<<i<<"]["<<j<<"]: ";
cin>>matrix[i][j];
}}
for ( int i = 0; i < m; i++ ) {
for ( int j = 0; j < n; j++ ) {
cout<<"Number["<<i<<"]["<<j<<"]: "<<matrix[i][j];
}}
}
Second, I created a variable to store the sum of the array elements. So the program can calculate the norm.
1 2 3 4 5 6 7
sum=0;
for i=1 :m
for j=1... n (?)
sum= a(i,j)^2 + sum
end
end
norm=sum^(1/2)
#include <iostream>
#include <cmath>
usingnamespace std;
int main() {
int i,j,m,n,a[10][10],sum=0,trace=0;
float norm;
cout << "Number of rows:" ;
cin>>m;
cout<<"Number of columns:";
cin>>n;
for ( int i = 0; i < m; i++ ) {
for ( int j = 0; j < n; j++ ) {
cout<<"Element["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
}}
for ( int i = 0; i < m; i++ ) {
for ( int j = 0; j < n; j++ ) {
sum=sum+(a[i][j]^2);
if(i==j)
trace=trace+a[i][j];
}
}
norm=sqrt(sum);
cout<<""<<norm<<"";
}
Well, the obvious thing is that you're defining your matrix as being 10 x 10, but you're not checking the user-inputted dimensions to make sure they're not bigger than 10.
I'm really sorry because I just started to look for exercises and I saw some examples that the person creates a matrix just for testing, maybe I'm getting confuse with it, coz I want to make a matrix with the size determined by the user.
Btw, thanks again to correct me, I changed the way to use the function for that model u sent me.
I'm really lost but I'll keep trying :D