summing up rows in c showing garbage numbers in columns - c

I'm trying to sum columns in C. My code only adds the sum for the firsts columns for example if is a 2x2 array it only add the first column but for the rest it displays weird numbers. this is what i got so far. I haven't made the code for the rows yet. Thanks for your help.
#include <stdio.h>
int main(){
printf("Enter the number of columns");
int i;
scanf("%d", &i);
printf("Enter the number of rows");
int y;
scanf("%d", &y);
int r[i][y];
int a;
int b;
int columntotal[i],rowtotal[y];
for (a=0; a<i; a++){
for (b=0; b<y; b++){
scanf("%d",&r[a][b]);
}
}
//printing
for(a=0;a<i;a++)
{
for(b=0;b<y;b++){
printf("\t%d", r[a][b]);
}
printf("\n");
}
for (a=0;a<i;a++){
for (b=0;b<y;b++){
columntotal[a]=columntotal[a]+r[a][b];
}
}
for (a=0;a<i;a++){
printf("%d\n", columntotal[a]);
}
return(0);
}

As far as I remember dynamic rows,col assign while creating array is not possible in C.So your this statement int columntotal[i],rowtotal[y]; will not work unless i,y is a constant variable i.e #define i,y,etc which is not in your case.
Second you are iterating over a columntotal array which is not properly declared. You can make use of dynamic memory allocation to allocate number of blocks to columntotal array and then fill it with you column sum as you iterate over it.
int *columntotal= malloc(i * sizeof (int));
for (a=0;a<i;a++){
for (b=0;b<y;b++){
columntotal[a]=columntotal[a]+r[a][b]; //r is your 2D array
}
}

Related

Reading and Printing a matrix

I tried to read and print a matrix using an external function (from another c file), the thing is that I want to read the matrix dimensions in the function and store them in the main function, how can I do this?
Do I need to return an array with the m and n dimensions of the matrix or can I access the variables that I created in main and change their value within the external function? (I prefer if someone would explain the second) I don't actually know how to use pointers and stuff.
Sorry for my English, I'm not a native speaker, also thanks for your response
The second and the third functions are in an external function.c file
int main(){
int num_of_rows, num_of_columns;
int matrix[10][10];
read_matrix(num_of_rows, num_of_columns, matrix);
print_matrix(num_of_rows, num_of_columns, matrix);
printf("\n Press any key to exit the program: ");
_getch();
return 0;
}
void read_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){
int i,j;
printf("\nPlease specify the number of rows:");
scanf("%d", &num_of_rows);
printf("\nPlease specify the number of columns: ");
scanf("%d", &num_of_columns);
printf("\nPlease introduce the matrix elements below:\n");
for(i=0; i<num_of_rows; i++){
for(j=0; j<num_of_columns; j++){
printf("matrix[%d][%d]= ", i, j);
scanf("%d", &matrix[i][j]);
}
}
}
void print_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){
int i,j;
for(i=0; i<num_of_rows; i++){
for(j=0; j<num_of_columns; j++){
printf("matrix[%d][%d]= %d", i, j, matrix[i][j]);
}
}
}
Parameters are passed by value in C.
In read_matrix, the num_of_rows parameter is a local variable. Even if you modify it, the caller won't see anything change. Same for num_of_columns.
You want this:
void read_matrix(int *num_of_rows, int *num_of_columns, int matrix[10][10]) {
// ^ add * ^ add *
...
scanf("%d", num_of_rows); // << remove the &
printf("\nPlease specify the number of columns: ");
scanf("%d", num_of_columns); // << remove the &
...
for (i = 0; i < *num_of_rows; i++) {
// ^add *
for (j = 0; j < *num_of_columns; j++) {
// ^add *
and in main:
read_matrix(&num_of_rows, &num_of_columns, matrix);
// ^ ^ add the &s
This is basic knowledge that is covered in your C learning material. Most likely in the chapter dealing with pointers and the one dealing with function calls.
Here's the catch. I tested your code and it works nicely. The problem is, what you want to achieve is only possible by using dynamic memory allocation. Take a look at the malloc and free functions.
You can read more about it on:
https://www.tutorialspoint.com/what-is-malloc-in-c-language
https://www.tutorialspoint.com/how-do-malloc-and-free-work-in-c-cplusplus
In C language you are responsible for allocation a space in memory for variable length data structures. Pointers just store an address to a specific memory space allocated to the desired data type.
e.g.:
int n, *p;
p = (int*) malloc(n * sizeof(int));
In this example, you are just giving p an address to the first integer from n integers you just allocated.
p will work just like a vector when using for loops because behind the scenes, it's exactly what happens when you traverse your fixed length vectors and matrices, but this time you were in control of it's length in runtime.
#include<stdio.h>
void main()
{
int x[3][3], p, q, max;
printf("Enter the elements of matrix: \n");
for(p=0;p<3;p++)
{
for(q=0;q<3;q++)
scanf("%d", &x[p][q]);
}
max=x[0][0];
printf("The matrix is as follows: \n");
for(p=0;p<3;p++)
{
for(q=0;q<=3;q++)
scanf(" %d", &x[p][q]);
}
for(p=0;p<3;p++)
{
for(q=0;q<3;q++)
{
if(x[p][q]>max)
max=x[p][q];
}
printf("\n");
}
printf("Maximum number in the matrix is: %d", max);
}
Output:
Enter the elements of matrix:
23 65 12
12 23 56
12 10 32
The matrix is as follows:
23 65 12
12 23 56
12 10 32
Maximum number in the matrix is: 65
Matrix Programs
Explore more matrix programs.

Print all inputted number by the user in C

I am trying to print all inputted number by the user using the code below but instead of printing all inputted numbers it only print the last number I inputted.
#include<stdio.h>
int display(int n, int a, int b)
{
printf("\n\nOrdered pairs are: ");
for(int j=0;j<n;j++)
{
printf("(%d,%d) ",a,b);
}
return 0;
}
int main()
{
int num,i,j,x,y;
printf("Total number of points: ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
printf("\n\nPoint #%d: \n",i+1);
printf("x=");
scanf("%d",&x);
printf("y=");
scanf("%d",&y);
printf("Point #%d: (%d,%d)",i+1,x,y);
}
display(i,x,y);
return 0;
}
You don't have memory for storing more than 2 numbers (x and y) which are over-written during each iteration of the loop.
Perhaps you meant to use arrays, or dynamically allocated memory. This:
int x[100], y[100];
is one way, then you can store up to 100 numbers in each of the two arrays. Use array indexing when accessing.
Actually you are changing the value stored in x and y again and again and so, the previous values get destroyed and only the last value is stored. So you can you arrays (which are more easier to use) or you can even use structure (I would prefer to use arrays).

Having trouble while adding elements to array and print them

I'm trying to create an array which has size depended upon input elements count. After that I want to print it but I'm getting very strange outputs.
int main(void)
{
int input_arr;
int i,size=0;
int arr[size];
while(input_arr!=-1){
printf("enter positive int");
scanf("%d",&input_arr);
arr[size]=input_arr;
printf("%d",arr[size]);
for(i=0;arr[i]!='\0';i++){
printf("%d ",arr[i]);
}
size+=1;
}
return 0;
}
33 3 3 3 3 3 6487488 enter positive int3.
It gives output like this and after a while it stops taking elements. I could not recognize where am I doing wrong.
In C the size of the array is fixed the moment you define it. Increasing the size variable does not increase the array size. Therefore you immediately get a buffer overflow the moment you read the first element. You can instead declare a large array like this:
static const int maxSize = 4096;
int arr[maxSize];
int main(void)
{
int i, size=0;
while(size < maxSize){
printf("enter positive int");
scanf("%d", &arr[size]);
++size;
for(i=0; i < size; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
return 0;
}
Alternatively you can use malloc and realloc to grow the array dynamically.

Error while calculating sum of two matrices in c

So I'm new to C and was trying to write a program to add two matrices
program 1
#include <stdio.h>
int main(){
int m,n,o,p,i,j;
int mat1[m][n];
int mat2[m][n];
int result[m][n];
printf("enter the number of rows and columns for matrix ");
scanf("%i%i",&m,&n);
printf("enter elements of matrix one :");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%i",&mat1[i][j]);
}
}
printf("enter the elements of matrix two:");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%i",&mat2[i][j]);
}
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
result[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf("the sum of the matrices are");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%i",result[i][j]);
}
}
return 0;
}
this produced no error
method two
when i used a function to enter the values in two the matrix, it produced the following error
25 24 C:\Users\Hp\my-programs\matrix-entry-function.cpp [Error] invalid types 'int[int]' for array subscript
25 35 C:\Users\Hp\my-programs\matrix-entry-function.cpp [Error] invalid types 'int[int]' for array subscript
code:
#include <stdio.h>
int mat_entry(int m,int n)
{
printf("enter the rows and columns of matrix ");
scanf("%i%i",&m,&n);
int mat[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
printf("\nenter the %i'th element %i'th row :",j+1,i+1);
scanf("%i",&mat[i][j]);
}
}
}
int main()
{
int a,b,c,d,e,f,m,n;
int res[m][n];
int mat1=mat_entry(a,b);
int mat2=mat_entry(c,d);
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
res[i][j]=(mat1[i][j]+mat2[i][j]);
}
}
}
Your program 1 happened not to produce error. You are unlucky. You invoked undefined behavior by using values in uninitialized variables having automatic storage duration, which are indeterminate. You must declare mat1, mat2 and result after reading m and n.
int main(){
int m,n,o,p,i,j;
printf("enter the number of rows and columns for matrix ");
scanf("%i%i",&m,&n);
/* move these declaretions after reading number of rows and columns */
int mat1[m][n];
int mat2[m][n];
int result[m][n];
printf("enter elements of matrix one :");
Your program 2 invokes undefined behavior by using return values of functions with no return statements. Also using [] operator with two operands having type int is wrong. E1[E2] is equivalent to (*((E1)+(E2))) (N1570 6.5.2.1 Array subscripting, paragraph 2), so exactly one operand of it must be a pointer (including one converted from arrays).
To return matrixes as return values of functions, consider using structures and allocating memory for elements dinamically.
You have used
int mat1=mat_entry(a,b);
int mat2=mat_entry(c,d);
instead of sending parameters from one function to another, which would work only when the variables you take are pointers, here you have to either use mat1 and mat2 as pointers or you have to make them integer matrices.
There isn't one thing that you are doing wrong my friend.
You are not even using dynamic memory allocation but still trying to declare matrices with values which are not defined yet.Try to run your code,even your first code won't run.
i have corrected your code for you :
#include <stdio.h>
int main(){
int m,n;
printf("enter the number of rows and columns for matrix ");
scanf("%i%i",&m,&n);
int mat1[m][n];
int mat2[m][n];
int result [m][n];
int i,j;
printf("enter elements of matrix one :");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d",&mat1[i][j]);
}
}
printf("enter the elements of matrix two:");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%d",&mat2[i][j]);
}
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
result[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf("the sum of the matrices are");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("%d",result[i][j]);
}
}
return 0;
}
I don't think it would be that difficult to put this functionality into a function . Try it out
It is impossible to write a function that makes a matrix with user-supplied dimensions, unless you use dynamic allocation (which you probably don't want to, at this stage).
Luckily, you don't need that! Since all you want is adding matrices, they should have the same dimensions, and you only want to ask the user once what the dimensions are. Afterwards, fill both matrices, and do the "adding" part.
That is:
int main()
{
int a,b,c,d,e,f,m,n;
printf("enter the rows and columns of matrix ");
scanf("%i%i",&m,&n);
int res[m][n];
int mat1[m][n];
int mat2[m][n];
mat_entry(m, n, mat1); // fill matrix 1
mat_entry(m, n, mat2); // fill matrix 2
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
res[i][j]=(mat1[i][j]+mat2[i][j]);
}
}
}
The function mat_entry has no return value (i.e. void), but it receives the matrix to fill by pointer (the details are a bit complicated, but the syntax is straightforward):
void mat_entry(int m,int n, int mat[m][n])
{
...
}
The code inside is the same as you suggested, minus the asking for dimensions:
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
printf("\nenter the %i'th element %i'th row :",j+1,i+1);
scanf("%i",&mat[i][j]);
}
}

Can anybody resolve my mistake

I cant seem to find out where i'm going wrong in C. its on line 37 it says assignment to expression with array type any help or advice would be great thanks.
I was wondering also is it something to do with not adding in the brackets to show that they're arrays on line 37 but when i put them in it displays more errors
/*
This program uses pass by reference to calculate the values after two arrays are multiplied by each other
16/02/2015
Jake Young
*/
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *[], int *[]);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
answer=multiply_function(&array1, &array2); // line 37
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1[], int *array2[])
{
int *answer[size];
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
*answer[i]= *array1[i]* *array2[i];
}//end for loop
return(*answer);
}//end function()
int multiply_function(int *[], int *[]);
This doesn't make any sense. You intend to pass arrays of integers to the function, not arrays of pointers. You'll have to study how arrays should be passed to functions.
main()
This form is not standard. Unless you are programming a "bare metal" embedded system, you should use int main (void).
answer=multiply_function(&array1, &array2);
This doesn't make any sense. You declared the function to return an int. Again, study how arrays are passed to and from a function. Furthermore, you can't copy arrays with the assignment operator: you have to use memcpy() or similar functions.
multiply_function(int *array1[], int *array2[])
The function definition is different than the prototype: that is always bad practice. Apart from that, the function doesn't make any sense, as already mentioned.
int *answer[size];
This doesn't make any sense, you are declaring an array of pointers where you want an array of integers.
return(*answer);
Returning a pointer to a local variable in C is always a bug. And you can't return arrays like this. And there is no need for the parenthesis.
OK, you should really invest some more time to study arrays, pointers and fundamentals of functions in C.
Apart from grammatical problems in the code, the fundamental problem in this code is the answer[] array. it is defined both in main() and the multiply_function(). What you must do is to pass this array to the multiply_function() and have the function fill in the array.
I'm giving the solution below, with the hope that you'll compare it to your version and study the differences and continue to learn the basics of C:
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *, int *, int *);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
multiply_function(array1, array2, answer);
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1, int *array2, int *answer)
{
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
answer[i]= array1[i] * array2[i];
}//end for loop
return(*answer);
}//end function()

Resources