Finding minimum in 2D array C - c

So I have this program to take in an integer(i) and then make a 2D array i x i
and that part I can get to work fine, but now I am trying to find the smallest number in the array and this is always returning 0.
int smallest_number(int b[MAXrow][MAXcol], int n)
{
int min = b[0][0];
int x,y;
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{
if (min > b[x][y])
{
min = b[x][y];
}
}
}
return min;
}

You are returning the "min" variable too soon. Currently, it is in the outer loop. What you want is to have it outside of the other loop.
Like this:
int smallest_number(int b[MAXrow][MAXcol], int n)
{
int min = b[0][0];
int x,y;
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{
if (min > b[x][y])
{
min = b[x][y];
}
}
}
return min;
}

You can try code below to find maximum & minimum from a matrix of any order.
Code :
#include<stdio.h>
void acc(int [5][5],int,int );
void maxmin(int [5][5],int,int);
void main()
{
int a[5][5],r,c;
printf("\n\t\t**Smallest & largest no. from matrix**\n");
printf("\n\tEnter the size of row:\n\t");
scanf("%d",&r);
printf("\tEnter the size of column:\n\t");
scanf("%d",&c);
acc(a,r,c);
maxmin(a,r,c);
}
void acc(int m[5][5],int r,int c)
{
int i,j;
printf("\n\tenter the elements of matrix\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\telement[%d][%d]= ",i,j);
scanf("%d",&m[i][j]);
}
}
}
void maxmin(int m[5][5],int r, int c)
{
int max=m[0][0], min=m[0][0],i,j;
for (i=0; i<r; i++)
{
for (j=0; j<c; j++)
{
if(m[i][j]>max)
max= m[i][j];
if(m[i][j]<min)
min= m[i][j];
}
}
printf("\n\tGreatest no. is : %d\n",max);
printf("\n\tSmallest no. is : %d\n",min);
}

Related

Function declaration is not allowed

When i run my code in online GCC compiler i get no errors and program gets compiled but when i try to run it in VSCODE it gives me error that function declaration is not allowed here.
Code.
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int main()
{
int n, x, y, i, j;
printf("How many numbers do you want to enter? ");
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
printf("Enter the numbers: ");
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the value of the two distance x and y: ");
scanf("%d %d",&x,&y);
int minDist(int arr[], int n, int x, int y)
{
int i, j;
int min_dist = INT_MAX;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if ((x == arr[i] && y == arr[j]
|| y == arr[i] && x == arr[j])
&& min_dist > abs(i - j)) {
min_dist = abs(i - j);
}
}
}
if (min_dist > n) {
return -1;
}
return min_dist;
}
printf("\nThe Minimum Distance between %d and %d is %d.\n",x, y,minDist(a,n,x,y));
free(a);
return 0;
}
You're declaring minDist inside main. Nested functions are a GNU extension. Other compilers might not allow them.
Take it and move it before the main function.
Here is your code
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int minDist(int arr[], int n, int x, int y);
int minDist(int arr[], int n, int x, int y)
{
int i, j;
int min_dist = INT_MAX;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if ((x == arr[i] && y == arr[j]
|| y == arr[i] && x == arr[j])
&& min_dist > abs(i - j)) {
min_dist = abs(i - j);
}
}
}
if (min_dist > n) {
return -1;
}
return min_dist;
}
int main()
{
int n, x, y, i, j;
printf("How many numbers do you want to enter? ");
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
printf("Enter the numbers: ");
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the value of the two distance x and y: ");
scanf("%d %d",&x,&y);
printf("\nThe Minimum Distance between %d and %d is %d.\n",x, y,minDist(a,n,x,y));
free(a);
return 0;
}
Following C standards, your program is not wrong.
You've used nested functions and that's supported in C. The reason to why your program worked just fine when compiled using gcc and not in VS Code is that
Nested functions are supported as an extension in GNU C, but are not supported by GNU C++
according to this(which was also pointed out by #luther in his answer).
VS Code's C/C++ extension uses the g++ command to compile C and C++ programs (yes, you can use both gcc and g++ to compile .c and .cpp files). g++ will compile .c and .cpp files, but will treat them as C++ files. So, now it's clear why your program does not work when compiled and run in VS Code.
Check this to look at VS Code's C/C++ extension and this to know the difference between gcc and g++.
If you really want to have your program compile and run in VS Code then you can choose to do one of these 2:
You can place the the minDist() before the main() function in your code like this:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int minDist(int arr[], int n, int x, int y)
{
int i, j;
int min_dist = INT_MAX;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if ((x == arr[i] && y == arr[j]
|| y == arr[i] && x == arr[j])
&& min_dist > abs(i - j)) {
min_dist = abs(i - j);
}
}
}
if (min_dist > n) {
return -1;
}
return min_dist;
}
int main()
{
int n, x, y, i, j;
printf("How many numbers do you want to enter? ");
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
printf("Enter the numbers: ");
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the value of the two distance x and y: ");
scanf("%d %d",&x,&y);
printf("\nThe Minimum Distance between %d and %d is %d.\n",x, y,minDist(a,n,x,y));
free(a);
return 0;
}
You may declare the function before the main() function and have the function's body after the main() function. Like this:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int minDist(int arr[], int n, int x, int y); // declaration of the minDist() function
int main()
{
int n, x, y, i, j;
printf("How many numbers do you want to enter? ");
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
printf("Enter the numbers: ");
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the value of the two distance x and y: ");
scanf("%d %d",&x,&y);
printf("\nThe Minimum Distance between %d and %d is %d.\n",x, y,minDist(a,n,x,y));
free(a);
return 0;
}
int minDist(int arr[], int n, int x, int y)
{
int i, j;
int min_dist = INT_MAX;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if ((x == arr[i] && y == arr[j]
|| y == arr[i] && x == arr[j])
&& min_dist > abs(i - j)) {
min_dist = abs(i - j);
}
}
}
if (min_dist > n) {
return -1;
}
return min_dist;
}
Edit: Many thanks to Erik Postpischil for pointing out that I have not completely answered the question.
c program is compiled in top to bottom so before using function in main you have to specify that there is a function that exist. for this write function prototype in up or write entire function body before main().
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int minDist(int arr[], int n, int x, int y);
int main()
{
int n, x, y, i, j;
printf("How many numbers do you want to enter? ");
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
printf("Enter the numbers: ");
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the value of the two distance x and y: ");
scanf("%d %d",&x,&y);
printf("\nThe Minimum Distance between %d and %d is %d.\n",x,y,minDist(a,n,x,y));
free(a);
return 0;
}
int minDist(int arr[], int n, int x, int y)
{
int i, j;
int min_dist = INT_MAX;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if ((x == arr[i] && y == arr[j]
|| y == arr[i] && x == arr[j])
&& min_dist > abs(i - j)) {
min_dist = abs(i - j);
}
}
}
if (min_dist > n) {
return -1;
}
return min_dist;
}
Why are you declaring the function inside the main function?
Take it and move it before the main function.

Used function to find the sum of the array elements, I am getting garbage value

I wrote a code for finding the sum of array elements using functions. I have written like this(mentioned below). I am getting a garbage value as output.
#include<stdio.h>
int fact(int n, int i) {
int sum = 0, arr[100];
for (i = 0; i < n; i++) {
sum = sum + arr[i];
}
return sum;
}
int main() {
int n, arr[100], i;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int sum = fact(n, i);
printf("%d", sum);
return 0;
}
Pass the array arr to your function instead of re-declaring it inside fact
PS: Change the name of your function to something meaningful like arrSum.
Code:
#include<stdio.h>
int arrSum (int arr[], int n) {
int i, sum = 0;
for (i = 0; i < n; i++) {
sum = sum + arr[i];
}
return sum;
}
int main() {
int n, arr[100], i;
scanf("%d", &n);
if(n < 0 || n > 100)
return -1;
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int sum = arrSum(arr, n);
printf("%d ", sum);
return 0;
}

Linear Search function compiles but no output

I do not understand what is wrong with this code of Linear search. It compiles but on execution exits without output.
turns - no. of test cases.
size - size of array.
x - element to be searched.
#include <stdio.h>
int linearSearch(int arr[], int size, int element)
{
int i = 0;
for(i=0; i< size; i++)
{
if(arr[i] == element)
{
return i;
}
}
return 0;
}
int main()
{
int turns, size;
scanf("%d", &turns);
while(turns--)
{
scanf("%d", &size);
int arr[size];
for(int j=0; j < size; j++)
{
scanf("%d", arr[j]);
}
int x;
scanf("%d", &x);
int k = linearSearch(arr, size, x);
}
return 0;
}
There is one major problem in your code.
First you need to pass address of your array element(&arr[j]).
And the output is not displaying because you are not printing it out.
The correct code is
#include <stdio.h>
int linearSearch(int arr[], int size, int element)
{
int i = 0;
for(i=0; i< size; i++)
{
if(arr[i] == element)
{
return i;
}
}
return 0;
}
int main()
{
int turns, size;
scanf("%d", &turns);
while(turns--)
{
scanf("%d", &size);
int arr[size];
for(int j=0; j < size; j++)
{
scanf("%d", &arr[j]);
}
int x;
scanf("%d", &x);
int k = linearSearch(arr, size, x);
printf("%d\n", k);
}
return 0;
}

C - Two dimensional matrix, add in a shape of two symmetrical up-down triangles (almost like X)

The objective: Add only the pieces of the matrix that are part of a full X (upper and lower triangle).
1 1 1
0 1 0
1 1 1
Like this, middle one should add only once.
I can't add the lower triangle properly. Help much appreciated :)
void write(int niz[20][20], int n){
int i, j;
for(i=0; i<n; i++){
for(j=0; j<n; j++){
scanf("%d", &niz[i][j]);
}
}
}
void x(int niz[20][20], int n){
//Upper triangle
int i, j, pr=n, suma=0;
for(i=0; i<n/2 + n%2; i++,pr--){
for(j=i; j<pr; j++){
suma += niz[i][j];
}
}
printf("%d\n",suma);
//Lower triangle
pr = n;
for(i=n; i>n/2 + n%2; i--,pr--){
printf("%d",pr);
for(j=n-i; j<pr; j++){
printf("\n%d", niz[i][j]);
suma += niz[i][j];
}
}
printf("%d", suma);
}
int main()
{
int n;
printf("Matrix dimensions: ");
scanf("%d", &n);
printf("Numbers in the matrix: \n");
int niz[n][n];
write(niz, n);
x(niz, n);
}
Instead of writing separate functions for each lower, upper & diagonals you can do all together with little tricks, but it works only if row == column and thats's what you want I think.
int main() {
/* it can be anything like a[3][3] or a[7][7] and elements can
be all one or all 2 or any number */
int arr[5][5] = { {1,1,1,1,1},
{0,0,1,0,0},
{0,0,1,0,0},
{0,0,1,0,0},
{1,1,1,1,1} };
int row = sizeof(arr)/sizeof(arr[0]);
int col = sizeof(arr[0])/sizeof(arr[0][0]);
int sum = 0;
for(int index = 0; index < row; index++) {
for(int sub_index = 0; sub_index < col; sub_index++) {
if(index == 0 || (index == row-1) || sub_index == row/2)
sum = sum + arr[index][sub_index];
}
}
printf("sum = %d \n",sum);
return 0;
}
Its fine if it helps you otherwise write your own logic.
There are some mismatches between the declarations and types of the arguments passed to OP's function. While in main they declare a variable length array, named niz:
int n;
// ...
int niz[n][n];
The posted signature of both write and x requires an int niz(*)[20]. It should be changed to:
void write(int n, int niz[n][n]);
// this ^^^ may be a size_t, just remember to write it before the array
About the pattern you have to follow for the sum, I can't say to fully understand your requirement, but if I'm not completely wrong, it could be done this way:
#include <stdio.h>
#include <stdlib.h>
void read_matrix(int n, int niz[n][n])
{
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
scanf("%d", &niz[i][j]);
}
}
}
// Separate the calculation from the printing
int hourglass_sum(int n, int niz[n][n])
{
int sum = 0;
int i = 0;
//Upper triangle
for(int k = n; i < k; ++i, --k) {
for(int j = i; j < k; ++j) {
sum += niz[i][j];
}
}
//Lower triangle
for(int k = i + 1; i < n; ++i, ++k) {
for(int j = n - i - 1; j < k; ++j) {
sum += niz[i][j];
}
}
return sum;
}
int main()
{
int n;
printf("Matrix dimensions: ");
scanf("%d", &n);
int niz[n][n];
read_matrix(n, niz);
printf("\nSum: %d", hourglass_sum(n, niz));
}

C error: expected declaration or statement at end of input

Alright, so from what I've seen, it seems these errors usually show up whenever there's a semicolon missing, or a misplaced curly-brace or something of that nature. I'm surely just missing it somehow, but I'm not able to find where the error is, or if it is due to an error of that sort. This error in pointing toward line 235, so the end of the last function.
This is the code
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX 100
void display_menu();
int check_option(int option);
int check_size(int size);
void initialize_2Darray(int x[][MAX], int size);
void print_2Darray(int x[][MAX], int size);
void initialize_1Darray(int y[], int size);
void print_1Darray(int y[], int size);
int search_min(int x[][MAX], int r, int c, int size);
int count_match(int x[][MAX], int y[], int size, int r);
int closest_row(int x[][MAX], int y[], int size);
void sort_1Darray(int y[], int size);
void sort_2Darray(int x[][MAX], int size);
int main()
{
int size, r, c, option;
int exit = 0; //exits program when = 1
int x[MAX][MAX], y[MAX];
srand(time(NULL));
printf("Enter the size: ");
scanf("%d", &size);
while(check_size(size) == 0) {
printf("\nInvalid input, enter the size of the array again: ");
scanf("%d", &size);
}
while(exit != 6) {
initialize_2Darray(x, size);
initialize_1Darray(y, size);
display_menu();
scanf("%d", &option);
while(check_option(option) == 0) {
printf("Invalid option, enter again: ");
scanf("%d", &option);
}
//Search Min Operation
if(option == 1) {
print_2Darray(x, size);
printf("Enter the row: ");
scanf("%d", &r);
printf("\nEnter the col: ");
scanf("%d", &c);
printf("The smallest number present in row %d and col %d is %d", r, c, search_min(x, r, c, size));
}
//Count Matches Op.
else if(option == 2) {
printf("Count Matches Operation\n\n2D array\n");
print_2Darray(x, size);
printf("\n1D array\n");
print_1Darray(y, size);
printf("\nEnter the row: ");
scanf("%d", &r);
if(count_match(x, y, size, r) > 0)
printf("There are %d matches from 1D array present in 2D array", count_match(x, y, size, r));
else
printf("There are no numbers from 1D array present in 2D array");
}
//Closest Row Op.
else if(option == 3) {
printf("\nClosest Row Operation\n\n2D array\n");
print_2Darray(x, size);
printf("\n1D array\n");
print_1Darray(y, size);
printf("Row closest to the 1D array is row %d", closest_row(x, y, size));
}
//Sort 1D Array Op.
else if(option == 4) {
printf("Sort 1D Array Operation\n\n1D Array before sorting:\n");
print_1Darray(y, size);
sort_1Darray(y, size);
printf("\n\n1D Array after sorting:\n");
print_1Darray(y, size);
}
//Sort 2D Array Op.
else if(option == 5) {
printf("\nSort 2D Array Option\n\n2D Array before sorting:\n");
print_2Darray(x, size);
sort_2Darray(x, size);
printf("\n\n2D Array after sorting:\n");
print_2Darray(x, size);
}
//Exit
else if(option == 6)
exit = 6;
}
return 0;
}
void display_menu()
{
printf("\nArray operations, your options are:\n\n1: Search Min\n2: Count Matches\n3: Closest Row\n4: Sort 1D Array\n5: Sort 2D Array\n6: Exit\nEnter the operation you want to perform: ");
}
int check_option(int option)
{
if(option > 0 && option < 7)
return 1;
else
return 0;
}
int check_size(int size)
{
if(size > 0 && size <= 100)
return 1;
else
return 0;
}
void initialize_2Darray(int x[][MAX], int size)
{
int i, s; //counters
for(i=0; i < size; i++) {
for(s=0; s < size; s++) {
x[i][s] = rand()%10;
}
}
}
void print_2Darray(int x[][MAX], int size)
{
int i, s; //counters
for(i=0; i < size; i++) {
printf("\n");
for(s=0; s < size; s++) {
printf("%d ", x[i][s]);
}
}
printf("\n");
}
void initialize_1Darray(int y[], int size)
{
int i, r;
for(i=0; i < size; i++) {
r = rand()%10;
y[i] = r;
}
}
void print_1Darray(int y[], int size)
{
int i;
//Prints array values until (s)ize is reached
for(i=0; i < size; i++) {
printf("%d ", y[i]);
}
}
int search_min(int x[][MAX], int r, int c, int size)
{
int i, j; //counters
int min = 9;
for(i=0; i < size; i++) {
if(x[r][i] < min) {
min = x[r][i];
}
}
for(j=0; j < size; j++) {
if(x[j][c] < min) {
min = x[j][c];
}
}
return min;
}
int count_match(int x[][MAX], int y[], int size, int r)
{
int i, j, count;
for(i=0; i < size; i++) {
for(j=0; j < size; j++) {
if(y[i] == x[r][j])
count++;
}
return count;
}
int closest_row(int x[][MAX], int y[], int size)
{
int l, i, j; //counters
int sum = 0;
int dif = 0;
int row, totaldif; //best matching row & total dif
for(l=0; l < size; l++) {
for(i=0; i < size; i++) {
for(j=0; j < size; j++) {
dif = abs(y[j] - x[i][j]);
sum += dif;
}
if(sum < totaldif) {
totaldif = sum;
row = i;
}
sum = 0;
}
}
return row;
}
void sort_1Darray(int y[], int size)
{
int a, b, temp;
//Loops through the array, swapping values until in proper order of ascension
for(a = 0; a < size; a++) {
for(b = 0; b < size-1; b++) {
if(y[b] > y[b+1]) {
temp = y[b+1];
y[b+1] = y[b];
y[b] = temp;
}
}
}
}
void sort_2Darray(int x[][MAX], int size)
{
int a, b, c, temp;
//Loops through the array, swapping values until in proper order of ascension
for(c=0; c < size; c++) {
for(a = 0; a < size; a++) {
for(b = 0; b < size-1; b++) {
if(x[a][b] > x[a][b+1]) {
temp = x[a][b+1];
x[a][b+1] = x[a][b];
x[a][b] = temp;
}
}
}
}
}
Run your code through indent. It can help you find this sort of problem very quickly.
Here's the output from your code. As you can see, the problem is caused by a missing brace at the end of count_match():
int
count_match(int x[][MAX], int y[], int size, int r)
{
int i , j, count;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if (y[i] == x[r][j])
count++;
}
return count;
}
/*** CLOSING BRACE MISSING HERE ***/
int closest_row(int x[][MAX], int y[], int size){
int l , i, j;
//counters

Resources