Creating a function for a random number 2D array - c

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.

Related

Problem in C : How to properly call function inside main

So there is this project in Data Structures that i have to deal with this semester and it requires that i have to code in C . The problem is that i am a little bit rusty in C and i am dealing with basic problems. One of the problems is that i have to write a simple program in C that implements BubbleSort . The BubbleSort algorithm has to be a seperate function and call it in the main program . Here is my effort . The problem is that it doesnt type the sorted array . I hope you can help me .
THE CODE :
int calculateRand()
{
int num;
num = (rand())%(UPPER-LOWER+1)+LOWER;
return num;
}
void swap(int *xp, int *yp)
{
int temp=*xp;
*xp=*yp;
*yp=temp;
}
void BubbleSort(int S[], int n)
{
int up=n;
int i,j;
while(up>1)
{
j=0;
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
}
for(i=0; i<n; i++)
{
printf("%d\n", S[i]);
}
}
int main()
{
int n,i;
printf("Parakalw dwste mia timh sto n: \n");
scanf("%d", &n);
int S[sizeof(n)];
printf("O mi taxinomimenos pinakas einai o exis \n");
for(i=0; i<n-1; i++)
{
S[i]=calculateRand();
printf("%d\n", S[i]);
}
printf("O pinakas meta thn taxinomisi einai \n");
BubbleSort(S[sizeof(n)], n);
return 0;
}
So if we start from the top there is a problem in the calculateRand() function as you do not declare the UPPER and LOWER variables or pass them as parameters to function.
Swap function is ok.
In the BubbleSort() function you need to decrease the up variable value after the for loop.
while(up>1)
{
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
up--;
}
Also at this point you should start iterating from 0 instead of 1 since arrays start from index 0. So for(i=0; i<up-1; i++) is the correct way to go.
Lastly in the main() function when you're declaring the array variable S you shouldn't pass the sizeof(n) since n is an integer and size of an integer is 4. Instead you want to use n as it is int S[n];
For loop to populate the array should go up to n not n-1 if you want to fill all elements of the array. However if you change this you'll need to make the similar change in the BubbleSort() function.
And finally in the BubbleSort() function call you are passing the last element of the array which is an integer whereas function expects you to pass an array. It should look like this BubbleSort(S, n); instead.
sizeof(n) has nothing to do with the value of the variable n. It's the the size of the variable n, i.e. mostly 4 bytes for the modern architectures.
Modern variants of C permit variable size arrays thus
int S[n];
would have been legit. Otherwise
int *S = (int *)malloc(n*sizeof(int));
will help.
When you call BubbleSort , your argument should be S not S[sizeof(n)];

Program stops after loop in function

My prog doesn't reach outArray function. it stops after loop of fillArray function. Why this happens. It looks strangely, cause it's simple void function and shouldn't return anything. This should continue run commands in main. And that stops as usual program without any problems and bugs
#include <stdio.h>
#define N 100
int enterNofArray();
void fillArray(int n, float arr[N]);
void outArray(int n, float arr[N]);
int main()
{
float arr[N], sum = 0.0, average;
int n;
//input
n = enterNofArray();
//compute
fillArray(n, &arr[N]);
//output
outArray(n, &arr[N]);
return 0;
}
int enterNofArray()
{
int n;
printf("Enter amount of array...\n");
scanf("%d", &n);
while (n < 1 || n > N)
{
printf("Incorrect!!\n");
printf("Enter in range 1 - 100...\n");
scanf("%d", &n);
}
return n;
}
void fillArray(int n, float arr[N])
{
int num;
for(int i = 0; i < n; i++)
{
printf("Enter number for array[%d times left]...\n", n - i);
scanf("%d", &num);
arr[i] = num;
}
}
void outArray(int n, float arr[N])
{
for(int i = 0; i < n; i++)
{
printf("%f ", arr[i]);
}
}
&arr[N] refers to the memory location (or lvalue) that contains the N-th (out of index!!!) element in the array.
That code invokes Undefined Behavior (UB).
So, you weren't actually passing the whole array to your functions, you were just attempting to pass the N-th element of that array... Read more about that expression here.
Change this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
to this:
fillArray(n, arr);
outArray(n, arr);
Live Demo
The problem was that with your code n was corrupted, containing garbage value after the call to fillArray function. As a result, when outArray function was called, n had a garbage value, which resulted in an uncontrolled for-loop that ended in looping far further than the limits of your array, eventually accessing memory that you didn't own, thus causing a Segmentation Fault.
Not the cause of your problem, but I suggest you do scanf("%f", &num); in your fillArray function (after declaring num as a float of course), since you want to populate an array of floats.
Because you're send double pointer when you do this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
Looks like:
fillArray(n, **arr);
outArray(n, **arr);
This happends so much when you work with Structures.

Outputting result of one-dimensional array with calculation in C language?

I am a new person on stackoverflow. I have stuck in a problem when I try to make a program with C language that will print out a maximum element in an one-dimensional array by using functions. I decided print out my element in in many ways. I have try to put "printf" in the "checkmax" fuction, in "main" function and make a function
"printmax" just for print my elements but none of these ways seem like work well.I need some helps.
int checkmax(int a[], int n)
{
int max=a[0];
for(i=0;i<n;i++);
{
if(a[i]>max) max=a[i];
}
return max;
//printf("max = %d", max);
}
/*void printmax()
{
if(checkmax(a,n)==max) printf("max = %d", max)
}*/
int main()
{
int n;
printf("Enter number of elements => ");
scanf("%d",&n);
int *a=(int*)calloc(n,sizeof(int));
inputarray(a,n);
checkmax(a,n);
//printf("max = %d", max);
getchar(); getchar();
}
You have i undeclared in the for loop.
Also this for(i=0;i<n;i++); means that you have an empty for loop because of the semicolon at the end. If you fix these you should be fine.
e.g.
for(int i=0;i<n;i++) {
if(a[i]>max) max=a[i];
}
There are a few errors we should address.
First, you are trying to use local variables as global ones. E.g. trying to use max in printmax() when it was defined locally in checkmax().
Second, your for loop does nothing due to the semicolon at the end. Also make sure to do int i = 0 instead of i = 0, since i was not declared before entering the loop.
Third, if you are getting errors from calling printf(), you should make sure that you included stdio.h at the top of your file: #include <stdio.h>
(the printf() in checkmax() also needs to be before return max;)
Solution:
Remove the declaration of max, a, and n in their functions, and instead declare them at the top of your file,
#include <stdio.h>
int max = 0, n = 0;
int a[] = {0};
...
fix the for loop,
for(int i = 0; i < n; i++){
...
}
and remove printmax(). The function is useless, since you print max in checkmax().

Passing arrays into functions, file.exe stopped working

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.

How to pass multi-dimensional array to function?

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.

Resources