This is a program to find norm of a matrix. I am using Code Blocks to write codes. The 1st for loop in this code which is used to fill the matrix doesn't get executed in Code Blocks but gets executed in a online c compiler. Why is this happening?
///find the norm of a matrix
#include<stdio.h>
#include<math.h>
void main()
{
short int r,c;
register short int i,j;
//fill matrix
printf("\nENTER MATRIX DIMENSION");
printf("\nROWS: ");
scanf(" %d",&r);
printf("COLUMNS: ");
scanf(" %d",&c);
printf("\ncheck1");
--r; --c;
printf("\ncheck2");
float mat[r][c],sum,norm;
printf("\ncheck3");
//1st for loop:fill array
for(i=0 ;i<= r ;i++)
{
for(j=0 ;j<= c ;j++)
{
printf(" \nELEMENT %d x %d: ",i,j);
scanf(" %f",&mat[i][j]);
}
}
printf("\ncheck4");
//finding norm
sum = 0;
for(i=0;i<=r;i++)
{
for(j=0;j<=c;j++)
{
sum = sum + pow(mat[i][j],2);
}
}
norm = pow(sum,0.5);
printf("\n\nNORM: %f",norm);
}
The code is correct but the for loop is not executing because the condition:
i<=r
is getting false.Why? Because garbage value is being stored in your variable
r
andc
.You are using format specifier
%d
which is for int. The Format specifier for short is %hd.Just use
%hd
and everything will work fine.