I first apologize if some of you find my problem stupid and easy to solve, but I am a very beginner in "c".
My task is to create an inverse of a 3x3 matrix using different functions.
What I am trying to do now is to tell the user to input values for the 3x3 matrix and then print them. I made 2 functions which read and print the values, but I have problems with calling them since I cannot directly call an array in printf.
For now I am able to run the program, enter the values and print a wrong result which leads to a not responding program.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 3 //defining the size of the matrix (3x3)
//prototyping the functions used to calculate the inverse of the matrix
void readMatrix(double a[SIZE][SIZE]);
void printMatrix(double a[SIZE][SIZE]);
main()
{
double a[SIZE][SIZE];
int i,j;
printf("Enter the values for the matrix:\n", i, j);
readMatrix(a);
printf("Your Matrix:%d\n",a[i][j]);
printMatrix(a);
return 0;
}
//function 1
//letting the user to enter a matrix
void readMatrix(double a[SIZE][SIZE]){
int i,j;
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
scanf("%d", &a[i][j]);
}
}
}
//function 2
//outputing the given matrix
void printMatrix(double a[SIZE][SIZE]){
int i,j;
for(i = 0; i < SIZE; i++){
for(i = 0; i < SIZE; j++){
printf("Your matrix is: %d", a[i][j]);
}
}
}
In printf and scanf, it is crucial that you pass the exact format specifier that matches the type of the pointer to the variable. If your format specifier doesn't match the supplied argument, the result is undefined behaviour.
In effect, this
scanf("%d", &a[i][j]);
Needs to be replaced with
scanf("%lf", &a[i][j]);
And the same for printf("Your matrix is: %d", a[i][j]); -> printf("Your matrix is: %lf", a[i][j]);
Also, in printMatrix, you've used the loop variable i in the inner loop twice. What you want is
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
printf("%lf ", a[i][j]);
printf("\n");
}
Edit: As pointed out by #cse in the comments, remove this line in main:
printf("Enter the values for the matrix:\n", i, j);
Since at this point, i, and j are not initialised, they'd contain junk.
in printMatrix, there is a infinite loop which will definitely lead your program to no responding. Should be:
for(j = 0; j < SIZE; j++){
printf("Your matrix is: %d", a[i][j]);
}
For printing the output: you will want to actually print out the entire thing rather than one value after another, correct?
printf ("matrix is:\n")
char outstr[64]; //arbitrary but plenty big enough
char * pout; //points to a point in the string
for(j = 0; j < SIZE; j++){
pout = outstr;
for(i = 0; i < SIZE; i++){
pout += sprintf (pout, "%lf," a [i][j]);
*(--pout) = 0; //end the string one char earlier (dangling ',')
printf ("[%s]\n", outstr);
}
Will print:
matrix is:
[1,2,3]
[4,5,6]
[7,8,9]
Where the numbers are of course the ones in the array.
Also unless you were intending on filling the matrix in a columnar fashion, you should switch the i and j loops on the input function. You are storing the matrix in memory transposed. (This code assumes that you are not)
There are following problems with above code:
In line printf("Your Matrix:%d\n",a[i][j]); of main() function, since variable i and j are not initialized so it contains garbage value. So don't print value at a[i][j] because it may cause of segmentation fault. OR initialize i and j with a valid value i.e. which is a valid index in array double a[][]. Also you can change line printf("Enter the values for the matrix:\n", i, j); in main() to printf("Enter the values for the matrix:\n");. Because i and j are not being used here.
In line scanf("%d", &a[i][j]); of function void readMatrix(double a[SIZE][SIZE]). Since you are reading a double primitive data type then you should use %lf formatter instead of %d. Same for line printf("Your matrix is: %d", a[i][j]) in function void printMatrix(double a[SIZE][SIZE]).
In line for(i = 0; i < SIZE; j++) of function void readMatrix(double a[SIZE][SIZE]). It should be for(j = 0; j < SIZE; j++) i.e. the variable to be used in inner loop should be j not i.
You can find working code here which is after correcting the code.
Related
When i want to print a matrix which i input,i can use code:
#include <stdio.h>
int main(void)
{
int n, m; //row and column
printf("Enter row and column:\n");
scanf("%d %d", &n, &m);
int x[n][m];
printf("Enter your matrix:\n");
for (int i = 0; i < n; i++) //input my matrix
{
for (int j = 0; j < m; j++)
{
scanf("%d", &x[i][j]);
}
}
printf("print it:\n");
for (int i = 0; i < n; i++) //print it
{
for (int j = 0; j < m; j++)
{
printf("%d ", x[i][j]);
}
putchar('\n');
}
}
enter image description here(a possible case)
In code above, I have to assign values to the rows and columns of the matrix,which named "n" and "m".
int n, m;
scanf("%d %d", &n, &m);
But now I am asking a way to automatic tally .
Can I get this one directly?
enter image description here
You can simulate a two-dimensional array with a one-dimensional array, if that's what you mean:
#include <stdio.h>
#include <stdlib.h>
#define DIGITS 3
int main(void) { // It's good practice to fill function arguments with void if not planning on using them
/* scanf("%d %d", &n, &m); Using scanf with uninitialised variables will result in
* undefined behaviour if it is unable to convert the input. Using fgets
* is easier to debug, safer, and cleaner.
* I highly recommend this: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
*/
char buf[DIGITS+1];
printf("%s", "Enter array rows:");
fgets(buf, DIGITS+1, stdin);
const int n = atoi(buf);
printf("%s", "Enter array columns:");
fgets(buf, DIGITS+1, stdin);
const int m = atoi(buf);
int x[n*m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("Enter array value at %d, %d: ", i, j);
fgets(buf, DIGITS+1, stdin);
x[i+j] = atoi(buf);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%d ", x[i+j]);
}
printf("\n");
}
}
I'm not really sure as to why you would do this when C supports your two-dimensional array answer equally.
But now I am asking a way to automatic tally. Can I get this one directly?
Yes.
Form a linked-list of lines. Initially the list is empty.
Read the first line of input, the "1 2 3" into a string. Use fgets().
Parse the line to detect the number of values in it.
Append the line to the linked list of lines.
Continue doing so until 1) end-of-file, 2) a blank line or 3) number of integer is not the same as the first (error condition).
Now code has the m (number of values per line) and n, the number of lines.
Form int x[n][m];
Parse the lines for values and save in x.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int score,i,j;
int *ptr, *ptr1;
int over;
printf("Enter the number of over");
scanf("%d",&over);
ptr=(int*)malloc(over*sizeof(int));
// do the iteration, outer for loop, read row by row...
for(i=0; i <= (over-1); i++)
{
printf("%d%d ", i, ptr[i]);
// inner for loop, for every row, read column by column and print the bar...
printf("Enter the number of run per over");
scanf("%d",&score);
ptr1=(int*)malloc(score*sizeof(int));
for(j = 1; j<= ptr1[i]; j++)
// print the 'bar', and repeat...
printf("|");
// go to new line for new row, and repeats...
printf("\n");
}
return 0;
}
You are using
ptr1=(int*)malloc(score*sizeof(int));
inside your for loop. That causes memory leak. You should free the memory.
You also have
printf("%d%d ", i, ptr[i]);
But ptr[i] has not been assigned any value, so it just gives garbage value. The same problem occurs in
for(j = 1; j<= ptr1[i]; j++)
So you need to assign some value to them before using them like this.
Casting the result of malloc doesn't make any sense, it is pointless and potentially bad practice.
printf("%d%d ", i, ptr[i]);. You print the value of an uninitialized memory cell. This is undefined behavior and might in theory cause the program to crash on some platforms. If you need the memory allocated to be initialized to zero, you should be using calloc() instead.
ptr1=(int*)malloc(score*sizeof(int)); for(j = 1; j<= ptr1[i]; j++) This code makes no sense whatsoever and will crash the program. You use ptr1 as if it was an initialied array of integers, while it is actually an uninitialized, single integer.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int **scores;
int over, score;
int i, j;
printf("Enter the number of over : ");
scanf("%d", &over);
scores = (int**)malloc(over*sizeof(int*));
for(i = 0; i < over; i++){
printf("%d ", i + 1);
printf("Enter the number of run per over : ");
scanf("%d", &score);
scores[i] = (int*)malloc((score+1) * sizeof(int));// +1 for number of columns
scores[i][0] = score;
for(j = 1; j <= score; j++){
printf("%d Enter the score : ", j);
scanf("%d", &scores[i][j]);
}
}
for(i = 0; i < over; i++){
for(j = 1; j <= scores[i][0]; j++){
printf("|%d", scores[i][j]);
}
printf("|\n");
}
//deallocate
for(i = 0; i < over; i++)
free(scores[i]);
free(scores);
return 0;
}
I am trying to learn C and I am trying to write a piece of code which does the following:
Take user input of a natural number n
Take user input of n elements and store them in the array x
Delete all negative numbers from the array x
Print the new array, with the length n - number of deleted elements
Here is my code:
#include <stdio.h>
int main(void)
{
int n, i, count=0;
double x[1000];
scanf("%d", &n);
for (i=0; i<n; i++)
scanf("%lg", &x[i]);
for (i=0; i<n; i++)
{
if (x[i] < 0)
{
count++;
continue;
};
x[i-count]=x[i];
};
n -= count;
for (i=0; i<n; i++)
printf("%d: %g\n", i, x[i]);
return 0;
}
I have been told that I should replace my second for loop with the following code:
int j=0
...
for (i=0; i<n; i++)
{
if (x[i] < 0)
{
count++;
continue;
};
if (i > j)
x[j] = x[i];
j++;
};
Could someone please explain why is the latter code better?
If i==j, then you're assigning an element to itself: not wrong, but a (small) waste of effort.
If you really want to improve this, avoid putting the negative values in the array in the first place.
I need to find the sum of all the integers in the first row and the sum of all the numbers in the diagonal. The code I have gives me a huge incorrect number for the sum, can someone point me in the right direction?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i,j, matrix [10][10], sum_row[10];
srand(time(NULL));
for (i = 0; i <10;++i)
{
printf("\n\n");
for (j = 0; j <10; ++j)
{
matrix [i][j] = rand()%10;
printf("%d\t", matrix[i][j]);
}
}
printf("\n\n");
matrix[i][j]= rand()%10;
for (i = 0; i<10; ++i)
{
for (j = 0; j<10; ++j)
{
sum_row[i] += matrix[i][j];
}
}
printf("%d", sum_row);
return 0;
}
You do not initialize sum_row, automatic variables are not zero initialized, their values are indeterminate. So the initial value of the elements of sum_row are indeterminate. So on this line:
sum_row[i] += matrix[i][j];
you are adding values to an indeterminate initial value which will result in an indeterminate end value. You can change the declaration to this:
sum_row[10] = {0}
to zero initialize all the elements.
This line looks like a typo:
printf("%d", sum_row);
and probably was meant to be:
printf("%d\n", sum_row[0]);
^^^
You also should remove the final:
matrix[i][j]= rand()%10;
after the initial loop since it will be using invalid indices for both i and j.
To obtain the sum of the diagonal you just need a new variable initialized to zero and only add an element to that sum when i == j within the final for loop.
Try this
For finding the sum in a row keep i as constant and change j
For finding the sum of diagonal elements keep i = j.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i,j, matrix [10][10], sum_row=0, sum_diag=0;
srand(time(NULL));
for (i = 0; i <10;++i)
{
printf("\n\n");
for (j = 0; j <10; ++j)
{
matrix [i][j] = rand()%10;
printf("%d\t", matrix[i][j]);
}
}
printf("\n\n");
for (j = 0; j<10; ++j)
{
/* i = 0 indicates row 0 */
sum_row += matrix[0][j];
/* i = j indicates diagnoal */
sum_diag += matrix[j][j];
}
printf("row sum: %d, diag sum: %d", sum_row, sum_diag);
return 0;
}
In your code you have not calculated sum of diagonal elements. You have calculated only sum of row elements. In that it seems there are 3 mistakes.
You have not initialised the sum_row[10]. You have to initialise it to zero before using it.
printf("%d", sum_row); this statement tries to print address of sum_row[] array. If you want the value to be printed then use sum_row['some index'].
matrix[i][j]= rand()%10; This statement may give error b'caz you have declare matrix as an array of size 10*10 but you are trying to access matrix[10][10] which is 11*11 th element
To calculate sum of diagonal elements, take some variable lets say sum, initialise it to zero, and increment it while calculating sum of row elements. It is as below
sum=0;
sum_row[10]={0};
for (i = 0; i<10; ++i)
{
for (j = 0; j<10; ++j)
{
sum_row[i] += matrix[i][j];
if(i==j)
sum+=matrix[i][j];
}
}
printf("Sum of diagonal elements: %d\n",sum);
for(i=0;i<10;i++)
printf("Sum of elements in row %d is %d",i+1,sum_row[i]);
You didn't initialise
sum_row[10] = { 0 };
if you had used i++, then you could have skipped the line
matrix[i][j]= rand()%10; // then second one
for(i=0; i<10; i++)
printf(%d\n, sum_row[i]);
I am trying to do this in c:
scanf("%d",a+i);
where a is an array of size 10. And i is counter for loop. So is this possible?
Absolutely: if a is an int* or an array int a[10], and i is between 0 and 9, this expression is valid.
The a+i expression is the pointer arithmetic equivalent of &a[i], which is also a valid expression to pass to scanf.
yes you can use a+i instead of &a[i],,,, The following code ask you to enter 10 numbers and will save them in an array,,,,and then displays the numbers in it.
check this code :
#include <stdio.h>
int main (void)
{
int a[10], i, j = 0;
for(i = 0; i < 10; ++i ){
printf("Element no %d = ",i);
scanf("%d",a+i);}
printf("Elements in your array are: ");
for(j = 0; j < 10; j++)
printf("%d ",a[j]);
return 0;
}
I hope if this code could help you !!
Try this solution:
#include <stdio.h>
int main (void)
{
int *p, i, j = 0, n;
printf("enter the value of n ");
scanf("%d",&n);
for(i = 0; i < n; ++i ){
scanf("%d",p+i);}
printf("Elements in your array are: ");
for(j = 0; j < 10; j++)
printf("%d ",*(p+i));
return 0;
}