I am trying to pass a 2D array of variable size to a function to print it.but the code doesn't show the exact result of sum.
this is the code:
#include <stdio.h>
#define ROW 5
#define COLL 5
void print_arr(int a[][COLL],int m,int n){
int i,j,sum;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("a[%d][%d]=%d\n",i,j,a[i][j]);
}
}
}
int sum_arr(int a[][COLL],int m,int n){
int i,j,sum;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
sum+=a[i][j];
}
}
return sum;
}
int main (void){
int a[ROW][COLL];
int i,j,m,n;
int sum;
printf("enter rows:");scanf("%d",&m);
printf("enter coll:");scanf("%d",&n);
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("a[%d][%d]=",i,j);scanf("%d",&a[i][j]);
}
}
print_arr(a,m,n);
printf("\n");
sum=sum_arr(a,m,n);
printf("sum=%d\n",sum);
return 0;
}
this is the result of the code
enter rows:2
enter coll:3
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6
sum=-1217388517
please tell me what's wrong with the code....
You should pass the exact size of the second dimension of the array to the function, not COLL. change it to m (or n, whatever)
It passes the number 5 to the function while the number should be 3 :) How ever, this is not the main reason that you're code is not working, just a suggestion.
Initialize the variable sum. It will make your code work. e.g. sum = 0;
If you don't initialize it, you won't get any compile errors, but it points to a location of memory and reads thing been there before (not a valid amount) and uses it as the initial amount of that for sum.
So your array is being added to a non-valid amount, that's why your code doesn't work.
There is no technical problem with passing, but in sum_arr,
your variable sum does not start at 0 (but some strange value).
You have to initialize sum to zero in sum_arr function.
Related
I've written a function to rotate an array,
I've checked and it works when code is in one block I.E. everything
is coded under main(), but when I divide the code so that the rotation is done under a different function I can't get it to work (it truncates instead of rotating).
I'm pretty sure it's something to do with the array pointer.
sorry complete noob
please help:
#include<stdio.h>
void rotate(int *arr,int length);
int main()
{
// this code creates an array via input
int length;
int i;
int num;
printf("enter length of array\n");
scanf("%d",&length);
int arr[length];
for (i=0;i<length;i++) {
printf("enter number\n");
scanf("%d",&num);
arr[i]=num;
}
// just prints original
for(i=0;i<length;i++){
printf("original arr[%d]=%d\n",i,arr[i]);
}
//runs rotate function
rotate(arr,length);
return 0;
}
//the rotate function inputs rotation amount and uses nested for loop to
execute
void rotate(int *arr,int length)
{
int n;
printf("by how many do you want to rotate array?");
scanf("%d",&n);
int i;
int j;
int temp;
for (j=0;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
printf("rotated arr[%d] = %d\n",i,arr[i]);
}
}
my output looks like this:
enter length of array
5
enter number
1
enter number
2
enter number
3
enter number
4
enter number
5
original arr[0]=1
original arr[1]=2
original arr[2]=3
original arr[3]=4
original arr[4]=5
by how many do you want to rotate array?
3
rotated arr[4] = 1
rotated arr[4] = 2
rotated arr[4] = 3
RUN FINISHED; exit value 0; real time: 9s; user: 0ms; system: 0ms
In C you need to declare the function before "main" function, or do the declaration and definition both above the main function. Also do share your error message, for help.
Also, in C language you can't really create dynamic arrays like that( i.e. taking an integer value and then defining the size of array using it "int array[integer] " is wrong of doing it, if the value of integer is being given during runtime)
Read http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/2-C-adv-data/dyn-array.html , or any other tutorial about dynamic arrays in C and how to use malloc and calloc.
According to me the problem is in your last print statement in rotate method which is inside the loop.
you must loop through the whole array again to print the rotated array.
like this.
void rotate(int *arr,int length)
{
int n;
printf("by how many do you want to rotate array?");
scanf("%d",&n);
int i;
int j;
int temp;
for (j=0;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
}
for(i=0;i<length;i++){
printf("original arr[%d]=%d\n",i,arr[i]);
}
}
this will work.
And also, Always define functions at the top in 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
}
}
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]);
}
}
I am a complete beginner in C and I am practicing passing arrays into functions. I wrote a program to take a two dimensional array as input and find sum of the individual columns.
And when I compiled the program I got no errors, but once I run it, I get a dialogue box saying "untitled5.exe stopped working" where untitled5 is the file name.
I got this error quite a few times. I have used both dev c++ and codeblocks to compile my program, so what is the reason for this? Is this a problem with my code or with my compiler or with my laptop?
#include<stdio.h>
void summation (int arr[][5], int size);
int main()
{
int n,arr[n][5],sum,i,j;
printf("enter the number of rows");
scanf("%d",&n);
for (i=0;i<n;i++)
{
for (j=0;j<5;j++)
{
printf("%d,%d th element is",i,j);
scanf("%d",&arr[i][j]);
}
}
summation (arr,5);
return 0;
}
void summation (int arr[][5], int size)
{
int i,j,s=0;
for(j=0;j<5;j++)
{
for (i=0;i<5;i++)
{
s=s+arr[i][j];
}
printf("%d",s);
}
}
In main() you are using i to index the first dimension of the array. In summation() you are using i to index the second dimension of the array. I think that you are going beyond the end of the first dimension inside summation() when main() does not fill up that much of the array (e.g., when you enter 2 for the number of rows).
I think you want
summation (arr,5);
And, inside summation():
for (i=0;i<size;i++)
{
s=s+arr[i][j];
}
#include<stdio.h>
void summation (int arr[][5], int size, int rows);
int main()
{
int n, sum, i, j;
printf("enter the number of rows");
scanf("%d",&n);
int arr[n][5];
for (i=0;i<n;i++)
{
for (j=0;j<5;j++)
{
printf("%d,%d th element is",i,j);
scanf("%d",&arr[i][j]);
}
}
summation (arr, 5, n);
return 0;
}
void summation (int arr[][5], int size, int rows)
{
int i,j,s=0;
for(i=0;i<rows;j++)
{
for (j=0;i<size;i++)
{
s=s+arr[i][j];
}
}
printf("%d",s);
}
So first off I moved your array declaration to after you have initialized n and made it equal to something.
Then your next problem was you were probably going out of bounds in your summation function. You always have 5 columns in your 2darray, but you can have a different amount of rows. Pass the amount of rows, n, into the function summation to make sure you don't go out of bounds.
So, I have this code which I need to turn into a function:
int main(void) {
int i=0,seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
printf("\nSeed value is:%d\n\n",seed);
srand(seed);
int a[5][5];
int x,y;
printf("Matrix A:\n");
for(x=0;x<5;x++) {
for(y=0;y<5;y++) {
a[x][y] = rand() %51 + (-25);
printf("%d ",a[x][y]); }
printf("\n"); }
printf("\n\n");
So basically, it produces a 2D 5x5 array of random numbers. This works fine, however my next task is applying a function to this code, with the function name of:
void generate_matrices(int a[5][5])
I have tried multiple times, the closest I got to a successful code was:
#include <stdio.h>
#include <stdlib.h>
void generate_matrices(int a[5][5]);
int main(void) {
int a, seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
srand(seed);
printf("\nSeed value is:%d\n\n",seed);
generate_matrices(a);
return 0;
}
void generate_matrices(int a[5][5]) {
int y,z;
printf("Matrix A:\n");
for(y=0;y<5;y++) {
for(z=0;z<5;z++) {
a[y][z] = rand() %51 + (-25); }
printf("%d ",a[y][z]); }
printf("\n");
}
But this returns the error, "expected 'int(*)[5]' but arguement is of type 'int'.
All/any help is muchly appreciated. To be fair on my part, I have done 90% of the code. This is the only bit I need help with so that I can apply this to the rest of my code.
Cheers!
You have declared a as a single integer on this line int a, seed;
When you call the function with generate_matrices(a); you are passing a single integer instead of a pointer to an array.
Change your declaration line to int a[5][5], seed;
generate_matrices(a); will pass a pointer to the first element in your 5 * 5 array, to the function.
You should really print the results in main and not in the function, then you will know that the array has been modified and is available for use in the body of your program.
You have used unconventional placement of braces '}' and this makes it harder to see what belongs in each part of your for loops.
You have the print statements in the wrong places - as a result only part of the matrix is printed.
This is what it should be (just the results - in main):
printf("Matrix\n ");
for (y = 0; y < 5; y++) {
for (z = 0; z < 5; z++) {
printf("%d\t ", a[y][z]);
}
printf("\n");
}
If you use int a[5][5] and call the function with generate_matrices(a);
a function void generate_matrices(int a[5][5]) {...} compiles without error
#include<stdio.h>
#include<stdlib.h>
void modify(int b[5][5]);
int main()
{
srand(4562);
int i,j,arr[5][5];
modify(arr);
for(i=0;i<5;i++){
for(j=0;j<5;j++){
printf("%d ",arr[i][j]=rand() %51 + (-26)); }
}
return 0;
}
void modify(int b[5][5])
{
int i,j;
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
b[i][j]; }
}
}
So this is the closest I have come to completing it. It produces the number of elements I want, also within the range I want. However its not producing the 5x5 grid I need. Where have I gone wrong?
EDIT: I'm not going for neatness at the moment, I just want to get the program working how I want it too and then i'll neaten it up.
EDIT 2: Never mind, realised what I didn't include. Its fine now. Thanks for the help.